Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): offer Macro links for attachments over the size limit (#8292)
gbirman58dc70da4c2f
diff --git a/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsx b/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsxindex cec044ae19..ae6590e7fd 100644--- a/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsx+++ b/apps/web/src/features/email-compose/browser-test/android-back-fixture.tsx@@ -68,6 +68,7 @@ function MobileComposePanel(props: { onLeave: () => void }) {dismiss: () => {},},blockingNotice: async () => {},+ confirm: async () => false,reportError: () => {},},accounts: {@@ -79,6 +80,7 @@ function MobileComposePanel(props: { onLeave: () => void }) {primaryId: () => 'inbox',},connectivity: { looksOffline: () => false },+ editorFiles: { uploadDocuments: async () => [], makePublic: () => {} },viewerEmail: () => '[email protected]',hasPaidAccess: () => true,recipients: () => [],diff --git a/apps/web/src/features/email-compose/browser-test/draft-recovery-fixture.tsx b/apps/web/src/features/email-compose/browser-test/draft-recovery-fixture.tsxindex 3348c07a90..858229ae8a 100644--- a/apps/web/src/features/email-compose/browser-test/draft-recovery-fixture.tsx+++ b/apps/web/src/features/email-compose/browser-test/draft-recovery-fixture.tsx@@ -82,6 +82,7 @@ function RecoveryEditor() {},},blockingNotice: async () => {},+ confirm: async () => false,reportError: () => {},},accounts: {@@ -93,6 +94,7 @@ function RecoveryEditor() {primaryId: () => 'inbox',},connectivity: { looksOffline: () => false },+ editorFiles: { uploadDocuments: async () => [], makePublic: () => {} },viewerEmail: () => '[email protected]',hasPaidAccess: () => true,recipients: () => [],diff --git a/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsx b/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsxindex f47a587ee2..0010b10fe0 100644--- a/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsx+++ b/apps/web/src/features/email-compose/browser-test/recipient-hotkeys-fixture.tsx@@ -66,6 +66,7 @@ const context: EmailComposeContext = {dismiss: () => {},},blockingNotice: async () => {},+ confirm: async () => false,reportError: () => {},},accounts: {@@ -90,6 +91,7 @@ const context: EmailComposeContext = {readDroppedFiles: () => {},makePublic: () => {},uploadEditorFiles: () => {},+ uploadDocuments: async () => [],},viewerEmail: () => '[email protected]',recipients: () => [],@@ -151,7 +153,6 @@ function NewEmail() {},isMobile: () => false,scheduleEnabled: false,- attachmentFailure: () => {},}}><ComposeLayout />diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.tsindex 1f8f911e90..0bb05c6dc5 100644--- a/apps/web/src/features/email-compose/compose-adapter.ts+++ b/apps/web/src/features/email-compose/compose-adapter.ts@@ -102,6 +102,7 @@ import {import { createEmailInboxSource } from './queries/inbox-source';import { queuedDraftSaveArgs } from './queries/queued-draft';import { restoreDraftBodyAfterUndo, runUndoSend } from './undo-send';+import { uploadAttachmentDocuments } from './upload-documents';export type EmailComposeContextOptions = {/** Transport of the thread read this surface sits under; a compose surface has none. */@@ -248,6 +249,7 @@ export function createEmailComposeContext(editorFiles: {readDroppedFiles: readDroppedEmailFiles,makePublic: makeAttachmentPublic,+ uploadDocuments: uploadAttachmentDocuments,uploadEditorFiles(input) {if (!input.editor) return;handleFileFolderDrop(@@ -297,6 +299,7 @@ export function createEmailComposeContext({ owner: dialogOwner });},+ confirm: (input) => confirmDialog(input, { owner: dialogOwner }),reportError,},drafts: {diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.tsindex 05d8cc8101..cba7cbe26e 100644--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts@@ -267,6 +267,12 @@ export interface EmailComposeFeedback {};/** A modal notice with a single acknowledgement; resolves when dismissed. */blockingNotice(input: { title: string; body: string }): Promise<void>;+ /** A modal choice; resolves true only when the user confirms. */+ confirm(input: {+ title: string;+ body: string;+ confirmLabel: string;+ }): Promise<boolean>;reportError(error: unknown): void;}@@ -293,9 +299,18 @@ export interface EmailComposePresentation {signaturesEnabled: Accessor<boolean>;}+/** A file stored as a Macro document, as a body link names it. */+export interface UploadedDocument {+ documentId: string;+ name: string;+ blockName: string;+}+export interface EmailEditorFiles {readDroppedFiles: import('./editor-capabilities').ComposeBodyActions['readDroppedFiles'];makePublic(id: string): void;+ /** Stores files as documents; resolves with the ones that succeeded after reporting the rest. */+ uploadDocuments(files: File[]): Promise<UploadedDocument[]>;uploadEditorFiles(input: {editor: LexicalEditor | undefined;sourceId?: string;diff --git a/apps/web/src/features/email-compose/core/constants.ts b/apps/web/src/features/email-compose/core/constants.tsindex 8f65f352d4..f687853805 100644--- a/apps/web/src/features/email-compose/core/constants.ts+++ b/apps/web/src/features/email-compose/core/constants.ts@@ -1,8 +1,12 @@export const MACRO_EMAIL_SIGNATURE = '-- Sent with Macro';export const MAX_ATTACHMENTS_BYTES_SIZE = 18_000_000;+// Raw bytes the provider will still deliver once base64 adds about a third:+// Gmail caps a message's attachments at 25 MB; Exchange Online sends at most+// 35 MB by default and Outlook.com attachments stop at 25 MB. Graph accepts+// uploads up to 150 MB, but the mailbox bounces anything over its send size.export function attachmentLimitBytes(provider?: 'GMAIL' | 'OUTLOOK'): number {- return provider === 'OUTLOOK' ? 150_000_000 : MAX_ATTACHMENTS_BYTES_SIZE;+ return provider === 'OUTLOOK' ? 25_000_000 : MAX_ATTACHMENTS_BYTES_SIZE;}// Stable id for the compose "To" input so the create gesture can focus itdiff --git a/apps/web/src/features/email-compose/primitives/attachment-limit.test.ts b/apps/web/src/features/email-compose/primitives/attachment-limit.test.tsnew file mode 100644index 0000000000..e42ba2062b--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/attachment-limit.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';+import {+ attachmentLimitBytes,+ MAX_ATTACHMENTS_BYTES_SIZE,+} from '../core/constants';+import { partitionByAttachmentLimit } from './attachment-limit';++const MB = 1_000_000;++function fileOf(bytes: number, name: string) {+ return new File([new ArrayBuffer(bytes)], name);+}++describe('partitionByAttachmentLimit', () => {+ it('attaches the files that fit and sets the others aside in picking order', () => {+ const huge = fileOf(MAX_ATTACHMENTS_BYTES_SIZE + 1, 'huge.mov');+ const small = fileOf(2 * MB, 'small.pdf');+ expect(+ partitionByAttachmentLimit([huge, small], [], MAX_ATTACHMENTS_BYTES_SIZE)+ ).toEqual({+ attachable: [small],+ oversized: [huge],+ });+ });++ it('counts attachments already on the draft toward the limit', () => {+ const over = fileOf(3 * MB, 'over.pdf');+ const fits = fileOf(1 * MB, 'fits.pdf');+ expect(+ partitionByAttachmentLimit(+ [over, fits],+ [+ {+ type: 'remote',+ attachmentId: 'remote',+ url: 'https://example.com/file',+ fileName: 'remote.pdf',+ contentType: 'application/pdf',+ fileSize: 10 * MB,+ },+ { type: 'local', file: fileOf(6 * MB, 'local.pdf') },+ ],+ MAX_ATTACHMENTS_BYTES_SIZE+ )+ ).toEqual({ attachable: [fits], oversized: [over] });+ });++ it('fills the limit exactly and sets aside the next byte', () => {+ const half = fileOf(MAX_ATTACHMENTS_BYTES_SIZE / 2, 'half.zip');+ const rest = fileOf(MAX_ATTACHMENTS_BYTES_SIZE / 2, 'rest.zip');+ const extra = fileOf(1, 'extra.zip');+ expect(+ partitionByAttachmentLimit(+ [half, rest, extra],+ [],+ MAX_ATTACHMENTS_BYTES_SIZE+ )+ ).toEqual({ attachable: [half, rest], oversized: [extra] });+ });++ it('lets an Outlook inbox attach what Gmail cannot', () => {+ const large = fileOf(20 * MB, 'large.mov');+ expect(+ partitionByAttachmentLimit([large], [], attachmentLimitBytes('GMAIL'))+ ).toEqual({ attachable: [], oversized: [large] });+ expect(+ partitionByAttachmentLimit([large], [], attachmentLimitBytes('OUTLOOK'))+ ).toEqual({ attachable: [large], oversized: [] });+ });+});diff --git a/apps/web/src/features/email-compose/primitives/attachment-limit.ts b/apps/web/src/features/email-compose/primitives/attachment-limit.tsnew file mode 100644index 0000000000..13563bc703--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/attachment-limit.ts@@ -0,0 +1,34 @@+import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';+import type { DraftFormAttachment } from './email-form-state';++/**+ * Splits picked files, in picking order, into those that still fit under the+ * inbox's delivery limit beside the current attachments and those that do not.+ * A file that does not fit is skipped, so a smaller later file can still attach.+ */+export function partitionByAttachmentLimit(+ files: readonly File[],+ current: readonly DraftFormAttachment[],+ limitBytes: number+): { attachable: File[]; oversized: File[] } {+ let total = current.reduce(+ (sum, attachment) =>+ sum ++ (attachment.type === 'local'+ ? getUploadFileSize(attachment.file)+ : attachment.fileSize),+ 0+ );+ const attachable: File[] = [];+ const oversized: File[] = [];+ for (const file of files) {+ const size = getUploadFileSize(file);+ if (total + size > limitBytes) {+ oversized.push(file);+ continue;+ }+ total += size;+ attachable.push(file);+ }+ return { attachable, oversized };+}diff --git a/apps/web/src/features/email-compose/primitives/attachment-links.test.ts b/apps/web/src/features/email-compose/primitives/attachment-links.test.tsnew file mode 100644index 0000000000..9ec0c36ce0--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/attachment-links.test.ts@@ -0,0 +1,279 @@+import {+ $createClassedBlockNode,+ $isClassedBlockNode,+ $isDocumentMentionNode,+} from '@macro-inc/lexical-core';+import { $getRoot, $isElementNode, type LexicalEditor } from 'lexical';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { MAX_ATTACHMENTS_BYTES_SIZE } from '../core/constants';+import { createComposeContext } from '../tests/capabilities';+import { mountEmailComposer } from '../tests/composer';+import { createEmailEditor } from '../tests/editor';+import { mountReplyComposer } from '../tests/reply';+import {+ appendAttachmentLinks,+ createAttachmentLinkOffer,+} from './attachment-links';++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++const report = {+ documentId: 'doc-1',+ name: 'Quarterly report',+ blockName: 'pdf',+};+const huge = new File(+ [new ArrayBuffer(MAX_ATTACHMENTS_BYTES_SIZE + 1)],+ 'huge.mov'+);+const small = new File(['notes'], 'notes.txt');++/** One entry per top-level block: the written text, a link's document, or the quoted thread. */+function outline(editor: LexicalEditor): string[] {+ return editor.read(() =>+ $getRoot()+ .getChildren()+ .map((node) => {+ if ($isClassedBlockNode(node)) return 'quote';+ const mention = $isElementNode(node)+ ? node.getChildren().find((child) => $isDocumentMentionNode(child))+ : undefined;+ return mention+ ? `link:${mention.getDocumentId()}`+ : `text:${node.getTextContent()}`;+ })+ );+}++function appendQuotedThread(editor: LexicalEditor) {+ editor.update(+ () =>+ $getRoot().append(+ $createClassedBlockNode({+ tag: 'div',+ classes: ['macro_quote', 'gmail_quote'],+ })+ ),+ { discrete: true }+ );+}++describe('appendAttachmentLinks', () => {+ it('links each document after the written text, above the quoted thread', () => {+ const editor = createEmailEditor('Please review');+ appendQuotedThread(editor);+ appendAttachmentLinks(editor, [+ report,+ { documentId: 'doc-2', name: 'Recording', blockName: 'video' },+ ]);+ expect(outline(editor)).toEqual([+ 'text:Please review',+ 'link:doc-1',+ 'link:doc-2',+ 'quote',+ ]);+ });++ it('links at the end of a message without a quoted thread', () => {+ const editor = createEmailEditor('Please review');+ appendAttachmentLinks(editor, [report]);+ expect(outline(editor)).toEqual(['text:Please review', 'link:doc-1']);+ });+});++describe('createAttachmentLinkOffer', () => {+ function offerFor(editor: LexicalEditor, confirmed: boolean) {+ const confirm = vi.fn(async () => confirmed);+ const uploadDocuments = vi.fn(async () => [report]);+ const makePublic = vi.fn();+ const links = createAttachmentLinkOffer({+ editor: () => editor,+ notices: { confirm },+ editorFiles: { uploadDocuments, makePublic },+ });+ return { ...links, confirm, uploadDocuments, makePublic };+ }++ it('uploads nothing when the user declines', async () => {+ const editor = createEmailEditor('Hi');+ const { share, confirm, uploadDocuments } = offerFor(editor, false);+ await share([huge], MAX_ATTACHMENTS_BYTES_SIZE);+ expect(confirm).toHaveBeenCalledExactlyOnceWith({+ title: 'Attachments exceed 18 MB',+ body: '"huge.mov" won\'t fit as an attachment. Upload it to Macro and share a view-only link instead?',+ confirmLabel: 'Share link',+ });+ expect(uploadDocuments).not.toHaveBeenCalled();+ expect(outline(editor)).toEqual(['text:Hi']);+ });++ it('uploads, opens, and links each confirmed file', async () => {+ const editor = createEmailEditor('Hi');+ const { share, confirm, uploadDocuments, makePublic } = offerFor(+ editor,+ true+ );+ await share([huge, small], MAX_ATTACHMENTS_BYTES_SIZE);+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({+ body: "2 files won't fit as attachments. Upload them to Macro and share view-only links instead?",+ confirmLabel: 'Share links',+ })+ );+ expect(uploadDocuments).toHaveBeenCalledExactlyOnceWith([huge, small]);+ expect(makePublic).toHaveBeenCalledExactlyOnceWith('doc-1');+ expect(outline(editor)).toEqual(['text:Hi', 'link:doc-1']);+ });++ it('asks nothing when every file fits', async () => {+ const editor = createEmailEditor('Hi');+ const { share, confirm } = offerFor(editor, true);+ await share([], MAX_ATTACHMENTS_BYTES_SIZE);+ expect(confirm).not.toHaveBeenCalled();+ });++ it('reports the upload in flight until it settles', async () => {+ const editor = createEmailEditor('Hi');+ const pending = Promise.withResolvers<(typeof report)[]>();+ const links = offerFor(editor, true);+ links.uploadDocuments.mockReturnValue(pending.promise);+ const sharing = links.share([huge], MAX_ATTACHMENTS_BYTES_SIZE);+ await vi.advanceTimersByTimeAsync(0);+ expect(links.uploading()).toBe(true);+ pending.resolve([report]);+ await sharing;+ expect(links.uploading()).toBe(false);+ expect(outline(editor)).toEqual(['text:Hi', 'link:doc-1']);+ });++ it('uploads nothing when the composer moved on while the prompt was open', async () => {+ const editor = createEmailEditor('Hi');+ const decision = Promise.withResolvers<boolean>();+ const links = offerFor(editor, true);+ links.confirm.mockReturnValue(decision.promise);+ const sharing = links.share([huge], MAX_ATTACHMENTS_BYTES_SIZE);+ links.detach();+ decision.resolve(true);+ await sharing;+ expect(links.uploadDocuments).not.toHaveBeenCalled();+ expect(outline(editor)).toEqual(['text:Hi']);+ });++ it('keeps a file private and unlinked when the composer moved on mid-upload', async () => {+ const editor = createEmailEditor('Hi');+ const pending = Promise.withResolvers<(typeof report)[]>();+ const links = offerFor(editor, true);+ links.uploadDocuments.mockReturnValue(pending.promise);+ const sharing = links.share([huge], MAX_ATTACHMENTS_BYTES_SIZE);+ await vi.advanceTimersByTimeAsync(0);+ links.detach();+ pending.resolve([report]);+ await sharing;+ expect(links.makePublic).not.toHaveBeenCalled();+ expect(outline(editor)).toEqual(['text:Hi']);+ });+});++describe('oversized attachments in the composers', () => {+ it('attaches what fits in a new email and offers the rest as links', async () => {+ const context = createComposeContext();+ const root = mountEmailComposer(context);+ try {+ root.edit('With files');+ await root.state.context.onAddAttachments([small, huge]);+ expect(root.state.context.attachments()).toEqual([+ { type: 'local', file: small },+ ]);+ expect(context.notices.confirm).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ confirmLabel: 'Share link' })+ );+ expect(context.editorFiles.uploadDocuments).not.toHaveBeenCalled();+ expect(outline(root.editor)).toEqual(['text:With files']);+ } finally {+ root.dispose();+ }+ });++ it('refuses to send a new email while a shared file is still uploading', async () => {+ const context = createComposeContext();+ const pending = Promise.withResolvers<(typeof report)[]>();+ vi.mocked(context.notices.confirm).mockResolvedValue(true);+ vi.mocked(context.editorFiles.uploadDocuments).mockReturnValue(+ pending.promise+ );+ const root = mountEmailComposer(context);+ try {+ root.edit('Sent too early');+ const adding = root.state.context.onAddAttachments([huge]);+ await vi.advanceTimersByTimeAsync(0);+ expect(root.state.context.primaryActionDisabled()).toBe(true);+ expect(root.state.context.sendUnavailableReason?.()).toBe(+ 'Uploading files to share…'+ );+ root.state.context.onSend();+ await vi.advanceTimersByTimeAsync(0);+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();+ expect(context.notices.feedback.failure).toHaveBeenCalledWith(+ 'Failed to send email',+ { subtext: 'Files are still uploading' }+ );+ pending.resolve([report]);+ await adding;+ expect(root.state.context.primaryActionDisabled()).toBe(false);+ expect(outline(root.editor)).toEqual([+ 'text:Sent too early',+ 'link:doc-1',+ ]);+ } finally {+ root.dispose();+ }+ });++ it('drops a link that lands after the reply was discarded', async () => {+ const context = createComposeContext();+ const pending = Promise.withResolvers<(typeof report)[]>();+ vi.mocked(context.notices.confirm).mockResolvedValue(true);+ vi.mocked(context.editorFiles.uploadDocuments).mockReturnValue(+ pending.promise+ );+ const composer = mountReplyComposer(context);+ try {+ const adding = composer.handleAddAttachments([huge]);+ await vi.advanceTimersByTimeAsync(0);+ expect(composer.sendActionDisabled()).toBe(true);+ await composer.deleteDraftAndReset();+ pending.resolve([report]);+ await adding;+ expect(context.editorFiles.makePublic).not.toHaveBeenCalled();+ expect(outline(composer.editor)).toEqual(['text:']);+ } finally {+ composer.dispose();+ }+ });++ it('links a confirmed file above the quoted thread of a reply without attaching it', async () => {+ const context = createComposeContext();+ vi.mocked(context.notices.confirm).mockResolvedValue(true);+ vi.mocked(context.editorFiles.uploadDocuments).mockResolvedValue([report]);+ const composer = mountReplyComposer(context);+ try {+ appendQuotedThread(composer.editor);+ await composer.handleAddAttachments([huge]);+ expect(+ context.editorFiles.uploadDocuments+ ).toHaveBeenCalledExactlyOnceWith([huge]);+ expect(context.editorFiles.makePublic).toHaveBeenCalledExactlyOnceWith(+ 'doc-1'+ );+ expect(composer.form.attachments.list()).toEqual([]);+ expect(outline(composer.editor)).toEqual([+ 'text:Ready to send',+ 'link:doc-1',+ 'quote',+ ]);+ } finally {+ composer.dispose();+ }+ });+});diff --git a/apps/web/src/features/email-compose/primitives/attachment-links.ts b/apps/web/src/features/email-compose/primitives/attachment-links.tsnew file mode 100644index 0000000000..3c1895b54e--- /dev/null+++ b/apps/web/src/features/email-compose/primitives/attachment-links.ts@@ -0,0 +1,131 @@+import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';+import {+ $createDocumentMentionNode,+ $isClassedBlockNode,+} from '@macro-inc/lexical-core';+import { Telemetry } from '@macro-inc/observability';+import {+ $addUpdateTag,+ $createParagraphNode,+ $getRoot,+ type LexicalEditor,+} from 'lexical';+import { type Accessor, createSignal } from 'solid-js';+import type {+ EmailComposeFeedback,+ EmailEditorFiles,+ UploadedDocument,+} from '../context/compose-capabilities';++/**+ * Links each document on its own line at the end of the written message,+ * above the quoted thread a reply carries, where recipients expect attachments.+ */+export function appendAttachmentLinks(+ editor: LexicalEditor,+ documents: readonly UploadedDocument[]+) {+ if (documents.length === 0) return;+ editor.update(() => {+ // Attaching from the toolbar must not pull focus into the editor.+ $addUpdateTag('skip-dom-selection');+ const root = $getRoot();+ const quote = root+ .getChildren()+ .find(+ (node) =>+ $isClassedBlockNode(node) && node.__classes.includes('macro_quote')+ );+ for (const document of documents) {+ const paragraph = $createParagraphNode().append(+ $createDocumentMentionNode({+ documentId: document.documentId,+ documentName: document.name,+ blockName: document.blockName,+ })+ );+ if (quote) quote.insertBefore(paragraph);+ else root.append(paragraph);+ }+ });+}++/**+ * Offers to share files that exceed the delivery limit as Macro links. Each+ * confirmed file is uploaded as a document, opened to anyone with the link,+ * and linked from the body, as a file dropped into the body would be. A send+ * must wait for `uploading`, and a composer that moves to another draft calls+ * `detach` so uploads still in flight link nothing.+ */+export function createAttachmentLinkOffer(options: {+ editor: Accessor<LexicalEditor | undefined>;+ notices: Pick<EmailComposeFeedback, 'confirm'>;+ editorFiles: Pick<EmailEditorFiles, 'uploadDocuments' | 'makePublic'>;+}) {+ const inFlight = new Set<Promise<UploadedDocument[]>>();+ const [uploading, setUploading] = createSignal(false);+ let generation = 0;++ const share = async (files: File[], limitBytes: number): Promise<void> => {+ if (files.length === 0) return;+ const started = generation;+ const single = files.length === 1;+ const limitLabel = `${limitBytes / 1_000_000} MB`;+ await Telemetry.span('email.attachment_links', async (span) => {+ span.setAttr('email.attachment_links.file_count', files.length);+ span.setAttr(+ 'email.attachment_links.total_bytes',+ files.reduce((sum, file) => sum + getUploadFileSize(file), 0)+ );+ const confirmed = await options.notices.confirm({+ title: `Attachments exceed ${limitLabel}`,+ body: single+ ? `"${files[0].name}" won't fit as an attachment. Upload it to Macro and share a view-only link instead?`+ : `${files.length} files won't fit as attachments. Upload them to Macro and share view-only links instead?`,+ confirmLabel: single ? 'Share link' : 'Share links',+ });+ span.setAttr('email.attachment_links.confirmed', confirmed);+ // The composer may have reset while the prompt was open; nothing to+ // upload for then.+ if (!confirmed || started !== generation) {+ span.setAttr('email.attachment_links.linked', false);+ return;+ }+ const upload = span.span('email.attachment_links.upload', () =>+ options.editorFiles.uploadDocuments(files)+ );+ inFlight.add(upload);+ setUploading(true);+ let documents: UploadedDocument[];+ try {+ documents = await upload;+ } finally {+ inFlight.delete(upload);+ setUploading(inFlight.size > 0);+ }+ span.setAttr('email.attachment_links.uploaded_count', documents.length);+ // The composer moved on while the files uploaded: they stay private and+ // unlinked rather than landing in whatever is being written now.+ const current = started === generation;+ span.setAttr('email.attachment_links.linked', current);+ if (!current) return;+ for (const document of documents) {+ options.editorFiles.makePublic(document.documentId);+ }+ const editor = options.editor();+ if (editor) appendAttachmentLinks(editor, documents);+ });+ };++ return {+ share,+ uploading,+ /** Resolves once every upload in flight has settled, linked or not. */+ async settled() {+ while (inFlight.size > 0) await Promise.allSettled([...inFlight]);+ },+ detach() {+ generation += 1;+ },+ };+}diff --git a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts b/apps/web/src/features/email-compose/primitives/compose-persistence.test.tsindex 86fafee7dc..28e85310d7 100644--- a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts+++ b/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts@@ -277,10 +277,7 @@ it('waits for an existing attachment upload before flushing newer body edits', aconst root = mountEmailComposer(composeContext);root.edit('With attachment');root.state.context.onAddAttachments([- {- type: 'local',- file: new File(['notes'], 'notes.txt', { type: 'text/plain' }),- },+ new File(['notes'], 'notes.txt', { type: 'text/plain' }),]);await vi.advanceTimersByTimeAsync(600);root.edit('Final attachment note');@@ -353,9 +350,7 @@ it('uses the captured inbox for attachment upload when a sender switch queues be);const root = mountEmailComposer(composeContext);root.edit('With files');- root.state.context.onAddAttachments([- { type: 'local', file: new File(['notes'], 'notes.txt') },- ]);+ root.state.context.onAddAttachments([new File(['notes'], 'notes.txt')]);await vi.advanceTimersByTimeAsync(600);root.state.context.onSelectInbox?.('other');pending.resolve(response);@@ -942,24 +937,22 @@ it('recovers local and forwarded attachments without retaining remote-only attacconst root = mountEmailComposer(context);const file = new File(['notes'], 'notes.txt');root.edit('Saved with files');- root.state.context.onAddAttachments([- { type: 'local', file },- {- type: 'remote',- attachmentId: 'remote',- url: 'https://example.com/file',- fileName: 'remote.txt',- contentType: 'text/plain',- fileSize: 10,- },- {- type: 'forwarded',- attachmentId: 'original-file',- fileName: 'forward.txt',- mimeType: 'text/plain',- fileSize: 10,- },- ]);+ await root.state.context.onAddAttachments([file]);+ root.state.form.attachments.add({+ type: 'remote',+ attachmentId: 'remote',+ url: 'https://example.com/file',+ fileName: 'remote.txt',+ contentType: 'text/plain',+ fileSize: 10,+ });+ root.state.form.attachments.add({+ type: 'forwarded',+ attachmentId: 'original-file',+ fileName: 'forward.txt',+ mimeType: 'text/plain',+ fileSize: 10,+ });await vi.advanceTimersByTimeAsync(600);vi.mocked(context.drafts.saveDraft).mockResolvedValue({...response,diff --git a/apps/web/src/features/email-compose/primitives/compose-view-state.ts b/apps/web/src/features/email-compose/primitives/compose-view-state.tsindex d4dc5972b2..bc0d0b8945 100644--- a/apps/web/src/features/email-compose/primitives/compose-view-state.ts+++ b/apps/web/src/features/email-compose/primitives/compose-view-state.ts@@ -18,7 +18,6 @@ export interface ComposeContextValue extends ComposeState {bodyActions: ComposeBodyActions;isMobile: Accessor<boolean>;scheduleEnabled: boolean;- attachmentFailure(message: string, options?: { subtext?: string }): void;onUpgrade?: () => void;viewerLoading?: Accessor<boolean>;}@@ -28,7 +27,6 @@ export interface ComposeState {recipients: () => EmailFormRecipients;subject: () => string;attachments: () => DraftFormAttachment[];- attachmentLimitBytes?: Accessor<number>;initialHtml: () => string | undefined;initialMarkdown?: () => string | undefined;@@ -39,7 +37,8 @@ export interface ComposeState {) => void;setSubject: (value: string) => void;onContentChange: (content: string) => void;- onAddAttachments: (attachments: DraftFormAttachment[]) => void;+ /** Files the user picked or dropped; the controller decides what attaches. */+ onAddAttachments: (files: File[]) => void;onRemoveAttachment: (attachment: DraftFormAttachment) => void;// Editordiff --git a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.tsindex 1df820dbb1..806552d227 100644--- a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts+++ b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts@@ -411,7 +411,7 @@ describe('draft session: compose composer', () => {const root = mountEmailComposer(context);try {root.edit('With an attachment');- await root.state.context.onAddAttachments([{ type: 'local', file }]);+ await root.state.context.onAddAttachments([file]);await vi.advanceTimersByTimeAsync(600);root.state.context.onSend();await vi.advanceTimersByTimeAsync(10);@@ -451,7 +451,7 @@ describe.each(['reply', 'compose'] as const)(schedule: root.state.context.schedule.onSelect,cancelSchedule: root.state.context.schedule.onCancel,addAttachment: (file: File) =>- root.state.context.onAddAttachments([{ type: 'local', file }]),+ root.state.context.onAddAttachments([file]),};};diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex b9e6cfeff7..1f8017cfd2 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -1,5 +1,7 @@-import { MACRO_EMAIL_SIGNATURE } from '@app/features/email-compose/core/constants';-import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';+import {+ attachmentLimitBytes,+ MACRO_EMAIL_SIGNATURE,+} from '@app/features/email-compose/core/constants';import { fireAndForget } from '@core/util/fireAndForget';import { $generateHtmlFromNodes } from '@lexical/html';import {@@ -34,9 +36,9 @@ import type {EmailDelivery,EmailDraftLifecycleSource,EmailDraftStorage,+ EmailEditorFiles,PersistedEmailIdentity,} from '../context/compose-capabilities';-import { attachmentLimitBytes } from '../core/constants';import { decodeBase64Utf8 } from '../core/decode-base64';import type { EmailRecipient } from '../core/email-recipient';import { fromInboxOptions } from '../core/email-sender';@@ -57,6 +59,8 @@ import {prepareEmailBody,} from '../primitives/prepare-email-body';import { endUndoSend } from '../primitives/undo-send-claim';+import { partitionByAttachmentLimit } from './attachment-limit';+import { createAttachmentLinkOffer } from './attachment-links';import {createAttachmentPersistence,refuseAttachmentsOffline,@@ -106,6 +110,7 @@ export type EmailComposerOptions = {notices: EmailComposeFeedback;accounts: EmailComposeAccounts;connectivity: EmailConnectivity;+ editorFiles: Pick<EmailEditorFiles, 'uploadDocuments' | 'makePublic'>;viewerEmail: Accessor<string | undefined>;hasPaidAccess: Accessor<boolean>;recipients: Accessor<EmailRecipient[]>;@@ -530,33 +535,37 @@ export function createEmailComposer(props: EmailComposerOptions) {// --- Attachment handling ---- const handleAddAttachments = async (attachments: DraftFormAttachment[]) => {+ const attachmentLinks = createAttachmentLinkOffer({+ editor,+ notices: props.notices,+ editorFiles: props.editorFiles,+ });++ const handleAddAttachments = async (files: File[]) => {if (persistencePaused()) return;if (!props.drafts.saveLocalDraft &&(await refuseAttachmentsOffline(props.connectivity, props.notices)))return;- const size = (a: DraftFormAttachment) =>- a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize;const limit = attachmentLimitBytes(- props.accounts.inboxes().find((i) => i.id === activeInboxId())?.provider+ props.accounts.inboxes().find((inbox) => inbox.id === activeInboxId())+ ?.provider);- if (- [...form.attachments.list(), ...attachments].reduce(- (sum, a) => sum + size(a),- 0- ) > limit- ) {- props.notices.feedback.failure(- `Combined attachments exceed the ${limit / 1_000_000} MB limit for this inbox.`- );- return;+ const { attachable, oversized } = partitionByAttachmentLimit(+ files,+ form.attachments.list(),+ limit+ );+ for (const file of attachable) {+ form.attachments.add({ type: 'local', file });}- for (const attachment of attachments) {- form.attachments.add(attachment);+ if (attachable.length > 0) markDirtyAndScheduleSave();+ try {+ await attachmentLinks.share(oversized, limit);+ } catch (error) {+ props.notices.reportError(error);}- markDirtyAndScheduleSave();};const handleRemoveAttachment = async (attachment: DraftFormAttachment) => {@@ -734,6 +743,8 @@ export function createEmailComposer(props: EmailComposerOptions) {const offline = sendRefusalBeforeSave(props.connectivity);if (offline) return refuseSend(props.notices, offline);+ if (attachmentLinks.uploading())+ return refuseSend(props.notices, 'files-uploading');const scheduleAction = schedule.action();if (scheduleAction === 'unavailable') {props.notices.feedback.alert(@@ -869,6 +880,7 @@ export function createEmailComposer(props: EmailComposerOptions) {// --- Reset / delete ---const resetState = () => {+ attachmentLinks.detach();clearEmailBody(editor());setContent('');session.dispatch({ type: 'reset' });@@ -929,6 +941,7 @@ export function createEmailComposer(props: EmailComposerOptions) {autosave.cancel();session.dispatch({ type: 'reset' });const omittedAttachments = attachmentPersistence.detach();+ attachmentLinks.detach();schedule.detach();setCompleted(false);setTerminalState(undefined);@@ -1166,10 +1179,6 @@ export function createEmailComposer(props: EmailComposerOptions) {recipients: form.recipients,subject: form.subject,attachments: form.attachments.list,- attachmentLimitBytes: () =>- attachmentLimitBytes(- props.accounts.inboxes().find((i) => i.id === activeInboxId())?.provider- ),initialHtml,// Form state (write)@@ -1228,6 +1237,7 @@ export function createEmailComposer(props: EmailComposerOptions) {completed() ||terminalState() !== undefined ||scheduling() ||+ attachmentLinks.uploading() ||schedule.action() === 'unavailable',isSending: () => submitting() || scheduling(),hasDraft: () => currentDraftId() != null,@@ -1243,6 +1253,7 @@ export function createEmailComposer(props: EmailComposerOptions) {if (schedule.operation() === 'updating') return 'Updating schedule…';if (schedule.operation() === 'cancelling') return 'Cancelling schedule…';if (submitting()) return 'Sending…';+ if (attachmentLinks.uploading()) return 'Uploading files to share…';if (schedule.action() === 'unavailable')return `Scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`;return undefined;@@ -1290,6 +1301,7 @@ export function createEmailComposer(props: EmailComposerOptions) {acknowledgeSaved: autosave.acknowledgeSaved,context: ctxValue,editor,+ form,previewName,hasInboxError,draftDirty,diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.tsindex 30dceb7650..10cffc89e7 100644--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts@@ -5,9 +5,7 @@ import {import type { EmailMessage } from '@app/features/email-message/core/email-message';import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';import { setEditorStateFromHtml } from '@core/component/LexicalMarkdown/utils/setEditorStateFromHtml';-import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';import { fireAndForget } from '@core/util/fireAndForget';-import { plural } from '@core/util/string';import { $generateHtmlFromNodes } from '@lexical/html';import {$appendWatermarkNodeToLast,@@ -40,6 +38,7 @@ import type {EmailDelivery,EmailDraftLifecycleSource,EmailDraftStorage,+ EmailEditorFiles,EmailUndoHandle,} from '../context/compose-capabilities';import type { EmailReplySession } from '../context/email-form-inputs';@@ -48,6 +47,8 @@ import {convertContactInfoToEmailRecipient,convertEmailRecipientToContactInfo,} from '../core/recipient-conversion';+import { partitionByAttachmentLimit } from './attachment-limit';+import { createAttachmentLinkOffer } from './attachment-links';import {createAttachmentPersistence,refuseAttachmentsOffline,@@ -113,6 +114,7 @@ export type ReplyComposerOptions = {notices: EmailComposeFeedback;accounts: EmailComposeAccounts;connectivity: EmailConnectivity;+ editorFiles: Pick<EmailEditorFiles, 'uploadDocuments' | 'makePublic'>;viewerEmail: Accessor<string | undefined>;hasPaidAccess: Accessor<boolean>;recordMention(sourceId: string, targetId: string): void;@@ -955,6 +957,8 @@ export function createReplyComposer(const offline = sendRefusalBeforeSave(props.connectivity);if (offline) return refuseSend(props.notices, offline);+ if (attachmentLinks.uploading())+ return refuseSend(props.notices, 'files-uploading');const currentEditor = editor();const rememberCurrentReply = () => {if (!currentEditor) return;@@ -1216,6 +1220,7 @@ export function createReplyComposer(};const resetState = () => {+ attachmentLinks.detach();clearEmailBody(editor());setBodyMacro('');session.dispatch({ type: 'reset' });@@ -1292,6 +1297,12 @@ export function createReplyComposer(});};+ const attachmentLinks = createAttachmentLinkOffer({+ editor,+ notices: props.notices,+ editorFiles: props.editorFiles,+ });+const handleAddAttachments = async (files: File[]) => {if (operationBlocked() ||@@ -1309,43 +1320,21 @@ export function createReplyComposer((await refuseAttachmentsOffline(props.connectivity, props.notices)))return;- const currentAttachments = form.attachments.list();const limit = attachmentLimitBytes(sendingInbox()?.provider);- const limitMB = limit / 1_000_000;-- const attachmentsToAddByteSize = files.reduce(- (sum, f) => sum + getUploadFileSize(f),- 0+ const { attachable, oversized } = partitionByAttachmentLimit(+ files,+ form.attachments.list(),+ limit);-- if (attachmentsToAddByteSize > limit) {- props.notices.feedback.failure(- `${plural('Attachment', files.length)} exceed ${limitMB}MB`- );- return;+ for (const file of attachable) {+ form.attachments.add({ type: 'local', file });}-- const currentAttachmentsByteSize = currentAttachments.reduce(- (sum, a) =>- sum + (a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize),- 0- );-- if (currentAttachmentsByteSize + attachmentsToAddByteSize > limit) {- props.notices.feedback.failure("Can't add more attachments", {- subtext: `Total attachments exceed ${limitMB}MB limit`,- });- return;- }-- for (const file of files) {- form.attachments.add({- type: 'local',- file,- });+ if (attachable.length > 0) scheduleDraftSave();+ try {+ await attachmentLinks.share(oversized, limit);+ } catch (error) {+ props.notices.reportError(error);}-- scheduleDraftSave();};const handleRemoveAttachment = async (attachment: DraftFormAttachment) => {@@ -1385,6 +1374,7 @@ export function createReplyComposer(autosave.cancel();session.dispatch({ type: 'reset' });const omittedAttachments = attachmentPersistence.detach();+ attachmentLinks.detach();schedule.detach();setTerminalState(undefined);persistedEditVersion = 0;@@ -1504,6 +1494,7 @@ export function createReplyComposer(if (schedule.operation() === 'updating') return 'Updating schedule…';if (schedule.operation() === 'cancelling') return 'Cancelling schedule…';if (submitting()) return 'Sending…';+ if (attachmentLinks.uploading()) return 'Uploading files to share…';if (schedule.action() === 'unavailable')return `Scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`;return undefined;@@ -1517,6 +1508,7 @@ export function createReplyComposer(scheduling() ||terminalState() !== undefined ||attachmentPersistence.uploading() ||+ attachmentLinks.uploading() ||schedule.action() === 'unavailable';const toggleQuotedText = () => {if (editingDisabled()) return;diff --git a/apps/web/src/features/email-compose/primitives/send-readiness.test.ts b/apps/web/src/features/email-compose/primitives/send-readiness.test.tsindex 6760ee3359..c504cd507e 100644--- a/apps/web/src/features/email-compose/primitives/send-readiness.test.ts+++ b/apps/web/src/features/email-compose/primitives/send-readiness.test.ts@@ -105,8 +105,6 @@ describe('refuseSend', () => {alert: vi.fn(),dismiss: vi.fn(),},- blockingNotice: vi.fn(),- reportError: vi.fn(),},'attachment-not-uploaded');diff --git a/apps/web/src/features/email-compose/primitives/send-readiness.ts b/apps/web/src/features/email-compose/primitives/send-readiness.tsindex d5b7b0a242..8960414586 100644--- a/apps/web/src/features/email-compose/primitives/send-readiness.ts+++ b/apps/web/src/features/email-compose/primitives/send-readiness.ts@@ -15,16 +15,21 @@ export type SendRefusal =| 'offline'| 'draft-not-saved'| 'draft-not-confirmed'- | 'attachment-not-uploaded';+ | 'attachment-not-uploaded'+ | 'files-uploading';const SEND_REFUSAL_SUBTEXT: Record<SendRefusal, string> = {offline: "You're offline",'draft-not-saved': 'Draft not saved','draft-not-confirmed': 'Draft still syncing, try again','attachment-not-uploaded': 'Attachment not uploaded',+ 'files-uploading': 'Files are still uploading',};-export function refuseSend(notices: EmailComposeFeedback, reason: SendRefusal) {+export function refuseSend(+ notices: Pick<EmailComposeFeedback, 'feedback'>,+ reason: SendRefusal+) {notices.feedback.failure('Failed to send email', {subtext: SEND_REFUSAL_SUBTEXT[reason],});diff --git a/apps/web/src/features/email-compose/tests/capabilities.ts b/apps/web/src/features/email-compose/tests/capabilities.tsindex 5d84febfff..065a7d5348 100644--- a/apps/web/src/features/email-compose/tests/capabilities.ts+++ b/apps/web/src/features/email-compose/tests/capabilities.ts@@ -62,6 +62,7 @@ export function createComposeContext(): EmailComposeContext & {readDroppedFiles: vi.fn(),makePublic: vi.fn(),uploadEditorFiles: vi.fn(),+ uploadDocuments: vi.fn(async () => []),},notices: {feedback: {@@ -71,6 +72,7 @@ export function createComposeContext(): EmailComposeContext & {dismiss: vi.fn(),},blockingNotice: vi.fn(async () => {}),+ confirm: vi.fn(async () => false),reportError: vi.fn(),},drafts: {diff --git a/apps/web/src/features/email-compose/upload-documents.ts b/apps/web/src/features/email-compose/upload-documents.tsnew file mode 100644index 0000000000..98737a1e00--- /dev/null+++ b/apps/web/src/features/email-compose/upload-documents.ts@@ -0,0 +1,27 @@+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { forceDssRuleset, uploadFiles } from '@core/util/upload';+import type { UploadedDocument } from './context/compose-capabilities';++/** Uploads files as Macro documents; the upload toasts report each outcome. */+export async function uploadAttachmentDocuments(+ files: File[]+): Promise<UploadedDocument[]> {+ let results: Awaited<ReturnType<typeof uploadFiles>>;+ try {+ results = await uploadFiles(files, forceDssRuleset);+ } catch {+ // A file over the upload size limit has already been reported by its toast.+ return [];+ }+ return results.flatMap((result) =>+ result.failed || result.destination !== 'dss' || result.type !== 'document'+ ? []+ : [+ {+ documentId: result.documentId,+ name: result.name,+ blockName: fileTypeToBlockName(result.fileType),+ },+ ]+ );+}diff --git a/apps/web/src/features/email-compose/views/compose-layout.tsx b/apps/web/src/features/email-compose/views/compose-layout.tsxindex adcc324ce7..175575ae77 100644--- a/apps/web/src/features/email-compose/views/compose-layout.tsx+++ b/apps/web/src/features/email-compose/views/compose-layout.tsx@@ -281,11 +281,7 @@ export function ComposeLayout(props: {debugName={props.bodyDebugName}inputRef={registerRef('messageInput')}mobileScrollRef={() => mobileScrollRef}- onAddFiles={(files) => {- ctx.onAddAttachments(- files.map((file) => ({ type: 'local', file }))- );- }}+ onAddFiles={ctx.onAddAttachments}/>{props.toolbar}</div>diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.test.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.test.tsxindex adad84fee7..459d93db05 100644--- a/apps/web/src/features/email-compose/views/compose-toolbar.test.tsx+++ b/apps/web/src/features/email-compose/views/compose-toolbar.test.tsx@@ -6,9 +6,6 @@ import { EmailComposeToolbar } from './compose-toolbar';const send = vi.hoisted(() => vi.fn());vi.mock('@core/directive/fileSelector', () => ({ fileSelector: vi.fn() }));-vi.mock('@core/mobile/nativeStagedUpload', () => ({- getUploadFileSize: (file: File) => file.size,-}));vi.mock('@core/component/LexicalMarkdown/plugins', () => ({defaultSelectionData: {},}));diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.tsxindex 99a475056e..f8921d0cfd 100644--- a/apps/web/src/features/email-compose/views/compose-toolbar.tsx+++ b/apps/web/src/features/email-compose/views/compose-toolbar.tsx@@ -1,4 +1,3 @@-import { MAX_ATTACHMENTS_BYTES_SIZE } from '@app/features/email-compose/core/constants';import { FormatButtons } from '@channel/Input/FormatButtons';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';import {@@ -11,8 +10,6 @@ import {type NodeTransformType,} from '@core/component/LexicalMarkdown/plugins/node-transform/nodeTransformPlugin';import { fileSelector } from '@core/directive/fileSelector';-import { getUploadFileSize } from '@core/mobile/nativeStagedUpload';-import { plural } from '@core/util/string';import PaperclipIcon from '@phosphor/paperclip.svg?component-solid';import TextAa from '@phosphor/text-aa.svg';import Trash from '@phosphor/trash.svg';@@ -31,53 +28,11 @@ export function EmailComposeToolbar(props: {}) {const ctx = useCompose();const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);- const handleAddAttachments = (files: File[]) => {- const currentAttachments = ctx.attachments();- const limit = ctx.attachmentLimitBytes?.() ?? MAX_ATTACHMENTS_BYTES_SIZE;- const limitMB = limit / 1_000_000;-- const attachmentsToAddByteSize = files.reduce(- (sum, f) => sum + getUploadFileSize(f),- 0- );-- if (attachmentsToAddByteSize > limit) {- ctx.attachmentFailure(- `${plural('Attachment', files.length)} exceed ${limitMB}MB`- );- return;- }-- const currentAttachmentsByteSize = currentAttachments.reduce(- (sum, a) =>- sum + (a.type === 'local' ? getUploadFileSize(a.file) : a.fileSize),- 0- );-- if (currentAttachmentsByteSize + attachmentsToAddByteSize > limit) {- ctx.attachmentFailure("Can't add more attachments", {- subtext: `Total attachments exceed ${limitMB}MB limit`,- });- return;- }-- ctx.onAddAttachments(- files.map((file) => ({- type: 'local',- file,- }))- );- };return (<Showwhen={props.inline || !ctx.isMobile()}- fallback={- <MobileToolbar- handleAddAttachments={handleAddAttachments}- status={props.status}- />- }+ fallback={<MobileToolbar status={props.status} />}><Show when={showFormatRibbon()}><div class="flex flex-row w-full gap-2 items-center p-2 -ml-3">@@ -110,7 +65,7 @@ export function EmailComposeToolbar(props: {ref={(el) =>fileSelector(el, () => ({multiple: true,- onSelect: handleAddAttachments,+ onSelect: ctx.onAddAttachments,}))}tooltip="Attach"@@ -159,10 +114,7 @@ export function EmailComposeToolbar(props: {);}-function MobileToolbar(props: {- handleAddAttachments: (files: File[]) => void;- status?: JSX.Element;-}) {+function MobileToolbar(props: { status?: JSX.Element }) {const ctx = useCompose();const hasScheduleSummary = () => {const state = ctx.schedule.state();@@ -192,7 +144,7 @@ function MobileToolbar(props: {ref={(el) =>fileSelector(el, () => ({multiple: true,- onSelect: props.handleAddAttachments,+ onSelect: ctx.onAddAttachments,}))}size="icon-sm"diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsxindex 24acd24c7c..4718682203 100644--- a/apps/web/src/features/email-compose/views/email-compose.tsx+++ b/apps/web/src/features/email-compose/views/email-compose.tsx@@ -118,6 +118,7 @@ function LoadedEmailComposeView(notices: composeContext.notices,accounts: composeContext.accounts,connectivity: composeContext.connectivity,+ editorFiles: composeContext.editorFiles,viewerEmail: composeContext.viewerEmail,hasPaidAccess: composeContext.hasPaidAccess,recipients: composeContext.recipients,@@ -168,7 +169,6 @@ function LoadedEmailComposeView(},isMobile: composeContext.presentation.isMobile,scheduleEnabled: composeContext.presentation.scheduleEnabled,- attachmentFailure: composeContext.notices.feedback.failure,onUpgrade: composeContext.presentation.onUpgrade,viewerLoading: composeContext.presentation.viewerLoading,signaturePreview: () => (diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsxindex 68427af818..ab00713c29 100644--- a/apps/web/src/features/email-compose/views/reply-input.tsx+++ b/apps/web/src/features/email-compose/views/reply-input.tsx@@ -57,6 +57,7 @@ type ReplyInputViewProps = Omit<| 'notices'| 'accounts'| 'connectivity'+ | 'editorFiles'| 'viewerEmail'| 'hasPaidAccess'| 'recordMention'@@ -127,6 +128,7 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {notices: composeContext.notices,accounts: composeContext.accounts,connectivity: composeContext.connectivity,+ editorFiles: composeContext.editorFiles,viewerEmail: composeContext.viewerEmail,hasPaidAccess: composeContext.hasPaidAccess,recordMention: composeContext.recordMention,diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsxindex fff93147d6..d551ae8868 100644--- a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.test.tsx@@ -73,6 +73,7 @@ vi.mock('@tanstack/solid-query', () => ({ useQueryClient: () => ({}) }));vi.mock('@ui', () => ({ComposerSurface: () => null,cn: () => '',+ confirmDialog: vi.fn(async () => false),Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (<button {...props} />),@@ -80,6 +81,12 @@ vi.mock('@ui', () => ({vi.mock('@app/features/email-compose/editor-adapter', () => ({createComposeBodyActions: () => ({}),}));+vi.mock('@app/features/email-compose/make-attachment-public', () => ({+ makeAttachmentPublic: vi.fn(),+}));+vi.mock('@app/features/email-compose/upload-documents', () => ({+ uploadAttachmentDocuments: vi.fn(async () => []),+}));vi.mock('@app/features/email-compose/components/signature-preview', () => ({SignaturePreview: (props: { html: string }) => (<span aria-label="Signature">{props.html}</span>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.tsxindex 7debc4441d..b0d2946e4b 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@@ -10,17 +10,22 @@import { SignaturePreview } from '@app/features/email-compose/components/signature-preview';import { ComposeProvider } from '@app/features/email-compose/context/compose-context';+import { attachmentLimitBytes } from '@app/features/email-compose/core/constants';import { decodeBase64Utf8 } from '@app/features/email-compose/core/decode-base64';import type { EmailRecipient } from '@app/features/email-compose/core/email-recipient';import { fromInboxOptions } from '@app/features/email-compose/core/email-sender';import { convertContactInfoToEmailRecipient } from '@app/features/email-compose/core/recipient-conversion';import { createComposeBodyActions } from '@app/features/email-compose/editor-adapter';+import { makeAttachmentPublic } from '@app/features/email-compose/make-attachment-public';+import { partitionByAttachmentLimit } from '@app/features/email-compose/primitives/attachment-limit';+import { createAttachmentLinkOffer } from '@app/features/email-compose/primitives/attachment-links';import type {ComposeContextValue,ComposeValidationError,} from '@app/features/email-compose/primitives/compose-view-state';import type { DraftFormAttachment } from '@app/features/email-compose/primitives/email-form-state';import { prepareEmailBody } from '@app/features/email-compose/primitives/prepare-email-body';+import { uploadAttachmentDocuments } from '@app/features/email-compose/upload-documents';import { ComposeLayout } from '@app/features/email-compose/views/compose-layout';import { EmailComposeToolbar } from '@app/features/email-compose/views/compose-toolbar';import { useFeatureFlag } from '@app/lib/analytics/posthog';@@ -29,6 +34,7 @@ import { enableEmailSignatures } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { isMobile } from '@core/mobile/isMobile';import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { fireAndForget } from '@core/util/fireAndForget';import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';import { forceDssRuleset, uploadFile } from '@core/util/upload';import {@@ -44,12 +50,13 @@ 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 { Button, ComposerSurface, cn } from '@ui';+import { Button, ComposerSurface, cn, confirmDialog } from '@ui';import type { LexicalEditor } from 'lexical';import {type ComponentProps,createMemo,createSignal,+ getOwner,type JSX,onCleanup,Show,@@ -254,6 +261,18 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {upload: uploadAttachmentDocument,onChange: () => scheduleUpdate(),});+ // Attach handlers run as event handlers without a Solid owner; the dialog needs this one.+ const dialogOwner = getOwner();+ const attachmentLinks = createAttachmentLinkOffer({+ editor,+ notices: {+ confirm: (input) => confirmDialog(input, { owner: dialogOwner }),+ },+ editorFiles: {+ uploadDocuments: uploadAttachmentDocuments,+ makePublic: makeAttachmentPublic,+ },+ });function collectArgs(): SendEmail {return {@@ -274,15 +293,14 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {}props.registerDraftReader?.(() =>- !bodyInitialized() || attachments.uploading() ? undefined : collectArgs()+ !bodyInitialized() || attachments.uploading() || attachmentLinks.uploading()+ ? undefined+ : collectArgs());props.registerSubmitReader?.(async () => {- if (- !bodyInitialized() ||- !(await attachments.waitForUploads()) ||- !sendingLink() ||- !validate()- )+ if (!bodyInitialized()) return;+ await attachmentLinks.settled();+ if (!(await attachments.waitForUploads()) || !sendingLink() || !validate())return;debouncedEdit.clear();return collectArgs();@@ -318,6 +336,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {}onCleanup(() => {debouncedEdit.clear();+ attachmentLinks.detach();props.sink.onDispose?.();});@@ -327,6 +346,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {uiDisabled() ||isSending() ||attachments.uploading() ||+ attachmentLinks.uploading() ||!sendingLink())return;@@ -335,7 +355,10 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {setIsSending(true);const done = await props.sink.onExecute(collectArgs());setIsSending(false);- if (done) finalized = true;+ if (done) {+ finalized = true;+ attachmentLinks.detach();+ }}// `body` is markdown while the AI is drafting, but every persist path@@ -355,7 +378,6 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {isMobile,// The AI tool has its own execute contract and does not expose scheduled send.scheduleEnabled: false,- attachmentFailure: toast.failure,subject,attachments: attachments.list,schedule: {@@ -381,9 +403,16 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {onContentChange: () => {scheduleUpdate();},- onAddAttachments: (added: DraftFormAttachment[]) => {+ onAddAttachments: (files: File[]) => {if (uiDisabled()) return;- attachments.add(added);+ const limit = attachmentLimitBytes(sendingLink()?.provider);+ const { attachable, oversized } = partitionByAttachmentLimit(+ files,+ attachments.list(),+ limit+ );+ attachments.add(attachable.map((file) => ({ type: 'local', file })));+ fireAndForget(attachmentLinks.share(oversized, limit), 'ai-email-draft');},onRemoveAttachment: (attachment: DraftFormAttachment) => {if (uiDisabled()) return;@@ -398,7 +427,11 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {disabled: () => isSending() || uiDisabled(),// Send waits for files the user just added to finish becoming documents.primaryActionDisabled: () =>- isSending() || uiDisabled() || attachments.uploading() || !sendingLink(),+ isSending() ||+ uiDisabled() ||+ attachments.uploading() ||+ attachmentLinks.uploading() ||+ !sendingLink(),isSending,isSavingDraft: () => false,hasDraft: () => false,diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex fe37d74b4c..b20bedf70e 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -973,9 +973,12 @@ removable file pill under the body once its name resolves. The card's paperclipuploaded 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 theeditor 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.+could not be attached. Attachments together may total the sending inbox's limit+(18 MB on Gmail, 25 MB on Outlook): a picked or dropped file that would pass it+opens the same confirmation as the email composer, offering to upload it to Macro and link it from the body as a public+view-only document instead; Cancel adds nothing, and files that fit still+attach. 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 — pollwith `evaluate_script`. Do not wait on response text: the page displaysdiff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex d61c3deaf0..a8c377e516 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -392,6 +392,13 @@ During send or discard, its sender and scheduling controls cannot change the opeAttachments that can be opened are buttons named by their filename; Tab to oneand press Enter or Space. Removal is a separate button named `Remove <filename>`.Removing a forwarded file keeps the received original.+Files that would push the email over the sending inbox's delivery limit (18 MB+on Gmail, 25 MB on Outlook) are not attached:+a confirmation (a drawer on phones) offers to upload them to Macro and share+view-only links instead. Confirming inserts one link per file at the end of the+written message, above a reply's quoted thread, and the draft autosaves; Cancel+adds nothing. Files that fit still attach, and the same check covers files+dropped onto the body.To forward from another inbox, open Forward, expand the forwarding envelope ondesktop, and select a different account in From (already visible on mobile).Forwarded files must remain attached after switching to an owned or delegated