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(calendar): forward an event by email with its .ics attached (#8555)
gbirmanaf2f466fdcbf
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex d59f1a479d..f7e1a881a2 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -400,11 +400,27 @@ registerComponent('email-compose', (params) => {typeof params.initialInboxId === 'string'? params.initialInboxId: undefined;+ const initialSubject =+ typeof params.initialSubject === 'string'+ ? params.initialSubject+ : undefined;+ const initialBodyText =+ typeof params.initialBodyText === 'string'+ ? params.initialBodyText+ : undefined;+ const initialAttachments = Array.isArray(params.initialAttachments)+ ? params.initialAttachments.filter(+ (value): value is File => value instanceof File+ )+ : undefined;return (<EmailComposedraftId={draftID}initialTo={initialTo}initialInboxId={initialInboxId}+ initialSubject={initialSubject}+ initialBodyText={initialBodyText}+ initialAttachments={initialAttachments}/>);});diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsxindex ac24ca3dcb..cb6f7c9126 100644--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx@@ -11,6 +11,7 @@ import { handleOpenEventOutsidePress } from '@app/features/calendar/utils/open-eimport { TeamEventDetails } from '@app/features/calendar-team/components/team-event-details';import { EventGuests } from '@app/features/calendar-view/components/EventGuests';import { EventRsvpSection } from '@app/features/calendar-view/components/EventRsvpSection';+import { useForwardEventEmail } from '@app/features/calendar-view/components/use-forward-event-email';import { useOpenEventComposer } from '@app/features/calendar-view/components/use-open-event-composer';import { copyCalendarEventMention } from '@app/features/calendar-view/copy-event-mention';import { downloadCalendarEventIcs } from '@app/features/calendar-view/download-event-ics';@@ -19,6 +20,7 @@ import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';import { openExternalUrl } from '@core/util/url';import { Popover } from '@kobalte/core/popover';+import ArrowBendUpRightIcon from '@phosphor/arrow-bend-up-right.svg';import DownloadSimpleIcon from '@phosphor/download-simple.svg';import ExclamationIcon from '@phosphor/exclamation-mark.svg';import LinkIcon from '@phosphor/link.svg';@@ -186,6 +188,12 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {openEventComposer({ event: props.event });props.onOpenChange(false);};+ const forwardEventEmail = useForwardEventEmail();+ const forwardByEmail = () =>+ forwardEventEmail(props.event, {+ timeFormat: props.timeFormat,+ closeDetails: () => props.onOpenChange(false),+ });return (<MobileDrawer@@ -238,6 +246,16 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {><DownloadSimpleIcon /></Button>+ <Button+ aria-label="Forward by email"+ variant="ghost"+ size="icon-md"+ depth={3}+ class="size-11 bg-ink/6 text-ink-muted [&_svg]:size-5"+ onClick={forwardByEmail}+ >+ <ArrowBendUpRightIcon />+ </Button></Show><Show when={canModify()}><Button@@ -434,6 +452,12 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {openEventComposer({ event: props.event });props.onOpenChange(false);};+ const forwardEventEmail = useForwardEventEmail();+ const forwardByEmail = () =>+ forwardEventEmail(props.event, {+ timeFormat: props.timeFormat,+ closeDetails: () => props.onOpenChange(false),+ });return (<Popover@@ -507,6 +531,16 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {><DownloadSimpleIcon /></Button>+ <Button+ aria-label="Forward by email"+ variant="ghost"+ size="icon-sm"+ depth={3}+ class="text-ink-muted [&_svg]:size-4"+ onClick={forwardByEmail}+ >+ <ArrowBendUpRightIcon />+ </Button></Show><Show when={canModify()}><Buttondiff --git a/apps/web/src/features/calendar-view/components/use-forward-event-email.test.ts b/apps/web/src/features/calendar-view/components/use-forward-event-email.test.tsnew file mode 100644index 0000000000..49dbed02c9--- /dev/null+++ b/apps/web/src/features/calendar-view/components/use-forward-event-email.test.ts@@ -0,0 +1,87 @@+/**+ * @vitest-environment jsdom+ */++import {+ type CalendarEvent,+ DEFAULT_GUEST_POLICY,+ NO_VIEWER_CAPABILITIES,+} from '@app/features/calendar/types';+import { err, ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useForwardEventEmail } from './use-forward-event-email';++const mocks = vi.hoisted(() => ({+ openWithSplit: vi.fn(),+ fetchIcs: vi.fn(),+ failure: vi.fn(),+}));++vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: mocks.openWithSplit }),+}));+vi.mock('@queries/calendar/ics', () => ({+ fetchCalendarEventIcs: mocks.fetchIcs,+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: mocks.failure },+}));++const event: CalendarEvent = {+ id: '["event","occurrence"]',+ eventId: 'event',+ occurrenceKey: 'occurrence',+ isCancelled: false,+ isReadOnly: false,+ guestPolicy: DEFAULT_GUEST_POLICY,+ viewerCan: NO_VIEWER_CAPABILITIES,+ attendees: [],+ recurrenceLines: [],+ sourceCalendarIds: [],+ title: 'Design review',+ start: '2026-10-23T14:00:00.000Z',+ end: '2026-10-23T15:00:00.000Z',+ allDay: false,+ calendar: { id: 'calendar', name: 'Gab', color: 'orange' },+ visibleCalendars: [],+};++beforeEach(() => vi.clearAllMocks());++describe('useForwardEventEmail', () => {+ it('closes the details and opens an unaddressed email with the event file attached', async () => {+ const ics = new Blob(['BEGIN:VCALENDAR'], { type: 'text/calendar' });+ mocks.fetchIcs.mockResolvedValue(ok(ics));+ const closeDetails = vi.fn();++ await useForwardEventEmail()(event, {+ timeFormat: '12-hour',+ closeDetails,+ });++ expect(closeDetails).toHaveBeenCalledOnce();+ expect(mocks.fetchIcs).toHaveBeenCalledWith('event');+ expect(mocks.openWithSplit).toHaveBeenCalledOnce();+ const [content, options] = mocks.openWithSplit.mock.calls[0];+ expect(options).toEqual({ preferNewSplit: true, allowDuplicate: true });+ expect(content.params.initialTo).toBeUndefined();+ expect(content.params.initialSubject).toBe('Design review');+ expect(content.params.initialBodyText).toMatch(/^Design review\nWhen: /);+ const [file] = content.params.initialAttachments;+ expect(file.name).toBe('Design review.ics');+ expect(file.type).toBe('text/calendar');+ expect(file.size).toBe(ics.size);+ });++ it('opens no composer and says so when the event file cannot be fetched', async () => {+ mocks.fetchIcs.mockResolvedValue(err([{ code: 'NOT_FOUND' }]));++ await useForwardEventEmail()(event, {+ timeFormat: '12-hour',+ closeDetails: vi.fn(),+ });++ expect(mocks.failure).toHaveBeenCalledWith('Failed to forward event');+ expect(mocks.openWithSplit).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/calendar-view/components/use-forward-event-email.ts b/apps/web/src/features/calendar-view/components/use-forward-event-email.tsnew file mode 100644index 0000000000..0d58d24638--- /dev/null+++ b/apps/web/src/features/calendar-view/components/use-forward-event-email.ts@@ -0,0 +1,66 @@+import type {+ CalendarEvent,+ CalendarTimeFormat,+} from '@app/features/calendar/types';+import {+ eventDisplayTitle,+ eventForwardSummary,+} from '@app/features/calendar/utils/event-forward-summary';+import { EMAIL_COMPOSE_TO_INPUT_ID } from '@app/features/email-compose/core/constants';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { toast } from '@core/component/Toast/Toast';+import { triggerFocusInput } from '@core/directive/focusInput';+import { Telemetry } from '@macro-inc/observability';+import { fetchCalendarEventIcs } from '@queries/calendar/ics';++/**+ * Opens a new email that passes the event on, as Gmail forwards an+ * invitation: no recipients, the title as subject, a summary in the body and+ * the event's `.ics` attached. Like Email guests, it closes the details+ * first, since closing hands focus back to the calendar chip and the+ * composer's To field has to win that exchange. Without the file there is+ * nothing to forward, so a failed fetch opens no composer and shows a toast,+ * as a failed Download .ics does.+ */+export function useForwardEventEmail() {+ const { openWithSplit } = useSplitLayout();++ return (+ event: CalendarEvent,+ options: { timeFormat: CalendarTimeFormat; closeDetails: () => void }+ ) =>+ Telemetry.span('calendar.forward_event', async (span) => {+ span.setAttr('calendar.event_id', event.eventId);+ options.closeDetails();+ // Focus the To field within this gesture so the iOS keyboard opens; the+ // composer mounts after the file arrives, so this waits for the input.+ triggerFocusInput(() =>+ document.getElementById(EMAIL_COMPOSE_TO_INPUT_ID)+ );+ const ics = await fetchCalendarEventIcs(event.eventId);+ if (ics.isErr()) {+ span.error('Calendar event .ics fetch failed');+ toast.failure('Failed to forward event');+ return;+ }+ span.setAttr('calendar.ics_bytes', ics.value.size);+ const title = eventDisplayTitle(event);+ openWithSplit(+ {+ type: 'component',+ id: 'email-compose',+ params: {+ initialSubject: title,+ initialBodyText: eventForwardSummary(event, options.timeFormat),+ initialAttachments: [+ new File([ics.value], `${title}.ics`, { type: 'text/calendar' }),+ ],+ },+ preserveParams: true,+ },+ // A composer already open holds another message; reusing it would+ // drop this one's subject, body and file.+ { preferNewSplit: true, allowDuplicate: true }+ );+ });+}diff --git a/apps/web/src/features/calendar-view/download-event-ics.ts b/apps/web/src/features/calendar-view/download-event-ics.tsindex 9f9fd8dc57..337683b34a 100644--- a/apps/web/src/features/calendar-view/download-event-ics.ts+++ b/apps/web/src/features/calendar-view/download-event-ics.ts@@ -1,4 +1,5 @@import type { CalendarEvent } from '@app/features/calendar/types';+import { eventDisplayTitle } from '@app/features/calendar/utils/event-forward-summary';import { toast } from '@core/component/Toast/Toast';import { downloadFile } from '@filesystem/download';import { fetchCalendarEventIcs } from '@queries/calendar/ics';@@ -10,8 +11,5 @@ export async function downloadCalendarEventIcs(event: CalendarEvent) {toast.failure('Failed to download event');return;}- await downloadFile(- file.value,- `${event.title.trim() || 'Untitled event'}.ics`- );+ await downloadFile(file.value, `${eventDisplayTitle(event)}.ics`);}diff --git a/apps/web/src/features/calendar/components/EventDetails.tsx b/apps/web/src/features/calendar/components/EventDetails.tsxindex d28b6207f1..9fa96a5a61 100644--- a/apps/web/src/features/calendar/components/EventDetails.tsx+++ b/apps/web/src/features/calendar/components/EventDetails.tsx@@ -42,11 +42,6 @@ import {} from 'solid-js';import { Dynamic } from 'solid-js/web';import type { CalendarEvent, CalendarTimeFormat } from '../types';-import {- isSameLocalDate,- isTimedPointEvent,- parseLocalDate,-} from '../utils/calendar-date';import {parseMacroAppLink,sanitizeCalendarDescription,@@ -65,25 +60,17 @@ import {REMINDER_METHOD_POPUP,resolveReminderOverrides,} from '../utils/event-reminders';+import {+ formatEventSchedule,+ parseCalendarDate,+} from '../utils/event-schedule';import {calendarMacroCallUrl,removeCalendarMacroCall,} from '../utils/macro-call-link';-import { formatRecurrenceDescription } from '../utils/recurrence';-import {- CALENDAR_TIME_FORMAT_OPTIONS,- formatCalendarTime,-} from '../utils/time-format';--const formatDate = new Intl.DateTimeFormat(undefined, {- weekday: 'short',- month: 'long',- day: 'numeric',-});-const formatShortDate = new Intl.DateTimeFormat(undefined, {- month: 'short',- day: 'numeric',-});+import { eventRecurrenceDescription } from '../utils/recurrence';+import { CALENDAR_TIME_FORMAT_OPTIONS } from '../utils/time-format';+const ATTENDEE_RESPONSE = {accepted: {label: 'Accepted',@@ -313,34 +300,6 @@ function ScrollableAttendeeList(props: { attendees: CalendarAttendee[] }) {);}-function parseCalendarDate(value: string) {- return parseLocalDate(value) ?? new Date(value);-}--function formatEventSchedule(- event: CalendarEvent,- timeFormat: CalendarTimeFormat-) {- const start = parseCalendarDate(event.start);- const end = parseCalendarDate(event.end);-- if (event.allDay) {- const inclusiveEnd = new Date(end);- inclusiveEnd.setDate(inclusiveEnd.getDate() - 1);- return isSameLocalDate(start, inclusiveEnd)- ? `${formatDate.format(start)} · All day`- : `${formatShortDate.format(start)}–${formatShortDate.format(inclusiveEnd)} · All day`;- }-- if (isTimedPointEvent(event)) {- return `${formatDate.format(start)} · ${formatCalendarTime(start, timeFormat)} · No duration`;- }-- return isSameLocalDate(start, end)- ? `${formatDate.format(start)} · ${formatCalendarTime(start, timeFormat)}–${formatCalendarTime(end, timeFormat)}`- : `${formatDate.format(start)}, ${formatCalendarTime(start, timeFormat)}–${formatDate.format(end)}, ${formatCalendarTime(end, timeFormat)}`;-}-/*** The location row. A phone number written into the location becomes a call* link, so a dial-in number takes one click instead of being retyped into a@@ -542,17 +501,9 @@ export function EventDetails(props: {}openExternalUrl(anchor.href);});- const recurrenceDescription = createMemo(() => {- const description = formatRecurrenceDescription(- props.event.recurrenceLines- );- if (description) return description;-- return props.event.recurrenceLines.length > 0 ||- props.event.recurrenceId !== undefined- ? 'Recurring event'- : undefined;- });+ const recurrenceDescription = createMemo(() =>+ eventRecurrenceDescription(props.event)+ );return (<div class="ph-no-capture grid min-w-0 grid-cols-[1.25rem_minmax(0,1fr)] gap-x-4 gap-y-5 p-1 text-sm text-ink-muted sm:grid-cols-[1rem_minmax(0,1fr)] sm:gap-x-3 sm:gap-y-3 sm:text-xs">diff --git a/apps/web/src/features/calendar/utils/calendar-description.ts b/apps/web/src/features/calendar/utils/calendar-description.tsindex a76aa16726..80cd612f71 100644--- a/apps/web/src/features/calendar/utils/calendar-description.ts+++ b/apps/web/src/features/calendar/utils/calendar-description.ts@@ -58,6 +58,31 @@ export function calendarDescriptionToEditorHtml(raw: string): string {return doc.body.innerHTML;}+/**+ * The description as plain text, as an `.ics` export carries it: one line per+ * paragraph, line break and list item, and a link's address after its text+ * when the text does not already show it.+ */+export function calendarDescriptionText(raw: string): string {+ const safe = sanitizeCalendarDescription(raw);+ if (!safe) return '';+ const doc = parseHtml(safe);+ for (const anchor of doc.body.querySelectorAll('a[href]')) {+ const href = anchor.getAttribute('href') ?? '';+ const text = anchor.textContent?.trim() ?? '';+ if (text !== href) anchor.append(text ? ` (${href})` : href);+ }+ for (const lineBreak of doc.body.querySelectorAll('br')) {+ lineBreak.replaceWith('\n');+ }+ for (const item of doc.body.querySelectorAll('li')) item.prepend('- ');+ for (const block of doc.body.querySelectorAll('p, li')) block.append('\n');+ return (doc.body.textContent ?? '')+ .replace(/[ \t]+\n/g, '\n')+ .replace(/\n{3,}/g, '\n\n')+ .trim();+}+/*** The description to store for the editor's current content. Document* mentions become plain Macro links, every other mention keeps only itsdiff --git a/apps/web/src/features/calendar/utils/event-attribution.ts b/apps/web/src/features/calendar/utils/event-attribution.tsindex 79f55ab9de..528d5a915d 100644--- a/apps/web/src/features/calendar/utils/event-attribution.ts+++ b/apps/web/src/features/calendar/utils/event-attribution.ts@@ -58,7 +58,10 @@ function sameAsCalendar(person: CalendarPerson, calendar: CalendarSource) {);}-function findOrganizer(event: CalendarEvent): CalendarPerson | undefined {+/** Who organizes the event, whether or not event details show them. */+export function findOrganizer(+ event: CalendarEvent+): CalendarPerson | undefined {const organizerAttendee = event.attendees.find((attendee) => attendee.isOrganizer);diff --git a/apps/web/src/features/calendar/utils/event-forward-summary.test.ts b/apps/web/src/features/calendar/utils/event-forward-summary.test.tsnew file mode 100644index 0000000000..8ee459fa86--- /dev/null+++ b/apps/web/src/features/calendar/utils/event-forward-summary.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it, vi } from 'vitest';+import {+ type CalendarEvent,+ DEFAULT_GUEST_POLICY,+ NO_VIEWER_CAPABILITIES,+} from '../types';+import { eventForwardSummary } from './event-forward-summary';++vi.hoisted(() => {+ process.env.TZ = 'America/New_York';+});++function event(overrides: Partial<CalendarEvent>): CalendarEvent {+ return {+ id: '["event","occurrence"]',+ eventId: 'event',+ occurrenceKey: 'occurrence',+ isCancelled: false,+ isReadOnly: false,+ guestPolicy: DEFAULT_GUEST_POLICY,+ viewerCan: NO_VIEWER_CAPABILITIES,+ attendees: [],+ recurrenceLines: [],+ sourceCalendarIds: [],+ title: 'Design review',+ start: '2026-10-23T14:00:00.000Z',+ end: '2026-10-23T15:00:00.000Z',+ allDay: false,+ calendar: {+ id: 'calendar',+ name: 'Gab',+ color: 'orange',+ emailAddress: '[email protected]',+ isPrimary: true,+ },+ visibleCalendars: [],+ ...overrides,+ };+}++describe('eventForwardSummary', () => {+ it('writes the time in the viewer zone with the location, organizer and description as text', () => {+ const summary = eventForwardSummary(+ event({+ location: 'Room 4',+ organizerName: 'Jacob Lee',+ organizerEmail: '[email protected]',+ description:+ '<p>Agenda in <a href="https://example.com/doc">the doc</a></p><ul><li>Scope</li><li>Dates</li></ul>',+ }),+ '12-hour'+ );++ expect(summary).toBe(+ [+ 'Design review',+ 'When: Fri, October 23 · 10:00 AM–11:00 AM (EDT)',+ 'Where: Room 4',+ 'Organizer: Jacob Lee <[email protected]>',+ '',+ 'Agenda in the doc (https://example.com/doc)',+ '- Scope',+ '- Dates',+ ].join('\n')+ );+ });++ it('describes a recurring all-day event without a zone', () => {+ const summary = eventForwardSummary(+ event({+ title: ' ',+ allDay: true,+ start: '2026-10-26',+ end: '2026-10-27',+ recurrenceLines: ['RRULE:FREQ=WEEKLY;BYDAY=MO'],+ description: 'Bring a laptop\nand a charger',+ }),+ '24-hour'+ );++ expect(summary).toBe(+ [+ 'Untitled event',+ 'When: Mon, October 26 · All day',+ 'Repeats: Weekly on Monday',+ '',+ 'Bring a laptop',+ 'and a charger',+ ].join('\n')+ );+ });++ it('leaves out the guest list and every join link', () => {+ const callUrl = 'https://macro.com/app/meet/AbCdEfGhIjKlMnOpQr';+ const summary = eventForwardSummary(+ event({+ attendees: [+ {+ email: '[email protected]',+ displayName: 'Guest Person',+ isOrganizer: false,+ isSelf: false,+ isOptional: false,+ responseStatus: 'accepted',+ },+ ],+ conferenceUrl: 'https://meet.google.com/abc-defg-hij',+ conferenceProvider: 'google_meet',+ location: callUrl,+ description: `<p>Notes</p><p>Join Macro call: <a href="${callUrl}">${callUrl}</a></p>`,+ }),+ '12-hour'+ );++ expect(summary).not.toMatch(/guest|meet\.google|macro\.com\/app\/meet/i);+ expect(summary.endsWith('\n\nNotes')).toBe(true);+ });+});diff --git a/apps/web/src/features/calendar/utils/event-forward-summary.ts b/apps/web/src/features/calendar/utils/event-forward-summary.tsnew file mode 100644index 0000000000..6b5a6e0c4c--- /dev/null+++ b/apps/web/src/features/calendar/utils/event-forward-summary.ts@@ -0,0 +1,55 @@+import { rangeTimeZoneLabel } from '../availability/zone-label';+import type { CalendarEvent, CalendarTimeFormat } from '../types';+import { calendarDescriptionText } from './calendar-description';+import { type CalendarPerson, findOrganizer } from './event-attribution';+import { formatEventSchedule, parseCalendarDate } from './event-schedule';+import {+ calendarMacroCallUrl,+ removeCalendarMacroCall,+} from './macro-call-link';+import { eventRecurrenceDescription } from './recurrence';++/** What an event is called in a file name or an email subject. */+export function eventDisplayTitle(event: Pick<CalendarEvent, 'title'>) {+ return event.title.trim() || 'Untitled event';+}++function personLabel(person: CalendarPerson) {+ const name = person.displayName?.trim();+ const email = person.email?.trim();+ if (name && email && name !== email) return `${name} <${email}>`;+ return name || email;+}++/**+ * The body of an email forwarding an event: the fields its `.ics` carries, in+ * words, with the time in the viewer's zone. Like the file, it leaves out the+ * guest list and the join link.+ */+export function eventForwardSummary(+ event: CalendarEvent,+ timeFormat: CalendarTimeFormat+): string {+ const content = removeCalendarMacroCall(event, calendarMacroCallUrl(event));+ const schedule = formatEventSchedule(event, timeFormat);+ const zone = event.allDay+ ? undefined+ : rangeTimeZoneLabel([+ parseCalendarDate(event.start),+ parseCalendarDate(event.end),+ ]);+ const recurrence = eventRecurrenceDescription(event);+ const location = content.location.trim();+ const organizer = findOrganizer(event);+ const lines = [+ eventDisplayTitle(event),+ `When: ${zone ? `${schedule} (${zone})` : schedule}`,+ recurrence && `Repeats: ${recurrence}`,+ location && `Where: ${location}`,+ organizer && `Organizer: ${personLabel(organizer)}`,+ ].filter(Boolean);+ const description = calendarDescriptionText(content.description);+ return description+ ? `${lines.join('\n')}\n\n${description}`+ : lines.join('\n');+}diff --git a/apps/web/src/features/calendar/utils/event-schedule.ts b/apps/web/src/features/calendar/utils/event-schedule.tsnew file mode 100644index 0000000000..45fe2b62ba--- /dev/null+++ b/apps/web/src/features/calendar/utils/event-schedule.ts@@ -0,0 +1,45 @@+import type { CalendarEvent, CalendarTimeFormat } from '../types';+import {+ isSameLocalDate,+ isTimedPointEvent,+ parseLocalDate,+} from './calendar-date';+import { formatCalendarTime } from './time-format';++const formatDate = new Intl.DateTimeFormat(undefined, {+ weekday: 'short',+ month: 'long',+ day: 'numeric',+});+const formatShortDate = new Intl.DateTimeFormat(undefined, {+ month: 'short',+ day: 'numeric',+});++export function parseCalendarDate(value: string) {+ return parseLocalDate(value) ?? new Date(value);+}++export function formatEventSchedule(+ event: CalendarEvent,+ timeFormat: CalendarTimeFormat+) {+ const start = parseCalendarDate(event.start);+ const end = parseCalendarDate(event.end);++ if (event.allDay) {+ const inclusiveEnd = new Date(end);+ inclusiveEnd.setDate(inclusiveEnd.getDate() - 1);+ return isSameLocalDate(start, inclusiveEnd)+ ? `${formatDate.format(start)} · All day`+ : `${formatShortDate.format(start)}–${formatShortDate.format(inclusiveEnd)} · All day`;+ }++ if (isTimedPointEvent(event)) {+ return `${formatDate.format(start)} · ${formatCalendarTime(start, timeFormat)} · No duration`;+ }++ return isSameLocalDate(start, end)+ ? `${formatDate.format(start)} · ${formatCalendarTime(start, timeFormat)}–${formatCalendarTime(end, timeFormat)}`+ : `${formatDate.format(start)}, ${formatCalendarTime(start, timeFormat)}–${formatDate.format(end)}, ${formatCalendarTime(end, timeFormat)}`;+}diff --git a/apps/web/src/features/calendar/utils/recurrence.ts b/apps/web/src/features/calendar/utils/recurrence.tsindex 810c99ceef..b7ab11d88b 100644--- a/apps/web/src/features/calendar/utils/recurrence.ts+++ b/apps/web/src/features/calendar/utils/recurrence.ts@@ -1,6 +1,7 @@import { formatOrdinal, plural } from '@core/util/string';import { TZDateMini } from '@date-fns/tz';import { format } from 'date-fns';+import type { CalendarEvent } from '../types';const POSITIVE_INTEGER_REGEX = /^\d+$/;const BYDAY_VALUE_REGEX = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/i;@@ -688,3 +689,15 @@ export function defaultCustomConfig(start: Date): RecurrenceConfig {ends: NEVER,};}++/** How an event repeats, as event details describe it; undefined for a one-off event. */+export function eventRecurrenceDescription(+ event: Pick<CalendarEvent, 'recurrenceLines' | 'recurrenceId'>+): string | undefined {+ const description = formatRecurrenceDescription(event.recurrenceLines);+ if (description) return description;++ return event.recurrenceLines.length > 0 || event.recurrenceId !== undefined+ ? 'Recurring event'+ : undefined;+}diff --git a/apps/web/src/features/email-compose/primitives/email-composer.test.ts b/apps/web/src/features/email-compose/primitives/email-composer.test.tsindex 824285b283..a0cbc42471 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.test.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.test.ts@@ -1,3 +1,4 @@+import { createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { message } from '../../email-message/tests/messages';import { decodeBase64Utf8 } from '../core/decode-base64';@@ -255,6 +256,83 @@ describe('standalone compose controller', () => {}});+ it('prefills a new message whose generated attachment saves with the first edit', async () => {+ const context = createComposeContext();+ const ics = new File(['BEGIN:VCALENDAR'], 'Team sync.ics', {+ type: 'text/calendar',+ });+ const root = mountEmailComposer(context, undefined, {+ initialSubject: 'Team sync',+ initialBodyText: 'Team sync\nWhere: Room 4',+ initialAttachments: [ics],+ });+ try {+ expect(root.state.context.subject()).toBe('Team sync');+ expect(root.state.context.initialHtml()).toContain('Where: Room 4');+ expect(root.state.context.attachments()).toEqual([]);++ root.state.context.onEditorInitialized?.(root.editor);+ root.state.context.onEditorInitialized?.(root.editor);+ await vi.advanceTimersByTimeAsync(600);+ expect(root.state.context.attachments()).toEqual([+ { type: 'local', file: ics },+ ]);+ expect(root.state.draftDirty()).toBe(false);+ expect(context.drafts.saveDraft).not.toHaveBeenCalled();++ root.edit('Passing this on', 'Team sync');+ await vi.advanceTimersByTimeAsync(600);+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();+ expect(context.attachmentStorage.uploadAttachments).toHaveBeenCalledWith(+ expect.objectContaining({ attachments: [ics] })+ );+ } finally {+ root.dispose();+ }+ });++ it('attaches a generated file once the outbox stops locking the composer', async () => {+ const context = createComposeContext();+ const [locked, setLocked] = createSignal(true);+ context.delivery.sendLocked = locked;+ const ics = new File(['BEGIN:VCALENDAR'], 'Team sync.ics');+ const root = mountEmailComposer(context, undefined, {+ initialAttachments: [ics],+ });+ try {+ root.state.context.onEditorInitialized?.(root.editor);+ await vi.advanceTimersByTimeAsync(0);+ expect(root.state.context.attachments()).toEqual([]);++ setLocked(false);+ await vi.advanceTimersByTimeAsync(0);+ expect(root.state.context.attachments()).toEqual([+ { type: 'local', file: ics },+ ]);+ } finally {+ root.dispose();+ }+ });++ it('offers a generated attachment over the inbox limit as a link, like a picked file', async () => {+ const context = createComposeContext();+ const oversized = new File(['x'], 'Team sync.ics');+ Object.defineProperty(oversized, 'size', { value: 30_000_000 });+ const root = mountEmailComposer(context, undefined, {+ initialAttachments: [oversized],+ });+ try {+ root.state.context.onEditorInitialized?.(root.editor);+ await vi.advanceTimersByTimeAsync(0);+ expect(root.state.context.attachments()).toEqual([]);+ expect(context.notices.confirm).toHaveBeenCalledWith(+ expect.objectContaining({ confirmLabel: 'Share link' })+ );+ } finally {+ root.dispose();+ }+ });+it('rejects an empty body in an otherwise ready composer and sends once content is added', async () => {const context = createComposeContext();const root = mountEmailComposer(context);diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.tsindex d20fb1aef4..4c9b26a11d 100644--- a/apps/web/src/features/email-compose/primitives/email-composer.ts+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts@@ -132,6 +132,17 @@ export type EmailComposerOptions = {initialTo?: string[];/** Initial sending inbox for new messages. Existing drafts retain their sender. */initialInboxId?: string;+ /** Prefill for the subject of a new message. */+ initialSubject?: string;+ /** Prefill for the body of a new message, as plain text. */+ initialBodyText?: string;+ /**+ * Files the app generated for a new message, such as an event's `.ics`.+ * They attach as picked files do once the editor holds the body; like the+ * other prefills, they are not an edit, so no draft exists until the user+ * changes something.+ */+ initialAttachments?: File[];};export function createEmailComposer(props: EmailComposerOptions) {@@ -164,6 +175,10 @@ export function createEmailComposer(props: EmailComposerOptions) {form.setSelectedInbox(props.initialInboxId);}+ if (!initialDraftId && props.initialSubject) {+ form.setSubject(props.initialSubject);+ }+if (props.localAttachments) {form.attachments.clear();for (const attachment of props.localAttachments)@@ -625,7 +640,7 @@ export function createEmailComposer(props: EmailComposerOptions) {editorFiles: props.editorFiles,});- const handleAddAttachments = async (files: File[]) => {+ const addAttachments = async (files: File[], { edit }: { edit: boolean }) => {if (persistencePaused()) return;if (await refuseAttachmentsOffline(props.connectivity, props.notices))return;@@ -642,13 +657,40 @@ export function createEmailComposer(props: EmailComposerOptions) {for (const file of attachable) {form.attachments.add({ type: 'local', file });}- if (attachable.length > 0) markDirtyAndScheduleSave();+ if (edit && attachable.length > 0) markDirtyAndScheduleSave();try {await attachmentLinks.share(oversized, limit);} catch (error) {props.notices.reportError(error);}};+ const handleAddAttachments = (files: File[]) =>+ addAttachments(files, { edit: true });++ // Generated files wait for the editor, which a link offer writes into, and+ // for the composer to accept attachments: the outbox locks it until it loads.+ const [initialAttachmentsPending, setInitialAttachmentsPending] =+ createSignal(false);+ let editorInitialized = false;+ const addInitialAttachments = () => {+ if (editorInitialized) return;+ editorInitialized = true;+ if (!initialDraftId && props.initialAttachments?.length)+ setInitialAttachmentsPending(true);+ };+ createEffect(+ on(+ () => initialAttachmentsPending() && !persistencePaused(),+ (ready) => {+ if (!ready) return;+ setInitialAttachmentsPending(false);+ fireAndForget(+ addAttachments(props.initialAttachments ?? [], { edit: false }),+ 'email-compose'+ );+ }+ )+ );const handleRemoveAttachment = async (attachment: DraftFormAttachment) => {if (persistencePaused()) return;@@ -1332,7 +1374,11 @@ export function createEmailComposer(props: EmailComposerOptions) {}const draft = form.draft;- if (!draft) return;+ if (!draft) {+ return !initialDraftId && props.initialBodyText+ ? plainTextToHtml(props.initialBodyText)+ : undefined;+ }if (draft.body_html_sanitized) {return decodeBase64Utf8(draft.body_html_sanitized);@@ -1407,6 +1453,7 @@ export function createEmailComposer(props: EmailComposerOptions) {// EditorcaptureEditor: setEditor,+ onEditorInitialized: addInitialAttachments,// ActionsonSend: () => fireAndForget(onSubmit(), 'email-compose'),diff --git a/apps/web/src/features/email-compose/tests/composer.ts b/apps/web/src/features/email-compose/tests/composer.tsindex 59f137a48f..f8dac480f1 100644--- a/apps/web/src/features/email-compose/tests/composer.ts+++ b/apps/web/src/features/email-compose/tests/composer.ts@@ -13,7 +13,15 @@ import { createEmailEditor, setEmailEditorText } from './editor';export function mountEmailComposer(context: EmailComposeContext,host?: EmailComposeHost,- seed?: Pick<EmailComposerOptions, 'draft' | 'draftId' | 'initialInboxId'>+ seed?: Pick<+ EmailComposerOptions,+ | 'draft'+ | 'draftId'+ | 'initialInboxId'+ | 'initialSubject'+ | 'initialBodyText'+ | 'initialAttachments'+ >) {const root = createRoot((dispose) => ({dispose,diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsxindex f0d33488db..d7a651c4a3 100644--- a/apps/web/src/features/email-compose/views/email-compose.tsx+++ b/apps/web/src/features/email-compose/views/email-compose.tsx@@ -33,6 +33,9 @@ export type EmailComposeViewProps = Pick<| 'onRecipientsChange'| 'initialTo'| 'initialInboxId'+ | 'initialSubject'+ | 'initialBodyText'+ | 'initialAttachments'> & { context: EmailComposeContext };export function EmailComposeView(props: EmailComposeViewProps) {// The split mounts one composer per initial draft. Keep this content load@@ -133,6 +136,9 @@ function LoadedEmailComposeView(onRecipientsChange: props.onRecipientsChange,initialTo: props.initialTo,initialInboxId: props.initialInboxId,+ initialSubject: props.initialSubject,+ initialBodyText: props.initialBodyText,+ initialAttachments: props.initialAttachments,});const sync = createDraftSyncStatus({drafts: composeContext.drafts,diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 03a2a620a4..f73883ad48 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -459,6 +459,15 @@ as plain text, location and organizer, never the guest list or join link. Like `is absent from teammates' out-of-office chips. Its endpoint, document storage's`GET /calendar-events/{event_id}/ics`, also exports an event shared with a channel the viewerbelongs to.+Beside it, `Forward by email` (shown under the same rule) passes the event on the way Gmail+forwards an invitation: it closes the details, fetches the same file, and opens a new email+where `Email guests` does (its own composer, even when another one is open), with no recipients, the title as subject, a plain-text summary in+the body (title, when in the viewer's zone, the repeat rule in words, location, organizer and+description, never guests or a join link) and the `.ics` attached as a picked file would be.+Nothing is saved as a draft until you edit something. The file is `METHOD:PUBLISH`, so+recipients get a copy to add to their calendar, not an invitation they can answer. If the file+cannot be fetched, no composer opens and a `Failed to forward event` toast shows; to check it,+answer the `.ics` route with an error.With the `enable-calendar-team-ooo` flag on, teammates' Google Calendar out-of-office eventsoverlay the grid as read-only chips titled `<name>: <event title>`. The sidebar's