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.

feat(email): attachments for the SendEmail draft composer (#7422)

teo48d69711eb3f
diff --git a/.sqlx/query-478ecdf9dc5e832a7d7ec45ad77fc3f4adf55ac70e8b72c8ba3cecfce2f5063d.json b/.sqlx/query-478ecdf9dc5e832a7d7ec45ad77fc3f4adf55ac70e8b72c8ba3cecfce2f5063d.json
new file mode 100644
index 0000000000..7095532a03
--- /dev/null
+++ b/.sqlx/query-478ecdf9dc5e832a7d7ec45ad77fc3f4adf55ac70e8b72c8ba3cecfce2f5063d.json
@@ -0,0 +1,21 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO email_attachments_drafts (\n id, draft_id, file_name, content_type, sha, size, s3_key\n )\n SELECT $1, $2, $3, $4, $5, $6, $7\n FROM email_messages m\n WHERE m.id = $2 AND m.link_id = $8\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Int4",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "478ecdf9dc5e832a7d7ec45ad77fc3f4adf55ac70e8b72c8ba3cecfce2f5063d"
+}
diff --git a/Cargo.lock b/Cargo.lock
index afac650d14..edbeb59235 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6893,6 +6893,7 @@ dependencies = [
"async-trait",
"attachment",
"authentication_service_client",
+ "aws-sdk-s3",
"axum",
"axum-extra",
"base64 0.22.1",
diff --git a/apps/docs/AI/mcp/tools/send-confirmed-email.mdx b/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
index a57edfd66f..0a0d5ff1e0 100644
--- a/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
+++ b/apps/docs/AI/mcp/tools/send-confirmed-email.mdx
@@ -19,4 +19,5 @@ Send an email immediately, with no review card or composer. Only for a prompt th
| `bcc` | EmailRecipient[] | No | Blind carbon copy recipients (optional). |
| `replyingToId` | string | No | The ID of a message to reply to (optional). When set, the email is sent as a reply within the same thread. |
| `includeSignature` | boolean | No | Per-message signature override, set by the composer's signature preview — not normally by you. Omit to use the inbox's default policy (always on a new email; on replies/forwards only when the user enabled it). `false` excludes the signature for this one email. |
+| `attachments` | EmailAttachment[] | No | Macro documents to attach as files (optional). Each must be an uploaded file the user can view; together they may total 18 MB. |
| `userConfirmation` | string | Yes | The user's own message approving this specific email, quoted verbatim - for example their "yes, send it" in reply to the email you wrote out for them. It is a reply to your draft, never the earlier request that asked you to write one: if the user has not yet seen this email, there is nothing to quote here and the tool must not be called. Required: do not paraphrase it, and never supply it yourself. |
diff --git a/apps/docs/AI/mcp/tools/send-email.mdx b/apps/docs/AI/mcp/tools/send-email.mdx
index cec54f1b2e..c50de64ac0 100644
--- a/apps/docs/AI/mcp/tools/send-email.mdx
+++ b/apps/docs/AI/mcp/tools/send-email.mdx
@@ -7,7 +7,7 @@ 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. 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. 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
@@ -20,3 +20,4 @@ Draft, compose, and send an email the user confirms in a review card or composer
| `bcc` | EmailRecipient[] | No | Blind carbon copy recipients (optional). |
| `replyingToId` | string | No | The ID of a message to reply to (optional). When set, the email is sent as a reply within the same thread. |
| `includeSignature` | boolean | No | Per-message signature override, set by the composer's signature preview — not normally by you. Omit to use the inbox's default policy (always on a new email; on replies/forwards only when the user enabled it). `false` excludes the signature for this one email. |
+| `attachments` | EmailAttachment[] | No | Macro documents to attach as files (optional). Each must be an uploaded file the user can view; together they may total 18 MB. |
diff --git a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
index 7586153050..d1d4e2e3ec 100644
--- a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
@@ -147,6 +147,9 @@ export function createAttachmentPersistence(options: {
},
async remove(attachment: DraftFormAttachment) {
const state = options.attachments;
+ // Document attachments exist only in the AI draft composer, which owns
+ // their removal; no draft row holds them.
+ if (attachment.type === 'document') return false;
const draftId = options.draftId();
const removalGeneration = generation;
const operation =
diff --git a/apps/web/src/features/email-compose/primitives/email-form-state.ts b/apps/web/src/features/email-compose/primitives/email-form-state.ts
index 7cb272d6c1..3db204a68b 100644
--- a/apps/web/src/features/email-compose/primitives/email-form-state.ts
+++ b/apps/web/src/features/email-compose/primitives/email-form-state.ts
@@ -40,6 +40,21 @@ export type DraftFormAttachment =
fileName: string;
mimeType: string;
fileSize: number;
+ }
+ | {
+ /**
+ * A Macro document attached by reference; the backend fetches its file
+ * when the email is sent. Used by the AI draft composer, whose email has
+ * no draft row to upload into until it is sent.
+ */
+ type: 'document';
+ documentId: string;
+ /** No draft row holds it, so it never has a draft attachment id. */
+ attachmentId?: never;
+ fileName: string;
+ mimeType?: string;
+ /** Unknown (0) until the document's metadata resolves. */
+ fileSize: number;
};
export interface EmailFormStateOptions {
diff --git a/apps/web/src/features/email-compose/views/compose-body.tsx b/apps/web/src/features/email-compose/views/compose-body.tsx
index 8c5f31a8c1..c9999e320d 100644
--- a/apps/web/src/features/email-compose/views/compose-body.tsx
+++ b/apps/web/src/features/email-compose/views/compose-body.tsx
@@ -256,6 +256,19 @@ function AttachmentItem(props: {
/>
)}
</Match>
+ <Match when={props.attachment.type === 'document' && props.attachment}>
+ {(attachment) => (
+ <EmailAttachmentPill
+ attachment={{
+ fileName: attachment().fileName,
+ mimeType: attachment().mimeType,
+ }}
+ removable={!ctx.disabled()}
+ onRemove={handleRemove}
+ onClick={props.onOpen}
+ />
+ )}
+ </Match>
</Switch>
);
}
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 5b10d1e343..d46adfb0d9 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
@@ -33,6 +33,12 @@ function getRecipientsLabel(data: SendEmail) {
return `${labels[0]}, ${labels[1]}, +${labels.length - 2} more`;
}
+function getAttachmentsLabel(data: SendEmail) {
+ const count = data.attachments?.length ?? 0;
+ if (count === 0) return undefined;
+ return `${count} ${count === 1 ? 'attachment' : 'attachments'}`;
+}
+
function getUserAction(response: SendEmailResponse | undefined) {
if (
typeof response === 'object' &&
@@ -138,6 +144,9 @@ export function SentEmailResponse(props: {
Email sent to{' '}
<span class="text-ink">{getRecipientsLabel(props.args)}</span>
</span>
+ <Show when={getAttachmentsLabel(props.args)}>
+ {(label) => <span>with {label()}</span>}
+ </Show>
<Suspense>
<ItemPreview class="ring-0" id={props.threadId} type="email" />
</Suspense>
@@ -176,6 +185,9 @@ export function DraftEmailResponse(props: {
Email saved as draft for{' '}
<span class="text-ink">{getRecipientsLabel(props.args)}</span>
</span>
+ <Show when={getAttachmentsLabel(props.args)}>
+ {(label) => <span>with {label()}</span>}
+ </Show>
<DraftPreviewButton
draftId={props.draftId}
subject={props.args.subject}
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 f61fa45cb1..28d4f01147 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
@@ -30,6 +30,7 @@ type ComposeToolProps = {
};
type SendEmailSnapshot = {
+ attachments: string[];
body: string;
bcc: Array<{ email: string; name: string | null }>;
cc: Array<{ email: string; name: string | null }>;
@@ -57,6 +58,7 @@ function createSendEmailSnapshot(data: SendEmail): SendEmailSnapshot {
subject: data.subject ?? '',
replyingToId: data.replyingToId ?? 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.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
index 3f2d5a310e..c52e8ab21e 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
@@ -28,9 +28,14 @@ import { enableEmailSignatures } from '@core/constant/featureFlags';
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 { 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 type { LexicalEditor } from 'lexical';
import {
@@ -42,6 +47,11 @@ import {
Show,
} from 'solid-js';
import type { UserToolReviewSink } from '../user-tool-review';
+import {
+ createDraftAttachments,
+ type DocumentDescription,
+ documentAttachmentFileName,
+} from './draft-attachments';
export type EmailDraftComposerProps = {
/** The draft as the agent wrote it, or as the user last saved it. */
@@ -81,6 +91,24 @@ function DraftComposerSurface(props: ComponentProps<typeof ComposerSurface>) {
return <ComposerSurface {...props} as="div" />;
}
+/** Uploads a user-added file as a Macro document, the form the send attaches. */
+async function uploadAttachmentDocument(
+ file: File
+): Promise<{ documentId: string } | undefined> {
+ const result = await uploadFile(file, forceDssRuleset, {
+ hideProgressIndicator: true,
+ });
+ if (
+ result.failed ||
+ result.destination !== 'dss' ||
+ result.type !== 'document'
+ ) {
+ toast.failure(`Failed to attach ${file.name}`);
+ return undefined;
+ }
+ return { documentId: result.documentId };
+}
+
export function EmailDraftComposer(props: EmailDraftComposerProps) {
const uiDisabled = () => !props.sink.canAct() || props.readOnly === true;
const emailLinksQuery = useEmailLinksQuery();
@@ -141,6 +169,30 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
>([]);
let finalized = false;
+ const queryClient = useQueryClient();
+ const describeDocument = async (
+ documentId: string
+ ): Promise<DocumentDescription> => {
+ const metadata = await queryClient.fetchQuery({
+ queryKey: entityKeys.documentMetadata(documentId).queryKey,
+ queryFn: () => fetchDocumentMetadata(documentId),
+ staleTime: 60 * 1000,
+ });
+ const fileType = metadata.fileType ?? undefined;
+ return {
+ fileName: documentAttachmentFileName(metadata.documentName, fileType),
+ mimeType: fileType
+ ? FileTypeMap[fileType as keyof typeof FileTypeMap]?.mime
+ : undefined,
+ };
+ };
+ const attachments = createDraftAttachments({
+ initial: props.initialData.attachments,
+ describe: describeDocument,
+ upload: uploadAttachmentDocument,
+ onChange: () => scheduleUpdate(),
+ });
+
function collectArgs(): SendEmail {
return {
to: fromEmailRecipients(recipients().to),
@@ -151,6 +203,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
replyingToId: props.initialData.replyingToId,
// Omit to use the backend default policy; false only when dismissed.
includeSignature: includeSignature() ? undefined : false,
+ attachments: attachments.toToolArgs(),
};
}
@@ -188,7 +241,8 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
});
async function handleSend() {
- if (finalized || uiDisabled() || isSending()) return;
+ if (finalized || uiDisabled() || isSending() || attachments.uploading())
+ return;
if (!validate()) return;
debouncedEdit.clear();
setIsSending(true);
@@ -216,7 +270,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
scheduleEnabled: false,
attachmentFailure: toast.failure,
subject,
- attachments: () => [],
+ attachments: attachments.list,
schedule: {
state: () => ({ type: 'editing', intent: { type: 'immediate' } }),
selectedTime: () => undefined,
@@ -240,22 +294,30 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
onContentChange: () => {
scheduleUpdate();
},
- onAddAttachments: (_: DraftFormAttachment[]) => {},
- onRemoveAttachment: (_: DraftFormAttachment) => {},
+ onAddAttachments: (added: DraftFormAttachment[]) => {
+ if (uiDisabled()) return;
+ attachments.add(added);
+ },
+ onRemoveAttachment: (attachment: DraftFormAttachment) => {
+ if (uiDisabled()) return;
+ attachments.remove(attachment);
+ },
captureEditor: setEditor,
onEditorInitialized: (editor) => {
props.onBodyInitialized?.(prepareEmailBody(editor)?.bodyHtml ?? '');
},
onSend: handleSend,
disabled: () => isSending() || uiDisabled(),
- primaryActionDisabled: () => isSending() || uiDisabled(),
+ // Send waits for files the user just added to finish becoming documents.
+ primaryActionDisabled: () =>
+ isSending() || uiDisabled() || attachments.uploading(),
isSending,
isSavingDraft: () => false,
hasDraft: () => false,
hasPaidAccess: () => true,
focusRecipientsOnMount: false,
includeSelf: true,
- hideAttachments: true,
+ hideAttachments: props.readOnly === true,
recipientOptions: () => [
...recipients().to,
...recipients().cc,
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/draft-attachments.test.ts b/apps/web/src/lib/core/component/AI/component/tool/email/draft-attachments.test.ts
new file mode 100644
index 0000000000..1e3039840c
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/draft-attachments.test.ts
@@ -0,0 +1,205 @@
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ createDraftAttachments,
+ type DraftAttachmentsOptions,
+ documentAttachmentFileName,
+ PENDING_ATTACHMENT_NAME,
+} from './draft-attachments';
+
+const disposers: (() => void)[] = [];
+afterEach(() => disposers.splice(0).forEach((dispose) => dispose()));
+
+function setup(options: Partial<DraftAttachmentsOptions> = {}) {
+ return createRoot((dispose) => {
+ disposers.push(dispose);
+ const onChange = vi.fn();
+ const describe = vi.fn(
+ options.describe ??
+ (async (documentId: string) => ({
+ fileName: `${documentId}.pdf`,
+ mimeType: 'application/pdf',
+ }))
+ );
+ const upload = vi.fn(
+ options.upload ??
+ (async (file: File) => ({ documentId: `doc-for-${file.name}` }))
+ );
+ const attachments = createDraftAttachments({
+ initial: options.initial,
+ describe,
+ upload,
+ onChange,
+ });
+ return { attachments, onChange, describe, upload };
+ });
+}
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe('documentAttachmentFileName', () => {
+ it('appends the extension the send attaches with', () => {
+ expect(documentAttachmentFileName('Q3 report', 'pdf')).toBe(
+ 'Q3 report.pdf'
+ );
+ });
+
+ it('keeps a name that already ends with the extension', () => {
+ expect(documentAttachmentFileName('photo.PNG', 'png')).toBe('photo.PNG');
+ });
+
+ it('falls back to a placeholder for a blank name', () => {
+ expect(documentAttachmentFileName(' ', 'pdf')).toBe(
+ `${PENDING_ATTACHMENT_NAME}.pdf`
+ );
+ expect(documentAttachmentFileName('', undefined)).toBe(
+ PENDING_ATTACHMENT_NAME
+ );
+ });
+});
+
+describe('createDraftAttachments', () => {
+ it('lists the agent-named documents at once and names them when metadata resolves', async () => {
+ const { attachments, describe } = setup({
+ initial: [{ documentId: 'a' }, { documentId: 'b' }],
+ });
+
+ expect(attachments.list()).toEqual([
+ expect.objectContaining({
+ type: 'document',
+ documentId: 'a',
+ fileName: PENDING_ATTACHMENT_NAME,
+ }),
+ expect.objectContaining({ type: 'document', documentId: 'b' }),
+ ]);
+ expect(attachments.toToolArgs()).toEqual([
+ { documentId: 'a' },
+ { documentId: 'b' },
+ ]);
+
+ await flush();
+ expect(describe).toHaveBeenCalledTimes(2);
+ expect(
+ attachments
+ .list()
+ .map((a) => (a.type === 'document' ? a.fileName : undefined))
+ ).toEqual(['a.pdf', 'b.pdf']);
+ });
+
+ it('keeps the placeholder when metadata cannot be read', async () => {
+ const { attachments } = setup({
+ initial: [{ documentId: 'gone' }],
+ describe: async () => {
+ throw new Error('404');
+ },
+ });
+ await flush();
+ expect(attachments.list()[0]).toMatchObject({
+ type: 'document',
+ fileName: PENDING_ATTACHMENT_NAME,
+ });
+ expect(attachments.toToolArgs()).toEqual([{ documentId: 'gone' }]);
+ });
+
+ it('shows a user-added file while it uploads, then carries it as a document', async () => {
+ const { promise, resolve } = Promise.withResolvers<{
+ documentId: string;
+ }>();
+ const { attachments, onChange } = setup({ upload: () => promise });
+ const file = new File(['x'], 'notes.txt', { type: 'text/plain' });
+
+ attachments.add([{ type: 'local', file }]);
+ expect(attachments.uploading()).toBe(true);
+ expect(attachments.list()).toEqual([{ type: 'local', file }]);
+ expect(attachments.toToolArgs()).toEqual([]);
+
+ resolve({ documentId: 'doc-1' });
+ await flush();
+ expect(attachments.uploading()).toBe(false);
+ expect(attachments.list()).toEqual([
+ {
+ type: 'document',
+ documentId: 'doc-1',
+ fileName: 'notes.txt',
+ mimeType: 'text/plain',
+ fileSize: 1,
+ },
+ ]);
+ expect(attachments.toToolArgs()).toEqual([{ documentId: 'doc-1' }]);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops a file whose upload fails without touching the tool args', async () => {
+ const { attachments, onChange } = setup({ upload: async () => undefined });
+ attachments.add([{ type: 'local', file: new File(['x'], 'bad.bin') }]);
+ await flush();
+ expect(attachments.list()).toEqual([]);
+ expect(attachments.uploading()).toBe(false);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('drops a file whose upload throws', async () => {
+ const { attachments, onChange } = setup({
+ upload: async () => {
+ throw new Error('network down');
+ },
+ });
+ attachments.add([{ type: 'local', file: new File(['x'], 'bad.bin') }]);
+ await flush();
+ expect(attachments.list()).toEqual([]);
+ expect(attachments.uploading()).toBe(false);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('forgets a file the user removed before its upload finished', async () => {
+ const { promise, resolve } = Promise.withResolvers<{
+ documentId: string;
+ }>();
+ const { attachments, onChange } = setup({ upload: () => promise });
+ const file = new File(['x'], 'late.txt');
+ attachments.add([{ type: 'local', file }]);
+ attachments.remove({ type: 'local', file });
+ expect(attachments.list()).toEqual([]);
+
+ resolve({ documentId: 'doc-late' });
+ await flush();
+ expect(attachments.list()).toEqual([]);
+ expect(attachments.toToolArgs()).toEqual([]);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('removes a document and reports the change', () => {
+ const { attachments, onChange } = setup({
+ initial: [{ documentId: 'a' }, { documentId: 'b' }],
+ });
+ const [first] = attachments.list();
+ attachments.remove(first!);
+ expect(attachments.toToolArgs()).toEqual([{ documentId: 'b' }]);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores remote and forwarded attachments, which only a saved draft has', () => {
+ const { attachments, onChange } = setup({
+ initial: [{ documentId: 'a' }],
+ });
+ attachments.add([
+ {
+ type: 'forwarded',
+ attachmentId: 'f',
+ fileName: 'f.pdf',
+ mimeType: 'application/pdf',
+ fileSize: 1,
+ },
+ ]);
+ attachments.remove({
+ type: 'remote',
+ attachmentId: 'r',
+ fileName: 'r.pdf',
+ contentType: 'application/pdf',
+ url: 'key',
+ fileSize: 1,
+ });
+ expect(attachments.toToolArgs()).toEqual([{ documentId: 'a' }]);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/draft-attachments.ts b/apps/web/src/lib/core/component/AI/component/tool/email/draft-attachments.ts
new file mode 100644
index 0000000000..41b67861ca
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/draft-attachments.ts
@@ -0,0 +1,173 @@
+/**
+ * The attachments of a drafted `SendEmail`: Macro documents by reference.
+ *
+ * The email behind the tool has no draft row until it is sent, so there is
+ * nothing to upload attachment bytes into. Instead every attachment is a
+ * Macro document - the ones the agent named, plus files the user adds, which
+ * are uploaded as documents first - and the backend fetches their files when
+ * the send runs. The list keeps uploading files beside resolved documents so
+ * the composer can show both.
+ */
+
+import type { DraftFormAttachment } from '@app/features/email-compose/primitives/email-form-state';
+import type { EmailAttachment } from '@service-cognition/generated/tools/types';
+import { createSignal } from 'solid-js';
+
+export type DocumentAttachment = Extract<
+ DraftFormAttachment,
+ { type: 'document' }
+>;
+type UploadingAttachment = Extract<DraftFormAttachment, { type: 'local' }>;
+
+/** What a document looks like once its metadata has been read. */
+export type DocumentDescription = {
+ fileName: string;
+ mimeType?: string;
+};
+
+/** The pill's placeholder until the document's metadata resolves. */
+export const PENDING_ATTACHMENT_NAME = 'Attachment';
+
+/**
+ * The attachment's display name: the document's name with its extension,
+ * added when the stored name lacks it, mirroring what the send attaches.
+ */
+export function documentAttachmentFileName(
+ documentName: string,
+ fileType?: string | null
+): string {
+ const name = documentName.trim() || PENDING_ATTACHMENT_NAME;
+ if (!fileType) return name;
+ const suffix = `.${fileType.toLowerCase()}`;
+ return name.toLowerCase().endsWith(suffix) ? name : `${name}${suffix}`;
+}
+
+export type DraftAttachmentsOptions = {
+ /** The attachments as the tool call carries them. */
+ initial: EmailAttachment[] | undefined;
+ /** Reads a document's name and type; rejects when it cannot be read. */
+ describe: (documentId: string) => Promise<DocumentDescription>;
+ /** Uploads a file as a Macro document; resolves undefined on failure. */
+ upload: (file: File) => Promise<{ documentId: string } | undefined>;
+ /** Called after any change the tool args should pick up. */
+ onChange: () => void;
+};
+
+export function createDraftAttachments(options: DraftAttachmentsOptions) {
+ const [list, setList] = createSignal<DraftFormAttachment[]>(
+ (options.initial ?? []).map(
+ (attachment): DocumentAttachment => ({
+ type: 'document',
+ documentId: attachment.documentId,
+ fileName: PENDING_ATTACHMENT_NAME,
+ fileSize: 0,
+ })
+ )
+ );
+ const [uploadingCount, setUploadingCount] = createSignal(0);
+
+ const describe = async (documentId: string) => {
+ let description: DocumentDescription;
+ try {
+ description = await options.describe(documentId);
+ } catch {
+ // The pill keeps its placeholder; the send reports a document it
+ // cannot read.
+ return;
+ }
+ setList((current) =>
+ current.map((attachment) =>
+ attachment.type === 'document' && attachment.documentId === documentId
+ ? { ...attachment, ...description }
+ : attachment
+ )
+ );
+ };
+ for (const attachment of list()) {
+ if (attachment.type === 'document') void describe(attachment.documentId);
+ }
+
+ const removeUploading = (file: File) =>
+ setList((current) =>
+ current.filter(
+ (attachment) => attachment.type !== 'local' || attachment.file !== file
+ )
+ );
+
+ const upload = async (entry: UploadingAttachment) => {
+ setUploadingCount((count) => count + 1);
+ try {
+ let uploaded: { documentId: string } | undefined;
+ try {
+ uploaded = await options.upload(entry.file);
+ } catch {
+ // A throw is a failed upload too: the pill must not linger as a file
+ // the send would silently leave out.
+ uploaded = undefined;
+ }
+ // The user may have removed the file while it uploaded.
+ const stillListed = list().some(
+ (attachment) =>
+ attachment.type === 'local' && attachment.file === entry.file
+ );
+ if (!uploaded || !stillListed) {
+ removeUploading(entry.file);
+ return;
+ }
+ setList((current) =>
+ current.map(
+ (attachment): DraftFormAttachment =>
+ attachment.type === 'local' && attachment.file === entry.file
+ ? {
+ type: 'document',
+ documentId: uploaded.documentId,
+ fileName: entry.file.name,
+ mimeType: entry.file.type || undefined,
+ fileSize: entry.file.size,
+ }
+ : attachment
+ )
+ );
+ options.onChange();
+ } finally {
+ setUploadingCount((count) => count - 1);
+ }
+ };
+
+ return {
+ list,
+ /** Whether a file added by the user is still becoming a document. */
+ uploading: () => uploadingCount() > 0,
+ /** Only the attachments the send can carry; uploads in flight are not yet documents. */
+ toToolArgs: (): EmailAttachment[] =>
+ list().flatMap((attachment) =>
+ attachment.type === 'document'
+ ? [{ documentId: attachment.documentId }]
+ : []
+ ),
+ add: (added: DraftFormAttachment[]) => {
+ const uploads = added.filter(
+ (attachment): attachment is UploadingAttachment =>
+ attachment.type === 'local'
+ );
+ if (uploads.length === 0) return;
+ setList((current) => [...current, ...uploads]);
+ for (const entry of uploads) void upload(entry);
+ },
+ remove: (removed: DraftFormAttachment) => {
+ if (removed.type === 'local') {
+ removeUploading(removed.file);
+ return;
+ }
+ if (removed.type !== 'document') return;
+ setList((current) =>
+ current.filter(
+ (attachment) =>
+ attachment.type !== 'document' ||
+ attachment.documentId !== removed.documentId
+ )
+ );
+ options.onChange();
+ },
+ };
+}
diff --git a/apps/web/src/lib/queries/email/local-drafts.ts b/apps/web/src/lib/queries/email/local-drafts.ts
index 5d009f1a44..f7f6acb13e 100644
--- a/apps/web/src/lib/queries/email/local-drafts.ts
+++ b/apps/web/src/lib/queries/email/local-drafts.ts
@@ -227,6 +227,9 @@ async function persistLocalDraft(input: LocalDraftInput): Promise<LocalDraft> {
const files = new Map<string, Blob>();
const attachments: LocalDraftAttachment[] = [];
for (const attachment of input.attachments) {
+ // Document attachments exist only in the AI draft composer, which keeps no
+ // local draft.
+ if (attachment.type === 'document') continue;
if (attachment.type !== 'local') {
attachments.push({ ...attachment });
continue;
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 9fd65a868b..a8606fbbc0 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
@@ -12884,6 +12884,7 @@ export const SendConfirmedEmail = z.object({
.optional(),
replyingToId: z.union([z.string().uuid(), z.null()]).optional(),
includeSignature: z.union([z.boolean(), z.null()]).optional(),
+ attachments: z.array(z.object({ documentId: z.string().uuid() })).optional(),
userConfirmation: z.string(),
});
@@ -12946,6 +12947,7 @@ export const SendEmail = z.object({
.optional(),
replyingToId: z.union([z.string().uuid(), z.null()]).optional(),
includeSignature: z.union([z.boolean(), z.null()]).optional(),
+ attachments: z.array(z.object({ documentId: z.string().uuid() })).optional(),
});
export const UserToolResponseForSendEmailResponse = z
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 d92ec371a6..00a443f33d 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
@@ -11929,6 +11929,11 @@ export interface SendConfirmedEmail {
* excludes the signature for this one email.
*/
includeSignature?: boolean | null;
+ /**
+ * Macro documents to attach as files (optional). Each must be an
+ * uploaded file the user can view; together they may total 18 MB.
+ */
+ attachments?: EmailAttachment[];
/**
* The user's own message approving this specific email, quoted verbatim - for example their "yes, send it" in reply to the email you wrote out for them. It is a reply to your draft, never the earlier request that asked you to write one: if the user has not yet seen this email, there is nothing to quote here and the tool must not be called. Required: do not paraphrase it, and never supply it yourself.
*/
@@ -11948,7 +11953,19 @@ export interface EmailRecipient {
name?: string | null;
}
/**
- * 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. 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.
+ * A Macro document attached to an outgoing email as a file.
+ */
+export interface EmailAttachment {
+ /**
+ * The id of the Macro document to attach. It must be a stored file -
+ * an uploaded PDF, image, spreadsheet, Word document, or other upload -
+ * that the user can view. A Macro-native document (one written in the
+ * editor) has no file to attach; link to it in the body instead.
+ */
+ 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.
*/
export interface SendEmail {
/**
@@ -11986,6 +12003,11 @@ export interface SendEmail {
* excludes the signature for this one email.
*/
includeSignature?: boolean | null;
+ /**
+ * Macro documents to attach as files (optional). Each must be an
+ * uploaded file the user can view; together they may total 18 MB.
+ */
+ attachments?: EmailAttachment[];
}
/**
* Set or update a property value on an entity. Tasks are targeted as entity_type='document'. Projects in the Tasks UI are entity_type='initiative'; entity_type='project' still means a folder. Initiatives share the Assignees, Status, Priority and Due Date definitions below and their clearing behavior. Project Status accepts only Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), and Completed (...0004); In Review and Canceled are task-only options. Provide the property_definition_id and exactly one value field matching the property's data type.
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index d75d185937..f52f7e3f54 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -48,7 +48,7 @@ crm = { path = "../crm" }
databases = { path = "../databases", default-features = false, features = ["ai_tools", "gateway", "postgres"] }
databases_sql = { path = "../databases_sql", features = ["ai_tools"] }
documents = { path = "../documents", features = ["ai_tools", "attachment", "purge"] }
-email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound"] }
+email = { path = "../email", features = ["ai_schema", "ai_tools", "axum", "outbound", "s3"] }
email_service_client = { path = "../email_service_client" }
entity_access = { path = "../entity_access" }
entity_access_management = { path = "../entity_access_management" }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 7fd5369ba6..e54ec9253f 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -130,6 +130,9 @@ pub fn build_image_generator_from_env() -> Arc<dyn ImageGenerator> {
/// - `ENABLE_GMAIL_OPS_QUEUE` (if disabled, thread-label updates can't enqueue Gmail sync ops)
/// - `ENABLE_NOTIFICATION_QUEUE` (if disabled, notification status updates skip push clearing)
///
+/// `ATTACHMENT_BUCKET` (the email service's draft attachment bucket) is
+/// optional; without it `SendEmail` refuses attachments but still sends.
+///
/// `enforcement` is validated by the host at startup and shared with all other
/// AI entry points. It configures quota admission here and must be the policy
/// `recorder` was composed with. `pricing` is the host's mandatory AI pricing
@@ -399,6 +402,14 @@ pub async fn build_tool_service_context_from_env(
pool.clone(),
))),
Arc::new(lexical_client),
+ )
+ .with_attachment_sender(
+ crate::email_attachments::build_email_attachment_sender(
+ user_email_service.clone(),
+ EmailPgRepo::new(pool.clone()),
+ document_tool_context.service.clone(),
+ )
+ .await,
);
let call_service = call::domain::service::CallServiceImpl::new(
diff --git a/crates/ai_tools/src/email_attachments.rs b/crates/ai_tools/src/email_attachments.rs
new file mode 100644
index 0000000000..53040ca1ca
--- /dev/null
+++ b/crates/ai_tools/src/email_attachments.rs
@@ -0,0 +1,237 @@
+//! Composition of `SendEmail`'s attachment support: the documents domain as
+//! the email domain's attachment source, S3 as its attachment store.
+//!
+//! The email crate defines the ports and the staged-send use case; it knows
+//! nothing about documents. This module is the bridge, which is why it lives
+//! in the composition root rather than in either domain crate.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use documents::domain::{
+ models::LocationQueryParams, ports::DocumentService, response::LocationResponseV3,
+};
+use email::domain::{
+ models::{EmailErr, MAX_DRAFT_ATTACHMENTS_BYTES, SourcedAttachment},
+ ports::{
+ DraftAttachmentRepo, DraftAttachmentSource, DraftSendService, EmailAttachmentSendService,
+ NoOpEmailAttachmentSender,
+ },
+ service::attachments::DraftAttachmentSender,
+};
+use email::outbound::S3DraftAttachmentStorage;
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+use macro_env_var::maybe_env_var;
+use model::document::{ContentType, FileType};
+
+maybe_env_var! {
+ /// The bucket the email service stages draft attachments in. Shared
+ /// with the email service, whose scheduled sender reads it.
+ struct AttachmentBucket;
+}
+
+/// How long one attachment download may take, body included. A stalled
+/// fetch fails the send instead of holding the tool call open.
+const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60);
+
+/// [`DraftAttachmentSource`] that resolves a document through the documents
+/// domain and downloads the file it points at.
+///
+/// Only single-file documents attach: uploads such as PDFs, images, and
+/// spreadsheets served from document storage. A Word document attaches as
+/// its PDF rendering, the one single-file form the storage keeps of it. A
+/// Macro-native document is sync-service content with no file, and is
+/// refused with a reason the model can relay.
+pub struct DocumentAttachmentSource<D> {
+ documents: Arc<D>,
+ http: reqwest::Client,
+}
+
+impl<D> DocumentAttachmentSource<D> {
+ /// Resolve attachments through `documents`.
+ pub fn new(documents: Arc<D>) -> Self {
+ Self {
+ documents,
+ http: reqwest::Client::new(),
+ }
+ }
+}
+
+fn unavailable(name: &str, reason: impl Into<String>) -> EmailErr {
+ EmailErr::AttachmentUnavailable {
+ name: name.to_owned(),
+ reason: reason.into(),
+ }
+}
+
+/// The attachment's file name: the document's name with the extension of
+/// what is actually attached, added when the stored name lacks it.
+fn attachment_file_name(document_name: &str, extension: Option<&str>) -> String {
+ let name = document_name.trim();
+ let name = if name.is_empty() { "attachment" } else { name };
+ match extension {
+ Some(ext) if !name.to_ascii_lowercase().ends_with(&format!(".{ext}")) => {
+ format!("{name}.{ext}")
+ }
+ _ => name.to_owned(),
+ }
+}
+
+impl<D: DocumentService> DraftAttachmentSource for DocumentAttachmentSource<D> {
+ #[tracing::instrument(skip_all, fields(document_id = %receipt.entity().entity_id), err)]
+ async fn fetch_attachment(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<SourcedAttachment, EmailErr> {
+ let document_id = receipt.entity().entity_id.to_string();
+ // The receipt already proves view access; this read is the metadata
+ // the location lookup needs.
+ let basic = self
+ .documents
+ .internal_get_basic_document(&document_id)
+ .await
+ .map_err(|e| unavailable(&document_id, format!("it could not be found ({e})")))?;
+ let name = basic.document_name.clone();
+ let file_type = basic.try_file_type();
+
+ let location = self
+ .documents
+ .get_document_location(
+ &basic,
+ receipt,
+ LocationQueryParams {
+ document_version_id: None,
+ // A docx is stored as unzipped parts; its PDF rendering is
+ // the single file there is to attach.
+ get_converted_docx_url: Some(true),
+ },
+ )
+ .await
+ .map_err(|e| unavailable(&name, format!("its file could not be located ({e})")))?;
+
+ let presigned_url = match location {
+ // The location is browser-facing; a server-side fetch on the
+ // local stack must reach LocalStack directly (a no-op elsewhere).
+ LocationResponseV3::PresignedUrl { presigned_url, .. } => {
+ macro_aws_config::transform_aws_url_for_internal_fetch(&presigned_url)
+ }
+ LocationResponseV3::PresignedUrls { .. }
+ | LocationResponseV3::SyncServiceContent { .. } => {
+ return Err(unavailable(
+ &name,
+ "it is a Macro document rather than an uploaded file; link to it in the email instead",
+ ));
+ }
+ };
+
+ let (attached_type, extension) = match file_type {
+ Some(FileType::Docx) => (Some(FileType::Pdf), Some("pdf")),
+ other => (other, other.as_ref().map(FileType::as_str)),
+ };
+
+ let mut response = self
+ .http
+ .get(&presigned_url)
+ .timeout(DOWNLOAD_TIMEOUT)
+ .send()
+ .await
+ .map_err(|e| unavailable(&name, format!("its file could not be downloaded ({e})")))?;
+ if !response.status().is_success() {
+ return Err(unavailable(
+ &name,
+ format!(
+ "its file could not be downloaded (HTTP {})",
+ response.status()
+ ),
+ ));
+ }
+ let header_type = response
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .map(|v| v.split(';').next().unwrap_or(v).trim().to_ascii_lowercase())
+ .filter(|v| {
+ !v.is_empty() && v != "application/octet-stream" && v != "binary/octet-stream"
+ });
+
+ let mut bytes = Vec::new();
+ loop {
+ let chunk = response.chunk().await.map_err(|e| {
+ unavailable(&name, format!("its file could not be downloaded ({e})"))
+ })?;
+ let Some(chunk) = chunk else { break };
+ bytes.extend_from_slice(&chunk);
+ if bytes.len() > MAX_DRAFT_ATTACHMENTS_BYTES {
+ return Err(EmailErr::AttachmentsTooLarge {
+ total_bytes: bytes.len(),
+ limit_bytes: MAX_DRAFT_ATTACHMENTS_BYTES,
+ });
+ }
+ }
+
+ let content_type =
+ header_type.unwrap_or_else(|| ContentType::from(attached_type).mime_type().to_owned());
+
+ Ok(SourcedAttachment {
+ file_name: attachment_file_name(&name, extension),
+ content_type,
+ bytes,
+ })
+ }
+}
+
+/// The sender `SendEmail` finishes through on a host with the attachment
+/// bucket configured (`ATTACHMENT_BUCKET`), or one that refuses attachments
+/// when it is not, so the host still boots and plain sends still work.
+pub async fn build_email_attachment_sender<Svc, R, D>(
+ email_service: Arc<Svc>,
+ repo: R,
+ documents: Arc<D>,
+) -> Arc<dyn EmailAttachmentSendService>
+where
+ Svc: DraftSendService,
+ R: DraftAttachmentRepo,
+ D: DocumentService,
+ anyhow::Error: From<R::Err>,
+{
+ let bucket = AttachmentBucket::new()
+ .as_ref()
+ .and_then(|bucket| bucket.value())
+ .map(|bucket| bucket.trim().to_owned())
+ .filter(|bucket| !bucket.is_empty());
+ let Some(bucket) = bucket else {
+ tracing::warn!("ATTACHMENT_BUCKET is not set; SendEmail attachments are disabled");
+ return Arc::new(NoOpEmailAttachmentSender(email_service));
+ };
+ let storage = S3DraftAttachmentStorage::new(macro_aws_config::s3_client().await, bucket);
+ Arc::new(DraftAttachmentSender::new(
+ email_service,
+ repo,
+ DocumentAttachmentSource::new(documents),
+ storage,
+ ))
+}
+
+#[cfg(test)]
+mod test {
+ use super::attachment_file_name;
+
+ #[test]
+ fn appends_the_extension_when_the_name_lacks_it() {
+ assert_eq!(
+ attachment_file_name("Q3 report", Some("pdf")),
+ "Q3 report.pdf"
+ );
+ }
+
+ #[test]
+ fn keeps_a_name_that_already_carries_the_extension() {
+ assert_eq!(attachment_file_name("photo.PNG", Some("png")), "photo.PNG");
+ }
+
+ #[test]
+ fn a_blank_name_still_yields_a_file_name() {
+ assert_eq!(attachment_file_name(" ", Some("pdf")), "attachment.pdf");
+ assert_eq!(attachment_file_name("", None), "attachment");
+ }
+}
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 1eb25354eb..33fb23c731 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -12,6 +12,7 @@ pub mod ai_operations;
mod build_context;
mod deferred;
mod display_results;
+pub mod email_attachments;
mod import_channels;
mod mcp_app_catalog;
mod schemas;
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index 34be3ea1cf..645a3b3e03 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -6,7 +6,7 @@ version = "0.1.0"
[features]
# Calendar invitation extraction and resolution against the viewer's calendar.
-calendar_invitations = ["dep:calendar_events", "dep:chrono-tz", "dep:ical", "dep:sha2", "dep:url"]
+calendar_invitations = ["dep:calendar_events", "dep:chrono-tz", "dep:ical", "dep:url"]
all = [
"ai_tools",
"gmail_token",
@@ -14,6 +14,7 @@ all = [
"inbound",
"outbound",
"ports",
+ "s3",
]
attachment = [
"dep:attachment",
@@ -40,18 +41,21 @@ http_client = ["dep:reqwest", "ports"]
inbound = ["ports"]
outbound = ["dep:calendar_events", "dep:sqlx", "ports"]
ports = ["crm/ports", "dep:tokio", "frecency/ports"]
+# The S3 adapter for staged draft attachments.
+s3 = ["dep:aws-sdk-s3", "ports"]
[dependencies]
calendar_events = { path = "../calendar_events", optional = true }
ical = { version = "0.11", default-features = false, features = ["ical"], optional = true }
chrono-tz = { workspace = true, optional = true }
-sha2 = { workspace = true, optional = true }
+sha2 = { workspace = true }
url = { workspace = true, optional = true }
activity = { path = "../activity", default-features = false }
ai_toolset = { path = "../ai_toolset", optional = true }
attachment = { path = "../attachment", optional = true }
anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
+aws-sdk-s3 = { workspace = true, optional = true }
base64 = { workspace = true }
lexical_client = { path = "../lexical_client" }
entity_access = { path = "../entity_access" }
diff --git a/crates/email/src/domain/models/attachment.rs b/crates/email/src/domain/models/attachment.rs
index 1137534818..f578ab2914 100644
--- a/crates/email/src/domain/models/attachment.rs
+++ b/crates/email/src/domain/models/attachment.rs
@@ -65,6 +65,25 @@ pub struct AttachmentDraft {
pub s3_key: String,
}
+/// The most raw bytes one outgoing message may attach in total. Gmail caps
+/// the encoded message at 25 MB; base64 adds about a third, so 18 MB of raw
+/// content is the safe ceiling the draft attachment API enforces too.
+pub const MAX_DRAFT_ATTACHMENTS_BYTES: usize = 18_000_000;
+
+/// A file resolved from a Macro document, ready to be staged as a draft
+/// attachment. Produced by a [`DraftAttachmentSource`].
+///
+/// [`DraftAttachmentSource`]: crate::domain::ports::DraftAttachmentSource
+#[derive(Debug, Clone)]
+pub struct SourcedAttachment {
+ /// The file name the recipient sees, extension included.
+ pub file_name: String,
+ /// The MIME type the attachment part is sent with.
+ pub content_type: String,
+ /// The file's raw bytes.
+ pub bytes: Vec<u8>,
+}
+
/// A forwarded attachment linking a draft to an original message's attachment.
#[derive(Debug, Clone)]
pub struct AttachmentForwarded {
diff --git a/crates/email/src/domain/models/error.rs b/crates/email/src/domain/models/error.rs
index 210681a112..4dca9f86d8 100644
--- a/crates/email/src/domain/models/error.rs
+++ b/crates/email/src/domain/models/error.rs
@@ -63,6 +63,29 @@ pub enum EmailErr {
/// Invalid email filter input.
#[error("{0}")]
InvalidEmailFilter(String),
+ /// This host has no attachment source or storage wired, so a send that
+ /// names attachments cannot be honoured.
+ #[error("Email attachments are not available here")]
+ AttachmentsUnavailable,
+ /// A referenced document cannot be attached: it is not a file (a Macro
+ /// document with no stored bytes), is gone, or could not be read.
+ #[error("Cannot attach \"{name}\": {reason}")]
+ AttachmentUnavailable {
+ /// What the document is called, for the message the user reads.
+ name: String,
+ /// Why it cannot be attached.
+ reason: String,
+ },
+ /// The attachments together exceed what one email can carry.
+ #[error(
+ "Attachments total {total_bytes} bytes, over the {limit_bytes} byte limit for one email"
+ )]
+ AttachmentsTooLarge {
+ /// The combined raw size of every attachment requested.
+ total_bytes: usize,
+ /// The ceiling it crossed.
+ limit_bytes: usize,
+ },
/// The caller's team has `team_crm_settings.crm_enabled = false` (or no
/// row at all), so no CRM-scoped query is allowed.
#[error("CRM is disabled for this team")]
diff --git a/crates/email/src/domain/models/mod.rs b/crates/email/src/domain/models/mod.rs
index 53b10b3da4..694cb1b1b1 100644
--- a/crates/email/src/domain/models/mod.rs
+++ b/crates/email/src/domain/models/mod.rs
@@ -16,7 +16,10 @@ pub mod thread;
#[cfg(test)]
mod tests;
-pub use attachment::{Attachment, AttachmentDraft, AttachmentForwarded, MessageAttachment};
+pub use attachment::{
+ Attachment, AttachmentDraft, AttachmentForwarded, MAX_DRAFT_ATTACHMENTS_BYTES,
+ MessageAttachment, SourcedAttachment,
+};
pub use contact::{Contact, ContactInfo, RecipientType};
pub use draft::{
CreateDraftInput, CreatedDraft, DeletedUserDraft, DraftDeletion, MessageTimestamps,
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index f4568adb2f..8109a6538b 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -5,14 +5,17 @@ use crate::domain::models::{
GetEmailsRequest, Label, Link, LinkLabel, Message, MessageAttachment, MessageLabel, MessageRow,
MessageTimestamps, ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery,
RecipientType, ResolvedDraftInput, SavedUserDraft, SenderPolicy, SettledDraftIds,
- SimpleMessage, SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult,
- UpsertEmailFilterInput, UpsertedContacts, UserEmailLink, UserProvider,
+ SimpleMessage, SimpleMessageInfo, SourcedAttachment, Thread, ThreadRow,
+ UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts, UserEmailLink,
+ UserProvider,
};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
use std::collections::HashMap;
+use std::pin::Pin;
+use std::sync::Arc;
use uuid::Uuid;
/// Keyed map of message recipients grouped by message ID.
@@ -806,6 +809,174 @@ impl GmailTokenProvider for NoOpGmailTokenProvider {
}
}
+/// Port for turning a Macro document the caller may view into the file an
+/// outgoing email attaches. The email domain never reads document storage
+/// itself; a composition root implements this over the documents domain.
+pub trait DraftAttachmentSource: Send + Sync + 'static {
+ /// Resolve the document the receipt names into its bytes, name, and
+ /// MIME type. Errors with [`EmailErr::AttachmentUnavailable`] when the
+ /// document has no file to attach.
+ fn fetch_attachment(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<SourcedAttachment, EmailErr>> + Send;
+}
+
+/// Port for the object store the scheduled sender reads draft attachments
+/// from. Keys are the domain's; the adapter only owns the bucket.
+pub trait DraftAttachmentStorage: Send + Sync + 'static {
+ /// Store one attachment's bytes under `key`.
+ fn put_attachment(
+ &self,
+ key: &str,
+ content_type: &str,
+ bytes: &[u8],
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
+}
+
+/// Port for recording a staged draft attachment against its draft row.
+pub trait DraftAttachmentRepo: Send + Sync + 'static {
+ /// Error type for repository operations.
+ type Err: Send;
+
+ /// Record `attachment` on its draft. A draft outside `link_id` must be
+ /// left untouched: the row the record points at is the sending inbox's.
+ fn insert_draft_attachment(
+ &self,
+ link_id: Uuid,
+ attachment: &AttachmentDraft,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+impl<T: DraftAttachmentSource> DraftAttachmentSource for Arc<T> {
+ fn fetch_attachment(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<SourcedAttachment, EmailErr>> + Send {
+ T::fetch_attachment(self, receipt)
+ }
+}
+
+impl<T: DraftAttachmentStorage> DraftAttachmentStorage for Arc<T> {
+ fn put_attachment(
+ &self,
+ key: &str,
+ content_type: &str,
+ bytes: &[u8],
+ ) -> impl Future<Output = anyhow::Result<()>> + Send {
+ T::put_attachment(self, key, content_type, bytes)
+ }
+}
+
+impl<T: DraftAttachmentRepo> DraftAttachmentRepo for Arc<T> {
+ type Err = T::Err;
+
+ fn insert_draft_attachment(
+ &self,
+ link_id: Uuid,
+ attachment: &AttachmentDraft,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send {
+ T::insert_draft_attachment(self, link_id, attachment)
+ }
+}
+
+/// The slice of [`EmailService`] a staged send needs: save the draft, send
+/// it, discard it. Every `EmailService` is one; the narrower bound lets the
+/// use case be tested against a fake of three methods.
+pub trait DraftSendService: Send + Sync + 'static {
+ /// See [`EmailService::create_draft`].
+ fn create_draft(
+ &self,
+ link: &Link,
+ accessible_inboxes: &[Link],
+ input: CreateDraftInput,
+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;
+
+ /// See [`EmailService::send_message`].
+ fn send_message(
+ &self,
+ link: &Link,
+ accessible_inboxes: &[Link],
+ input: CreateDraftInput,
+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;
+
+ /// See [`EmailService::delete_draft_for_user`].
+ fn delete_draft_for_user(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ draft_id: Uuid,
+ ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send;
+}
+
+impl<T: EmailService> DraftSendService for T {
+ fn create_draft(
+ &self,
+ link: &Link,
+ accessible_inboxes: &[Link],
+ input: CreateDraftInput,
+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send {
+ EmailService::create_draft(self, link, accessible_inboxes, input)
+ }
+
+ fn send_message(
+ &self,
+ link: &Link,
+ accessible_inboxes: &[Link],
+ input: CreateDraftInput,
+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send {
+ EmailService::send_message(self, link, accessible_inboxes, input)
+ }
+
+ fn delete_draft_for_user(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ draft_id: Uuid,
+ ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send {
+ EmailService::delete_draft_for_user(self, macro_id, draft_id)
+ }
+}
+
+/// Use case: send a message carrying Macro documents as attachments.
+///
+/// Object-safe (boxed future) so a tool context can hold any implementation
+/// behind one `Arc<dyn _>`, and hosts without attachment infrastructure can
+/// hold [`NoOpEmailAttachmentSender`] under the same type.
+pub trait EmailAttachmentSendService: Send + Sync + 'static {
+ /// Like [`EmailService::send_message`], with every document in
+ /// `attachments` staged on the message before delivery is queued. With
+ /// no attachments it is exactly a send.
+ fn send_message_with_attachments<'a>(
+ &'a self,
+ link: &'a Link,
+ accessible_inboxes: &'a [Link],
+ input: CreateDraftInput,
+ attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Pin<Box<dyn Future<Output = Result<CreatedDraft, EmailErr>> + Send + 'a>>;
+}
+
+/// [`EmailAttachmentSendService`] for hosts with no attachment source or
+/// storage. Sends without attachments pass through to `service`; a send
+/// naming attachments fails with [`EmailErr::AttachmentsUnavailable`]
+/// rather than silently dropping them.
+pub struct NoOpEmailAttachmentSender<T>(pub Arc<T>);
+
+impl<T: DraftSendService> EmailAttachmentSendService for NoOpEmailAttachmentSender<T> {
+ fn send_message_with_attachments<'a>(
+ &'a self,
+ link: &'a Link,
+ accessible_inboxes: &'a [Link],
+ input: CreateDraftInput,
+ attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Pin<Box<dyn Future<Output = Result<CreatedDraft, EmailErr>> + Send + 'a>> {
+ Box::pin(async move {
+ if !attachments.is_empty() {
+ return Err(EmailErr::AttachmentsUnavailable);
+ }
+ self.0.send_message(link, accessible_inboxes, input).await
+ })
+ }
+}
+
/// No-op enqueuer for callers that don't need send capability.
#[derive(Clone)]
pub struct NoOpEnqueuer;
diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rs
index 2adf4f3971..134c934a0e 100644
--- a/crates/email/src/domain/service.rs
+++ b/crates/email/src/domain/service.rs
@@ -1,3 +1,4 @@
+pub mod attachments;
mod draft;
mod followup;
mod previews;
diff --git a/crates/email/src/domain/service/attachments.rs b/crates/email/src/domain/service/attachments.rs
new file mode 100644
index 0000000000..2adf10e442
--- /dev/null
+++ b/crates/email/src/domain/service/attachments.rs
@@ -0,0 +1,204 @@
+//! Sending an email with Macro documents attached.
+//!
+//! The scheduled sender attaches whatever `email_attachments_drafts` rows a
+//! message has when its delivery runs, so attachments must be staged on a
+//! draft row before the send is committed. A plain `send_message` has no row
+//! until it commits, and the undo window it then enqueues is a few
+//! seconds: staging after it would race delivery. This service therefore
+//! sends in three steps - save the draft, stage every attachment on it, then
+//! send that draft - and resolves every attachment before the first step so
+//! a document that cannot be attached leaves nothing behind.
+
+use std::pin::Pin;
+use std::sync::Arc;
+
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+use sha2::{Digest, Sha256};
+
+use crate::domain::{
+ models::{
+ AttachmentDraft, CreateDraftInput, CreatedDraft, EmailErr, Link,
+ MAX_DRAFT_ATTACHMENTS_BYTES, SourcedAttachment,
+ },
+ ports::{
+ DraftAttachmentRepo, DraftAttachmentSource, DraftAttachmentStorage, DraftSendService,
+ EmailAttachmentSendService,
+ },
+};
+
+/// [`EmailAttachmentSendService`] over a [`DraftSendService`] (any
+/// `EmailService`) for the draft and the send, plus the three attachment ports.
+pub struct DraftAttachmentSender<Svc, R, S, St> {
+ email: Arc<Svc>,
+ repo: R,
+ source: S,
+ storage: St,
+}
+
+impl<Svc, R, S, St> DraftAttachmentSender<Svc, R, S, St> {
+ /// Compose the sender from the email service and the attachment ports.
+ pub fn new(email: Arc<Svc>, repo: R, source: S, storage: St) -> Self {
+ Self {
+ email,
+ repo,
+ source,
+ storage,
+ }
+ }
+}
+
+/// The object key a staged attachment is stored under: the same layout the
+/// draft attachment API uses, so the scheduled sender and its cleanup treat
+/// both alike.
+pub(crate) fn draft_attachment_key(draft_id: uuid::Uuid, attachment_id: uuid::Uuid) -> String {
+ format!("draft/{draft_id}/{attachment_id}")
+}
+
+/// Add up the attachments' raw sizes, refusing the set once it crosses the
+/// per-message ceiling.
+pub(crate) fn total_attachment_bytes(attachments: &[SourcedAttachment]) -> Result<usize, EmailErr> {
+ let total_bytes = attachments.iter().map(|a| a.bytes.len()).sum::<usize>();
+ if total_bytes > MAX_DRAFT_ATTACHMENTS_BYTES {
+ return Err(EmailErr::AttachmentsTooLarge {
+ total_bytes,
+ limit_bytes: MAX_DRAFT_ATTACHMENTS_BYTES,
+ });
+ }
+ Ok(total_bytes)
+}
+
+/// The send input re-targeted at the draft the attachments were staged on,
+/// so the send updates that row instead of minting another.
+pub(crate) fn input_for_staged_draft(
+ mut input: CreateDraftInput,
+ draft: &CreatedDraft,
+) -> CreateDraftInput {
+ input.db_id = Some(draft.db_id);
+ input.thread_db_id = Some(draft.thread_db_id);
+ input.provider_thread_id = draft.provider_thread_id.clone();
+ input.headers_json = draft.headers_json.clone();
+ input
+}
+
+impl<Svc, R, S, St> DraftAttachmentSender<Svc, R, S, St>
+where
+ Svc: DraftSendService,
+ R: DraftAttachmentRepo,
+ S: DraftAttachmentSource,
+ St: DraftAttachmentStorage,
+ anyhow::Error: From<R::Err>,
+{
+ async fn stage(
+ &self,
+ link: &Link,
+ draft: &CreatedDraft,
+ attachments: Vec<SourcedAttachment>,
+ ) -> Result<(), EmailErr> {
+ for sourced in attachments {
+ let attachment_id = macro_uuid::generate_uuid_v7();
+ let s3_key = draft_attachment_key(draft.db_id, attachment_id);
+ let sha = format!("{:x}", Sha256::digest(&sourced.bytes));
+ self.storage
+ .put_attachment(&s3_key, &sourced.content_type, &sourced.bytes)
+ .await?;
+ let record = AttachmentDraft {
+ id: attachment_id,
+ draft_id: draft.db_id,
+ file_name: sourced.file_name,
+ content_type: sourced.content_type,
+ sha,
+ // Bounded by MAX_DRAFT_ATTACHMENTS_BYTES, well inside i32.
+ size: sourced.bytes.len() as i32,
+ s3_key,
+ };
+ self.repo
+ .insert_draft_attachment(link.id, &record)
+ .await
+ .map_err(anyhow::Error::from)?;
+ }
+ Ok(())
+ }
+
+ /// A failure after the draft row exists would otherwise surface it in
+ /// the user's drafts with the email they never got to send; remove it.
+ /// Best effort: the original error is what the caller hears.
+ async fn discard_draft(&self, input: &CreateDraftInput, draft: &CreatedDraft) {
+ let Some(actor) = input.actor.as_ref() else {
+ return;
+ };
+ if let Err(error) = self
+ .email
+ .delete_draft_for_user(actor.clone(), draft.db_id)
+ .await
+ {
+ tracing::warn!(
+ ?error,
+ draft_id = %draft.db_id,
+ "failed to discard the draft of a send whose attachments could not be staged"
+ );
+ }
+ }
+
+ async fn send_with_attachments(
+ &self,
+ link: &Link,
+ accessible_inboxes: &[Link],
+ input: CreateDraftInput,
+ attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Result<CreatedDraft, EmailErr> {
+ if attachments.is_empty() {
+ return self
+ .email
+ .send_message(link, accessible_inboxes, input)
+ .await;
+ }
+
+ // Check the running total after each download, so an oversized set
+ // fails as soon as it crosses the limit rather than after every file
+ // is held in memory.
+ let mut sourced = Vec::with_capacity(attachments.len());
+ for receipt in attachments {
+ sourced.push(self.source.fetch_attachment(receipt).await?);
+ total_attachment_bytes(&sourced)?;
+ }
+
+ let mut draft_input = input.clone();
+ draft_input.send_time = None;
+ let draft = self
+ .email
+ .create_draft(link, accessible_inboxes, draft_input)
+ .await?;
+
+ if let Err(error) = self.stage(link, &draft, sourced).await {
+ self.discard_draft(&input, &draft).await;
+ return Err(error);
+ }
+
+ let send_input = input_for_staged_draft(input, &draft);
+ self.email
+ .send_message(link, accessible_inboxes, send_input)
+ .await
+ }
+}
+
+impl<Svc, R, S, St> EmailAttachmentSendService for DraftAttachmentSender<Svc, R, S, St>
+where
+ Svc: DraftSendService,
+ R: DraftAttachmentRepo,
+ S: DraftAttachmentSource,
+ St: DraftAttachmentStorage,
+ anyhow::Error: From<R::Err>,
+{
+ fn send_message_with_attachments<'a>(
+ &'a self,
+ link: &'a Link,
+ accessible_inboxes: &'a [Link],
+ input: CreateDraftInput,
+ attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Pin<Box<dyn Future<Output = Result<CreatedDraft, EmailErr>> + Send + 'a>> {
+ Box::pin(self.send_with_attachments(link, accessible_inboxes, input, attachments))
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email/src/domain/service/attachments/test.rs b/crates/email/src/domain/service/attachments/test.rs
new file mode 100644
index 0000000000..c186af69cb
--- /dev/null
+++ b/crates/email/src/domain/service/attachments/test.rs
@@ -0,0 +1,340 @@
+use super::*;
+use crate::domain::models::{DeletedUserDraft, UserProvider};
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use model_entity::EntityType;
+use std::sync::Mutex;
+use uuid::Uuid;
+
+#[derive(Default)]
+struct Calls(Mutex<Vec<String>>);
+
+impl Calls {
+ fn push(&self, call: impl Into<String>) {
+ self.0.lock().unwrap().push(call.into());
+ }
+ fn take(&self) -> Vec<String> {
+ std::mem::take(&mut *self.0.lock().unwrap())
+ }
+}
+
+/// One fake behind every port, recording the order the use case drives them in.
+#[derive(Default)]
+struct Fake {
+ calls: Calls,
+ /// Bytes served per document id; a missing id is "not a file".
+ files: Mutex<Vec<(String, Vec<u8>)>>,
+ fail_storage: bool,
+ draft_id: Uuid,
+ thread_id: Uuid,
+}
+
+fn created(fake: &Fake, input: &CreateDraftInput) -> CreatedDraft {
+ CreatedDraft {
+ db_id: fake.draft_id,
+ provider_id: None,
+ replying_to_id: input.replying_to_id,
+ provider_thread_id: Some("thread-provider".to_owned()),
+ thread_db_id: fake.thread_id,
+ link_id: Uuid::nil(),
+ subject: input.subject.clone(),
+ to: input.to.clone(),
+ cc: input.cc.clone(),
+ bcc: input.bcc.clone(),
+ body_text: None,
+ body_html: None,
+ body_macro: None,
+ headers_json: Some(serde_json::json!({"Macro-In-Reply-To": "x"})),
+ send_time: input.send_time,
+ }
+}
+
+impl DraftSendService for Fake {
+ async fn create_draft(
+ &self,
+ _: &Link,
+ _: &[Link],
+ input: CreateDraftInput,
+ ) -> Result<CreatedDraft, EmailErr> {
+ self.calls.push("create_draft");
+ assert!(input.db_id.is_none(), "the draft is minted by the service");
+ Ok(created(self, &input))
+ }
+
+ async fn send_message(
+ &self,
+ _: &Link,
+ _: &[Link],
+ input: CreateDraftInput,
+ ) -> Result<CreatedDraft, EmailErr> {
+ self.calls.push(format!(
+ "send:{}:{}",
+ input.db_id.map(|id| id.to_string()).unwrap_or_default(),
+ input
+ .thread_db_id
+ .map(|id| id.to_string())
+ .unwrap_or_default()
+ ));
+ Ok(created(self, &input))
+ }
+
+ async fn delete_draft_for_user(
+ &self,
+ _: MacroUserIdStr<'_>,
+ draft_id: Uuid,
+ ) -> Result<DeletedUserDraft, EmailErr> {
+ self.calls.push(format!("delete:{draft_id}"));
+ Ok(DeletedUserDraft {
+ thread_id: None,
+ deleted: true,
+ thread_deleted: true,
+ })
+ }
+}
+
+impl DraftAttachmentSource for Fake {
+ async fn fetch_attachment(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<SourcedAttachment, EmailErr> {
+ let id = receipt.entity().entity_id.clone();
+ self.calls.push(format!("fetch:{id}"));
+ let files = self.files.lock().unwrap();
+ let Some((_, bytes)) = files.iter().find(|(doc, _)| *doc == id) else {
+ return Err(EmailErr::AttachmentUnavailable {
+ name: id,
+ reason: "it is a Macro document, not a file".to_owned(),
+ });
+ };
+ Ok(SourcedAttachment {
+ file_name: format!("{id}.pdf"),
+ content_type: "application/pdf".to_owned(),
+ bytes: bytes.clone(),
+ })
+ }
+}
+
+impl DraftAttachmentStorage for Fake {
+ async fn put_attachment(&self, key: &str, content_type: &str, _: &[u8]) -> anyhow::Result<()> {
+ self.calls.push(format!("put:{key}:{content_type}"));
+ anyhow::ensure!(!self.fail_storage, "bucket unavailable");
+ Ok(())
+ }
+}
+
+impl DraftAttachmentRepo for Fake {
+ type Err = anyhow::Error;
+
+ async fn insert_draft_attachment(
+ &self,
+ link_id: Uuid,
+ attachment: &AttachmentDraft,
+ ) -> Result<(), Self::Err> {
+ assert_eq!(link_id, link().id);
+ assert_eq!(attachment.draft_id, self.draft_id);
+ assert_eq!(
+ attachment.s3_key,
+ draft_attachment_key(self.draft_id, attachment.id)
+ );
+ assert_eq!(attachment.sha.len(), 64);
+ self.calls.push(format!(
+ "record:{}:{}:{}",
+ attachment.file_name, attachment.content_type, attachment.size
+ ));
+ Ok(())
+ }
+}
+
+fn link() -> Link {
+ Link {
+ id: Uuid::from_u128(0xd01),
+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ fusionauth_user_id: String::new(),
+ email_address: EmailStr::try_from("[email protected]".to_owned()).unwrap(),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ is_primary: true,
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ }
+}
+
+fn input() -> CreateDraftInput {
+ CreateDraftInput {
+ db_id: None,
+ provider_id: None,
+ replying_to_id: None,
+ provider_thread_id: None,
+ thread_db_id: None,
+ subject: "Report".to_owned(),
+ to: vec![],
+ cc: vec![],
+ bcc: vec![],
+ body_text: None,
+ body_html: None,
+ body_macro: None,
+ headers_json: None,
+ send_time: None,
+ include_signature: None,
+ actor: Some(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()),
+ draft_client_binding: None,
+ thread_client_binding: None,
+ }
+}
+
+fn receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
+ document_id,
+ EntityType::Document,
+ )
+}
+
+fn sender(fake: Arc<Fake>) -> DraftAttachmentSender<Fake, Arc<Fake>, Arc<Fake>, Arc<Fake>> {
+ DraftAttachmentSender::new(fake.clone(), fake.clone(), fake.clone(), fake)
+}
+
+fn fake_with(files: Vec<(&str, Vec<u8>)>) -> Arc<Fake> {
+ Arc::new(Fake {
+ files: Mutex::new(
+ files
+ .into_iter()
+ .map(|(id, bytes)| (id.to_owned(), bytes))
+ .collect(),
+ ),
+ draft_id: Uuid::from_u128(0xd5a),
+ thread_id: Uuid::from_u128(0x7a),
+ ..Default::default()
+ })
+}
+
+#[tokio::test]
+async fn no_attachments_is_a_plain_send() {
+ let fake = fake_with(vec![]);
+ sender(fake.clone())
+ .send_message_with_attachments(&link(), &[link()], input(), vec![])
+ .await
+ .unwrap();
+ assert_eq!(fake.calls.take(), ["send::"]);
+}
+
+#[tokio::test]
+async fn stages_every_attachment_on_the_draft_then_sends_that_draft() {
+ let fake = fake_with(vec![("a", vec![1, 2, 3]), ("b", vec![4])]);
+ let sent = sender(fake.clone())
+ .send_message_with_attachments(
+ &link(),
+ &[link()],
+ input(),
+ vec![receipt("a"), receipt("b")],
+ )
+ .await
+ .unwrap();
+ assert_eq!(sent.db_id, fake.draft_id);
+
+ let calls = fake.calls.take();
+ assert_eq!(&calls[..3], ["fetch:a", "fetch:b", "create_draft"]);
+ assert!(calls[3].starts_with(&format!("put:draft/{}/", fake.draft_id)));
+ assert!(calls[3].ends_with(":application/pdf"));
+ assert_eq!(calls[4], "record:a.pdf:application/pdf:3");
+ assert!(calls[5].starts_with("put:"));
+ assert_eq!(calls[6], "record:b.pdf:application/pdf:1");
+ assert_eq!(
+ calls[7],
+ format!("send:{}:{}", fake.draft_id, fake.thread_id),
+ "the send targets the staged draft, not a fresh row"
+ );
+ assert_eq!(calls.len(), 8);
+}
+
+#[tokio::test]
+async fn send_input_adopts_the_staged_drafts_thread_identity() {
+ let fake = fake_with(vec![]);
+ let draft = created(&fake, &input());
+ let send_input = input_for_staged_draft(input(), &draft);
+ assert_eq!(send_input.db_id, Some(fake.draft_id));
+ assert_eq!(send_input.thread_db_id, Some(fake.thread_id));
+ assert_eq!(send_input.provider_thread_id, draft.provider_thread_id);
+ assert_eq!(send_input.headers_json, draft.headers_json);
+}
+
+#[tokio::test]
+async fn a_document_that_is_not_a_file_fails_before_any_draft_exists() {
+ let fake = fake_with(vec![("a", vec![1])]);
+ let error = sender(fake.clone())
+ .send_message_with_attachments(
+ &link(),
+ &[link()],
+ input(),
+ vec![receipt("a"), receipt("missing")],
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(error, EmailErr::AttachmentUnavailable { ref name, .. } if name == "missing"),
+ "got {error:?}"
+ );
+ assert_eq!(fake.calls.take(), ["fetch:a", "fetch:missing"]);
+}
+
+#[tokio::test]
+async fn oversized_attachments_are_refused_before_any_draft_exists() {
+ let fake = fake_with(vec![
+ ("a", vec![0; MAX_DRAFT_ATTACHMENTS_BYTES / 2 + 1]),
+ ("b", vec![0; MAX_DRAFT_ATTACHMENTS_BYTES / 2 + 1]),
+ ("c", vec![1]),
+ ]);
+ let error = sender(fake.clone())
+ .send_message_with_attachments(
+ &link(),
+ &[link()],
+ input(),
+ vec![receipt("a"), receipt("b"), receipt("c")],
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(
+ error,
+ EmailErr::AttachmentsTooLarge { total_bytes, limit_bytes }
+ if total_bytes == MAX_DRAFT_ATTACHMENTS_BYTES + 2
+ && limit_bytes == MAX_DRAFT_ATTACHMENTS_BYTES
+ ),
+ "got {error:?}"
+ );
+ // The set is refused as soon as it crosses the limit: "c" is never fetched.
+ assert_eq!(fake.calls.take(), ["fetch:a", "fetch:b"]);
+}
+
+#[tokio::test]
+async fn a_staging_failure_discards_the_draft_and_does_not_send() {
+ let fake = Arc::new(Fake {
+ fail_storage: true,
+ ..Arc::try_unwrap(fake_with(vec![("a", vec![1])]))
+ .ok()
+ .unwrap()
+ });
+ let error = sender(fake.clone())
+ .send_message_with_attachments(&link(), &[link()], input(), vec![receipt("a")])
+ .await
+ .unwrap_err();
+ assert!(
+ error.to_string().contains("bucket unavailable"),
+ "got {error}"
+ );
+
+ let calls = fake.calls.take();
+ assert_eq!(&calls[..2], ["fetch:a", "create_draft"]);
+ assert!(calls[2].starts_with("put:"));
+ assert_eq!(calls[3], format!("delete:{}", fake.draft_id));
+ assert_eq!(calls.len(), 4, "nothing was sent: {calls:?}");
+}
+
+#[test]
+fn the_attachment_key_matches_the_draft_attachment_api_layout() {
+ let draft = Uuid::from_u128(1);
+ let attachment = Uuid::from_u128(2);
+ assert_eq!(
+ draft_attachment_key(draft, attachment),
+ format!("draft/{draft}/{attachment}")
+ );
+}
diff --git a/crates/email/src/inbound/toolset.rs b/crates/email/src/inbound/toolset.rs
index 3a463e21f5..ae4b43201b 100644
--- a/crates/email/src/inbound/toolset.rs
+++ b/crates/email/src/inbound/toolset.rs
@@ -13,7 +13,9 @@ mod test;
use crate::domain::{
models::Link,
- ports::{EmailService, GmailTokenProvider},
+ ports::{
+ EmailAttachmentSendService, EmailService, GmailTokenProvider, NoOpEmailAttachmentSender,
+ },
};
use ai_toolset::{AsyncToolCollection, ToolCallError};
use base64::Engine;
@@ -26,7 +28,7 @@ pub use get_thread::{GetThread, GetThreadResponse};
pub use list_inboxes::{ListInboxes, ListInboxesResponse, ToolInbox};
pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
pub use send_confirmed_email::SendConfirmedEmail;
-pub use send_email::{SendEmail, SendEmailResponse};
+pub use send_email::{EmailAttachment, SendEmail, SendEmailResponse};
pub use set_sender_policy::{SetSenderPolicy, SetSenderPolicyResponse, ToolSenderPolicy};
pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};
@@ -100,6 +102,11 @@ pub struct EmailToolContext<
pub entity_access_service: Arc<E>,
/// Renders model-authored markdown into the HTML an email body carries.
pub lexical_client: Arc<lexical_client::LexicalClient>,
+ /// Sends a `SendEmail` call, staging its Macro-document attachments
+ /// first. [`new`](Self::new) installs a sender that refuses attachments;
+ /// hosts with attachment infrastructure swap in a real one through
+ /// [`with_attachment_sender`](Self::with_attachment_sender).
+ pub attachment_sender: Arc<dyn EmailAttachmentSendService>,
}
impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> Clone
@@ -111,6 +118,7 @@ impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> Clone
token_provider: self.token_provider.clone(),
entity_access_service: self.entity_access_service.clone(),
lexical_client: self.lexical_client.clone(),
+ attachment_sender: self.attachment_sender.clone(),
}
}
}
@@ -124,6 +132,7 @@ impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> EmailToolCo
lexical_client: Arc<lexical_client::LexicalClient>,
) -> Self {
Self {
+ attachment_sender: Arc::new(NoOpEmailAttachmentSender(service.clone())),
service,
token_provider,
entity_access_service,
@@ -131,6 +140,16 @@ impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> EmailToolCo
}
}
+ /// Replace the sender `SendEmail` finishes through with one that can
+ /// stage attachments.
+ pub fn with_attachment_sender(
+ mut self,
+ attachment_sender: Arc<dyn EmailAttachmentSendService>,
+ ) -> Self {
+ self.attachment_sender = attachment_sender;
+ self
+ }
+
/// Resolve the user's email link from their macro ID.
///
/// This is shared across all email tools that need an authenticated link.
diff --git a/crates/email/src/inbound/toolset/send_email.rs b/crates/email/src/inbound/toolset/send_email.rs
index e0de1039c4..bf28f37722 100644
--- a/crates/email/src/inbound/toolset/send_email.rs
+++ b/crates/email/src/inbound/toolset/send_email.rs
@@ -7,8 +7,9 @@ use crate::domain::{
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
use async_trait::async_trait;
-use entity_access::domain::ports::EntityAccessService;
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -36,11 +37,22 @@ impl From<EmailRecipient> for ContactInfo {
}
}
+/// A Macro document attached to an outgoing email as a file.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EmailAttachment {
+ /// The id of the Macro document to attach. It must be a stored file -
+ /// an uploaded PDF, image, spreadsheet, Word document, or other upload -
+ /// that the user can view. A Macro-native document (one written in the
+ /// editor) has no file to attach; link to it in the body instead.
+ pub document_id: Uuid,
+}
+
/// Compose and send an email. Creates a draft and immediately queues it for delivery.
#[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. 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. 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 {
@@ -69,6 +81,10 @@ pub struct SendEmail {
/// excludes the signature for this one email.
#[serde(default)]
pub include_signature: Option<bool>,
+ /// Macro documents to attach as files (optional). Each must be an
+ /// uploaded file the user can view; together they may total 18 MB.
+ #[serde(default)]
+ pub attachments: Vec<EmailAttachment>,
}
/// Response from the SendEmail tool.
@@ -105,6 +121,7 @@ where
user_id=?request_context.user_id,
subject=%self.subject,
to_count=%self.to.len(),
+ attachment_count=%self.attachments.len(),
), err)]
async fn call(
&self,
@@ -116,6 +133,24 @@ where
let body = service_context.render_body(&self.body).await?;
+ let mut attachments = Vec::with_capacity(self.attachments.len());
+ for attachment in &self.attachments {
+ let receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &request_context.user_id,
+ None,
+ &attachment.document_id.to_string(),
+ EntityType::Document,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Cannot attach document {}: {e}", attachment.document_id),
+ internal_error: e.into(),
+ })?;
+ attachments.push(receipt);
+ }
+
let input = CreateDraftInput {
db_id: None,
provider_id: None,
@@ -140,8 +175,8 @@ where
};
let sent = service_context
- .service
- .send_message(&link, std::slice::from_ref(&link), input)
+ .attachment_sender
+ .send_message_with_attachments(&link, std::slice::from_ref(&link), input, attachments)
.await
.map_err(|e| ToolCallError {
description: format!("Failed to send email: {e}"),
diff --git a/crates/email/src/lib.rs b/crates/email/src/lib.rs
index 0b4b0bc448..f92ebe48cd 100644
--- a/crates/email/src/lib.rs
+++ b/crates/email/src/lib.rs
@@ -1,5 +1,5 @@
pub mod domain;
#[cfg(feature = "inbound")]
pub mod inbound;
-#[cfg(any(feature = "outbound", feature = "http_client"))]
+#[cfg(any(feature = "outbound", feature = "http_client", feature = "s3"))]
pub mod outbound;
diff --git a/crates/email/src/outbound.rs b/crates/email/src/outbound.rs
index 6fadfa36f0..14274117cf 100644
--- a/crates/email/src/outbound.rs
+++ b/crates/email/src/outbound.rs
@@ -6,6 +6,8 @@ mod email_service_http;
mod gmail_token_provider;
#[cfg(feature = "outbound")]
pub mod invitation_pg;
+#[cfg(feature = "s3")]
+mod s3_draft_attachment_storage;
#[cfg(feature = "outbound")]
pub use email_pg_repo::EmailPgRepo;
@@ -13,3 +15,5 @@ pub use email_pg_repo::EmailPgRepo;
pub use email_service_http::EmailServiceHttpClient;
#[cfg(feature = "gmail_token")]
pub use gmail_token_provider::GmailTokenProviderImpl;
+#[cfg(feature = "s3")]
+pub use s3_draft_attachment_storage::S3DraftAttachmentStorage;
diff --git a/crates/email/src/outbound/email_pg_repo.rs b/crates/email/src/outbound/email_pg_repo.rs
index 2bf29bd20a..585199049c 100644
--- a/crates/email/src/outbound/email_pg_repo.rs
+++ b/crates/email/src/outbound/email_pg_repo.rs
@@ -7,7 +7,9 @@ use crate::domain::{
SettledDraftIds, SimpleMessage, SimpleMessageInfo, ThreadRow, UpsertEmailFilterInput,
UpsertedContacts, UserProvider,
},
- ports::{EmailRepo, EmailUserRepo, LinkEmailSettings, RecipientsByMessageId},
+ ports::{
+ DraftAttachmentRepo, EmailRepo, EmailUserRepo, LinkEmailSettings, RecipientsByMessageId,
+ },
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -524,3 +526,15 @@ impl EmailRepo for EmailPgRepo {
email_filter::list_email_filters(&self.pool, link_id).await
}
}
+
+impl DraftAttachmentRepo for EmailPgRepo {
+ type Err = sqlx::Error;
+
+ async fn insert_draft_attachment(
+ &self,
+ link_id: Uuid,
+ attachment: &AttachmentDraft,
+ ) -> Result<(), Self::Err> {
+ message::insert_draft_attachment(&self.pool, link_id, attachment).await
+ }
+}
diff --git a/crates/email/src/outbound/email_pg_repo/message.rs b/crates/email/src/outbound/email_pg_repo/message.rs
index 1fb8b248af..ec50dee71e 100644
--- a/crates/email/src/outbound/email_pg_repo/message.rs
+++ b/crates/email/src/outbound/email_pg_repo/message.rs
@@ -542,3 +542,39 @@ pub(super) async fn upsert_recipients(
Ok(())
}
+
+/// Record a staged attachment on a draft. The insert selects through the
+/// draft row under `link_id`, so a draft that belongs to another inbox (or
+/// does not exist) records nothing instead of leaking a cross-inbox row,
+/// and that is reported as [`sqlx::Error::RowNotFound`]: a send that went
+/// ahead would otherwise go out without the attachment.
+pub(super) async fn insert_draft_attachment(
+ pool: &PgPool,
+ link_id: Uuid,
+ attachment: &AttachmentDraft,
+) -> Result<(), sqlx::Error> {
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO email_attachments_drafts (
+ id, draft_id, file_name, content_type, sha, size, s3_key
+ )
+ SELECT $1, $2, $3, $4, $5, $6, $7
+ FROM email_messages m
+ WHERE m.id = $2 AND m.link_id = $8
+ "#,
+ attachment.id,
+ attachment.draft_id,
+ attachment.file_name,
+ attachment.content_type,
+ attachment.sha,
+ attachment.size,
+ attachment.s3_key,
+ link_id,
+ )
+ .execute(pool)
+ .await?;
+ if result.rows_affected() == 0 {
+ return Err(sqlx::Error::RowNotFound);
+ }
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/message.rs b/crates/email/src/outbound/email_pg_repo/test/message.rs
index cb9fe27c81..4d1d284ccd 100644
--- a/crates/email/src/outbound/email_pg_repo/test/message.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/message.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::domain::models::{RecipientType, UpsertedContacts, UpsertedRecipient};
+use crate::domain::models::{AttachmentDraft, RecipientType, UpsertedContacts, UpsertedRecipient};
use chrono::Timelike;
use sqlx::Row;
@@ -787,3 +787,74 @@ async fn test_delete_scheduled_messages_batch_empty_input(
assert!(deleted.is_empty());
Ok(())
}
+
+// ── insert_draft_attachment ─────────────────────────────────────────
+
+fn staged_attachment(draft_id: Uuid, id: Uuid) -> AttachmentDraft {
+ AttachmentDraft {
+ id,
+ draft_id,
+ file_name: "report.pdf".to_owned(),
+ content_type: "application/pdf".to_owned(),
+ sha: "f".repeat(64),
+ size: 42,
+ s3_key: format!("draft/{draft_id}/{id}"),
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn insert_draft_attachment_records_the_attachment_on_the_inboxs_draft(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ use crate::domain::ports::DraftAttachmentRepo;
+ let repo = EmailPgRepo::new(pool);
+ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let draft = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let id = Uuid::parse_str("dd000009-0000-0000-0000-000000000009")?;
+
+ repo.insert_draft_attachment(link, &staged_attachment(draft, id))
+ .await?;
+
+ let drafts = repo.draft_attachments_by_message_ids(&[draft]).await?;
+ let staged = drafts[&draft]
+ .iter()
+ .find(|a| a.id == id)
+ .expect("the staged attachment is recorded");
+ assert_eq!(staged.file_name, "report.pdf");
+ assert_eq!(staged.content_type, "application/pdf");
+ assert_eq!(staged.size, 42);
+ assert_eq!(staged.s3_key, format!("draft/{draft}/{id}"));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn insert_draft_attachment_refuses_another_inboxs_draft(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ use crate::domain::ports::DraftAttachmentRepo;
+ let repo = EmailPgRepo::new(pool);
+ let other_link = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;
+ let draft = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let id = Uuid::parse_str("dd000009-0000-0000-0000-000000000009")?;
+
+ let result = repo
+ .insert_draft_attachment(other_link, &staged_attachment(draft, id))
+ .await;
+ assert!(
+ matches!(result, Err(sqlx::Error::RowNotFound)),
+ "recording on another inbox's draft is an error, got {result:?}"
+ );
+
+ let drafts = repo.draft_attachments_by_message_ids(&[draft]).await?;
+ assert!(
+ drafts[&draft].iter().all(|a| a.id != id),
+ "a draft outside the inbox gains no attachment"
+ );
+ Ok(())
+}
diff --git a/crates/email/src/outbound/s3_draft_attachment_storage.rs b/crates/email/src/outbound/s3_draft_attachment_storage.rs
new file mode 100644
index 0000000000..736a2822f2
--- /dev/null
+++ b/crates/email/src/outbound/s3_draft_attachment_storage.rs
@@ -0,0 +1,46 @@
+//! S3 adapter for the bucket the scheduled sender reads draft attachments
+//! from: the same bucket the draft attachment API presigns uploads into.
+
+use anyhow::Context;
+use aws_sdk_s3::primitives::ByteStream;
+
+use crate::domain::ports::DraftAttachmentStorage;
+
+/// [`DraftAttachmentStorage`] over an `aws_sdk_s3::Client` and the email
+/// attachment bucket.
+#[derive(Clone)]
+pub struct S3DraftAttachmentStorage {
+ client: aws_sdk_s3::Client,
+ bucket: String,
+}
+
+impl S3DraftAttachmentStorage {
+ /// Store attachments in `bucket` through `client`.
+ pub fn new(client: aws_sdk_s3::Client, bucket: impl Into<String>) -> Self {
+ Self {
+ client,
+ bucket: bucket.into(),
+ }
+ }
+}
+
+impl DraftAttachmentStorage for S3DraftAttachmentStorage {
+ #[tracing::instrument(skip(self, bytes), fields(bucket = %self.bucket, size = bytes.len()), err)]
+ async fn put_attachment(
+ &self,
+ key: &str,
+ content_type: &str,
+ bytes: &[u8],
+ ) -> anyhow::Result<()> {
+ self.client
+ .put_object()
+ .bucket(&self.bucket)
+ .key(key)
+ .content_type(content_type)
+ .body(ByteStream::from(bytes.to_vec()))
+ .send()
+ .await
+ .with_context(|| format!("storing draft attachment {key}"))?;
+ Ok(())
+ }
+}
diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rs
index 554755be19..1ad607c684 100644
--- a/crates/prompt/src/user_tools.rs
+++ b/crates/prompt/src/user_tools.rs
@@ -45,6 +45,11 @@ static INSTRUCTIONS: &str = r##"- Booking links use conversational confirmation
sending are the same tool: it always creates a draft for the user to confirm before anything is
sent, so use it even when the user only wants a draft.
+- To attach a file, pass the Macro document's id in `SendEmail`'s `attachments`. Only uploaded
+ files attach (PDFs, images, spreadsheets, Word documents); a document written in the Macro
+ editor has no file, so link to it in the body instead. The user can add or remove attachments
+ in the composer before sending.
+
- `SendConfirmedEmail` and `CreateConfirmedCalendarEvent` send or create immediately, with no
composer. They are for conversation threads that have no composer, and this chat does, so
never use them here: `SendEmail` and `CreateCalendarEvent` and their composers are how the
@@ -109,6 +114,11 @@ static SESSION_INSTRUCTIONS: &str = r##"- Booking links use conversational confi
body as plain text in your reply. The review card is a real email composer the user can edit
before it sends; inline text does none of that and is wrong. Drafting and sending are the same
tool: the user decides in the card whether it goes out.
+
+- To attach a file, pass the Macro document's id in `SendEmail`'s `attachments`. Only uploaded
+ files attach (PDFs, images, spreadsheets, Word documents); a document written in the Macro
+ editor has no file, so link to it in the body instead. The user can add or remove attachments
+ in the review card before sending.
"##;
static SESSION_INTENT: &str = "The model checks where the newest prompt came from before using a \
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 8674af7d73..a8e007674d 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -799,6 +799,18 @@ as email blocks: an opaque background, subtle border and shadow, and a raised
rim in dark mode. The recipients, subject, body, and send controls stay inside
that card. Touch-device styling is unchanged.
+A drafted email can carry attachments. The agent attaches uploaded Macro files
+(PDFs, images, spreadsheets, Word documents; a Word document is attached as its
+PDF rendering) through `SendEmail`'s `attachments`, and each appears as a
+removable file pill under the body once its name resolves. The card's paperclip
+`Attach` control and dropping files onto the body add more: each file is first
+uploaded as a Macro document, shown as a pill while it uploads, and `Send email`
+stays disabled until every upload finishes. Macro-native documents written in the
+editor have no file and cannot be attached; the send reports which document
+could not be attached. Attachments together may total 18 MB. The sent and
+saved-draft rows read `with N attachments`, and the expanded sent card shows
+the pills read-only.
+
The reliable completion signal is the disappearance of the `Stop generating` button — poll
with `evaluate_script`. Do not wait on response text: the page displays
`Time to first token: N s` and doc content that easily false-matches `wait_for` patterns.
diff --git a/infra/packages/shared/src/ai_tools.ts b/infra/packages/shared/src/ai_tools.ts
index fc549c91ce..59fb310372 100644
--- a/infra/packages/shared/src/ai_tools.ts
+++ b/infra/packages/shared/src/ai_tools.ts
@@ -68,6 +68,15 @@ export function getAiToolsInfra(): AiToolsInfra {
.getOutput('gmailOpsQueueArn')
.apply((v) => v as string);
+ // `SendEmail` stages attachments in the email service's bucket; the hosts
+ // read its name from `ATTACHMENT_BUCKET` and need write access to it. The
+ // name is fixed by `stacks/email-service/attachments-bucket.ts`, so the ARN
+ // is derived here rather than read from that stack's outputs, which keeps
+ // these services deployable ahead of an email-service deploy.
+ const emailAttachmentsBucketArn: pulumi.Output<string> = pulumi.output(
+ `arn:aws:s3:::macro-email-attachments-${stack}`
+ );
+
const notificationIngressQueueArn: pulumi.Output<string> =
notificationServiceStack
.getOutput('notificationIngressQueueArn')
@@ -111,7 +120,11 @@ export function getAiToolsInfra(): AiToolsInfra {
searchEventQueueArn,
contactsQueueArn,
],
- bucketArns: [documentStorageBucketArn, docxUploadBucketArn],
+ bucketArns: [
+ documentStorageBucketArn,
+ docxUploadBucketArn,
+ emailAttachmentsBucketArn,
+ ],
};
}
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index bed1251881..0f9be1e613 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -386,6 +386,11 @@ emailAttachmentBucket.attachCloudfrontPolicy({
emailServiceRoleArn: emailServiceRole.arn,
});
+// Services hosting `ai_tools` stage SendEmail attachments in this bucket
+// (`ATTACHMENT_BUCKET`), which the scheduled sender then reads.
+export const emailAttachmentsBucketArn = emailAttachmentBucket.bucket.arn;
+export const emailAttachmentsBucketName = emailAttachmentBucket.bucket.bucket;
+
const containerEnvVars = [
{
name: 'ENVIRONMENT',
diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rs
index b61f64adf7..1b400c5984 100644
--- a/services/document_cognition_service/src/server.rs
+++ b/services/document_cognition_service/src/server.rs
@@ -439,6 +439,14 @@ pub async fn run() -> anyhow::Result<()> {
db.clone(),
))),
lexical_client.clone(),
+ )
+ .with_attachment_sender(
+ ai_tools::email_attachments::build_email_attachment_sender(
+ user_email_service.clone(),
+ EmailPgRepo::new(db.clone()),
+ document_tool_context.service.clone(),
+ )
+ .await,
);
tracing::info!("initialized email tool context");
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 9ea734e33d..ed97e9791f 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -343,6 +343,14 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
db.clone(),
))),
lexical_client.clone(),
+ )
+ .with_attachment_sender(
+ ai_tools::email_attachments::build_email_attachment_sender(
+ user_email_service.clone(),
+ EmailPgRepo::new(db.clone()),
+ document_tool_context.service.clone(),
+ )
+ .await,
);
let call_service = call::domain::service::CallServiceImpl::new(