Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): send AI-composed email from the right inbox (#8010)

Peter Chinman160318d20295
diff --git a/apps/docs/AI/mcp/tools/get-thread.mdx b/apps/docs/AI/mcp/tools/get-thread.mdx
index 754d619313..d01b309760 100644
--- a/apps/docs/AI/mcp/tools/get-thread.mdx
+++ b/apps/docs/AI/mcp/tools/get-thread.mdx
@@ -6,7 +6,7 @@ description: >-
# GetThread
-Retrieve an email thread and its messages. Returns the thread metadata, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation or to see which labels a thread or message has.
+Retrieve an email thread and its messages. Returns the thread metadata, the inbox the thread belongs to, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation, to see which labels a thread or message has, or to find out which of the user's inboxes received it before replying.
## Parameters
diff --git a/apps/docs/AI/mcp/tools/send-confirmed-email.mdx b/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
index 0a0d5ff1e0..c2c6db4e77 100644
--- a/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
+++ b/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
@@ -13,6 +13,7 @@ Send an email immediately, with no review card or composer. Only for a prompt th
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `subject` | string | Yes | The subject line of the email. |
+| `from` | string | No | The address of the inbox to send from, when the user has more than one connected and this email belongs to a particular one. Use the exact `emailAddress` of a connected inbox — `ListInboxes` lists them, and `GetThread` reports the `inbox` a thread belongs to. Omit it unless you know which inbox is right: a reply then goes out from the inbox that received the message it answers, and a new email from the user's primary inbox. The user can change it in the composer either way. |
| `body` | string | Yes | The body of the email, written as Markdown. A host with a composer (chat) replaces this with the base64url-encoded HTML the composer exported before the tool runs; a host without one (an agent session) leaves the Markdown, and this tool renders it the same way. |
| `to` | EmailRecipient[] | Yes | The primary recipients (To field). |
| `cc` | EmailRecipient[] | No | Carbon copy recipients (optional). |
diff --git a/apps/docs/AI/mcp/tools/send-email.mdx b/apps/docs/AI/mcp/tools/send-email.mdx
index c50de64ac0..b877c51ff2 100644
--- a/apps/docs/AI/mcp/tools/send-email.mdx
+++ b/apps/docs/AI/mcp/tools/send-email.mdx
@@ -7,13 +7,14 @@ description: >-
# SendEmail
-Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
+Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id; the reply then goes out from the inbox that received it unless `from` says otherwise. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
## Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `subject` | string | Yes | The subject line of the email. |
+| `from` | string | No | The address of the inbox to send from, when the user has more than one connected and this email belongs to a particular one. Use the exact `emailAddress` of a connected inbox — `ListInboxes` lists them, and `GetThread` reports the `inbox` a thread belongs to. Omit it unless you know which inbox is right: a reply then goes out from the inbox that received the message it answers, and a new email from the user's primary inbox. The user can change it in the composer either way. |
| `body` | string | Yes | The body of the email, written as Markdown. A host with a composer (chat) replaces this with the base64url-encoded HTML the composer exported before the tool runs; a host without one (an agent session) leaves the Markdown, and this tool renders it the same way. |
| `to` | EmailRecipient[] | Yes | The primary recipients (To field). |
| `cc` | EmailRecipient[] | No | Carbon copy recipients (optional). |
diff --git a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
index 69f74cb234..be5fa4b043 100644
--- a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
@@ -199,7 +199,7 @@ function htmlText(html: string): string {
);
}
-/** The email as drafted, read-only: recipients, subject, body. */
+/** The email as drafted, read-only: sender, recipients, subject, body. */
export function EmailDraft(props: { email: SendEmail; inFlight: boolean }) {
const body = createMemo(() => emailBody(props.email.body));
const recipients = () =>
@@ -211,6 +211,16 @@ export function EmailDraft(props: { email: SendEmail; inFlight: boolean }) {
return (
<div class="flex flex-col gap-2">
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
+ {/* Only once the draft names a sender: a transcript should not
+ claim an inbox the send would have derived for itself. */}
+ <Show when={props.email.from?.trim()}>
+ {(from) => (
+ <>
+ <dt class="text-ink-muted">From</dt>
+ <dd class="text-ink wrap-break-word">{from()}</dd>
+ </>
+ )}
+ </Show>
<For each={recipients()}>
{([field, list]) => (
<Show when={list.length > 0}>
diff --git a/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx b/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
index d46adfb0d9..2523503c50 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
@@ -144,6 +144,13 @@ export function SentEmailResponse(props: {
Email sent to{' '}
<span class="text-ink">{getRecipientsLabel(props.args)}</span>
</span>
+ <Show when={props.args.from?.trim()}>
+ {(from) => (
+ <span>
+ from <span class="text-ink">{from()}</span>
+ </span>
+ )}
+ </Show>
<Show when={getAttachmentsLabel(props.args)}>
{(label) => <span>with {label()}</span>}
</Show>
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx
index f2899dbcbe..1a5e7a7c97 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx
@@ -35,6 +35,7 @@ type SendEmailSnapshot = {
body: string;
bcc: Array<{ email: string; name: string | null }>;
cc: Array<{ email: string; name: string | null }>;
+ from: string | null;
includeSignature: boolean | null;
replyingToId: string | null;
subject: string;
@@ -58,6 +59,7 @@ function createSendEmailSnapshot(data: SendEmail): SendEmailSnapshot {
})),
subject: data.subject ?? '',
replyingToId: data.replyingToId ?? null,
+ from: data.from ?? null,
includeSignature: data.includeSignature ?? null,
attachments: (data.attachments ?? []).map((item) => item.documentId),
};
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsx
new file mode 100644
index 0000000000..fff93147d6
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsx
@@ -0,0 +1,388 @@
+import { useCompose } from '@app/features/email-compose/context/compose-context';
+import type { SendEmail } from '@service-cognition/generated/tools/types';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { createEditor } from 'lexical';
+import { type Accessor, createSignal, type JSX, onMount } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ reply: (): {
+ isPending: boolean;
+ isFetching: boolean;
+ isError: boolean;
+ data: string | undefined;
+ } => ({ isPending: true, isFetching: true, isError: false, data: undefined }),
+ links: (): {
+ id: string;
+ email_address: string;
+ settings: { signature_on_replies_forwards: boolean };
+ }[] => [],
+ linksPending: false,
+ retry: vi.fn(),
+ execute: vi.fn(),
+ edit: vi.fn(),
+}));
+
+vi.mock('@queries/email/link', () => ({
+ useEmailLinksQuery: () => ({
+ get isPending() {
+ return mocks.linksPending;
+ },
+ isError: false,
+ get data() {
+ return { links: mocks.links() };
+ },
+ }),
+ findPrimaryEmailLinkId: () => 'primary',
+ useMessageInboxQuery: () => ({
+ get isPending() {
+ return mocks.reply().isPending;
+ },
+ get isFetching() {
+ return mocks.reply().isFetching;
+ },
+ get isError() {
+ return mocks.reply().isError;
+ },
+ get data() {
+ return mocks.reply().data;
+ },
+ refetch: mocks.retry,
+ }),
+ useEmailSignature: (id: Accessor<string | undefined>) => () =>
+ id() ? `Signature for ${id()}` : undefined,
+}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'macro|self' }));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: true }),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));
+vi.mock('@core/util/interceptMailtoLinks', () => ({
+ interceptMailtoLinks: vi.fn(),
+}));
+vi.mock('@core/util/upload', () => ({
+ forceDssRuleset: {},
+ uploadFile: vi.fn(),
+}));
+vi.mock('@queries/storage/document-metadata', () => ({
+ fetchDocumentMetadata: vi.fn(),
+}));
+vi.mock('@tanstack/solid-query', () => ({ useQueryClient: () => ({}) }));
+vi.mock('@ui', () => ({
+ ComposerSurface: () => null,
+ cn: () => '',
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+vi.mock('@app/features/email-compose/editor-adapter', () => ({
+ createComposeBodyActions: () => ({}),
+}));
+vi.mock('@app/features/email-compose/components/signature-preview', () => ({
+ SignaturePreview: (props: { html: string }) => (
+ <span aria-label="Signature">{props.html}</span>
+ ),
+}));
+vi.mock('@app/features/email-compose/views/compose-toolbar', () => ({
+ EmailComposeToolbar: () => null,
+}));
+vi.mock('@app/features/email-compose/primitives/prepare-email-body', () => ({
+ prepareEmailBody: () => ({ bodyHtml: 'Reply body', bodyText: 'Reply body' }),
+}));
+vi.mock('@app/features/email-compose/views/compose-layout', () => ({
+ ComposeLayout: (props: { notice?: JSX.Element }) => {
+ const compose = useCompose();
+ onMount(() => compose.onEditorInitialized?.(createEditor()));
+ return (
+ <>
+ {props.notice}
+ <span aria-label="From">{compose.fromAddress?.()}</span>
+ {compose.signaturePreview?.()}
+ <button onClick={() => compose.onSelectInbox?.('secondary')}>
+ Choose secondary
+ </button>
+ <button onClick={() => compose.setSubject('Edited reply')}>
+ Edit subject
+ </button>
+ <button
+ disabled={compose.primaryActionDisabled()}
+ onClick={() => compose.onSend()}
+ >
+ Send
+ </button>
+ <button onClick={() => compose.onSend()}>Keyboard send</button>
+ </>
+ );
+ },
+}));
+
+import {
+ EmailDraftComposer,
+ type EmailDraftComposerProps,
+} from './DraftComposer';
+
+function showDraft(
+ from?: string,
+ replyingToId: string | null = 'received-in-secondary',
+ registerSubmitReader?: EmailDraftComposerProps['registerSubmitReader']
+) {
+ const draft: SendEmail = {
+ to: [{ email: '[email protected]' }],
+ subject: 'Reply',
+ body: 'Reply body',
+ replyingToId,
+ from,
+ };
+ render(() => (
+ <EmailDraftComposer
+ initialData={draft}
+ debugName="sending-inbox-test"
+ registerSubmitReader={registerSubmitReader}
+ sink={{
+ canAct: () => true,
+ lockedNotice: () => undefined,
+ onExecute: mocks.execute,
+ onEdit: mocks.edit,
+ onReject: async () => true,
+ }}
+ />
+ ));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.reply = () => ({
+ isPending: true,
+ isFetching: true,
+ isError: false,
+ data: undefined,
+ });
+ mocks.linksPending = false;
+ mocks.links = () => [
+ {
+ id: 'primary',
+ email_address: '[email protected]',
+ settings: { signature_on_replies_forwards: true },
+ },
+ {
+ id: 'secondary',
+ email_address: '[email protected]',
+ settings: { signature_on_replies_forwards: true },
+ },
+ ];
+ mocks.execute.mockResolvedValue(true);
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+it.each([undefined, ' '])(
+ 'waits for the reply sender without showing a guessed address or signature (from: %j)',
+ async (from) => {
+ showDraft(from);
+ expect(screen.getByLabelText('From').textContent).toBe('');
+ expect(screen.queryByLabelText('Signature')).toBeNull();
+ expect(screen.getByRole('status').textContent).toContain(
+ 'Resolving sender'
+ );
+ expect(screen.getByText('Send')).toHaveProperty('disabled', true);
+ await fireEvent.click(screen.getByText('Send'));
+ await fireEvent.click(screen.getByText('Keyboard send'));
+ expect(mocks.execute).not.toHaveBeenCalled();
+ }
+);
+
+it('does not persist the fallback sender when editing before the reply inbox resolves', async () => {
+ vi.useFakeTimers();
+ showDraft();
+ await fireEvent.click(screen.getByText('Edit subject'));
+ vi.runAllTimers();
+ expect(mocks.edit).toHaveBeenCalledWith(
+ expect.objectContaining({ subject: 'Edited reply', from: undefined })
+ );
+});
+
+it('leaves a resolved implicit reply sender to the backend', async () => {
+ mocks.reply = () => ({
+ isPending: false,
+ isFetching: false,
+ isError: false,
+ data: 'secondary',
+ });
+ showDraft();
+ expect(screen.getByLabelText('From').textContent).toBe(
+ );
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: undefined })
+ );
+});
+
+it('preserves an unavailable explicit sender on edits and blocks delivery until replaced', async () => {
+ vi.useFakeTimers();
+ showDraft('[email protected]');
+ expect(screen.getByRole('status').textContent).toContain(
+ '[email protected] is unavailable'
+ );
+ expect(screen.queryByLabelText('Signature')).toBeNull();
+ expect(screen.getByText('Send')).toHaveProperty('disabled', true);
+ await fireEvent.click(screen.getByText('Keyboard send'));
+ expect(mocks.execute).not.toHaveBeenCalled();
+ await fireEvent.click(screen.getByText('Edit subject'));
+ vi.runAllTimers();
+ expect(mocks.edit).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+ await fireEvent.click(screen.getByText('Choose secondary'));
+ expect(screen.queryByRole('status')).toBeNull();
+ expect(screen.getByText('Send')).toHaveProperty('disabled', false);
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+});
+
+it('recovers from a failed reply lookup through Retry', async () => {
+ const [reply, setReply] = createSignal({
+ isPending: false,
+ isFetching: false,
+ isError: true,
+ data: undefined as string | undefined,
+ });
+ mocks.reply = reply;
+ mocks.retry.mockImplementation(() =>
+ setReply({
+ isPending: false,
+ isFetching: false,
+ isError: false,
+ data: 'secondary',
+ })
+ );
+ showDraft();
+ expect(screen.getByRole('status').textContent).toContain(
+ 'Could not resolve the reply sender'
+ );
+ expect(screen.getByText('Send')).toHaveProperty('disabled', true);
+ expect(screen.queryByLabelText('Signature')).toBeNull();
+ await fireEvent.click(screen.getByText('Retry'));
+ expect(mocks.retry).toHaveBeenCalledOnce();
+ expect(screen.queryByRole('status')).toBeNull();
+ expect(screen.getByLabelText('From').textContent).toBe(
+ );
+ expect(screen.getByLabelText('Signature').textContent).toBe(
+ 'Signature for secondary'
+ );
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: undefined })
+ );
+});
+
+it('keeps a manual choice when a late reply lookup resolves to another inbox', async () => {
+ const [reply, setReply] = createSignal(mocks.reply());
+ mocks.reply = reply;
+ showDraft();
+ await fireEvent.click(screen.getByText('Choose secondary'));
+ setReply({
+ isPending: false,
+ isFetching: false,
+ isError: false,
+ data: 'primary',
+ });
+ expect(screen.getByLabelText('From').textContent).toBe(
+ );
+ expect(screen.getByLabelText('Signature').textContent).toBe(
+ 'Signature for secondary'
+ );
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+});
+
+it('preserves a selected sender after its inbox is disconnected', async () => {
+ vi.useFakeTimers();
+ const [links, setLinks] = createSignal(mocks.links());
+ mocks.links = links;
+ showDraft();
+ await fireEvent.click(screen.getByText('Choose secondary'));
+ setLinks(links().filter((link) => link.id === 'primary'));
+ expect(screen.getByRole('status').textContent).toContain(
+ '[email protected] is unavailable'
+ );
+ expect(screen.getByText('Send')).toHaveProperty('disabled', true);
+ await fireEvent.click(screen.getByText('Keyboard send'));
+ expect(mocks.execute).not.toHaveBeenCalled();
+ await fireEvent.click(screen.getByText('Edit subject'));
+ vi.runAllTimers();
+ expect(mocks.edit).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+});
+
+it('defaults a new email to the primary inbox', async () => {
+ showDraft(undefined, null);
+ expect(screen.getByLabelText('From').textContent).toBe('[email protected]');
+ expect(screen.getByText('Send')).toHaveProperty('disabled', false);
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: undefined })
+ );
+});
+
+it.each([undefined, '[email protected]'])(
+ 'blocks batch submission until a sender is resolved (from: %j)',
+ async (from) => {
+ const register =
+ vi.fn<NonNullable<EmailDraftComposerProps['registerSubmitReader']>>();
+ showDraft(from, 'received-in-secondary', register);
+ const read = register.mock.calls[0][0];
+ expect(await read()).toBeUndefined();
+ await fireEvent.click(screen.getByText('Choose secondary'));
+ expect(await read()).toEqual(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+ }
+);
+
+it('does not discard an explicit address while the inbox list is loading', async () => {
+ vi.useFakeTimers();
+ mocks.linksPending = true;
+ showDraft('[email protected]');
+ expect(screen.getByText('Send')).toHaveProperty('disabled', true);
+ expect(screen.queryByLabelText('Signature')).toBeNull();
+ await fireEvent.click(screen.getByText('Edit subject'));
+ vi.runAllTimers();
+ expect(mocks.edit).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+});
+
+it('preserves the sender named in the draft', async () => {
+ showDraft('[email protected]');
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+});
+
+it.each([undefined, '[email protected]'])(
+ 'sends from the user-selected inbox before the reply inbox resolves (draft sender: %j)',
+ async (from) => {
+ showDraft(from);
+ await fireEvent.click(screen.getByText('Choose secondary'));
+ expect(screen.getByLabelText('From').textContent).toBe(
+ );
+ await fireEvent.click(screen.getByText('Send'));
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({ from: '[email protected]' })
+ );
+ }
+);
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
index ad0a3c5eaa..7debc4441d 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
@@ -12,6 +12,7 @@ import { SignaturePreview } from '@app/features/email-compose/components/signatu
import { ComposeProvider } from '@app/features/email-compose/context/compose-context';
import { decodeBase64Utf8 } from '@app/features/email-compose/core/decode-base64';
import type { EmailRecipient } from '@app/features/email-compose/core/email-recipient';
+import { fromInboxOptions } from '@app/features/email-compose/core/email-sender';
import { convertContactInfoToEmailRecipient } from '@app/features/email-compose/core/recipient-conversion';
import { createComposeBodyActions } from '@app/features/email-compose/editor-adapter';
import type {
@@ -25,18 +26,25 @@ import { EmailComposeToolbar } from '@app/features/email-compose/views/compose-t
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { toast } from '@core/component/Toast/Toast';
import { enableEmailSignatures } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
import { isMobile } from '@core/mobile/isMobile';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
import { forceDssRuleset, uploadFile } from '@core/util/upload';
-import { useEmailLinksQuery, useEmailSignature } from '@queries/email/link';
+import {
+ findPrimaryEmailLinkId,
+ useEmailLinksQuery,
+ useEmailSignature,
+ useMessageInboxQuery,
+} from '@queries/email/link';
+import { queryReadyGate } from '@queries/gate';
import { fetchDocumentMetadata } from '@queries/storage/document-metadata';
import { entityKeys } from '@queries/storage/keys';
import type { SendEmail } from '@service-cognition/generated/tools/types';
import { FileTypeMap } from '@service-storage/fileTypeMap';
import { debounce } from '@solid-primitives/scheduled';
import { useQueryClient } from '@tanstack/solid-query';
-import { ComposerSurface, cn } from '@ui';
+import { Button, ComposerSurface, cn } from '@ui';
import type { LexicalEditor } from 'lexical';
import {
type ComponentProps,
@@ -52,6 +60,7 @@ import {
type DocumentDescription,
documentAttachmentFileName,
} from './draft-attachments';
+import { resolveSendingInbox } from './sending-inbox';
export type EmailDraftComposerProps = {
/** The draft as the agent wrote it, or as the user last saved it. */
@@ -115,14 +124,62 @@ async function uploadAttachmentDocument(
export function EmailDraftComposer(props: EmailDraftComposerProps) {
const uiDisabled = () => !props.sink.canAct() || props.readOnly === true;
+ const userId = useUserId();
const emailLinksQuery = useEmailLinksQuery();
- // The inbox this card sends from — always the first linked inbox (shown as
- // "from"); the backend resolves the same default at send time.
+ const inboxes = createMemo(() =>
+ queryReadyGate(emailLinksQuery) ? (emailLinksQuery.data.links ?? []) : []
+ );
+ // Keep the selected address even if its inbox is later disconnected, so
+ // edits cannot silently replace an explicit sender.
+ const [chosenInbox, setChosenInbox] = createSignal<{
+ id: string;
+ address: string;
+ }>();
+ const explicitFrom = () =>
+ chosenInbox()?.address || props.initialData.from?.trim() || undefined;
+ const replyInboxQuery = useMessageInboxQuery(() =>
+ explicitFrom() ? undefined : (props.initialData.replyingToId ?? undefined)
+ );
const sendingLink = createMemo(() => {
- if (!emailLinksQuery.isSuccess && !emailLinksQuery.isError) return;
- return emailLinksQuery.data?.links?.[0];
+ const list = inboxes();
+ return resolveSendingInbox(list, {
+ chosenInboxId: chosenInbox()?.id,
+ draftFrom: props.initialData.from,
+ isReply: Boolean(props.initialData.replyingToId),
+ replyTargetInboxId: queryReadyGate(replyInboxQuery)
+ ? (replyInboxQuery.data ?? undefined)
+ : undefined,
+ primaryInboxId:
+ findPrimaryEmailLinkId(list, userId()) ??
+ list.find((link) => link.macro_id === userId())?.id,
+ });
});
- const fromAddress = () => sendingLink()?.email_address;
+ const fromAddress = () => explicitFrom() ?? sendingLink()?.email_address;
+ const senderNotice = () => {
+ if (sendingLink()) return undefined;
+ if (emailLinksQuery.isPending) return 'Resolving sender...';
+ if (!queryReadyGate(emailLinksQuery)) {
+ return 'Could not load your inboxes. Try again.';
+ }
+ if (explicitFrom()) {
+ return `${explicitFrom()} is unavailable. Choose a connected sending inbox.`;
+ }
+ if (props.initialData.replyingToId) {
+ if (replyInboxQuery.isPending || replyInboxQuery.isFetching) {
+ return 'Resolving sender...';
+ }
+ return 'Could not resolve the reply sender. Try again or choose a sending inbox.';
+ }
+ return 'Connect an inbox to send email.';
+ };
+ const canRetrySender = () =>
+ !sendingLink() &&
+ (emailLinksQuery.isError || (!explicitFrom() && replyInboxQuery.isError));
+ const retrySender = async () => {
+ if (emailLinksQuery.isError) await emailLinksQuery.refetch();
+ if (!explicitFrom() && replyInboxQuery.isError)
+ await replyInboxQuery.refetch();
+ };
const signature = useEmailSignature(() => sendingLink()?.id);
const emailSignaturesFlag = useFeatureFlag(enableEmailSignatures);
// Whether this email includes the signature. Defaults on; the preview's ✕
@@ -208,6 +265,8 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
? (prepareEmailBody(editor())?.bodyHtml ?? props.initialData.body)
: props.initialData.body,
replyingToId: props.initialData.replyingToId,
+ // Preserve explicit choices; the backend resolves implicit senders.
+ from: explicitFrom(),
// Omit to use the backend default policy; false only when dismissed.
includeSignature: includeSignature() ? undefined : false,
attachments: attachments.toToolArgs(),
@@ -221,6 +280,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
if (
!bodyInitialized() ||
!(await attachments.waitForUploads()) ||
+ !sendingLink() ||
!validate()
)
return;
@@ -262,7 +322,13 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
});
async function handleSend() {
- if (finalized || uiDisabled() || isSending() || attachments.uploading())
+ if (
+ finalized ||
+ uiDisabled() ||
+ isSending() ||
+ attachments.uploading() ||
+ !sendingLink()
+ )
return;
if (!validate()) return;
debouncedEdit.clear();
@@ -332,7 +398,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
disabled: () => isSending() || uiDisabled(),
// Send waits for files the user just added to finish becoming documents.
primaryActionDisabled: () =>
- isSending() || uiDisabled() || attachments.uploading(),
+ isSending() || uiDisabled() || attachments.uploading() || !sendingLink(),
isSending,
isSavingDraft: () => false,
hasDraft: () => false,
@@ -348,6 +414,15 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
],
validationError: (type) => validationErrors().find((e) => e.type === type),
fromAddress,
+ fromInboxes: () => fromInboxOptions(inboxes()),
+ selectedInboxId: () => sendingLink()?.id,
+ onSelectInbox: (inboxId) => {
+ if (uiDisabled() || isSending()) return;
+ const inbox = inboxes().find((link) => link.id === inboxId);
+ if (!inbox) return;
+ setChosenInbox({ id: inbox.id, address: inbox.email_address });
+ scheduleUpdate();
+ },
recipients,
// Read-only preview of the signature the backend appends on send, with a ✕
// to drop it for this one email (persisted through the sink's edit).
@@ -390,6 +465,28 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
'[&_button:disabled]:opacity-50 [&_button:disabled]:text-ink-disabled [&_input:disabled]:text-ink-muted'
)}
header={header()}
+ notice={
+ <Show when={!props.readOnly && senderNotice()}>
+ {(notice) => (
+ <div
+ role="status"
+ class="flex flex-wrap items-center gap-2 text-sm text-ink-muted"
+ >
+ <span>{notice()}</span>
+ <Show when={canRetrySender()}>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={uiDisabled()}
+ onClick={retrySender}
+ >
+ Retry
+ </Button>
+ </Show>
+ </div>
+ )}
+ </Show>
+ }
toolbar={
props.readOnly === true ? undefined : (
<EmailComposeToolbar editor={editor} inline />
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/sending-inbox.test.ts b/apps/web/src/lib/core/component/AI/component/tool/email/sending-inbox.test.ts
new file mode 100644
index 0000000000..6033ccd0d2
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/sending-inbox.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from 'vitest';
+import { resolveSendingInbox } from './sending-inbox';
+
+const primary = { id: 'primary', email_address: '[email protected]' };
+const alt = { id: 'alt', email_address: '[email protected]' };
+const inboxes = [primary, alt];
+
+describe('resolveSendingInbox', () => {
+ it('sends a new email from the primary inbox', () => {
+ expect(resolveSendingInbox(inboxes, { primaryInboxId: 'primary' })).toBe(
+ primary
+ );
+ });
+
+ it('sends a reply from the inbox that received it', () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ replyTargetInboxId: 'alt',
+ primaryInboxId: 'primary',
+ })
+ ).toBe(alt);
+ });
+
+ it('honours the sender the draft names over the reply target', () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ draftFrom: '[email protected]',
+ replyTargetInboxId: 'alt',
+ primaryInboxId: 'primary',
+ })
+ ).toBe(primary);
+ });
+
+ it('matches a named sender whatever its case', () => {
+ expect(
+ resolveSendingInbox(inboxes, { draftFrom: ' [email protected] ' })
+ ).toBe(alt);
+ });
+
+ it('treats a blank sender as no choice at all', () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ draftFrom: ' ',
+ replyTargetInboxId: 'alt',
+ })
+ ).toBe(alt);
+ });
+
+ it("lets the user's own pick win over everything the draft says", () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ chosenInboxId: 'alt',
+ draftFrom: '[email protected]',
+ replyTargetInboxId: 'primary',
+ primaryInboxId: 'primary',
+ })
+ ).toBe(alt);
+ });
+
+ it('does not replace a user-selected inbox that is no longer connected', () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ chosenInboxId: 'gone',
+ draftFrom: '[email protected]',
+ replyTargetInboxId: 'gone',
+ primaryInboxId: 'primary',
+ })
+ ).toBeUndefined();
+ });
+
+ it('does not replace an unavailable sender named by the draft', () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ draftFrom: '[email protected]',
+ replyTargetInboxId: 'alt',
+ primaryInboxId: 'primary',
+ })
+ ).toBeUndefined();
+ });
+
+ it('waits for the receiving inbox instead of defaulting a reply', () => {
+ expect(
+ resolveSendingInbox(inboxes, {
+ isReply: true,
+ primaryInboxId: 'primary',
+ })
+ ).toBeUndefined();
+ expect(
+ resolveSendingInbox(inboxes, {
+ isReply: true,
+ replyTargetInboxId: 'gone',
+ primaryInboxId: 'primary',
+ })
+ ).toBeUndefined();
+ });
+
+ it('falls back to any connected inbox when none is the primary', () => {
+ // Only delegated inboxes: none of them is the viewer's own primary.
+ expect(resolveSendingInbox([alt], {})).toBe(alt);
+ });
+
+ it('resolves to nothing when no inbox is connected', () => {
+ expect(
+ resolveSendingInbox([], { primaryInboxId: 'primary' })
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/sending-inbox.ts b/apps/web/src/lib/core/component/AI/component/tool/email/sending-inbox.ts
new file mode 100644
index 0000000000..b2b14280ed
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/sending-inbox.ts
@@ -0,0 +1,55 @@
+/**
+ * Which inbox an AI-drafted email goes out from.
+ *
+ * The agent writes recipients and prose; the inbox has to be worked out. The
+ * card cannot guess, because the sender is what the recipient sees and
+ * replies to — so the From row it shows has to be the inbox the send will
+ * really use. Unavailable explicit choices and unresolved replies never fall
+ * back to another inbox.
+ */
+
+export type SelectableInbox = {
+ id: string;
+ email_address: string;
+};
+
+export type SendingInboxChoice = {
+ /** The inbox the user picked in this card, if they picked one. */
+ chosenInboxId?: string;
+ /** The sender the draft names, as an address. */
+ draftFrom?: string | null;
+ /** The inbox holding the message this draft replies to. */
+ replyTargetInboxId?: string;
+ /** A reply cannot default to the primary inbox before its target resolves. */
+ isReply?: boolean;
+ /** The viewer's own primary inbox. */
+ primaryInboxId?: string;
+};
+
+/**
+ * The inbox to send from, in precedence order: the user's own pick, the
+ * sender the draft names, the inbox that received the message being replied
+ * to, then the viewer's default inbox for a new email. `undefined` means the
+ * sender is unresolved or unavailable and sending must wait for a choice.
+ */
+export function resolveSendingInbox<T extends SelectableInbox>(
+ inboxes: readonly T[],
+ choice: SendingInboxChoice
+): T | undefined {
+ const byId = (id: string | undefined) =>
+ id === undefined ? undefined : inboxes.find((inbox) => inbox.id === id);
+ // Addresses compare case-insensitively, the way mail domains treat them,
+ // and a blank `from` is no choice at all rather than an inbox called
+ // nothing.
+ const named = choice.draftFrom?.trim().toLowerCase();
+ const byAddress = named
+ ? inboxes.find((inbox) => inbox.email_address.toLowerCase() === named)
+ : undefined;
+
+ if (choice.chosenInboxId !== undefined) return byId(choice.chosenInboxId);
+ if (named) return byAddress;
+ if (choice.isReply || choice.replyTargetInboxId !== undefined) {
+ return byId(choice.replyTargetInboxId);
+ }
+ return byId(choice.primaryInboxId) ?? inboxes[0];
+}
diff --git a/apps/web/src/lib/queries/email/keys.ts b/apps/web/src/lib/queries/email/keys.ts
index 8b74608d08..6ad4d15c19 100644
--- a/apps/web/src/lib/queries/email/keys.ts
+++ b/apps/web/src/lib/queries/email/keys.ts
@@ -17,6 +17,9 @@ export const emailKeys = createQueryKeys('email', {
threadMessages: (threadId: string) => ({
queryKey: ['messages', threadId],
}),
+ messageInbox: (messageId: string | undefined) => ({
+ queryKey: ['message-inbox', messageId],
+ }),
composeDraftState: (params: {
draftId: string;
threadId: string;
diff --git a/apps/web/src/lib/queries/email/link.ts b/apps/web/src/lib/queries/email/link.ts
index fae8c5a1bd..087c84af3a 100644
--- a/apps/web/src/lib/queries/email/link.ts
+++ b/apps/web/src/lib/queries/email/link.ts
@@ -85,6 +85,34 @@ export function usePrimaryEmailLinkId() {
});
}
+async function fetchMessageLinkId(messageId: string) {
+ const message = await throwOnErr(() =>
+ emailClient.getMessage({ message_id: messageId })
+ );
+ return message.link_id;
+}
+
+function messageInboxQueryOptions(messageId: string | undefined) {
+ return {
+ queryKey: emailKeys.messageInbox(messageId).queryKey,
+ queryFn: () => (messageId ? fetchMessageLinkId(messageId) : null),
+ enabled: messageId !== undefined,
+ staleTime: LINK_STALE_TIME,
+ retry: false,
+ };
+}
+
+/**
+ * The inbox a message belongs to. For a surface that holds a message id but
+ * not the account that received it — an AI-drafted reply, whose tool
+ * arguments name the message it answers — this is how it can show the sender
+ * the reply will actually go out as. Exposes loading, failure and retry so
+ * composers can require a known sender before sending.
+ */
+export function useMessageInboxQuery(messageId: Accessor<string | undefined>) {
+ return useQuery(() => messageInboxQueryOptions(messageId()));
+}
+
/** The `X-Email-Link-Id` value for a target inbox; see useNonPrimaryEmailLinkIdHeader. */
export function nonPrimaryEmailLinkIdHeader(
linkId: string | undefined | null,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 4f663b4be6..f03e5c4077 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -8889,6 +8889,7 @@ export const GetThread = z.object({
export const GetThreadResponse = z.object({
threadId: z.string().uuid(),
+ inbox: z.union([z.string(), z.null()]).optional(),
isRead: z.boolean(),
labels: z.array(z.string()),
messages: z.array(
@@ -14401,6 +14402,7 @@ export const SendChannelMessageResponse = z.object({
export const SendConfirmedEmail = z.object({
subject: z.string(),
+ from: z.union([z.string(), z.null()]).optional(),
body: z.string(),
to: z.array(
z.object({
@@ -14464,6 +14466,7 @@ export const SendEmailResponse = z.any().superRefine((x, ctx) => {
export const SendEmail = z.object({
subject: z.string(),
+ from: z.union([z.string(), z.null()]).optional(),
body: z.string(),
to: z.array(
z.object({
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 74fd6e5279..7fc1f335bc 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -10076,7 +10076,7 @@ export interface AvailabilityInterval {
end: string;
}
/**
- * Retrieve an email thread and its messages. Returns the thread metadata, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation or to see which labels a thread or message has.
+ * Retrieve an email thread and its messages. Returns the thread metadata, the inbox the thread belongs to, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation, to see which labels a thread or message has, or to find out which of the user's inboxes received it before replying.
*/
export interface GetThread {
/**
@@ -10096,6 +10096,13 @@ export interface GetThreadResponse {
* The thread's unique identifier.
*/
threadId: string;
+ /**
+ * The address of the inbox this thread belongs to — the account that
+ * received or sent it. Pass it as `SendEmail`'s `from` to answer the
+ * thread as the sender its participants expect. Absent only when the
+ * thread's inbox is no longer among the caller's.
+ */
+ inbox?: string | null;
/**
* Whether the thread has been read.
*/
@@ -13932,6 +13939,16 @@ export interface SendConfirmedEmail {
* The subject line of the email.
*/
subject: string;
+ /**
+ * The address of the inbox to send from, when the user has more than one
+ * connected and this email belongs to a particular one. Use the exact
+ * `emailAddress` of a connected inbox — `ListInboxes` lists them, and
+ * `GetThread` reports the `inbox` a thread belongs to. Omit it unless
+ * you know which inbox is right: a reply then goes out from the inbox
+ * that received the message it answers, and a new email from the user's
+ * primary inbox. The user can change it in the composer either way.
+ */
+ from?: string | null;
/**
* The body of the email, written as Markdown. A host with a composer
* (chat) replaces this with the base64url-encoded HTML the composer
@@ -13999,13 +14016,23 @@ export interface EmailAttachment {
documentId: string;
}
/**
- * Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
+ * Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id; the reply then goes out from the inbox that received it unless `from` says otherwise. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.
*/
export interface SendEmail {
/**
* The subject line of the email.
*/
subject: string;
+ /**
+ * The address of the inbox to send from, when the user has more than one
+ * connected and this email belongs to a particular one. Use the exact
+ * `emailAddress` of a connected inbox — `ListInboxes` lists them, and
+ * `GetThread` reports the `inbox` a thread belongs to. Omit it unless
+ * you know which inbox is right: a reply then goes out from the inbox
+ * that received the message it answers, and a new email from the user's
+ * primary inbox. The user can change it in the composer either way.
+ */
+ from?: string | null;
/**
* The body of the email, written as Markdown. A host with a composer
* (chat) replaces this with the base64url-encoded HTML the composer
diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.ts
index d319adf575..6d7dd80327 100644
--- a/apps/web/src/lib/service-clients/service-email/client.ts
+++ b/apps/web/src/lib/service-clients/service-email/client.ts
@@ -37,6 +37,7 @@ import type {
ListLabelsResponse,
ListLinksResponse,
MailboxSettingsOperation,
+ ParsedMessage,
PatchSettingsRequest,
PatchSettingsResponse,
ResolveMessageOperationRequest,
@@ -235,6 +236,13 @@ export const emailClient = {
)
).map((result) => result);
},
+ async getMessage(args: { message_id: string }) {
+ return (
+ await emailFetch<ParsedMessage>(`/email/messages/${args.message_id}`, {
+ method: 'GET',
+ })
+ ).map((result) => result);
+ },
async getUserLabels() {
return (
await emailFetch<ListLabelsResponse>(`/email/labels`, {
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 161f881714..e6bae96c3f 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -8,8 +8,9 @@ use email::domain::models::{
EmailSyncStatus, EmailThreadMailCacheFacts, EmailThreadMailPreviews, EmailThreadMailProjection,
EmailThreadMetadata, EnrichedEmailThreadPreview, GetEmailsRequest, LabelListVisibility,
LabelType, Link, LinkLabel, Message, MessageAttachment, MessageListVisibility, ParsedMessage,
- ParsedThread, SenderPolicy, Thread, UpdateThreadLabelsResult, UpsertEmailFilterInput,
- UserEmailLink, UserEmailLinkSettings, UserProvider,
+ ParsedThread, ResolvedSendingInbox, SenderPolicy, SendingInboxRequest, Thread,
+ UpdateThreadLabelsResult, UpsertEmailFilterInput, UserEmailLink, UserEmailLinkSettings,
+ UserProvider,
};
use entity_access::domain::models::{
AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,
@@ -503,10 +504,11 @@ impl EmailService for CountingEmailService {
Err(test_email_err())
}
- async fn get_link_by_macro_id(
+ async fn resolve_sending_inbox(
&self,
_macro_id: MacroUserIdStr<'_>,
- ) -> Result<Option<Link>, EmailErr> {
+ _request: SendingInboxRequest<'_>,
+ ) -> Result<ResolvedSendingInbox, EmailErr> {
Err(test_email_err())
}
diff --git a/crates/email/fixtures/email_sending_inbox.sql b/crates/email/fixtures/email_sending_inbox.sql
new file mode 100644
index 0000000000..35b1826223
--- /dev/null
+++ b/crates/email/fixtures/email_sending_inbox.sql
@@ -0,0 +1,30 @@
+-- Fixture for resolving which inbox a composed email is sent from.
+--
+-- One user with two of their own inboxes, each holding a received message, so
+-- a reply can be checked against the inbox that actually received it rather
+-- than the one that happens to come back first. `is_primary` is a generated
+-- column (macro_id = 'macro|' || lower(email_address)), so [email protected] is
+-- the primary inbox and [email protected] is not.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('a1111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '2 hours', NOW()),
+ ('a2222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL', true, NOW() - INTERVAL '1 hour', NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, name, sfs_photo_url, created_at, updated_at)
+VALUES
+ ('c1111111-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', '[email protected]', 'Alice Smith', NULL, NOW(), NOW()),
+ ('c2222222-0000-0000-0000-000000000002', 'a2222222-2222-2222-2222-222222222222', '[email protected]', 'Alice Smith', NULL, NOW(), NOW());
+
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('d1111111-0000-0000-0000-000000000001', 'provider-thread-primary', 'a1111111-1111-1111-1111-111111111111', true, false, NOW(), NOW()),
+ ('d2222222-0000-0000-0000-000000000002', 'provider-thread-alt', 'a2222222-2222-2222-2222-222222222222', true, false, NOW(), NOW());
+
+-- One received message in each inbox.
+INSERT INTO email_messages (id, provider_id, thread_id, provider_thread_id, link_id, from_contact_id, subject, is_read, is_sent, is_draft, has_attachments, internal_date_ts, created_at, updated_at)
+VALUES
+ ('e1111111-0000-0000-0000-000000000001', 'provider-msg-primary', 'd1111111-0000-0000-0000-000000000001', 'provider-thread-primary', 'a1111111-1111-1111-1111-111111111111',
+ 'c1111111-0000-0000-0000-000000000001', 'Hello primary', true, false, false, false, '2025-01-10 10:00:00+00', '2025-01-10 10:00:00+00', '2025-01-10 10:00:00+00'),
+ ('e2222222-0000-0000-0000-000000000002', 'provider-msg-alt', 'd2222222-0000-0000-0000-000000000002', 'provider-thread-alt', 'a2222222-2222-2222-2222-222222222222',
+ 'c2222222-0000-0000-0000-000000000002', 'Hello alt', true, false, false, false, '2025-01-11 10:00:00+00', '2025-01-11 10:00:00+00', '2025-01-11 10:00:00+00');
diff --git a/crates/email/src/domain/models/error.rs b/crates/email/src/domain/models/error.rs
index e4945a8f7d..c964aeb734 100644
--- a/crates/email/src/domain/models/error.rs
+++ b/crates/email/src/domain/models/error.rs
@@ -30,6 +30,19 @@ pub enum EmailErr {
/// accessible to the caller, or the caller has no primary inbox.
#[error("Email inbox not found")]
InboxNotFound,
+ /// The caller asked to send from an address that is none of the inboxes
+ /// they have connected or been delegated. The accessible addresses are
+ /// carried along so the caller can be told what it could have been.
+ #[error(
+ "No connected inbox matches \"{requested}\". Connected inboxes: {}.",
+ available.join(", ")
+ )]
+ UnknownSendingInbox {
+ /// The address the caller asked to send from.
+ requested: String,
+ /// The addresses of every inbox the caller can send from.
+ available: Vec<String>,
+ },
/// The referenced message has already been sent and cannot be modified.
#[error("Message with id {0} has already been sent")]
MessageAlreadySent(Uuid),
diff --git a/crates/email/src/domain/models/link.rs b/crates/email/src/domain/models/link.rs
index 419ccf836c..133891ea0d 100644
--- a/crates/email/src/domain/models/link.rs
+++ b/crates/email/src/domain/models/link.rs
@@ -204,3 +204,25 @@ pub struct Link {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
+
+/// What a composed email knows about where it should be sent from.
+///
+/// Both fields come from the caller and name an inbox by value, so neither is
+/// trusted: resolution only ever settles on an inbox the caller can reach.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SendingInboxRequest<'a> {
+ /// The inbox address the caller chose, when they chose one.
+ pub requested_address: Option<&'a str>,
+ /// The message this email replies to, when it is a reply.
+ pub replying_to_id: Option<Uuid>,
+}
+
+/// The inbox a composed email is sent from, with the set it came out of.
+#[derive(Clone)]
+pub struct ResolvedSendingInbox {
+ /// The sending inbox.
+ pub link: Link,
+ /// Every inbox the caller can reach. A reply target may live in any of
+ /// them, so a send has to be given the whole set rather than just `link`.
+ pub accessible_inboxes: Vec<Link>,
+}
diff --git a/crates/email/src/domain/models/mod.rs b/crates/email/src/domain/models/mod.rs
index 7fd7887c70..a3336b3610 100644
--- a/crates/email/src/domain/models/mod.rs
+++ b/crates/email/src/domain/models/mod.rs
@@ -36,8 +36,8 @@ pub use label::{
UpdateThreadLabelsResult,
};
pub use link::{
- EmailBackfillStatus, EmailInboxDetails, EmailSyncStatus, Link, UserEmailLink,
- UserEmailLinkSettings, UserProvider,
+ EmailBackfillStatus, EmailInboxDetails, EmailSyncStatus, Link, ResolvedSendingInbox,
+ SendingInboxRequest, UserEmailLink, UserEmailLinkSettings, UserProvider,
};
pub use mail_projection::{
EmailDraftAggregate, EmailDraftEntry, EmailPreview, EmailThreadDraftState,
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index 07d89c615f..e2fd60d01a 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -4,10 +4,10 @@ use crate::domain::models::{
EmailThreadMailProjection, EmailThreadMetadata, EmailThreadPreview, EnrichedEmailThreadPreview,
GetEmailsRequest, Label, Link, LinkLabel, Message, MessageAttachment, MessageLabel, MessageRow,
MessageTimestamps, ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery,
- RecipientType, ResolvedDraftInput, SavedUserDraft, SenderPolicy, SettledDraftIds,
- SimpleMessage, SimpleMessageInfo, SourcedAttachment, Thread, ThreadRow,
- UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts, UserEmailLink,
- UserProvider,
+ RecipientType, ResolvedDraftInput, ResolvedSendingInbox, SavedUserDraft, SenderPolicy,
+ SendingInboxRequest, SettledDraftIds, SimpleMessage, SimpleMessageInfo, SourcedAttachment,
+ Thread, ThreadRow, UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts,
+ UserEmailLink, UserProvider,
};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
@@ -183,11 +183,6 @@ pub trait EmailRepo: Send + Sync + 'static {
provider: UserProvider,
) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
- fn link_by_macro_id(
- &self,
- macro_id: MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
-
/// Resolve the inbox owning a thread, only when that inbox belongs to the
/// given fusionauth user.
fn owned_link_for_thread(
@@ -724,12 +719,6 @@ pub trait EmailService: Send + Sync + 'static {
macro_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
- /// Fetch the email link for a user by their macro ID only.
- fn get_link_by_macro_id(
- &self,
- macro_id: MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
-
/// Fetch every inbox the caller can read — their own email_links rows plus
/// any rows reachable via a `macro_user_links` edge (narrow-graph multi-inbox).
fn get_inboxes_for_macro_id(
@@ -737,6 +726,19 @@ pub trait EmailService: Send + Sync + 'static {
macro_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;
+ /// Resolve which inbox a composed email is sent from, for a transport
+ /// that carries the inbox by value instead of out of band: the address
+ /// the caller named, else the inbox that received the message being
+ /// replied to, else the caller's default inbox. Returns the whole
+ /// accessible set alongside it, which [`send_message`] needs anyway.
+ ///
+ /// [`send_message`]: EmailService::send_message
+ fn resolve_sending_inbox(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ request: SendingInboxRequest<'_>,
+ ) -> impl Future<Output = Result<ResolvedSendingInbox, EmailErr>> + Send;
+
/// Resolve the inbox owning a thread, scoped to the caller's own and
/// delegated inboxes. Lets thread-targeted mutations derive the inbox from
/// the thread instead of an `X-Email-Link-Id` header.
@@ -1230,17 +1232,18 @@ impl EmailService for NoOpEmailService {
Err(no_op_email_err())
}
- async fn get_link_by_macro_id(
+ async fn get_inboxes_for_macro_id(
&self,
_macro_id: MacroUserIdStr<'_>,
- ) -> Result<Option<Link>, EmailErr> {
+ ) -> Result<Vec<Link>, EmailErr> {
Err(no_op_email_err())
}
- async fn get_inboxes_for_macro_id(
+ async fn resolve_sending_inbox(
&self,
_macro_id: MacroUserIdStr<'_>,
- ) -> Result<Vec<Link>, EmailErr> {
+ _request: SendingInboxRequest<'_>,
+ ) -> Result<ResolvedSendingInbox, EmailErr> {
Err(no_op_email_err())
}
diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rs
index d43b9c2c79..de5d4d2944 100644
--- a/crates/email/src/domain/service.rs
+++ b/crates/email/src/domain/service.rs
@@ -4,6 +4,7 @@ mod followup;
mod previews;
mod send;
mod senders;
+mod sending_inbox;
pub(crate) mod signature;
mod thread;
mod thread_labels;
@@ -20,8 +21,8 @@ use crate::domain::{
models::{
CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EmailThreadMailProjection,
EmailThreadMetadata, EnrichedEmailThreadPreview, GetEmailsRequest, Link, LinkLabel,
- ParsedMessage, ParsedThread, SenderPolicy, Thread, UpdateThreadLabelsResult,
- UpsertEmailFilterInput,
+ ParsedMessage, ParsedThread, ResolvedSendingInbox, SenderPolicy, SendingInboxRequest,
+ Thread, UpdateThreadLabelsResult, UpsertEmailFilterInput,
},
ports::{
EmailContentService, EmailMessageEnqueuer, EmailRepo, EmailService,
@@ -253,24 +254,22 @@ where
.await
}
- async fn get_link_by_macro_id(
+ async fn get_inboxes_for_macro_id(
&self,
macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
- ) -> Result<Option<crate::domain::models::Link>, EmailErr> {
+ ) -> Result<Vec<crate::domain::models::Link>, EmailErr> {
self.email_repo
- .link_by_macro_id(macro_id)
+ .inboxes_for_macro_id(macro_id)
.await
.map_err(|e| EmailErr::RepoErr(e.into()))
}
- async fn get_inboxes_for_macro_id(
+ async fn resolve_sending_inbox(
&self,
macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
- ) -> Result<Vec<crate::domain::models::Link>, EmailErr> {
- self.email_repo
- .inboxes_for_macro_id(macro_id)
- .await
- .map_err(|e| EmailErr::RepoErr(e.into()))
+ request: SendingInboxRequest<'_>,
+ ) -> Result<ResolvedSendingInbox, EmailErr> {
+ self.resolve_sending_inbox_impl(macro_id, request).await
}
async fn get_owned_link_for_thread(
diff --git a/crates/email/src/domain/service/sending_inbox.rs b/crates/email/src/domain/service/sending_inbox.rs
new file mode 100644
index 0000000000..b87c5dffa6
--- /dev/null
+++ b/crates/email/src/domain/service/sending_inbox.rs
@@ -0,0 +1,127 @@
+//! Which inbox a composed email goes out from.
+//!
+//! A transport that carries the inbox out of band - the `X-Email-Link-Id`
+//! header, a GraphQL save's `link_id` - already knows. An AI-composed email
+//! does not: the model writes recipients and prose, and the inbox has to be
+//! derived. Getting it wrong is not cosmetic. The sender is what the
+//! recipient sees and replies to, and a reply can only join the provider
+//! thread of the account that received the original - so a reply sent from
+//! the wrong inbox both misrepresents the user and starts a new thread.
+
+use crate::domain::{
+ models::{EmailErr, Link, ResolvedSendingInbox, SendingInboxRequest},
+ ports::EmailRepo,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::EmailServiceImpl;
+
+#[cfg(test)]
+mod test;
+
+impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B>
+where
+ T: EmailRepo,
+ anyhow::Error: From<T::Err>,
+{
+ pub(crate) async fn resolve_sending_inbox_impl(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ request: SendingInboxRequest<'_>,
+ ) -> Result<ResolvedSendingInbox, EmailErr> {
+ let accessible_inboxes = self
+ .email_repo
+ .inboxes_for_macro_id(macro_id.clone())
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let chosen =
+ match requested_address(request.requested_address) {
+ // An explicit choice is honoured or refused, never quietly
+ // replaced: silently sending from a different address than the
+ // one the caller named is the bug this whole module exists for.
+ Some(address) => inbox_by_address(&accessible_inboxes, &macro_id, address)
+ .ok_or_else(|| EmailErr::UnknownSendingInbox {
+ requested: address.to_owned(),
+ available: accessible_inboxes
+ .iter()
+ .map(|inbox| inbox.email_address.0.as_ref().to_owned())
+ .collect(),
+ })?,
+ None => {
+ let from_reply_target = match request.replying_to_id {
+ Some(replying_to_id) => {
+ self.inbox_holding_message(&accessible_inboxes, replying_to_id)
+ .await?
+ }
+ None => None,
+ };
+ from_reply_target
+ .or_else(|| default_inbox(&accessible_inboxes, &macro_id))
+ .ok_or(EmailErr::InboxNotFound)?
+ }
+ };
+
+ Ok(ResolvedSendingInbox {
+ link: accessible_inboxes[chosen].clone(),
+ accessible_inboxes,
+ })
+ }
+
+ /// The accessible inbox `message_id` lives in. `None` when the caller
+ /// cannot reach the message at all, which is left to the send to report
+ /// against the inbox it ends up using rather than pre-empted here.
+ async fn inbox_holding_message(
+ &self,
+ accessible_inboxes: &[Link],
+ message_id: uuid::Uuid,
+ ) -> Result<Option<usize>, EmailErr> {
+ let accessible_link_ids: Vec<uuid::Uuid> =
+ accessible_inboxes.iter().map(|inbox| inbox.id).collect();
+ let Some(message) = self
+ .email_repo
+ .get_simple_message(message_id, &accessible_link_ids)
+ .await
+ .map_err(anyhow::Error::from)?
+ else {
+ return Ok(None);
+ };
+ Ok(accessible_inboxes
+ .iter()
+ .position(|inbox| inbox.id == message.link_id))
+ }
+}
+
+/// An address the caller actually supplied, as opposed to a present-but-blank
+/// field - models and form state both produce those.
+fn requested_address(requested: Option<&str>) -> Option<&str> {
+ requested
+ .map(str::trim)
+ .filter(|address| !address.is_empty())
+}
+
+/// The accessible inbox at `address`, matched the case-insensitive way mail
+/// domains treat addresses. An inbox the caller owns wins over one delegated
+/// to them, so an address reachable through two accounts resolves to the
+/// same one every time instead of by row order.
+fn inbox_by_address(inboxes: &[Link], caller: &MacroUserIdStr<'_>, address: &str) -> Option<usize> {
+ let at_address = |inbox: &&Link| inbox.email_address.0.as_ref().eq_ignore_ascii_case(address);
+ inboxes
+ .iter()
+ .position(|inbox| at_address(&inbox) && inbox.macro_id.as_ref() == caller.as_ref())
+ .or_else(|| inboxes.iter().position(|inbox| at_address(&inbox)))
+}
+
+/// Where a new email goes out from when nothing else picks an inbox: the
+/// caller's primary inbox, else any inbox they own, else any inbox they can
+/// reach. A delegated inbox is `is_primary` for *its* owner, so the macro-id
+/// guard is what keeps a teammate's mailbox from becoming the caller's
+/// default sender.
+fn default_inbox(inboxes: &[Link], caller: &MacroUserIdStr<'_>) -> Option<usize> {
+ let owned = |inbox: &Link| inbox.macro_id.as_ref() == caller.as_ref();
+ inboxes
+ .iter()
+ .position(|inbox| inbox.is_primary && owned(inbox))
+ .or_else(|| inboxes.iter().position(owned))
+ .or_else(|| (!inboxes.is_empty()).then_some(0))
+}
diff --git a/crates/email/src/domain/service/sending_inbox/test.rs b/crates/email/src/domain/service/sending_inbox/test.rs
new file mode 100644
index 0000000000..35a71b428a
--- /dev/null
+++ b/crates/email/src/domain/service/sending_inbox/test.rs
@@ -0,0 +1,106 @@
+use super::*;
+use crate::domain::models::UserProvider;
+use chrono::Utc;
+use macro_user_id::email::EmailStr;
+
+fn link(owner: &str, address: &str) -> Link {
+ Link {
+ id: uuid::Uuid::now_v7(),
+ macro_id: MacroUserIdStr::try_from_email(owner).unwrap(),
+ fusionauth_user_id: "fa-user".to_owned(),
+ email_address: EmailStr::try_from(address.to_owned()).unwrap(),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ // Generated in the database from macro_id and email_address; mirrored
+ // here so a fixture cannot claim a primary inbox it would not have.
+ is_primary: owner == address,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+}
+
+fn caller() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+#[test]
+fn a_blank_address_is_no_choice_at_all() {
+ // Both a model that emitted an empty string and form state that sent one
+ // mean "you pick", not "send from the inbox called nothing".
+ for blank in [Some(""), Some(" "), None] {
+ assert_eq!(requested_address(blank), None, "{blank:?}");
+ }
+ assert_eq!(
+ requested_address(Some(" [email protected] ")),
+ );
+}
+
+#[test]
+fn the_default_sender_is_the_callers_primary_inbox() {
+ let inboxes = vec![
+ ];
+
+ assert_eq!(default_inbox(&inboxes, &caller()), Some(1));
+}
+
+#[test]
+fn a_delegated_primary_inbox_is_never_the_callers_default() {
+ // A delegated inbox is primary for *its* owner. Without the macro-id
+ // guard a teammate's mailbox becomes the caller's default sender, which
+ // is how an agent ends up mailing from an address that is not the user's.
+ let inboxes = vec![
+ ];
+
+ assert_eq!(default_inbox(&inboxes, &caller()), Some(1));
+}
+
+#[test]
+fn a_caller_with_only_delegated_inboxes_still_gets_one() {
+ let inboxes = vec![link("[email protected]", "[email protected]")];
+
+ assert_eq!(default_inbox(&inboxes, &caller()), Some(0));
+}
+
+#[test]
+fn no_inbox_means_no_default() {
+ assert_eq!(default_inbox(&[], &caller()), None);
+}
+
+#[test]
+fn an_address_matches_whatever_its_case() {
+ let inboxes = vec![link("[email protected]", "[email protected]")];
+
+ assert_eq!(
+ inbox_by_address(&inboxes, &caller(), "[email protected]"),
+ Some(0)
+ );
+}
+
+#[test]
+fn an_address_reachable_through_two_accounts_resolves_to_the_callers_own() {
+ // Row order decides nothing: the delegated copy is listed first.
+ let inboxes = vec![
+ ];
+
+ assert_eq!(
+ inbox_by_address(&inboxes, &caller(), "[email protected]"),
+ Some(1)
+ );
+}
+
+#[test]
+fn an_unconnected_address_matches_nothing() {
+ let inboxes = vec![link("[email protected]", "[email protected]")];
+
+ assert_eq!(
+ inbox_by_address(&inboxes, &caller(), "[email protected]"),
+ None
+ );
+}
diff --git a/crates/email/src/inbound/toolset.rs b/crates/email/src/inbound/toolset.rs
index ae4b43201b..0230950674 100644
--- a/crates/email/src/inbound/toolset.rs
+++ b/crates/email/src/inbound/toolset.rs
@@ -12,7 +12,7 @@ mod update_thread_labels;
mod test;
use crate::domain::{
- models::Link,
+ models::{EmailErr, Link, ResolvedSendingInbox, SendingInboxRequest},
ports::{
EmailAttachmentSendService, EmailService, GmailTokenProvider, NoOpEmailAttachmentSender,
},
@@ -150,20 +150,28 @@ impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> EmailToolCo
self
}
- /// Resolve the user's email link from their macro ID.
+ /// Resolve the inbox a composed email goes out from, together with every
+ /// inbox the caller can reach.
///
- /// This is shared across all email tools that need an authenticated link.
- pub async fn resolve_link(&self, macro_id: MacroUserIdStr<'_>) -> Result<Link, ToolCallError> {
+ /// The choice is the domain's; this only turns its refusals into
+ /// something the model can act on - the error already names the
+ /// connected addresses, which is exactly the correction it needs.
+ pub async fn resolve_sending_inbox(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ request: SendingInboxRequest<'_>,
+ ) -> Result<ResolvedSendingInbox, ToolCallError> {
self.service
- .get_link_by_macro_id(macro_id)
+ .resolve_sending_inbox(macro_id, request)
.await
.map_err(|e| ToolCallError {
- description: format!("Failed to resolve email link: {e}"),
+ description: match e {
+ EmailErr::InboxNotFound => {
+ "No email account is linked for this user.".to_owned()
+ }
+ ref other => other.to_string(),
+ },
internal_error: e.into(),
- })?
- .ok_or_else(|| ToolCallError {
- description: "No email account linked for this user.".to_string(),
- internal_error: anyhow::anyhow!("No email link found for user"),
})
}
diff --git a/crates/email/src/inbound/toolset/get_thread.rs b/crates/email/src/inbound/toolset/get_thread.rs
index 9ceaffadd9..acc0199152 100644
--- a/crates/email/src/inbound/toolset/get_thread.rs
+++ b/crates/email/src/inbound/toolset/get_thread.rs
@@ -11,6 +11,7 @@ use entity_access::domain::{
models::{EntityType, ViewAccessLevel},
ports::EntityAccessService,
};
+use macro_user_id::user_id::MacroUserIdStr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -79,6 +80,11 @@ impl From<ParsedMessage> for ToolMessage {
pub struct GetThreadResponse {
/// The thread's unique identifier.
pub thread_id: Uuid,
+ /// The address of the inbox this thread belongs to — the account that
+ /// received or sent it. Pass it as `SendEmail`'s `from` to answer the
+ /// thread as the sender its participants expect. Absent only when the
+ /// thread's inbox is no longer among the caller's.
+ pub inbox: Option<String>,
/// Whether the thread has been read.
pub is_read: bool,
/// The labels applied to the thread — the distinct set of label names across
@@ -97,7 +103,7 @@ const DEFAULT_LIMIT: i64 = 10;
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(
title = "GetThread",
- description = "Retrieve an email thread and its messages. Returns the thread metadata, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation or to see which labels a thread or message has."
+ description = "Retrieve an email thread and its messages. Returns the thread metadata, the inbox the thread belongs to, the labels applied to the thread (e.g. INBOX, UNREAD, STARRED, and any custom labels), and message contents including sender, recipients, subject, body text, and the labels on each individual message. Use this to read the contents of a specific email conversation, to see which labels a thread or message has, or to find out which of the user's inboxes received it before replying."
)]
#[serde(rename_all = "camelCase")]
pub struct GetThread {
@@ -169,11 +175,24 @@ where
labels.sort();
labels.dedup();
+ let inbox = service_context
+ .service
+ .get_inboxes_for_macro_id(MacroUserIdStr((*request_context.user_id).clone()))
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to resolve the thread's inbox: {e}"),
+ internal_error: e.into(),
+ })?
+ .into_iter()
+ .find(|link| link.id == thread.row.link_id)
+ .map(|link| link.email_address.0.as_ref().to_owned());
+
let messages: Vec<ToolMessage> =
thread.messages.into_iter().map(ToolMessage::from).collect();
Ok(GetThreadResponse {
thread_id: thread.row.db_id,
+ inbox,
is_read: thread.row.is_read,
labels,
messages,
diff --git a/crates/email/src/inbound/toolset/send_email.rs b/crates/email/src/inbound/toolset/send_email.rs
index b703ccc893..a633811dc4 100644
--- a/crates/email/src/inbound/toolset/send_email.rs
+++ b/crates/email/src/inbound/toolset/send_email.rs
@@ -1,7 +1,7 @@
//! SendEmail tool for composing and sending an email in one step.
use crate::domain::{
- models::{ContactInfo, CreateDraftInput},
+ models::{ContactInfo, CreateDraftInput, SendingInboxRequest},
ports::{EmailService, GmailTokenProvider},
};
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
@@ -52,12 +52,21 @@ pub struct EmailAttachment {
#[derive(Debug, Deserialize, JsonSchema, Clone)]
#[schemars(
title = "SendEmail",
- description = "Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
+ description = "Draft, compose, and send an email the user confirms in a review card or composer. Use this tool whenever the user asks you to draft, write, compose, or send an email (or reply to one) from the agent session view or from chat — never write the email as plain text there. It opens the draft for the user to review, edit, and confirm before it is sent, so it is the correct tool even when the user only wants a draft. Do NOT use it for a prompt that came from a channel or document thread — the context block names a conversation parent when it did, and there is no surface to review a draft in: write the email out in your reply, ask whether to send it, and use SendConfirmedEmail once the user approves. To reply to an existing message, provide the replying_to_id; the reply then goes out from the inbox that received it unless `from` says otherwise. To attach files, list the Macro documents in attachments — uploaded files such as PDFs, images, spreadsheets, or Word documents the user can view; the user can add or remove attachments in the composer before sending. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body."
)]
#[serde(rename_all = "camelCase")]
pub struct SendEmail {
/// The subject line of the email.
pub subject: String,
+ /// The address of the inbox to send from, when the user has more than one
+ /// connected and this email belongs to a particular one. Use the exact
+ /// `emailAddress` of a connected inbox — `ListInboxes` lists them, and
+ /// `GetThread` reports the `inbox` a thread belongs to. Omit it unless
+ /// you know which inbox is right: a reply then goes out from the inbox
+ /// that received the message it answers, and a new email from the user's
+ /// primary inbox. The user can change it in the composer either way.
+ #[serde(default)]
+ pub from: Option<String>,
/// The body of the email, written as Markdown. A host with a composer
/// (chat) replaces this with the base64url-encoded HTML the composer
/// exported before the tool runs; a host without one (an agent session)
@@ -129,7 +138,15 @@ where
request_context: RequestContext,
) -> ToolResult<Self::Output> {
let acting_user = MacroUserIdStr((*request_context.user_id).clone());
- let link = service_context.resolve_link(acting_user.clone()).await?;
+ let sender = service_context
+ .resolve_sending_inbox(
+ acting_user.clone(),
+ SendingInboxRequest {
+ requested_address: self.from.as_deref(),
+ replying_to_id: self.replying_to_id,
+ },
+ )
+ .await?;
let body = service_context.render_body(&self.body).await?;
@@ -175,9 +192,17 @@ where
thread_client_binding: None,
};
+ // The whole accessible set, not just the sending inbox: a reply's
+ // target may live in another of the user's inboxes, and the send has
+ // to be able to find it to thread (or reference) the reply.
let sent = service_context
.attachment_sender
- .send_message_with_attachments(&link, std::slice::from_ref(&link), input, attachments)
+ .send_message_with_attachments(
+ &sender.link,
+ &sender.accessible_inboxes,
+ input,
+ attachments,
+ )
.await
.map_err(|e| ToolCallError {
description: format!("Failed to send email: {e}"),
diff --git a/crates/email/src/outbound/email_pg_repo.rs b/crates/email/src/outbound/email_pg_repo.rs
index f298bf57f3..d35c90cd6a 100644
--- a/crates/email/src/outbound/email_pg_repo.rs
+++ b/crates/email/src/outbound/email_pg_repo.rs
@@ -195,13 +195,6 @@ impl EmailRepo for EmailPgRepo {
.await
}
- async fn link_by_macro_id(
- &self,
- macro_id: MacroUserIdStr<'_>,
- ) -> Result<Option<Link>, Self::Err> {
- link::link_by_macro_id(&self.pool, macro_id).await
- }
-
async fn owned_link_for_thread(
&self,
thread_id: Uuid,
diff --git a/crates/email/src/outbound/email_pg_repo/link.rs b/crates/email/src/outbound/email_pg_repo/link.rs
index beffda501b..b893450d27 100644
--- a/crates/email/src/outbound/email_pg_repo/link.rs
+++ b/crates/email/src/outbound/email_pg_repo/link.rs
@@ -111,31 +111,6 @@ pub(super) async fn owned_link_for_thread(
.map_err(|e| sqlx::Error::Decode(Box::new(e)))
}
-#[tracing::instrument(err, skip(pool))]
-pub(super) async fn link_by_macro_id(
- pool: &PgPool,
- macro_id: MacroUserIdStr<'_>,
-) -> Result<Option<Link>, sqlx::Error> {
- let db_link: Option<DbLink> = sqlx::query_as!(
- DbLink,
- r#"
- SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
- is_sync_active, is_primary, created_at, updated_at
- FROM email_links
- WHERE macro_id = $1
- LIMIT 1
- "#,
- macro_id.as_ref()
- )
- .fetch_optional(pool)
- .await?;
-
- db_link
- .map(|v: DbLink| v.try_into_model())
- .transpose()
- .map_err(|e| sqlx::Error::Decode(Box::new(e)))
-}
-
#[tracing::instrument(err, skip(pool))]
pub(super) async fn inboxes_for_macro_id(
pool: &PgPool,
diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rs
index 8002d71b5e..9e97c52e26 100644
--- a/crates/email/src/outbound/email_pg_repo/test.rs
+++ b/crates/email/src/outbound/email_pg_repo/test.rs
@@ -13,6 +13,7 @@ mod reminder_collection;
mod scheduled;
mod sender_names;
mod senders;
+mod sending_inbox;
mod settings;
mod signal_flag;
mod thread;
diff --git a/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rs b/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rs
new file mode 100644
index 0000000000..f8fda3683d
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/test/sending_inbox.rs
@@ -0,0 +1,291 @@
+//! Which inbox an AI-composed email goes out from, against the real repo.
+//!
+//! The resolution reads two tables (the caller's accessible inboxes, and the
+//! message a reply answers), and the inbox it settles on decides whether the
+//! reply can thread at all - so these run against Postgres rather than a fake.
+
+use super::*;
+use crate::domain::{
+ models::{CreateDraftInput, EmailErr, SendingInboxRequest},
+ ports::NoOpEnqueuer,
+ service::EmailServiceImpl,
+};
+use crm::domain::service::NoOpCrmService;
+use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
+use macro_event_broker::NoopMacroEventBroker;
+
+const PRIMARY_INBOX: Uuid = Uuid::from_u128(0xa1111111_1111_1111_1111_111111111111);
+const ALT_INBOX: Uuid = Uuid::from_u128(0xa2222222_2222_2222_2222_222222222222);
+const ALT_THREAD: Uuid = Uuid::from_u128(0xd2222222_0000_0000_0000_000000000002);
+const MESSAGE_IN_PRIMARY: Uuid = Uuid::from_u128(0xe1111111_0000_0000_0000_000000000001);
+const MESSAGE_IN_ALT: Uuid = Uuid::from_u128(0xe2222222_0000_0000_0000_000000000002);
+
+fn service(
+ pool: Pool<Postgres>,
+) -> EmailServiceImpl<
+ EmailPgRepo,
+ FrecencyQueryServiceImpl<FrecencyPgStorage>,
+ NoOpEnqueuer,
+ NoOpCrmService,
+ (),
+> {
+ EmailServiceImpl {
+ email_repo: EmailPgRepo::new(pool.clone()),
+ frecency_service: FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool)),
+ enqueuer: NoOpEnqueuer,
+ crm_service: NoOpCrmService,
+ entity_access_management_service: (),
+ macro_event_broker: NoopMacroEventBroker,
+ sent_undo_delay_secs: 0,
+ sender_provider: std::sync::Arc::new(
+ crate::domain::senders::UnavailableEmailSenderProvider,
+ ),
+ }
+}
+
+fn caller() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+fn reply_to(replying_to_id: Uuid) -> SendingInboxRequest<'static> {
+ SendingInboxRequest {
+ requested_address: None,
+ replying_to_id: Some(replying_to_id),
+ }
+}
+
+fn reply_input(replying_to_id: Uuid) -> CreateDraftInput {
+ CreateDraftInput {
+ db_id: None,
+ provider_id: None,
+ replying_to_id: Some(replying_to_id),
+ provider_thread_id: None,
+ thread_db_id: None,
+ subject: "Re: Hello alt".to_owned(),
+ sender_email: None,
+ to: vec![crate::domain::models::ContactInfo {
+ email: "[email protected]".to_owned(),
+ name: None,
+ photo_url: None,
+ }],
+ cc: vec![],
+ bcc: vec![],
+ body_text: Some("Thanks".to_owned()),
+ body_html: None,
+ body_macro: None,
+ headers_json: None,
+ send_time: None,
+ include_signature: None,
+ actor: Some(caller()),
+ draft_client_binding: None,
+ thread_client_binding: None,
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn a_reply_is_sent_from_the_inbox_that_received_it(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = service(pool);
+
+ let resolved = service
+ .resolve_sending_inbox_impl(caller(), reply_to(MESSAGE_IN_ALT))
+ .await?;
+
+ assert_eq!(
+ resolved.link.id, ALT_INBOX,
+ "the reply must go out from the inbox that received the message, not the primary one"
+ );
+ assert_eq!(
+ resolved.accessible_inboxes.len(),
+ 2,
+ "the whole accessible set comes back so the send can find a reply target in any inbox"
+ );
+
+ // Resolution is only useful if the send it feeds can then reach the
+ // target: a reply handed the single sending inbox used to fail here with
+ // "message not found" whenever the target lived in another inbox.
+ let draft = service
+ .create_draft_impl(
+ &resolved.link,
+ &resolved.accessible_inboxes,
+ reply_input(MESSAGE_IN_ALT),
+ )
+ .await?;
+ assert_eq!(draft.link_id, ALT_INBOX);
+ assert_eq!(
+ draft.thread_db_id, ALT_THREAD,
+ "sent from the target's own inbox, the reply joins the target's thread"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn a_new_email_is_sent_from_the_primary_inbox(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let resolved = service(pool)
+ .resolve_sending_inbox_impl(caller(), SendingInboxRequest::default())
+ .await?;
+
+ assert_eq!(resolved.link.id, PRIMARY_INBOX);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn an_explicit_sender_overrides_the_reply_target(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let resolved = service(pool)
+ .resolve_sending_inbox_impl(
+ caller(),
+ SendingInboxRequest {
+ // Deliberately the other case, since addresses compare
+ // case-insensitively.
+ requested_address: Some("[email protected]"),
+ replying_to_id: Some(MESSAGE_IN_ALT),
+ },
+ )
+ .await?;
+
+ assert_eq!(resolved.link.id, PRIMARY_INBOX);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn an_address_that_is_no_inbox_of_the_callers_is_refused(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ // `expect_err` would need `ResolvedSendingInbox: Debug`, which would mean
+ // a `Link` that prints a user's mailbox identity into test output.
+ let Err(error) = service(pool)
+ .resolve_sending_inbox_impl(
+ caller(),
+ SendingInboxRequest {
+ requested_address: Some("[email protected]"),
+ replying_to_id: None,
+ },
+ )
+ .await
+ else {
+ panic!("an inbox the caller cannot send from must be refused, never substituted")
+ };
+
+ // The message is what the model reads back, so it has to say what the
+ // choices were.
+ let message = error.to_string();
+ assert!(message.contains("[email protected]"), "{message}");
+ assert!(message.contains("[email protected]"), "{message}");
+ assert!(message.contains("[email protected]"), "{message}");
+ assert!(
+ matches!(error, EmailErr::UnknownSendingInbox { .. }),
+ "{message}"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn a_reply_target_the_caller_cannot_reach_falls_back_to_the_default(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let resolved = service(pool)
+ .resolve_sending_inbox_impl(caller(), reply_to(Uuid::from_u128(0xdead)))
+ .await?;
+
+ // Resolution does not double as an existence check: the send reports the
+ // missing target, against the inbox it would have gone out from.
+ assert_eq!(resolved.link.id, PRIMARY_INBOX);
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_user_with_no_connected_inbox_cannot_send(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let Err(error) = service(pool)
+ .resolve_sending_inbox_impl(caller(), SendingInboxRequest::default())
+ .await
+ else {
+ panic!("there is no inbox to send from")
+ };
+
+ assert!(matches!(error, EmailErr::InboxNotFound), "{error}");
+
+ Ok(())
+}
+
+/// The reported failure, pinned: a reply handed only its own sending inbox
+/// cannot see a target living in another of the user's inboxes, and calls the
+/// target missing. Deriving the sender from the target is what normally keeps
+/// the two in the same inbox, but the accessible set still has to be passed
+/// through for the case where the user switches the sender by hand.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn a_reply_cannot_find_a_target_outside_the_inboxes_it_is_given(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = service(pool);
+ let alt = service
+ .resolve_sending_inbox_impl(caller(), reply_to(MESSAGE_IN_ALT))
+ .await?;
+
+ let Err(error) = service
+ .create_draft_impl(
+ &alt.link,
+ std::slice::from_ref(&alt.link),
+ reply_input(MESSAGE_IN_PRIMARY),
+ )
+ .await
+ else {
+ panic!("a target outside the given inboxes must be unreachable")
+ };
+ assert!(
+ matches!(error, EmailErr::MessageNotFound(id) if id == MESSAGE_IN_PRIMARY),
+ "{error}"
+ );
+
+ // Given every inbox the caller can reach, the same reply lands.
+ service
+ .create_draft_impl(
+ &alt.link,
+ &alt.accessible_inboxes,
+ reply_input(MESSAGE_IN_PRIMARY),
+ )
+ .await?;
+
+ Ok(())
+}
+
+/// A same-inbox reply is the ordinary case and must keep working: nothing
+/// about deriving the sender changes where it threads.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_sending_inbox"))
+)]
+async fn a_reply_in_the_primary_inbox_still_resolves_to_it(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let resolved = service(pool)
+ .resolve_sending_inbox_impl(caller(), reply_to(MESSAGE_IN_PRIMARY))
+ .await?;
+
+ assert_eq!(resolved.link.id, PRIMARY_INBOX);
+
+ Ok(())
+}
diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rs
index f946988ccd..67d7a484f0 100644
--- a/crates/soup/src/inbound/axum_router/tests.rs
+++ b/crates/soup/src/inbound/axum_router/tests.rs
@@ -292,10 +292,11 @@ impl EmailService for MockEmail {
}))
}
- async fn get_link_by_macro_id(
+ async fn resolve_sending_inbox(
&self,
_macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
- ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ _request: email::domain::models::SendingInboxRequest<'_>,
+ ) -> Result<email::domain::models::ResolvedSendingInbox, email::domain::models::EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
}
@@ -776,10 +777,11 @@ impl EmailService for MockEmailLinkResult {
(self.get_link_result)()
}
- async fn get_link_by_macro_id(
+ async fn resolve_sending_inbox(
&self,
_macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
- ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ _request: email::domain::models::SendingInboxRequest<'_>,
+ ) -> Result<email::domain::models::ResolvedSendingInbox, email::domain::models::EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
}
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index b5f44fb9f3..f76453ab7c 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -408,6 +408,15 @@ Ordinary queued saves must not request another `EmailThreadPage`; a missing
thread snapshot or a move between inboxes still requires reconciliation.
AI email tool drafts persist body-only edits; changing recipients or the subject
is not required to save the body.
+For an AI-drafted reply with no explicit sender, the backend selects the inbox
+that received the original message. Delay the reply-inbox lookup: the composer
+shows `Resolving sender...`, hides the signature, and disables Send (including
+the keyboard shortcut and batch submission). Fail the lookup and check Retry; choosing a From inbox
+also enables sending immediately. A late lookup must not overwrite that choice.
+Implicit senders omit `from` on edits and sends. An explicit sender is preserved
+even while inboxes load or after disconnection; an unavailable sender blocks Send
+until another connected inbox is selected. New emails default to the primary
+inbox after inboxes load. Repeat on mobile using the expanded `Cc/Bcc, From:` row.
With GraphQL draft queuing enabled, working copies and pending attachment bytes
are saved on this device independently of the mutation queue. A failed server