Skip to content

[Due for payment 2026-06-08] [$250] Add buttons to chat and copilot with agents #91343

Closed

Description

@puneetlath

Add two buttons to the agent row in Account > Agents. The first should open the DM with the agent. The second should copilot you into the agent account.

Image

Also add two buttons to the edit agent modal to do the same two actions.

Image
Issue OwnerCurrent Issue Owner: @mallenexpensify
Upwork Automation - Do Not Edit

Activity

  1. NicolasBonet commented on May 21, 2026

    @NicolasBonet
    Contributor

    @MelvinBot investigate this

  2. MelvinBot commented on May 21, 2026

    @MelvinBot
    Contributor

    Proposal

    Problem

    The Agents page (Account > Agents) and the Edit Agent modal lack buttons to (1) open a DM with the agent and (2) copilot into the agent's account.

    Solution

    Add two buttons in two locations:

    1. AgentsListRow.tsx — Add "Chat" and "Copilot" buttons next to the existing "Edit" button (wide layout), and as icon buttons or a row action menu (narrow layout).

    2. EditAgentPage.tsx — Add two MenuItem entries (similar to the existing delete item) for "Chat with agent" and "Copilot as agent", using the same action functions above.

    Implementation details

    Icons: Use ChatBubble for the DM button and a suitable user icon (e.g., User or UserPlus) for the copilot button, from the existing expensify-icons chunk.

    navigateToAndOpenReportWithAccountIDs signature requires several Onyx values (currentUserAccountID, introSelected, isSelfTourViewed, betas, personalDetails). These should be pulled via useOnyx hooks in the components, following the pattern in PromotedActionsBar.

    Delegate.connect() signature requires email, delegatedAccess, credentials, session, and activePolicyID. These are available via Onyx keys ONYXKEYS.SESSION, ONYXKEYS.CREDENTIALS, ONYXKEYS.ACCOUNT (for delegatedAccess), and ONYXKEYS.NVP_ACTIVE_POLICY_ID. The CopilotPage implementation at lines 174-210 shows the exact pattern including pre-switch checks for GPS trips and offline state.

    Narrow layout handling: On narrow layout, the entire AgentsListRow is currently a single pressable that navigates to edit. The two new buttons could be added as small icon-only buttons within the pressable row (similar to how brickRoadIndicator is already rendered inline), or the row could navigate to the edit page where the buttons are also available.


    Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 21, 2026
  4. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 21, 2026
  5. melvin-bot commented on May 21, 2026

    @melvin-bot

    Current assignee @ShridharGoel is eligible for the External assigner, not assigning anyone new.

  6. KJ21-ENG commented on May 21, 2026

    @KJ21-ENG
    Contributor

    Proposal

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

    Users can create and edit custom agents from Account > Agents, but the Agents UI does not expose the two primary actions for an existing agent: opening a DM with the agent and switching into the agent account as a copilot.

    What is the root cause of that problem?

    The Agents list row is currently edit-only. On narrow layouts, the whole AgentsListRow pressable navigates to the edit route, and on wide layouts the only explicit action button is Edit:

    {shouldUseNarrowLayout ? (
    <PressableWithFeedback
    style={[styles.selectionListPressableItemWrapper, styles.mb2, styles.gap3]}
    onPress={navigateToEdit}
    accessibilityLabel={displayName}
    role={CONST.ROLE.BUTTON}
    sentryLabel="AgentsListRow-Edit"
    disabled={isPendingDeletion}
    >
    <AgentInfoRow
    accountID={accountID}
    displayName={displayName}
    login={login}
    isPendingDeletion={isPendingDeletion}
    />
    {!!brickRoadIndicator && (
    <Icon
    src={icons.DotIndicator}
    fill={theme.danger}
    />
    )}
    </PressableWithFeedback>
    ) : (
    <View style={[styles.selectionListPressableItemWrapper, styles.mb2, styles.gap3]}>
    <AgentInfoRow
    accountID={accountID}
    displayName={displayName}
    login={login}
    isPendingDeletion={isPendingDeletion}
    />
    {!!brickRoadIndicator && (
    <Icon
    src={icons.DotIndicator}
    fill={theme.danger}
    />
    )}
    <Button
    small
    text={translate('common.edit')}
    onPress={navigateToEdit}
    isDisabled={isPendingDeletion}
    />

    The edit page has the same gap: it renders avatar/name/prompt editing plus delete, but no action controls for chat or copilot:

    <ScrollView contentContainerStyle={styles.flexGrow1}>
    <OfflineWithFeedback
    errors={agent?.avatarErrors}
    errorRowStyles={[styles.mh5, styles.mb2]}
    onClose={() => clearAgentAvatarUpdateError(accountID)}
    >
    <View style={[styles.alignItemsCenter, styles.pv5]}>
    <AvatarButtonWithIcon
    text={translate('editAgentAvatarPage.title')}
    source={personalDetails?.avatar ?? ''}
    avatarID={accountID}
    onPress={handleEditAvatarPress}
    size={CONST.AVATAR_SIZE.X_LARGE}
    avatarStyle={[styles.avatarXLarge, styles.alignSelfCenter]}
    pendingAction={personalDetails?.pendingFields?.avatar}
    sentryLabel={CONST.SENTRY_LABEL.EDIT_AGENT_PAGE.AVATAR}
    editIconStyle={styles.profilePageAvatar}
    />
    </View>
    </OfflineWithFeedback>
    <OfflineWithFeedback
    errors={agent?.nameErrors}
    errorRowStyles={[styles.mh5, styles.mb2]}
    onClose={() => clearAgentNameUpdateError(accountID)}
    >
    <MenuItemWithTopDescription
    description={translate('editAgentPage.agentName')}
    title={personalDetails?.displayName ?? ''}
    shouldShowRightIcon
    onPress={handleEditNamePress}
    />
    </OfflineWithFeedback>
    <OfflineWithFeedback
    errors={agent?.promptErrors}
    errorRowStyles={[styles.mh5, styles.mb2]}
    onClose={() => clearAgentPromptUpdateError(accountID)}
    >
    <MenuItemWithTopDescription
    description={translate('editAgentPage.instructions')}
    title={agent?.prompt?.trim() ?? ''}
    shouldShowRightIcon
    onPress={handleEditPromptPress}
    numberOfLinesTitle={10}
    />
    </OfflineWithFeedback>
    <MenuItem
    title={translate('editAgentPage.deleteAgent')}
    icon={icons.Trashcan}
    onPress={handleDeletePress}
    />

    The required behaviors already exist elsewhere. Opening a one-to-one chat is handled by navigateToAndOpenReport, which finds or creates the DM and navigates to it:

    function navigateToAndOpenReport(
    userLogins: string[],
    personalDetails: OnyxEntry<PersonalDetailsList>,
    currentUserAccountID: number,
    introSelected: OnyxEntry<IntroSelected>,
    isSelfTourViewed: boolean | undefined,
    betas: OnyxEntry<Beta[]>,
    shouldDismissModal = true,
    shouldRevalidateExistingChat = false,
    ) {
    const participantAccountIDs = PersonalDetailsUtils.getAccountIDsByLogins(userLogins);
    const chat = getChatByParticipants([...participantAccountIDs, currentUserAccountID]);
    const createAndOpenNewOptimisticChat = (sourceCachedReportID?: string) => {
    const fallbackChat = buildOptimisticChatReport({
    participantList: [...participantAccountIDs, currentUserAccountID],
    notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN,
    currentUserAccountID,
    });
    if (sourceCachedReportID) {
    setStaleDMRecoveryTarget(sourceCachedReportID, fallbackChat.reportID);
    }
    // We pass newReportObject to force chat creation on the server.
    openReport({
    reportID: fallbackChat.reportID,
    introSelected,
    reportActionID: '',
    participants: buildParticipantInfoFromLogins(userLogins),
    personalDetails,
    newReportObject: fallbackChat,
    isSelfTourViewed,
    betas,
    });
    navigateToReport(fallbackChat.reportID, shouldDismissModal);
    };
    if (isEmptyObject(chat) || isReportNotFound(chat)) {
    createAndOpenNewOptimisticChat(chat?.reportID);
    return;
    }
    if (!shouldRevalidateExistingChat) {
    navigateToReport(chat.reportID, shouldDismissModal);
    return;
    }
    let hasAttemptedFallback = false;
    const reportConnection = Onyx.connectWithoutView({
    key: `${ONYXKEYS.COLLECTION.REPORT}${chat.reportID}`,
    callback: (updatedReport) => {
    const notFoundError = updatedReport?.errorFields?.notFound;
    if (notFoundError === null) {
    Onyx.disconnect(reportConnection);
    return;
    }
    if (!notFoundError || hasAttemptedFallback) {
    return;
    }
    hasAttemptedFallback = true;
    Onyx.disconnect(reportConnection);
    createAndOpenNewOptimisticChat(chat.reportID);
    },
    });
    // 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);

    Starting a copilot session is handled by Delegate.connect, and the Copilot page already wraps that call with the offline, GPS-trip, and chained-delegation guards:

    function connect({email, delegatedAccess, credentials, session, activePolicyID, isFromOldDot = false}: ConnectParams) {
    if (!delegatedAccess?.delegators && !isFromOldDot) {
    return;
    }
    Onyx.set(ONYXKEYS.STASHED_CREDENTIALS, credentials ?? {});
    Onyx.set(ONYXKEYS.STASHED_SESSION, session ?? {});
    const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    delegatedAccess: {
    errorFields: {
    connect: {
    [email]: null,
    },
    },
    },
    },
    },
    ];
    const successData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    delegatedAccess: {
    errorFields: {
    connect: {
    [email]: null,
    },
    },
    },
    },
    },
    ];
    const failureData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    delegatedAccess: {
    errorFields: {
    connect: {
    [email]: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('delegate.genericError'),
    },
    },
    },
    },
    },
    ];
    // We need to access the authToken directly from the response to update the session
    // eslint-disable-next-line rulesdir/no-api-side-effects-method
    return API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.CONNECT_AS_DELEGATE, {to: email}, {optimisticData, successData, failureData})
    .then((response) => {
    if (!response?.restrictedToken || !response?.encryptedAuthToken) {
    Log.alert('[Delegate] No auth token returned while connecting as a delegate');
    Onyx.update(failureData);
    return;
    }
    if (!activePolicyID && CONFIG.IS_HYBRID_APP) {
    Log.alert('[Delegate] Unable to access activePolicyID');
    Onyx.update(failureData);
    return;
    }
    clearPreservedSearchNavigatorStates();
    const restrictedToken = response.restrictedToken;
    const policyID = activePolicyID;
    return SequentialQueue.waitForIdle()
    .then(() => {
    // Update authToken in Onyx so it persists if the further flow does not complete for any reason.
    return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken);
    })
    .then(() => {
    NetworkStore.setAuthToken(response?.restrictedToken ?? null);
    return clearOnyxForDelegateTransition();
    })
    .then(() => {

    const switchToDelegator = useCallback(
    (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: account?.delegatedAccess, credentials, session, activePolicyID});
    if (isTrackingGPS) {
    modalClose(() => showGpsInProgressModal(switchAction));
    return;
    }
    switchAction();

    So this is not a missing backend capability in the client; the Agents surfaces simply do not wire the existing DM and copilot actions into the row or edit modal.

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

    Add a small shared Agents helper/hook, for example useAgentQuickActions(accountID, login), that exposes openAgentChat and openAgentCopilot. openAgentChat should mirror NewChatPage by using navigateToAndOpenReport([login], personalDetails, currentUserAccountID, introSelected, isSelfTourViewed, betas). openAgentCopilot should reuse the same delegated-access switching rules as CopilotPage: show the existing offline modal while offline, show the GPS in-progress confirmation before switching during an active trip, block chained delegation with the existing "Not so fast" modal, and otherwise call connect({email: login, delegatedAccess: account?.delegatedAccess, credentials, session, activePolicyID}).

    Update AgentsListRow to render explicit Chat and Copilot action buttons next to the existing Edit action. On narrow layouts, stop making the entire row the only edit target; render the agent info as its own edit pressable and keep the action buttons as separate pressables so tapping Chat/Copilot does not also navigate to the edit page. Keep all three actions disabled when the row is pending deletion.

    Update EditAgentPage to render the same Chat and Copilot actions near the top of the modal, using the selected agent's personalDetails.login. Reuse existing translations where possible (common.chat, delegate.copilot) and add only missing accessibility labels/tooltips if icon-only buttons are used.

    Scope boundaries:

    • Files touched: src/pages/settings/Agents/AgentsListRow.tsx - add Chat/Copilot buttons and avoid nested row pressables; src/pages/settings/Agents/EditAgentPage.tsx - add Chat/Copilot actions; new src/pages/settings/Agents/useAgentQuickActions.ts (or equivalent local helper) - centralize DM and copilot behavior; src/languages/en.ts and generated locale files only if new action labels/accessibility text are needed.
    • Platforms: web, desktop, iOS, Android, and mWeb through shared React Native settings UI.
    • Code paths not touched: agent create/update/delete API behavior, the report creation/opening implementation, and the delegate auth-token switching implementation.
    • API/backend behavior changes: none expected.

    What alternative solutions did you explore? (Optional)

    • Duplicating the chat/copilot code independently in AgentsListRow and EditAgentPage. This would work, but it would duplicate a lot of sensitive copilot switching guard logic; a shared Agents helper keeps both surfaces consistent.
    • Navigating users to the existing Copilot settings page instead of switching directly. Rejected because the issue asks for a button that copilots into the agent account, and connect is already the direct action used by account switching.
    • Opening chat by manually searching reports or constructing a report route. Rejected because navigateToAndOpenReport already handles existing chats, optimistic new chats, stale cached DMs, and server revalidation.
  7. changed the title [-]Add buttons to chat and copilot with agents[/-] [+][$250] Add buttons to chat and copilot with agents[/+] on May 21, 2026
  8. melvin-bot commented on May 21, 2026

    @melvin-bot
  9. yusufdeveloper2903 commented on May 21, 2026

    @yusufdeveloper2903
    Contributor

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  10. github-actions commented on May 21, 2026

    @github-actions
    Contributor

    ⚠️ @yusufdeveloper2903 Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  11. 28 remaining items

  12. ShridharGoel commented on Jun 5, 2026

    @ShridharGoel
    Contributor

    BugZero Checklist:

    • [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      N/A, new feature

      Link to the comment on the PR:
      Link to the comment on the Issue:

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion: N/A

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue: https://github.com/Expensify/Expensify/issues/646557

    Regression Test Proposal

    Precondition:

    • Have agents beta enabled for your account.

    Test:

    1. Navigate to Settings > Account > Agents (ensure you have at least one agent set up)
    2. Wide layout (desktop): Verify you see Chat (chat bubble icon) and Copilot buttons next to the Edit button on each agent row
    3. Tap the Chat button → verify it opens a DM chat with that agent
    4. Navigate back to the Agents list, tap the Copilot button → verify it switches you into the agent's account (copilot mode)
    5. Tap on an agent row to open the Edit Agent page
    6. Verify you see "Chat with agent" and "Copilot into account" menu items above the Delete agent option
    7. Tap "Chat with agent" → verify it opens a DM chat with the agent
    8. Navigate back, tap "Copilot into account" → verify it switches you into the agent's account

    Do we agree 👍 or 👎

    Zapier Logs Run ID: 00040eee-6be6-ad7d-0421-34f8e0e9b5a4
  13. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    and removed on Jun 7, 2026
  14. melvin-bot commented on Jun 7, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  15. melvin-bot commented on Jun 7, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/2057563860350797742/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  16. mallenexpensify commented on Jun 8, 2026

    @mallenexpensify
    Contributor

    Deploy Blocker #92158 was identified to be related to the PR #91533 that attempted to fix this issue.

    @ShridharGoel from the C+ doc

    If there are posts on the PR or issue that reference a regression or deploy blocker, C+ posts on the issue and confirms regression (which will reduce pay by 50%) or provides reasoning why they shouldn’t be considered. If the C+ doesn’t update the issue, the contributor manager making the payment will assume any mention of a regression or deploy blockers reduces the issue amount.

    ^ Test case created. Thx

  17. ShridharGoel commented on Jun 8, 2026

    @ShridharGoel
    Contributor

    @mallenexpensify That was a pre-existing bug, unrelated to the changes of this feature.

    Same can be seen in MelvinBot's root cause summary #92158 (comment):

    Important: PR #91537 only added the profile button — it did not modify the AccountSwitcher, the delegate connect/disconnect logic, or CurrentUserPersonalDetailsProvider. This is a pre-existing reactivity bug that the new entry point exposes, not a defect in the PR's own code.

  18. mallenexpensify commented on Jun 8, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @ShridharGoel due $250 via NewDot

  19. garrettmknight commented on Jun 10, 2026

    @garrettmknight
    Contributor

    $250 approved for @ShridharGoel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionDailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions