Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
25 changes: 25 additions & 0 deletions src/hooks/useChatWithAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import {hasSeenTourSelector} from '@selectors/Onboarding';
import {navigateToAndOpenReportWithAccountIDs} from '@libs/actions/Report';
import ONYXKEYS from '@src/ONYXKEYS';
import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails';
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.
*/
function useChatWithAgent() {
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector});
const [betas] = useOnyx(ONYXKEYS.BETAS);
const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);

const chatWithAgent = (accountID: number) => {
navigateToAndOpenReportWithAccountIDs([accountID], currentUserPersonalDetails.accountID, introSelected, isSelfTourViewed, betas, personalDetails);
};

return chatWithAgent;
}

export default useChatWithAgent;
89 changes: 89 additions & 0 deletions src/hooks/useSwitchToDelegator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import {useDelegateNoAccessActions, useDelegateNoAccessState} from '@components/DelegateNoAccessModalProvider';
import {ModalActions} from '@components/Modal/Global/ModalContext';
import {connect, disconnect} from '@libs/actions/Delegate';
import {close as modalClose} from '@libs/actions/Modal';
import {getGpsPoints, stopGpsTrip} from '@libs/GPSDraftDetailsUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {isTrackingSelector} from '@src/selectors/GPSDraftDetails';
import type {Account} from '@src/types/onyx';
import useConfirmModal from './useConfirmModal';
import useLocalize from './useLocalize';
import useNetwork from './useNetwork';
import useOnyx from './useOnyx';

/**
* Encapsulates the safety checks needed before switching to a delegator account:
* 1. Offline check – blocks the switch and shows an offline modal.
* 2. Chained delegation check – if already acting as a delegate and not returning
* to the original user, shows the "not so fast" modal.
* 3. GPS tracking check – if a GPS trip is in progress, asks the user to confirm
* stopping the trip before switching.
*/
function useSwitchToDelegator() {
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const {showConfirmModal} = useConfirmModal();
const {isActingAsDelegate} = useDelegateNoAccessState();
const {showDelegateNoAccessModal} = useDelegateNoAccessActions();

const [delegatedAccess] = useOnyx(ONYXKEYS.ACCOUNT, {selector: (account: Account | undefined) => account?.delegatedAccess});
const [credentials] = useOnyx(ONYXKEYS.CREDENTIALS);
const [stashedCredentials = CONST.EMPTY_OBJECT] = useOnyx(ONYXKEYS.STASHED_CREDENTIALS);
const [session] = useOnyx(ONYXKEYS.SESSION);
const [stashedSession] = useOnyx(ONYXKEYS.STASHED_SESSION);
const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID);
const [gpsDraftDetails] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS);
const [isTrackingGPS = false] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS, {selector: isTrackingSelector});

const showOfflineModal = () => {
showConfirmModal({
title: translate('common.youAppearToBeOffline'),
prompt: translate('common.offlinePrompt'),
confirmText: translate('common.buttonConfirm'),
shouldShowCancelButton: false,
});
};

const showGpsInProgressModal = async (switchAccount: () => ReturnType<typeof connect | typeof disconnect>) => {
const result = await showConfirmModal({
title: translate('gps.switchAccountWarningTripInProgress.title'),
prompt: translate('gps.switchAccountWarningTripInProgress.prompt'),
confirmText: translate('gps.switchAccountWarningTripInProgress.confirm'),
cancelText: translate('common.cancel'),
});

if (result.action !== ModalActions.CONFIRM) {
return;
}

await stopGpsTrip(false, getGpsPoints(gpsDraftDetails), true);
switchAccount();
};

const switchToDelegator = (email: string) => {
if (isOffline) {
modalClose(() => showOfflineModal());
return;
}
const isReturningToOriginalUser = isActingAsDelegate && email === stashedSession?.email;
// Chained delegation isn't supported by the backend — if we're already acting as a delegate,
// the only legal switch is back to the original user. Anything else triggers the "Not so fast" modal.
if (isActingAsDelegate && !isReturningToOriginalUser) {
modalClose(() => showDelegateNoAccessModal());
return;
}
const switchAction = isReturningToOriginalUser
? () => disconnect({stashedCredentials, stashedSession})
: () => connect({email, delegatedAccess, credentials, session, activePolicyID});
if (isTrackingGPS) {
modalClose(() => showGpsInProgressModal(switchAction));
return;
}
switchAction();
};

return switchToDelegator;
}

