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
fix(email): open a calendar attachment as its event without saving it to Drive (#8650)
gbirman2b743436ee2f
diff --git a/apps/web/src/features/email-message/attachment-action-adapter.test.ts b/apps/web/src/features/email-message/attachment-action-adapter.test.tsnew file mode 100644index 0000000000..bfcbe7c02d--- /dev/null+++ b/apps/web/src/features/email-message/attachment-action-adapter.test.ts@@ -0,0 +1,92 @@+import { ok } from 'neverthrow';+import { createRoot } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { createEmailAttachmentOpener } from './attachment-action-adapter';++const mocks = vi.hoisted(() => ({+ openWithSplit: vi.fn(),+ getDocument: vi.fn(),+ getMetadata: vi.fn(),+ getDownloadUrl: vi.fn(),+ downloadFile: vi.fn(),+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: mocks.openWithSplit }),+}));+vi.mock('@queries/email/integration', () => ({+ getEmailAttachmentDocument: mocks.getDocument,+ getEmailAttachmentMetadata: mocks.getMetadata,+}));+vi.mock('@queries/email/attachment', () => ({+ getEmailAttachmentDownloadUrl: mocks.getDownloadUrl,+}));+vi.mock('@queries/soup/cache', () => ({+ refetchSoupEntity: () => Promise.resolve(),+}));+vi.mock('@filesystem/download', () => ({ downloadFile: mocks.downloadFile }));++beforeEach(() => {+ mocks.getDocument.mockResolvedValue(+ ok({ attachment_id: 'pdf', document_id: 'document' })+ );+ mocks.getMetadata.mockResolvedValue(ok({}));+ mocks.getDownloadUrl.mockResolvedValue('https://files.example.com/signed');+ mocks.downloadFile.mockResolvedValue({ saved: true });+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response('BEGIN:VCALENDAR', { status: 200 }))+ );+});+afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++const opener = () => createRoot(() => createEmailAttachmentOpener());++it('saves a calendar file without filing it into Drive', async () => {+ await opener()({+ db_id: 'ics',+ filename: 'Planning.ics',+ mime_type: 'text/calendar',+ });++ expect(mocks.getDocument).not.toHaveBeenCalled();+ expect(mocks.openWithSplit).not.toHaveBeenCalled();+ expect(mocks.getDownloadUrl).toHaveBeenCalledWith('ics');+ expect(mocks.downloadFile).toHaveBeenCalledWith(+ expect.any(Blob),+ 'Planning.ics'+ );+});++it('opens a previewable file in its viewer', async () => {+ await opener()({+ db_id: 'pdf',+ filename: 'Agenda.pdf',+ mime_type: 'application/pdf',+ });++ expect(mocks.getDocument).toHaveBeenCalledWith('pdf');+ expect(mocks.openWithSplit).toHaveBeenCalledWith(+ { type: 'pdf', id: 'document' },+ { preferNewSplit: true }+ );+ expect(mocks.downloadFile).not.toHaveBeenCalled();+});++it('keeps opening other files from their Drive copy, which previews workbooks', async () => {+ await opener()({+ db_id: 'xlsx',+ filename: 'Budget.xlsx',+ mime_type:+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ });++ expect(mocks.getDocument).toHaveBeenCalledWith('xlsx');+ expect(mocks.openWithSplit).toHaveBeenCalledWith(+ { type: 'unknown', id: 'document' },+ { preferNewSplit: true }+ );+ expect(mocks.downloadFile).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/email-message/attachment-action-adapter.ts b/apps/web/src/features/email-message/attachment-action-adapter.tsindex 55bb3e069f..e486e731eb 100644--- a/apps/web/src/features/email-message/attachment-action-adapter.ts+++ b/apps/web/src/features/email-message/attachment-action-adapter.ts@@ -1,7 +1,9 @@import { useSplitLayout } from '@components/app/split-layout/layout';import { toast } from '@core/component/Toast/Toast';import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { downloadFile } from '@filesystem/download';import { Telemetry } from '@macro-inc/observability';+import { getEmailAttachmentDownloadUrl } from '@queries/email/attachment';import {getEmailAttachmentDocument,getEmailAttachmentMetadata,@@ -9,7 +11,47 @@ import {import { refetchSoupEntity } from '@queries/soup/cache';import { FileTypeMap } from '@service-storage/fileTypeMap';import type { FileType } from '@service-storage/generated/schemas/fileType';-import type { EmailAttachment } from './core/email-message';+import { ResultAsync } from 'neverthrow';+import { type EmailAttachment, isCalendarFile } from './core/email-message';++function attachmentBlockName(attachment: EmailAttachment) {+ const fileType = Object.values(FileTypeMap).findLast(+ (type) => type.mime === attachment.mime_type+ )?.extension;+ return fileType ? fileTypeToBlockName(fileType as FileType) : 'unknown';+}++async function fetchAttachmentBlob(id: string) {+ const response = await fetch(await getEmailAttachmentDownloadUrl(id));+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ return response.blob();+}++/**+ * Save an attachment through its authorized download URL. No Drive document+ * is created, so nothing lands in the viewer's files unless they ask for it.+ */+export async function downloadEmailAttachment(attachment: EmailAttachment) {+ return Telemetry.span('email.download_attachment', async (span) => {+ span.setAttr('email.attachment_id', attachment.db_id);+ const blob = await ResultAsync.fromPromise(+ fetchAttachmentBlob(attachment.db_id),+ (error) => error+ );+ if (blob.isErr()) {+ span.error('Attachment download failed');+ toast.failure('Failed to download attachment. Please try again.');+ return;+ }+ await downloadFile(+ new Blob([blob.value], {+ type: attachment.mime_type ?? blob.value.type,+ }),+ attachment.filename ?? 'attachment'+ );+ });+}+export function createEmailAttachmentOpener() {const { openWithSplit } = useSplitLayout();const openAttachment = async (attachment: EmailAttachment) => {@@ -19,6 +61,13 @@ export function createEmailAttachmentOpener() {}const dbId = attachment.db_id;if (!dbId) return;+ // Macro has no viewer for a calendar file (a message that shows its+ // event opens that instead), so a Drive copy would only say "No preview+ // available"; save the file instead of filing it into Drive.+ if (isCalendarFile(attachment.filename, attachment.mime_type)) {+ await downloadEmailAttachment(attachment);+ return;+ }const response = await getEmailAttachmentDocument(dbId);if (response.isErr()) {toast.failure('Failed to get attachment. Please try again.');@@ -45,14 +94,8 @@ export function createEmailAttachmentOpener() {Telemetry.error(error, { surface: 'email-attachment' }));- const fileType = Object.values(FileTypeMap).findLast(- (type) => type.mime === attachment.mime_type- )?.extension;- const blockName = fileType- ? fileTypeToBlockName(fileType as FileType)- : 'unknown';openWithSplit(- { type: blockName, id: document_id },+ { type: attachmentBlockName(attachment), id: document_id },{ preferNewSplit: true });};diff --git a/apps/web/src/features/email-message/components/attachment-pill.tsx b/apps/web/src/features/email-message/components/attachment-pill.tsxindex 343da53a74..291a598330 100644--- a/apps/web/src/features/email-message/components/attachment-pill.tsx+++ b/apps/web/src/features/email-message/components/attachment-pill.tsx@@ -3,6 +3,7 @@ import X from '@phosphor/x.svg';import { FileTypeMap } from '@service-storage/fileTypeMap';import { Show } from 'solid-js';import { Dynamic } from 'solid-js/web';+import { isCalendarFile } from '../core/email-message';const mimeToFileExtTypeMap = new Map<string, string>(Object.values(FileTypeMap).map((value) => [value.mime, value.extension])@@ -19,16 +20,13 @@ export function EmailAttachmentPill(props: EmailAttachmentPillProps) {let parentDiv!: HTMLDivElement;const fileType = () => {+ if (isCalendarFile(props.attachment.fileName, props.attachment.mimeType)) {+ return 'ics';+ }const mimeType = props.attachment.mimeType?.split(';')[0].trim().toLowerCase();- if (- props.attachment.fileName.toLowerCase().endsWith('.ics') ||- mimeType === 'application/ics'- ) {- return 'ics';- }return mimeType ? mimeToFileExtTypeMap.get(mimeType) : undefined;};diff --git a/apps/web/src/features/email-message/components/calendar-file-preview.tsx b/apps/web/src/features/email-message/components/calendar-file-preview.tsxnew file mode 100644index 0000000000..4b29b4d509--- /dev/null+++ b/apps/web/src/features/email-message/components/calendar-file-preview.tsx@@ -0,0 +1,59 @@+import DownloadSimple from '@phosphor/download-simple.svg';+import X from '@phosphor/x.svg';+import { Button, Dialog, Panel } from '@ui';+import { type JSX, Show } from 'solid-js';++/**+ * A calendar attachment opened from an email: the event it describes, with+ * the event's own actions, and the file itself one click away. Opening it+ * saves nothing to the viewer's files.+ */+export function CalendarFilePreview(props: {+ fileName: string;+ open: boolean;+ onClose: () => void;+ onDownload?: () => void;+ children: JSX.Element;+}) {+ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!open) props.onClose();+ }}+ position="center"+ class="w-140 max-w-full"+ >+ <Panel depth={2} class="rounded-xl">+ <Panel.Header class="flex items-center gap-2 px-6">+ <Dialog.Title class="min-w-0 flex-1 truncate text-sm font-semibold text-ink">+ {props.fileName || 'Calendar file'}+ </Dialog.Title>+ <Show when={props.onDownload}>+ <Button+ variant="outline"+ depth={3}+ onClick={() => props.onDownload?.()}+ >+ <DownloadSimple />+ Download .ics+ </Button>+ </Show>+ <Button+ label="Close"+ variant="ghost"+ size="icon-md"+ depth={3}+ class="mobile:hidden"+ onClick={() => props.onClose()}+ >+ <X />+ </Button>+ </Panel.Header>+ <Panel.Body class="max-h-[70vh] overflow-y-auto px-6 pb-3">+ {props.children}+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}diff --git a/apps/web/src/features/email-message/core/email-message.ts b/apps/web/src/features/email-message/core/email-message.tsindex 7e10d63b02..8bf2a911ab 100644--- a/apps/web/src/features/email-message/core/email-message.ts+++ b/apps/web/src/features/email-message/core/email-message.ts@@ -17,6 +17,19 @@ export interface EmailAttachment {size_bytes?: number | null;}+/** Whether a file is an iCalendar event file, by its MIME type or `.ics` name. */+export function isCalendarFile(+ fileName: string | null | undefined,+ mimeType: string | null | undefined+): boolean {+ const type = mimeType?.split(';')[0].trim().toLowerCase();+ return (+ type === 'text/calendar' ||+ type === 'application/ics' ||+ !!fileName?.toLowerCase().endsWith('.ics')+ );+}+export interface EmailDraftAttachment {upload_pending?: boolean;content_id?: string | null;diff --git a/apps/web/src/features/email-message/views/email-message.test.tsx b/apps/web/src/features/email-message/views/email-message.test.tsxindex 4359cca774..ae272c2d50 100644--- a/apps/web/src/features/email-message/views/email-message.test.tsx+++ b/apps/web/src/features/email-message/views/email-message.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen } from '@solidjs/testing-library';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';import { createSignal, type JSX } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import type { CalendarInvitation } from '../core/calendar-invitation';@@ -21,7 +21,14 @@ vi.mock('@app/features/email-message/components/collapsed-message', () => ({CollapsedMessage: () => null,}));vi.mock('@app/features/email-message/components/attachment-pill', () => ({- EmailAttachmentPill: () => null,+ EmailAttachmentPill: (props: {+ attachment: { fileName: string };+ onClick?: () => void;+ }) => (+ <button type="button" onClick={() => props.onClick?.()}>+ {props.attachment.fileName}+ </button>+ ),}));vi.mock('@core/component/ImageGalleryPreview', () => ({ImageGalleryPreview: () => null,@@ -32,10 +39,21 @@ vi.mock('../components/calendar-invite-card', () => ({}));afterEach(cleanup);+const calendarFile = {+ db_id: 'ics',+ filename: 'Planning.ics',+ mime_type: 'text/calendar',+};+const pdfFile = {+ db_id: 'pdf',+ filename: 'Agenda.pdf',+ mime_type: 'application/pdf',+};+function message(invitations: CalendarInvitation[]): EmailMessage {return {db_id: 'message',- attachments: [],+ attachments: [calendarFile, pdfFile],attachments_draft: [],attachments_forwarded: [],calendar_invitations: invitations,@@ -65,3 +83,51 @@ it('keeps invitation cards mounted when the thread refreshes the message', () =>expect(screen.getByTestId('card')).toBe(card);expect(renderInvitation).toHaveBeenCalledOnce();});++it('opens a calendar file as the event it holds and other files through the host', () => {+ const onOpenAttachment = vi.fn();+ const onDownloadAttachment = vi.fn();+ render(() => (+ <EmailMessageView+ message={message([invitationFixture])}+ renderInvitation={(_message, invitation) => (+ <div data-testid="card">{invitation.id}</div>+ )}+ onOpenAttachment={onOpenAttachment}+ onDownloadAttachment={onDownloadAttachment}+ isTouch={false}+ isPersonal={false}+ isSelected={false}+ allowHover={false}+ isExpanded+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Planning.ics' }));+ const preview = screen.getByRole('dialog');+ expect(preview.textContent).toContain(invitationFixture.id);+ fireEvent.click(screen.getByRole('button', { name: 'Download .ics' }));+ expect(onDownloadAttachment).toHaveBeenCalledWith(calendarFile);+ expect(onOpenAttachment).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));+ expect(screen.queryByRole('dialog')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Agenda.pdf' }));+ expect(onOpenAttachment).toHaveBeenCalledWith(pdfFile);+});++it('hands a calendar file without a readable event to the host', () => {+ const onOpenAttachment = vi.fn();+ render(() => (+ <EmailMessageView+ message={message([])}+ onOpenAttachment={onOpenAttachment}+ isTouch={false}+ isPersonal={false}+ isSelected={false}+ allowHover={false}+ isExpanded+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Planning.ics' }));+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(onOpenAttachment).toHaveBeenCalledWith(calendarFile);+});diff --git a/apps/web/src/features/email-message/views/email-message.tsx b/apps/web/src/features/email-message/views/email-message.tsxindex 4c3ab15b8a..4cd9155b7a 100644--- a/apps/web/src/features/email-message/views/email-message.tsx+++ b/apps/web/src/features/email-message/views/email-message.tsx@@ -10,13 +10,14 @@ import CaretRight from '@phosphor/caret-right.svg';import { Key } from '@solid-primitives/keyed';import type { JSX } from 'solid-js';import { createMemo, createSignal, For, Show } from 'solid-js';+import { CalendarFilePreview } from '../components/calendar-file-preview';import { CalendarInviteCard } from '../components/calendar-invite-card';import type { EmailMessageAction } from '../components/message-actions';import {type CalendarInvitation,groupCalendarInvitations,} from '../core/calendar-invitation';-import type { EmailAttachment } from '../core/email-message';+import { type EmailAttachment, isCalendarFile } from '../core/email-message';import { inlineContentIds, normalizeContentId } from '../core/inline-images';export interface EmailMessageViewProps {message: EmailMessage;@@ -41,6 +42,7 @@ export interface EmailMessageViewProps {onFocus?: (element: HTMLElement) => void;onReply?: (action: EmailMessageAction) => void;onOpenAttachment?: (attachment: EmailAttachment) => void;+ onDownloadAttachment?: (attachment: EmailAttachment) => void;children?: JSX.Element;}@@ -55,6 +57,19 @@ export function EmailMessageView(props: EmailMessageViewProps) {const invitationGroups = createMemo(() =>groupCalendarInvitations(props.message.calendar_invitations ?? []));+ // A calendar file whose event the message already shows opens as that+ // event; any other file goes to the host.+ const [calendarFile, setCalendarFile] = createSignal<EmailAttachment>();+ const openAttachment = (attachment: EmailAttachment) => {+ if (+ invitationGroups().length > 0 &&+ isCalendarFile(attachment.filename, attachment.mime_type)+ ) {+ setCalendarFile(attachment);+ return;+ }+ props.onOpenAttachment?.(attachment);+ };const renderInvitation = (invitation: CalendarInvitation) =>props.renderInvitation ? (props.renderInvitation(props.message, invitation)@@ -225,7 +240,7 @@ export function EmailMessageView(props: EmailMessageViewProps) {}}onClick={props.onOpenAttachment- ? () => props.onOpenAttachment?.(attachment)+ ? () => openAttachment(attachment): undefined}/>@@ -267,6 +282,24 @@ export function EmailMessageView(props: EmailMessageViewProps) {</div>{props.children}</Show>+ <Show when={calendarFile()}>+ {(file) => (+ <CalendarFilePreview+ fileName={file().filename ?? ''}+ open+ onClose={() => setCalendarFile(undefined)}+ onDownload={+ props.onDownloadAttachment+ ? () => props.onDownloadAttachment?.(file())+ : undefined+ }+ >+ <For each={invitationGroups()}>+ {(group) => renderInvitation(group.primary)}+ </For>+ </CalendarFilePreview>+ )}+ </Show></MessageCard>);}diff --git a/apps/web/src/features/email-thread/context/email-thread-view-context.tsx b/apps/web/src/features/email-thread/context/email-thread-view-context.tsxindex 0b32ce747f..eadb777f71 100644--- a/apps/web/src/features/email-thread/context/email-thread-view-context.tsx+++ b/apps/web/src/features/email-thread/context/email-thread-view-context.tsx@@ -32,6 +32,7 @@ export interface EmailThreadViewContext {renderOperation?: (message: EmailMessage) => JSX.Element;renderAvatar?: (message: EmailMessage) => JSX.Element;openAttachment?: (attachment: EmailAttachment) => void;+ downloadAttachment?: (attachment: EmailAttachment) => void;};}diff --git a/apps/web/src/features/email-thread/email-thread.tsx b/apps/web/src/features/email-thread/email-thread.tsxindex 0c7581eed2..612380aba0 100644--- a/apps/web/src/features/email-thread/email-thread.tsx+++ b/apps/web/src/features/email-thread/email-thread.tsx@@ -2,6 +2,7 @@ import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useEmail, useUserContext } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { useContacts } from '@core/user';+import { fireAndForget } from '@core/util/fireAndForget';import { createEffectOnEntityTypeNotification } from '@notifications';import { InlineFetchedEntityTagsPill } from '@property/tags';import { clearSavedDraftThreadCache } from '@queries/email/draft-cache';@@ -17,9 +18,15 @@ import { useCalendarPreferences } from '../calendar/utils/preferences';import { createEmailComposeContext } from '../email-compose/compose-adapter';import { createEmailComposeHost } from '../email-compose/compose-host-adapter';import { convertContactInfoToEmailRecipient } from '../email-compose/core/recipient-conversion';-import { createEmailAttachmentOpener } from '../email-message/attachment-action-adapter';+import {+ createEmailAttachmentOpener,+ downloadEmailAttachment,+} from '../email-message/attachment-action-adapter';import type { CalendarInvitation } from '../email-message/core/calendar-invitation';-import type { EmailMessage } from '../email-message/core/email-message';+import type {+ EmailAttachment,+ EmailMessage,+} from '../email-message/core/email-message';import { operationSettled } from '../email-message/core/message-operation';import { EmailMessageOperation } from '../email-message/email-message-operation';import { createEmailRenderingContext } from '../email-message/rendering-adapter';@@ -125,6 +132,9 @@ export function EmailThread(props: EmailThreadProps) {/>),openAttachment: createEmailAttachmentOpener(),+ downloadAttachment: (attachment: EmailAttachment) => {+ fireAndForget(downloadEmailAttachment(attachment), 'email-attachment');+ },renderAvatar: (message: EmailMessage) => (<EmailSenderIcon message={message} />),diff --git a/apps/web/src/features/email-thread/views/message-container.tsx b/apps/web/src/features/email-thread/views/message-container.tsxindex 0b411fd4d2..f0b0099021 100644--- a/apps/web/src/features/email-thread/views/message-container.tsx+++ b/apps/web/src/features/email-thread/views/message-container.tsx@@ -131,6 +131,7 @@ export function MessageContainer(props: MessageContainerProps) {}}onFocus={scrollFocusedCardIntoView}onOpenAttachment={rendering.openAttachment}+ onDownloadAttachment={rendering.downloadAttachment}onReply={context.permissions().isOwner? (replyType) =>diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex b603cd6ac1..751474114d 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -1117,9 +1117,10 @@ is an accessible disclosure that starts closed and stays open across unchangedpermission refreshes and window refocus on desktop and mobile; attachments remain below it.ICS attachments show a calendar icon in the attachment pill and file headers ondesktop and mobile, including when the email uses `application/ics` or a-parameterized `text/calendar` MIME type. Opening the attachment still shows the-generic file viewer with download and share actions; the invitation card above-is the event preview.+parameterized `text/calendar` MIME type. Opening the attachment of a message that shows a+card opens a dialog (a drawer on phones) with the same card, so its RSVP or `Add to calendar`+works there, and `Download .ics`, which saves the file without adding it to Drive. A calendar+file with no card (nothing Macro could read) downloads directly.Related recurring components are grouped behind their own disclosure. Only mail syncedafter the feature shipped gets a card; older invitations render as plain email.A newly arrived scheduling update shows RSVP and Join only once its calendar state hasdiff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 4ded416a46..0ea3b058b6 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -85,6 +85,11 @@ the send button's pending state. Switching the senderinbox copies the draft and attachments into the destination; wait for completionbefore sending. If the copy is interrupted, use retry or keep the original.+Opening an attachment opens it in a split from its Drive copy, except a+calendar file: it opens its event (see the calendar invitations section of the+calendar guide), or downloads when Macro could not read one, and creates no+Drive file.+Imported Outlook attachments keep their provider identity, including inlineimages. Cloud-reference attachment chips open the original Outlook message.Forwarding a message with cloud references shows a notice to share those links