export default useSwitchToDelegator;
2 changes: 2 additions & 0 deletions src/languages/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2784,6 +2784,8 @@ ${amount} für ${merchant} – ${date}`,
title: 'Agent bearbeiten',
agentName: 'Name der Agentin/des Agenten',
instructions: 'Eigene Anweisungen schreiben',
chatWithAgent: 'Mit Agent chatten',
copilotIntoAccount: 'Copilot ins Konto',
deleteAgent: 'Agent löschen',
deleteAgentTitle: 'Agent löschen?',
deleteAgentMessage: 'Sind Sie sicher, dass Sie diese Vermittlerin/diesen Vermittler löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2843,6 +2843,8 @@ const translations = {
title: 'Edit agent',
agentName: 'Agent name',
instructions: 'Write custom instructions',
chatWithAgent: 'Chat with agent',
copilotIntoAccount: 'Copilot into account',
deleteAgent: 'Delete agent',
deleteAgentTitle: 'Delete agent?',
deleteAgentMessage: 'Are you sure you want to delete this agent? This action cannot be undone.',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2656,6 +2656,8 @@ ${amount} para ${merchant} - ${date}`,
title: 'Editar agente',
agentName: 'Nombre del agente',
instructions: 'Escribir instrucciones personalizadas',
chatWithAgent: 'Chatear con el agente',
copilotIntoAccount: 'Copilot en la cuenta',
deleteAgent: 'Eliminar agente',
deleteAgentTitle: '¿Eliminar agente?',
deleteAgentMessage: '¿Seguro que quieres eliminar a este agente? Esta acción no se puede deshacer.',
Expand Down
4 changes: 3 additions & 1 deletion src/languages/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2792,7 +2792,9 @@ ${amount} pour ${merchant} - ${date}`,
title: 'Modifier l’agent',
agentName: 'Nom de l’agent',
instructions: 'Écrire des instructions personnalisées',
deleteAgent: 'Supprimer l’agent',
chatWithAgent: 'Discuter avec l\u2019agent',
copilotIntoAccount: 'Copilote dans le compte',
deleteAgent: 'Supprimer l\u2019agent',
deleteAgentTitle: 'Supprimer l’agent ?',
deleteAgentMessage: 'Voulez-vous vraiment supprimer cet agent ? Cette action est irréversible.',
},
Expand Down
2 changes: 2 additions & 0 deletions src/languages/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2780,6 +2780,8 @@ ${amount} per ${merchant} - ${date}`,
title: 'Modifica agente',
agentName: 'Nome agente',
instructions: 'Scrivi istruzioni personalizzate',
chatWithAgent: 'Chatta con l\u2019agente',
copilotIntoAccount: 'Copilot nell\u2019account',
deleteAgent: 'Elimina agente',
deleteAgentTitle: 'Eliminare agente?',
deleteAgentMessage: 'Sei sicuro di voler eliminare questo agente? Questa azione non può essere annullata.',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2753,6 +2753,8 @@ ${date} の ${merchant} への ${amount}`,
title: 'エージェントを編集',
agentName: '担当者名',
instructions: 'カスタム手順を作成',
chatWithAgent: 'エージェントとチャット',
copilotIntoAccount: 'アカウントにコパイロット',
deleteAgent: 'エージェントを削除',
deleteAgentTitle: 'エージェントを削除しますか?',
deleteAgentMessage: 'このエージェントを削除してもよろしいですか?この操作は元に戻せません。',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/nl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2777,6 +2777,8 @@ ${amount} voor ${merchant} - ${date}`,
title: 'Agent bewerken',
agentName: 'Naam medewerker',
instructions: 'Aangepaste instructies schrijven',
chatWithAgent: 'Chat met agent',
copilotIntoAccount: 'Copilot in account',
deleteAgent: 'Agent verwijderen',
deleteAgentTitle: 'Agent verwijderen?',
deleteAgentMessage: 'Weet je zeker dat je deze agent wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2771,6 +2771,8 @@ ${amount} dla ${merchant} - ${date}`,
title: 'Edytuj agenta',
agentName: 'Nazwa agenta',
instructions: 'Napisz własne instrukcje',
chatWithAgent: 'Czat z agentem',
copilotIntoAccount: 'Copilot na konto',
deleteAgent: 'Usuń agenta',
deleteAgentTitle: 'Usunąć agenta?',
deleteAgentMessage: 'Czy na pewno chcesz usunąć tego agenta? Tej akcji nie można cofnąć.',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2771,6 +2771,8 @@ ${amount} para ${merchant} - ${date}`,
title: 'Editar agente',
agentName: 'Nome do agente',
instructions: 'Escrever instruções personalizadas',
chatWithAgent: 'Conversar com o agente',
copilotIntoAccount: 'Copilot na conta',
deleteAgent: 'Excluir agente',
deleteAgentTitle: 'Excluir agente?',
deleteAgentMessage: 'Tem certeza de que quer excluir este agente? Essa ação não pode ser desfeita.',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/zh-hans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2696,6 +2696,8 @@ ${amount},商户:${merchant} - 日期:${date}`,
title: '编辑代理',
agentName: '代理人姓名',
instructions: '编写自定义说明',
chatWithAgent: '与代理聊天',
copilotIntoAccount: 'Copilot 进入账户',
deleteAgent: '删除代理',
deleteAgentTitle: '删除代理?',
deleteAgentMessage: '确定要删除此代理吗?此操作无法撤销。',
Expand Down
34 changes: 31 additions & 3 deletions src/pages/settings/Agents/AgentsListRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,31 @@ type AgentsListRowProps = {

/** Whether to show the red error dot indicator */
brickRoadIndicator?: typeof CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR | null;

/** Called when the Chat button is pressed */
onChatPress?: (accountID: number) => void;

/** Called when the Copilot button is pressed */
onCopilotPress?: (login: string) => void;
};

function AgentsListRow({accountID, displayName, login, pendingAction, errors, onErrorClose, brickRoadIndicator}: AgentsListRowProps) {
function AgentsListRow({accountID, displayName, login, pendingAction, errors, onErrorClose, brickRoadIndicator, onChatPress, onCopilotPress}: AgentsListRowProps) {
const styles = useThemeStyles();
const theme = useTheme();
const {translate} = useLocalize();
const {shouldUseNarrowLayout} = useResponsiveLayout();
const icons = useMemoizedLazyExpensifyIcons(['DotIndicator']);
const icons = useMemoizedLazyExpensifyIcons(['DotIndicator', 'ChatBubble']);

const isPendingDeletion = pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
const isPendingAddOrDelete = pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || isPendingDeletion;
const areActionsDisabled = isPendingAddOrDelete || accountID <= 0 || !login;
const navigateToEdit = () => Navigation.navigate(ROUTES.SETTINGS_AGENTS_EDIT.getRoute(accountID));
const handleChatPress = () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ CONSISTENCY-3 (docs)

The handleChatPress logic (calling navigateToAndOpenReportWithAccountIDs with currentUserPersonalDetails.accountID, introSelected, isSelfTourViewed, betas, personalDetails) is duplicated identically in both AgentsListRow.tsx and EditAgentPage.tsx. All the supporting hooks (useCurrentUserPersonalDetails, useOnyx(NVP_INTRO_SELECTED), useOnyx(NVP_ONBOARDING), useOnyx(BETAS), useOnyx(PERSONAL_DETAILS_LIST)) are also duplicated.

Extract a reusable hook (e.g., useChatWithAccount) that encapsulates the data fetching and returns a (accountID: number) => void callback, similar to how useSwitchToDelegator was extracted.


Reviewed at: b1dd748 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MelvinBot Address this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed — extracted a useChatWithAgent hook that encapsulates the data fetching (introSelected, isSelfTourViewed, betas, personalDetails, currentUserPersonalDetails) and the navigateToAndOpenReportWithAccountIDs call. Both AgentsListRow and EditAgentPage now use this shared hook.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — see reply above.

onChatPress?.(accountID);
};
const handleCopilotPress = () => {
onCopilotPress?.(login);
};

return (
<OfflineWithFeedback
Expand Down Expand Up @@ -79,7 +93,7 @@ function AgentsListRow({accountID, displayName, login, pendingAction, errors, on
)}
</PressableWithFeedback>
) : (
<View style={[styles.selectionListPressableItemWrapper, styles.mb2, styles.gap3]}>
<View style={[styles.selectionListPressableItemWrapper, styles.mb2, styles.gap2]}>
<AgentInfoRow
accountID={accountID}
displayName={displayName}
Expand All @@ -92,6 +106,20 @@ function AgentsListRow({accountID, displayName, login, pendingAction, errors, on
fill={theme.danger}
/>
)}
<Button
small
icon={icons.ChatBubble}
onPress={handleChatPress}
isDisabled={areActionsDisabled}
accessibilityLabel={translate('editAgentPage.chatWithAgent')}
/>
Comment on lines +109 to +115

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MelvinBot Fix accessibility

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added accessibilityLabel using the existing editAgentPage.chatWithAgent translation key.

<Button
small
text={translate('delegate.copilot')}
onPress={handleCopilotPress}
isDisabled={areActionsDisabled}
accessibilityLabel={translate('editAgentPage.copilotIntoAccount')}
/>
Comment on lines +116 to +122

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MelvinBot Fix accessibility

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added accessibilityLabel to both icon-only buttons using existing translation keys (editAgentPage.chatWithAgent and editAgentPage.copilotIntoAccount).

<Button
small
text={translate('common.edit')}
Expand Down
6 changes: 6 additions & 0 deletions src/pages/settings/Agents/AgentsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import Text from '@components/Text';
import useChatWithAgent from '@hooks/useChatWithAgent';
import useDocumentTitle from '@hooks/useDocumentTitle';
import {useMemoizedLazyExpensifyIcons, useMemoizedLazyIllustrations} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import usePermissions from '@hooks/usePermissions';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSwitchToDelegator from '@hooks/useSwitchToDelegator';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
import NotFoundPage from '@pages/ErrorPage/NotFoundPage';
Expand All @@ -38,6 +40,8 @@ function AgentsPage() {
const {shouldUseNarrowLayout} = useResponsiveLayout();
const illustrations = useMemoizedLazyIllustrations(['TvScreenRobot', 'AiBot']);
const icons = useMemoizedLazyExpensifyIcons(['Plus']);
const chatWithAgent = useChatWithAgent();
const switchToDelegator = useSwitchToDelegator();
const {isBetaEnabled} = usePermissions();
const isCustomAgentEnabled = isBetaEnabled(CONST.BETAS.CUSTOM_AGENT);
useDocumentTitle(translate('agentsPage.title'));
Expand Down Expand Up @@ -95,6 +99,8 @@ function AgentsPage() {
errors={shouldShowErrors(item.pendingAction) ? item.errors : null}
onErrorClose={() => handleErrorClose(item.pendingAction, item.accountID)}
brickRoadIndicator={item.hasUpdateErrors ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : null}
onChatPress={chatWithAgent}
onCopilotPress={switchToDelegator}
/>
);

Expand Down
27 changes: 26 additions & 1 deletion src/pages/settings/Agents/EditAgentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import {ModalActions} from '@components/Modal/Global/ModalContext';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import useChatWithAgent from '@hooks/useChatWithAgent';
import useConfirmModal from '@hooks/useConfirmModal';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import useSwitchToDelegator from '@hooks/useSwitchToDelegator';
import useThemeStyles from '@hooks/useThemeStyles';
import {clearAgentAvatarUpdateError, clearAgentNameUpdateError, clearAgentPromptUpdateError, deleteAgent} from '@libs/actions/Agent';
import Navigation from '@libs/Navigation/Navigation';
Expand All @@ -28,11 +30,13 @@ type EditAgentPageProps = PlatformStackScreenProps<SettingsNavigatorParamList, t
function EditAgentPage({route}: EditAgentPageProps) {
const {translate} = useLocalize();
const styles = useThemeStyles();
const icons = useMemoizedLazyExpensifyIcons(['Trashcan']);
const icons = useMemoizedLazyExpensifyIcons(['Trashcan', 'ChatBubble', 'Users']);
const accountID = route.params.accountID;
const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`);
const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]});
const {showConfirmModal} = useConfirmModal();
const chatWithAgent = useChatWithAgent();
const switchToDelegator = useSwitchToDelegator();
const isOnyxLoaded = agentMetadata.status === 'loaded' && personalDetailsMetadata.status === 'loaded';
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;

Expand All @@ -54,6 +58,15 @@ function EditAgentPage({route}: EditAgentPageProps) {
}
deleteAgent(accountID);
};
const agentLogin = personalDetails?.login ?? '';
const isPendingAddOrDelete = agent?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || agent?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
const areActionsDisabled = isPendingAddOrDelete || accountID <= 0 || !agentLogin;
const handleChatPress = () => {
chatWithAgent(accountID);
};
const handleCopilotPress = () => {
switchToDelegator(agentLogin);
};

if (shouldShowNotFoundPage) {
return <NotFoundPage onBackButtonPress={() => Navigation.goBack(ROUTES.SETTINGS_AGENTS)} />;
Expand Down Expand Up @@ -114,6 +127,18 @@ function EditAgentPage({route}: EditAgentPageProps) {
numberOfLinesTitle={10}
/>
</OfflineWithFeedback>
<MenuItem
title={translate('editAgentPage.chatWithAgent')}
icon={icons.ChatBubble}
onPress={handleChatPress}
disabled={areActionsDisabled}
/>
<MenuItem
title={translate('editAgentPage.copilotIntoAccount')}
icon={icons.Users}
onPress={handleCopilotPress}
disabled={areActionsDisabled}
/>
<MenuItem
title={translate('editAgentPage.deleteAgent')}
icon={icons.Trashcan}
Expand Down
Loading
Loading