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 invitations when guests cannot add guests (#9035)
gbirman2908f110c024
diff --git a/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsxindex df7a614308..5aec654866 100644--- a/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsx+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsx@@ -1,18 +1,37 @@// @vitest-environment jsdomimport type { CalendarEventFormController } from '@app/features/calendar/components/composer/create-calendar-event-form-controller';+import type { CalendarEvent } from '@app/features/calendar/types';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { createSignal } from 'solid-js';+import { createSignal, type JSX } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import { EventComposerSplit } from './EventComposerSplit';const mocks = vi.hoisted(() => ({flag: () => ({ loading: true, enabled: false }),+ canForward: false,+ controllerEnabled: undefined as (() => boolean) | undefined,}));vi.mock('@app/features/meetings/use-quick-calls-flag', () => ({useQuickCallsFlag: () => () => mocks.flag(),}));vi.mock('@app/features/calendar/hooks/use-calendar-ui-flag', () => ({useCalendarGuestInvitesFlag: () => () => false,+ useCalendarInvitationForwardFlag: () => () => true,+}));+vi.mock('@app/features/calendar/hooks/create-guest-invite-controller', () => ({+ createGuestInviteController: (+ _event: unknown,+ _enabled: () => boolean,+ forwardEnabled: () => boolean+ ) => {+ mocks.controllerEnabled = forwardEnabled;+ return { canForward: () => mocks.canForward };+ },+}));+vi.mock('@app/features/calendar-view/components/EventGuests', () => ({+ EventForwardInvitationAction: () => (+ <button type="button">Forward invitation</button>+ ),}));vi.mock('@components/app/split-layout/layoutUtils', () => ({useSplitPanelOrThrow: () => ({@@ -33,8 +52,12 @@ vi.mock('@app/features/calendar/hooks/use-event-editor', () => ({}),}));vi.mock('@app/features/calendar/components/composer/EventForm', () => ({- EventForm: (props: { controller: CalendarEventFormController }) => (+ EventForm: (props: {+ controller: CalendarEventFormController;+ guestsAction?: JSX.Element;+ }) => (<>+ {props.guestsAction}<output aria-label="Conference">{props.controller.state().conference}</output>@@ -72,3 +95,37 @@ it.each([true, false])();});++const GUEST_COPY = {+ calendar: { id: 'calendar-1', name: 'Calendar', color: 'orange' },+ isCancelled: false,+} as CalendarEvent;++it('offers Forward invitation beside the guests of an event the viewer cannot invite to', () => {+ mocks.flag = () => ({ loading: false, enabled: false });+ mocks.canForward = true;+ render(() => <EventComposerSplit event={GUEST_COPY} />);+ expect(+ screen.getByRole('button', { name: 'Forward invitation' })+ ).toBeTruthy();+ // The forward follows its own flag.+ expect(mocks.controllerEnabled?.()).toBe(true);+});++it('offers no forward while composing a new event', () => {+ mocks.flag = () => ({ loading: false, enabled: false });+ mocks.canForward = true;+ render(() => <EventComposerSplit />);+ expect(+ screen.queryByRole('button', { name: 'Forward invitation' })+ ).toBeNull();+});++it('offers no forward when the viewer may not forward', () => {+ mocks.flag = () => ({ loading: false, enabled: false });+ mocks.canForward = false;+ render(() => <EventComposerSplit event={GUEST_COPY} />);+ expect(+ screen.queryByRole('button', { name: 'Forward invitation' })+ ).toBeNull();+});diff --git a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsxindex 15f21ac8cc..035613e358 100644--- a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx@@ -4,17 +4,43 @@ import {defaultEditorInitialValues,type EventEditorInitialValues,} from '@app/features/calendar/components/composer/event-form-model';-import { useCalendarGuestInvitesFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';+import { createGuestInviteController } from '@app/features/calendar/hooks/create-guest-invite-controller';+import {+ useCalendarGuestInvitesFlag,+ useCalendarInvitationForwardFlag,+} from '@app/features/calendar/hooks/use-calendar-ui-flag';import { useEventEditor } from '@app/features/calendar/hooks/use-event-editor';import { useSyncedCalendarEvent } from '@app/features/calendar/hooks/use-synced-calendar-event';import type { CalendarEvent } from '@app/features/calendar/types';import { viewerReplacesGuests } from '@app/features/calendar/utils/event-guest-editing';import { EventReplacementAction } from '@app/features/calendar/views/event-replacement';+import { EventForwardInvitationAction } from '@app/features/calendar-view/components/EventGuests';import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { type Accessor, createMemo, onMount, Show } from 'solid-js';+/**+ * Forward invitation beside a guest list the viewer cannot add to, as the+ * event details offer it there.+ */+function EditorForwardInvitation(props: {+ event: CalendarEvent;+ guestInvitesEnabled: Accessor<boolean>;+ forwardEnabled: Accessor<boolean>;+}) {+ const invites = createGuestInviteController(+ () => props.event,+ props.guestInvitesEnabled,+ props.forwardEnabled+ );+ return (+ <Show when={invites.canForward()}>+ <EventForwardInvitationAction event={props.event} invites={invites} />+ </Show>+ );+}+/** Standalone create/edit event composer hosted in a popover split. */type EventComposerSplitProps = {event?: CalendarEvent;@@ -56,10 +82,13 @@ function EventComposerContent(const macroCallsEnabled = props.macroCallsEnabled;const [attachHotkeys] = useHotkeyDOMScope('event-composer', true);const close = () => panel.handle.close();+ const guestInvitesEnabled = useCalendarGuestInvitesFlag();+ const invitationForwardEnabled = useCalendarInvitationForwardFlag();const editor = useEventEditor({event: () => props.event,macroCallsEnabled,- guestInvitesEnabled: useCalendarGuestInvitesFlag(),+ guestInvitesEnabled,+ invitationForwardEnabled,syncedEvent: useSyncedCalendarEvent(() => props.event),onDetailsLocked: () => controller.resetDetails(),onSaved: () => {@@ -97,6 +126,17 @@ function EventComposerContent(disabledFields={editor.disabledFields()}addOnlyGuests={editor.addOnlyGuests()}guestsReadOnlyReason={editor.guestsReadOnlyReason()}+ guestsAction={+ <Show when={props.event}>+ {(event) => (+ <EditorForwardInvitation+ event={event()}+ guestInvitesEnabled={guestInvitesEnabled}+ forwardEnabled={invitationForwardEnabled}+ />+ )}+ </Show>+ }guestListHidden={editor.guestListHidden()}guestPolicyEditable={editor.guestPolicyEditable()}detailsReadOnlyReason={editor.detailsReadOnlyReason()}diff --git a/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx b/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsxindex 45344db48f..5368048a4e 100644--- a/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx+++ b/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx@@ -108,8 +108,12 @@ export const useOpenEventComposer = () => () =>announce('Edit event · Preview only');export const useForwardEventEmail = () => () =>announce('Forward event · Preview only');-export const createGuestInviteController = () => ({ editorOpen: () => false });+export const createGuestInviteController = () => ({+ editorOpen: () => false,+ forwardEditorOpen: () => false,+});export const useCalendarGuestInvitesFlag = () => () => false;+export const useCalendarInvitationForwardFlag = () => () => false;export const useCalendarMeetingNotesFlag = () => () =>new URLSearchParams(location.search).get('notes') !== 'off';export const EventGuests = (props: { event: CalendarEvent }) => (diff --git a/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx b/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsxindex dfc94d6574..62161eb41f 100644--- a/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx+++ b/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx@@ -94,8 +94,12 @@ export const useOpenEventComposer = () => () =>announce('Edit event · Preview only');export const useForwardEventEmail = () => () =>announce('Forward event · Preview only');-export const createGuestInviteController = () => ({ editorOpen: () => false });+export const createGuestInviteController = () => ({+ editorOpen: () => false,+ forwardEditorOpen: () => false,+});export const useCalendarGuestInvitesFlag = () => () => false;+export const useCalendarInvitationForwardFlag = () => () => false;export const useCalendarMeetingNotesFlag = () => () => false;export const CalendarMeetingNotes = () => null;export const EventGuests = (props: { event: CalendarEvent }) => (diff --git a/apps/web/src/features/calendar-view/components/EventGuests.test.tsx b/apps/web/src/features/calendar-view/components/EventGuests.test.tsxindex 78a311e373..778ee535af 100644--- a/apps/web/src/features/calendar-view/components/EventGuests.test.tsx+++ b/apps/web/src/features/calendar-view/components/EventGuests.test.tsx@@ -13,6 +13,7 @@ import { EventGuests } from './EventGuests';const mocks = vi.hoisted(() => ({invite: vi.fn(),+ forward: vi.fn(),success: vi.fn(),failure: vi.fn(),alert: vi.fn(),@@ -52,6 +53,11 @@ vi.mock('@queries/calendar/mutations', () => ({isGuestListHiddenRefusal: (error: unknown) =>(error as { code?: string }).code === 'guest_list_hidden',}));+vi.mock('@queries/calendar/forward', () => ({+ useForwardCalendarEventMutation: () => ({ mutateAsync: mocks.forward }),+ isForwardRecipientRefusal: (error: unknown) =>+ (error as { code?: string }).code === 'invalid_recipients',+}));// The picker itself is the composer's and is tested there; this stand-in// offers every pool member it is not told to exclude.vi.mock('@property/editors/selectors/PropertyEntitySelector', async () => {@@ -156,11 +162,16 @@ function event(overrides: Partial<CalendarEvent> = {}): CalendarEvent {};}-function renderGuests(current: CalendarEvent, invitesEnabled = true) {+function renderGuests(+ current: CalendarEvent,+ invitesEnabled = true,+ forwardEnabled = true+) {render(() => {const invites = createGuestInviteController(() => current,- () => invitesEnabled+ () => invitesEnabled,+ () => forwardEnabled);return (<EventGuests event={current} invites={invites} closeDetails={vi.fn()} />@@ -168,9 +179,19 @@ function renderGuests(current: CalendarEvent, invitesEnabled = true) {});}+const RESTRICTED = 'Only the organizer can invite guests.';+const HIDDEN =+ 'Guests cannot be added while the organizer hides the guest list.';+const FORWARD_INSTEAD =+ "You can forward the invitation instead. The people you send it to can add the event to their calendar but won't be on the guest list.";+beforeEach(() => {vi.clearAllMocks();mocks.invite.mockResolvedValue('sent');+ mocks.forward.mockResolvedValue({+ messageId: 'message-1',+ threadId: 'thread-1',+ });Element.prototype.scrollIntoView = vi.fn();vi.stubGlobal('ResizeObserver', ResizeObserverStub);});@@ -301,19 +322,24 @@ describe('adding guests from event details', () => {expect(mocks.success).not.toHaveBeenCalled();});- it('explains instead of offering the action when the organizer does not let guests invite', () => {+ it('explains and offers to forward instead when the organizer does not let guests invite', () => {renderGuests(event({ viewerCan: { ...MAY_INVITE, inviteGuests: false } }));expect(screen.queryByRole('button', { name: 'Add guests' })).toBeNull();+ expect(screen.getByText(`${RESTRICTED} ${FORWARD_INSTEAD}`)).toBeTruthy();expect(- screen.getByText('Only the organizer can invite guests.')+ screen.getByRole('button', { name: 'Forward invitation' })).toBeTruthy();});it('switches to the explanation once the organizer turns inviting off', () => {const [current, setCurrent] = createSignal(event());render(() => {- const invites = createGuestInviteController(current, () => true);+ const invites = createGuestInviteController(+ current,+ () => true,+ () => true+ );return (<EventGuestsevent={current()}@@ -338,9 +364,7 @@ describe('adding guests from event details', () => {);expect(screen.queryByRole('button', { name: 'Add guests' })).toBeNull();- expect(- screen.getByText('Only the organizer can invite guests.')- ).toBeTruthy();+ expect(screen.getByText(`${RESTRICTED} ${FORWARD_INSTEAD}`)).toBeTruthy();});it('switches to the explanation when the organizer refuses the invitation', async () => {@@ -354,14 +378,11 @@ describe('adding guests from event details', () => {);await user.click(screen.getByRole('button', { name: 'Send invitations' }));- await waitFor(() =>- expect(mocks.failure).toHaveBeenCalledWith(- 'Only the organizer can invite guests.'- )- );+ await waitFor(() => expect(mocks.failure).toHaveBeenCalledWith(RESTRICTED));expect(screen.queryByRole('button', { name: 'Add guests' })).toBeNull();+ expect(screen.getByText(`${RESTRICTED} ${FORWARD_INSTEAD}`)).toBeTruthy();expect(- screen.getByText('Only the organizer can invite guests.')+ screen.getByRole('button', { name: 'Forward invitation' })).toBeTruthy();expect(mocks.success).not.toHaveBeenCalled();});@@ -382,14 +403,11 @@ describe('adding guests from event details', () => {expect(screen.getByText('Guest list hidden')).toBeTruthy();expect(screen.queryByText('1 attendee')).toBeNull();expect(screen.queryByRole('button', { name: 'Add guests' })).toBeNull();+ expect(screen.getByText(`${HIDDEN} ${FORWARD_INSTEAD}`)).toBeTruthy();+ expect(screen.queryByText(RESTRICTED, { exact: false })).toBeNull();expect(- screen.getByText(- 'Guests cannot be added while the organizer hides the guest list.'- )+ screen.getByRole('button', { name: 'Forward invitation' })).toBeTruthy();- expect(- screen.queryByText('Only the organizer can invite guests.')- ).toBeNull();});it('offers no guest addresses to copy while the organizer hides the guest list', () => {@@ -422,11 +440,9 @@ describe('adding guests from event details', () => {);await user.click(screen.getByRole('button', { name: 'Send invitations' }));- const reason =- 'Guests cannot be added while the organizer hides the guest list.';- await waitFor(() => expect(mocks.failure).toHaveBeenCalledWith(reason));+ await waitFor(() => expect(mocks.failure).toHaveBeenCalledWith(HIDDEN));expect(screen.queryByRole('button', { name: 'Add guests' })).toBeNull();- expect(screen.getByText(reason)).toBeTruthy();+ expect(screen.getByText(`${HIDDEN} ${FORWARD_INSTEAD}`)).toBeTruthy();});it('offers no guest addresses to copy or email when the viewer is the only guest', () => {@@ -445,14 +461,197 @@ describe('adding guests from event details', () => {});it('keeps today’s guest actions while guest invites are off', () => {- renderGuests(event(), false);+ renderGuests(event(), false, false);expect(screen.getByRole('button', { name: 'Copy guest emails' })).toBeTruthy();expect(screen.queryByRole('button', { name: 'Add guests' })).toBeNull();+ expect(screen.queryByText(RESTRICTED, { exact: false })).toBeNull();+ });+});++const CANNOT_INVITE = { ...MAY_INVITE, inviteGuests: false };++describe('forwarding the invitation from event details', () => {+ it('sends the picked people the event from the viewer’s copy, as Add guests picks them', async () => {+ const user = userEvent.setup();+ renderGuests(+ event({+ viewerCan: CANNOT_INVITE,+ recurrenceLines: ['RRULE:FREQ=WEEKLY'],+ })+ );++ await user.click(+ screen.getByRole('button', { name: 'Forward invitation' })+ );+ const invited = screen.getByRole('list', { name: 'Invited guests' });+ expect(invited.textContent).toContain('[email protected]');+ // A forward sends the series file, so there is no occurrence to pick.+ expect(screen.queryByRole('radio', { name: 'This event' })).toBeNull();+ expect(+ screen.getByText(+ "They can add the event to their calendar but won't appear in the guest list."+ )+ ).toBeTruthy();+ await user.click(+ screen.getByRole('button', { name: 'Suggest Ada Lovelace' })+ );+ expect(+ screen.getByRole('list', { name: 'Forward to' }).textContent+ ).toContain('Ada Lovelace');+ await user.click(screen.getByRole('button', { name: 'Forward' }));++ expect(mocks.forward).toHaveBeenCalledTimes(1);+ const [args] = mocks.forward.mock.calls[0];+ expect(args.eventId).toBe('event-1');+ expect(args.recipients).toEqual([+ { email: '[email protected]', name: 'Ada Lovelace' },+ ]);+ expect(args.bodyText).toMatch(/^Planning\n/);+ expect(+ args.bodyText.endsWith(+ "\n\nThis invitation was forwarded to you. Add the event to your calendar from the attached file. You won't be on the organizer's guest list."+ )+ ).toBe(true);+ expect(+ screen+ .getByRole('button', { name: 'Forward invitation' })+ .getAttribute('aria-expanded')+ ).toBe('false');+ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith(+ 'Invitation forwarded to Ada Lovelace'+ )+ );+ expect(mocks.invite).not.toHaveBeenCalled();+ });++ it('sends with Cmd+Enter and names how many people it reached', async () => {+ const user = userEvent.setup();+ renderGuests(event({ viewerCan: CANNOT_INVITE }));++ await user.click(+ screen.getByRole('button', { name: 'Forward invitation' })+ );+ await user.click(+ screen.getByRole('button', { name: 'Suggest Ada Lovelace' })+ );+ await user.click(+ screen.getByRole('button', { name: 'Suggest Grace Hopper' })+ );+ screen.getByRole('textbox', { name: 'Search for guests' }).focus();+ await user.keyboard('{Meta>}{Enter}{/Meta}');++ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith(+ 'Invitation forwarded to 2 people'+ )+ );+ });++ it('offers Retry when the email could not be sent, and Retry sends it again', async () => {+ mocks.forward.mockRejectedValueOnce({ code: 'send_failed' });+ const user = userEvent.setup();+ renderGuests(event({ viewerCan: CANNOT_INVITE }));++ await user.click(+ screen.getByRole('button', { name: 'Forward invitation' })+ );+ await user.click(+ screen.getByRole('button', { name: 'Suggest Ada Lovelace' })+ );+ await user.click(screen.getByRole('button', { name: 'Forward' }));++ await waitFor(() => expect(mocks.failure).toHaveBeenCalledTimes(1));+ const [message, options] = mocks.failure.mock.calls[0];+ expect(message).toBe('Could not forward the invitation');+ expect(+ options.actions.map((action: { label: string }) => action.label)+ ).toEqual(['Retry']);+ options.actions[0].onClick();+ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith(+ 'Invitation forwarded to Ada Lovelace'+ )+ );+ expect(mocks.forward).toHaveBeenCalledTimes(2);+ expect(mocks.forward.mock.calls[1][0]).toEqual(+ mocks.forward.mock.calls[0][0]+ );+ });++ it('shows why the recipients were refused, without a retry that cannot help', async () => {+ mocks.forward.mockRejectedValueOnce({ code: 'invalid_recipients' });+ const user = userEvent.setup();+ renderGuests(event({ viewerCan: CANNOT_INVITE }));++ await user.click(+ screen.getByRole('button', { name: 'Forward invitation' })+ );+ await user.click(+ screen.getByRole('button', { name: 'Suggest Ada Lovelace' })+ );+ await user.click(screen.getByRole('button', { name: 'Forward' }));++ await waitFor(() => expect(mocks.failure).toHaveBeenCalledTimes(1));+ const [message, options] = mocks.failure.mock.calls[0];+ expect(message).toBe('Could not forward the invitation');+ expect(options.actions).toBeUndefined();+ });++ it('offers nothing on a snapshot, a cancelled event, or while forwarding is off', () => {+ renderGuests(+ event({+ isSnapshot: true,+ viewerCan: { ...CANNOT_INVITE, rsvp: false },+ })+ );+ expect(+ screen.queryByRole('button', { name: 'Forward invitation' })+ ).toBeNull();+ cleanup();++ renderGuests(event({ viewerCan: CANNOT_INVITE, isCancelled: true }));+ expect(+ screen.queryByRole('button', { name: 'Forward invitation' })+ ).toBeNull();+ cleanup();++ renderGuests(event({ viewerCan: CANNOT_INVITE }), true, false);+ expect(+ screen.queryByRole('button', { name: 'Forward invitation' })+ ).toBeNull();+ expect(screen.getByText(RESTRICTED)).toBeTruthy();+ });++ it('forwards whether or not guest invites are on, since it adds no guests', () => {+ renderGuests(event({ viewerCan: CANNOT_INVITE }), false, true);+ expect(+ screen.getByRole('button', { name: 'Forward invitation' })+ ).toBeTruthy();+ expect(screen.getByText(`${RESTRICTED} ${FORWARD_INSTEAD}`)).toBeTruthy();+ });++ it('offers nothing on a team projection or a read-only copy', () => {+ renderGuests(+ event({+ viewerCan: CANNOT_INVITE,+ teamProjection: {+ ownerId: 'macro|[email protected]',+ kind: 'details',+ },+ })+ );+ expect(+ screen.queryByRole('button', { name: 'Forward invitation' })+ ).toBeNull();+ cleanup();++ renderGuests(event({ viewerCan: CANNOT_INVITE, isReadOnly: true }));expect(- screen.queryByText('Only the organizer can invite guests.')+ screen.queryByRole('button', { name: 'Forward invitation' })).toBeNull();});});diff --git a/apps/web/src/features/calendar-view/components/EventGuests.tsx b/apps/web/src/features/calendar-view/components/EventGuests.tsxindex 097ae4434f..d861382f37 100644--- a/apps/web/src/features/calendar-view/components/EventGuests.tsx+++ b/apps/web/src/features/calendar-view/components/EventGuests.tsx@@ -13,6 +13,7 @@ import { EventAttendeesSection } from '@app/features/calendar/components/EventDeimport type {GuestInvitation,GuestInviteController,+ InvitationForward,} from '@app/features/calendar/hooks/create-guest-invite-controller';import type { CalendarEvent } from '@app/features/calendar/types';import { guestListHidden } from '@app/features/calendar/utils/event-guest-editing';@@ -26,11 +27,12 @@ import { isMobile } from '@core/mobile/isMobile';import { recipientEntityMapper, useContacts } from '@core/user';import CopyIcon from '@icon/system/regular/copy.svg';import EnvelopeIcon from '@icon/system/regular/envelope.svg';+import PaperPlaneTiltIcon from '@icon/system/regular/paper-plane-tilt.svg';import UserPlusIcon from '@icon/system/regular/user-plus.svg';import { Popover } from '@kobalte/core/popover';import type { CalendarInviteScope } from '@service-email/client';import { Button, Checkbox, Dialog, Layer, Tabs } from '@ui';-import { createMemo, createSignal, Show } from 'solid-js';+import { createMemo, createSignal, type JSX, Show } from 'solid-js';/** Same wording as the RSVP and delete scope choices. */const INVITE_SCOPE_OPTIONS = [@@ -38,6 +40,45 @@ const INVITE_SCOPE_OPTIONS = [{ value: 'all', label: 'All events' },] satisfies { value: CalendarInviteScope; label: string }[];+/** The viewer's contacts as guest options, and the event's guests among them. */+function createGuestOptions(event: () => CalendarEvent) {+ const contacts = useContacts();+ const options = createMemo<EventEditorGuestOption[]>(() =>+ contacts().map(recipientEntityMapper('user'))+ );+ const current = createMemo(() =>+ initialGuestOptions(+ event()+ .attendees.map((attendee) => attendee.email)+ .join(', '),+ options()+ )+ );+ return { options, current };+}++/**+ * A guest form's keys: Cmd/Ctrl+Enter sends. Registered on the element so it+ * runs before the picker's document listener, which adds the highlighted+ * suggestion on every Enter, and Enter outside the picker's text field does+ * not reach it.+ */+function guestFormKeydown(send: () => void) {+ return (event: KeyboardEvent) => {+ if (event.key !== 'Enter') return;+ if (event.metaKey || event.ctrlKey) {+ event.preventDefault();+ event.stopPropagation();+ send();+ return;+ }+ const target = event.target;+ if (!(target instanceof HTMLInputElement && target.type === 'text')) {+ event.stopPropagation();+ }+ };+}+/*** The composer's add-only guest editor, plus what an invitation from event* details needs: an Optional choice per new guest, the occurrence scope of a@@ -48,16 +89,7 @@ function InviteGuestsForm(props: {onSend: (invitation: GuestInvitation) => void;onClose: () => void;}) {- const contacts = useContacts();- const options = createMemo<EventEditorGuestOption[]>(() =>- contacts().map(recipientEntityMapper('user'))- );- const current = createMemo(() =>- initialGuestOptions(- props.event.attendees.map((attendee) => attendee.email).join(', '),- options()- )- );+ const { options, current } = createGuestOptions(() => props.event);const [added, setAdded] = createSignal<SelectedEventEditorGuest[]>([]);const [optionalIds, setOptionalIds] = createSignal<ReadonlySet<string>>(new Set()@@ -90,21 +122,7 @@ function InviteGuestsForm(props: {return (<divclass="flex min-h-0 flex-1 flex-col"- // Registered on the element so it runs before the picker's document- // listener, which adds the highlighted suggestion on every Enter.- on:keydown={(event) => {- if (event.key !== 'Enter') return;- if (event.metaKey || event.ctrlKey) {- event.preventDefault();- event.stopPropagation();- send();- return;- }- const target = event.target;- if (!(target instanceof HTMLInputElement && target.type === 'text')) {- event.stopPropagation();- }- }}+ on:keydown={guestFormKeydown(send)}><AddOnlyGuestsEditoroptions={options}@@ -151,30 +169,81 @@ function InviteGuestsForm(props: {);}+/** Shown above the forward button; Google says the same of its own forward. */+const FORWARD_FORM_NOTE =+ "They can add the event to their calendar but won't appear in the guest list.";+/**- * The attendees header's "Add guests" action and the editor it opens,- * anchored to the action on desktop and a bottom sheet on phones.+ * Forwarding the invitation, for a guest who cannot add guests: the same+ * add-only picker as Add guests, for people who get the event by email+ * instead of a place on the guest list. A forward covers the whole series,+ * since the file it sends is the series.*/-function EventInviteGuestsAction(props: {+function ForwardInvitationForm(props: {event: CalendarEvent;- invites: GuestInviteController;+ onSend: (forward: InvitationForward) => void;+ onClose: () => void;}) {- const close = () => props.invites.setEditorOpen(false);- const form = () => (- <InviteGuestsForm- event={props.event}- onSend={props.invites.send}- onClose={close}- />+ const { options, current } = createGuestOptions(() => props.event);+ const [added, setAdded] = createSignal<SelectedEventEditorGuest[]>([]);+ const send = () => {+ if (added().length === 0) return;+ props.onSend({+ recipients: added().map((guest) => ({+ email: guestEmail(guest),+ name: guestDisplayName(guest),+ })),+ });+ };++ return (+ <div+ class="flex min-h-0 flex-1 flex-col"+ on:keydown={guestFormKeydown(send)}+ >+ <AddOnlyGuestsEditor+ options={options}+ current={current()}+ added={added()}+ onAddedChange={setAdded}+ onClose={props.onClose}+ addedLabel="Forward to"+ />+ <div class="flex shrink-0 items-center gap-2 border-t border-edge-muted p-2">+ <p class="min-w-0 flex-1 text-xs text-ink-muted">{FORWARD_FORM_NOTE}</p>+ <Button+ variant="strong"+ size="sm"+ depth={3}+ class="shrink-0"+ disabled={added().length === 0}+ onClick={send}+ >+ Forward+ </Button>+ </div>+ </div>);+}+/**+ * An attendees-header action and the guest editor it opens, anchored to the+ * action on desktop and a bottom sheet on phones.+ */+function GuestEditorAction(props: {+ label: string;+ icon: JSX.Element;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ children: JSX.Element;+}) {return (<Showwhen={isMobile()}fallback={<Popover- open={props.invites.editorOpen()}- onOpenChange={props.invites.setEditorOpen}+ open={props.open}+ onOpenChange={props.onOpenChange}placement="bottom-end"gutter={4}flip@@ -182,19 +251,19 @@ function EventInviteGuestsAction(props: {><Popover.Triggeras={Button}- label="Add guests"+ label={props.label}variant="ghost"size="icon-sm"depth={3}class="text-ink-muted [&_svg]:size-4">- <UserPlusIcon />+ {props.icon}</Popover.Trigger><EventComposerPopoverPortal><Layer depth={3}><Popover.Content class="menu-surface z-action-menu flex max-h-[min(30rem,var(--kb-popper-content-available-height,30rem))] w-80 max-w-[calc(100vw-1rem)] flex-col overflow-hidden text-sm menu-open-animation">- <Popover.Title class="sr-only">Add guests</Popover.Title>- {form()}+ <Popover.Title class="sr-only">{props.label}</Popover.Title>+ {props.children}</Popover.Content></Layer></EventComposerPopoverPortal>@@ -202,34 +271,76 @@ function EventInviteGuestsAction(props: {}><Button- label="Add guests"+ label={props.label}variant="ghost"size="icon-sm"depth={3}class="text-ink-muted [&_svg]:size-4"- onClick={() => props.invites.setEditorOpen(true)}+ onClick={() => props.onOpenChange(true)}>- <UserPlusIcon />+ {props.icon}</Button>- <Dialog- open={props.invites.editorOpen()}- onOpenChange={props.invites.setEditorOpen}- >+ <Dialog open={props.open} onOpenChange={props.onOpenChange}><Dialog.Title class="px-4 pb-2 text-base font-semibold text-ink">- Add guests+ {props.label}</Dialog.Title>- {form()}+ {props.children}</Dialog></Show>);}+/** The attendees header's "Add guests" action and its editor. */+function EventInviteGuestsAction(props: {+ event: CalendarEvent;+ invites: GuestInviteController;+}) {+ return (+ <GuestEditorAction+ label="Add guests"+ icon={<UserPlusIcon />}+ open={props.invites.editorOpen()}+ onOpenChange={props.invites.setEditorOpen}+ >+ <InviteGuestsForm+ event={props.event}+ onSend={props.invites.send}+ onClose={() => props.invites.setEditorOpen(false)}+ />+ </GuestEditorAction>+ );+}++/**+ * The attendees header's "Forward invitation" action, where Add guests+ * would be if the viewer could invite, and its editor.+ */+export function EventForwardInvitationAction(props: {+ event: CalendarEvent;+ invites: GuestInviteController;+}) {+ return (+ <GuestEditorAction+ label="Forward invitation"+ icon={<PaperPlaneTiltIcon />}+ open={props.invites.forwardEditorOpen()}+ onOpenChange={props.invites.setForwardEditorOpen}+ >+ <ForwardInvitationForm+ event={props.event}+ onSend={props.invites.forward}+ onClose={() => props.invites.setForwardEditorOpen(false)}+ />+ </GuestEditorAction>+ );+}+/*** The guest-row actions Google Calendar users know: copy every guest's* address and start an email to the other guests (both hidden when the* viewer is the only one, as on a snapshot, and copying while the organizer- * hides the guest list, which the copy does not hold), or add guests when the- * organizer allows it. Emailing closes the details first: closing hands focus+ * hides the guest list, which the copy does not hold), add guests when the+ * organizer allows it, or else forward the invitation. Emailing closes the details first: closing hands focus* back to the calendar chip, and the composer's To field has to win that* exchange.*/@@ -273,6 +384,12 @@ function EventGuestActions(props: {<Show when={props.invites.canInvite()}><EventInviteGuestsAction event={props.event} invites={props.invites} /></Show>+ <Show when={props.invites.canForward()}>+ <EventForwardInvitationAction+ event={props.event}+ invites={props.invites}+ />+ </Show></Show>);}diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsxindex cadacf4f09..4682a5f885 100644--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx@@ -13,6 +13,7 @@ import { SelectedEventDetails } from './SelectedEventDetails';const mocks = vi.hoisted(() => ({mobile: false,+ forwardEditorOpen: false,openComposer: vi.fn(),openDocument: vi.fn(),deleteEvent: vi.fn(),@@ -44,10 +45,14 @@ vi.mock(}));vi.mock('@app/features/calendar/hooks/create-guest-invite-controller', () => ({- createGuestInviteController: () => ({ editorOpen: () => false }),+ createGuestInviteController: () => ({+ editorOpen: () => false,+ forwardEditorOpen: () => mocks.forwardEditorOpen,+ }),}));vi.mock('@app/features/calendar/hooks/use-calendar-ui-flag', () => ({useCalendarGuestInvitesFlag: () => () => false,+ useCalendarInvitationForwardFlag: () => () => false,useCalendarMeetingNotesFlag: () => () => true,}));// The sections have their own tests; exercise the overlay's actions and@@ -158,6 +163,7 @@ function showDetails(selected: CalendarEvent) {beforeEach(() => {vi.clearAllMocks();+ mocks.forwardEditorOpen = false;vi.stubGlobal('ResizeObserver', ObserverStub);vi.stubGlobal('PointerEvent', MouseEvent);vi.stubGlobal('scrollTo', vi.fn());@@ -225,6 +231,20 @@ describe.each([mocks.mobile = mobile;});+ it('stays open while the forward editor is open, so its recipients are not lost', async () => {+ mocks.forwardEditorOpen = true;+ const user = userEvent.setup();+ showDetails(event());++ await user.click(+ screen.getByRole('button', { name: 'Close event details' })+ );++ expect(+ screen.getByRole('button', { name: 'Close event details' })+ ).toBeTruthy();+ });+it('offers no Edit on a snapshot, and deletes it as the viewer’s copy', async () => {const user = userEvent.setup();showDetails(event({ isSnapshot: true }));diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsxindex eb8c0b581c..d648cc0c8a 100644--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx@@ -3,6 +3,7 @@ import { EventDetails } from '@app/features/calendar/components/EventDetails';import { createGuestInviteController } from '@app/features/calendar/hooks/create-guest-invite-controller';import {useCalendarGuestInvitesFlag,+ useCalendarInvitationForwardFlag,useCalendarMeetingNotesFlag,} from '@app/features/calendar/hooks/use-calendar-ui-flag';import {@@ -193,7 +194,8 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {});const invites = createGuestInviteController(() => props.event,- useCalendarGuestInvitesFlag()+ useCalendarGuestInvitesFlag(),+ useCalendarInvitationForwardFlag());const canEdit = () => canEditCalendarEvent(props.event);const canDelete = () => canDeleteCalendarEvent(props.event);@@ -215,7 +217,10 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {onOpenChange={(open) => {if (!open &&- (deleteDialog.isOpen() || invites.editorOpen() || notesOpen())+ (deleteDialog.isOpen() ||+ invites.editorOpen() ||+ invites.forwardEditorOpen() ||+ notesOpen()))return;props.onOpenChange(open);@@ -497,7 +502,8 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {});const invites = createGuestInviteController(() => props.event,- useCalendarGuestInvitesFlag()+ useCalendarGuestInvitesFlag(),+ useCalendarInvitationForwardFlag());const canEdit = () => canEditCalendarEvent(props.event);const canDelete = () => canDeleteCalendarEvent(props.event);@@ -522,7 +528,10 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {// is open.if (!open &&- (deleteDialog.isOpen() || invites.editorOpen() || notesOpen())+ (deleteDialog.isOpen() ||+ invites.editorOpen() ||+ invites.forwardEditorOpen() ||+ notesOpen()))return;props.onOpenChange(open);diff --git a/apps/web/src/features/calendar/components/composer/EventForm.tsx b/apps/web/src/features/calendar/components/composer/EventForm.tsxindex e61c98bb64..1b58039b31 100644--- a/apps/web/src/features/calendar/components/composer/EventForm.tsx+++ b/apps/web/src/features/calendar/components/composer/EventForm.tsx@@ -9,6 +9,7 @@ import {createSignal,createUniqueId,For,+ type JSX,type ParentProps,Show,} from 'solid-js';@@ -47,6 +48,8 @@ export interface EventFormProps {addOnlyGuests?: boolean;/** Why a read-only guest list cannot change. */guestsReadOnlyReason?: string;+ /** An action beside the guests, such as forwarding the invitation. */+ guestsAction?: JSX.Element;/** The organizer hides the guest list, so the seeded guests are not all of them. */guestListHidden?: boolean;/** Whether the viewer may set what guests may do, as the organizer. */@@ -347,6 +350,7 @@ export function EventForm(props: EventFormProps) {props.addOnlyGuests ? controller.initialGuests() : undefined}/>+ {props.guestsAction}<LockedField reason={props.detailsReadOnlyReason}><EventComposerConferencePillvalue={state().conference}diff --git a/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsx b/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsxindex 1f705129d5..e88d48e697 100644--- a/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsx+++ b/apps/web/src/features/calendar/components/composer/EventGuestsEditor.tsx@@ -118,6 +118,8 @@ export function AddOnlyGuestsEditor(props: {onClose: () => void;/** Controls shown on each added guest, before its remove button. */addedControls?: (guest: SelectedEventEditorGuest) => JSX.Element;+ /** What the added people are, for assistive technology. */+ addedLabel?: string;}) {return (<div class="flex min-h-0 flex-col">@@ -130,7 +132,10 @@ export function AddOnlyGuestsEditor(props: {/><div class="flex min-h-0 flex-col overflow-y-auto p-1.5"><Show when={props.added.length > 0}>- <ul aria-label="New guests" class="flex flex-col">+ <ul+ aria-label={props.addedLabel ?? 'New guests'}+ class="flex flex-col"+ ><For each={props.added}>{(guest) => (<li>diff --git a/apps/web/src/features/calendar/hooks/create-guest-invite-controller.ts b/apps/web/src/features/calendar/hooks/create-guest-invite-controller.tsindex b25f5dd4c4..0891196364 100644--- a/apps/web/src/features/calendar/hooks/create-guest-invite-controller.ts+++ b/apps/web/src/features/calendar/hooks/create-guest-invite-controller.ts@@ -1,5 +1,9 @@import { toast } from '@core/component/Toast/Toast';import { fireAndForget } from '@core/util/fireAndForget';+import {+ isForwardRecipientRefusal,+ useForwardCalendarEventMutation,+} from '@queries/calendar/forward';import {type InviteCalendarEventGuestsArgs,isGuestInviteRefused,@@ -10,11 +14,16 @@ import type { CalendarInviteScope } from '@service-email/client';import { ResultAsync } from 'neverthrow';import { type Accessor, createSignal } from 'solid-js';import type { CalendarEvent } from '../types';+import { eventForwardSummary } from '../utils/event-forward-summary';import {+ canForwardInvitation,+ FORWARD_INVITATION_INSTEAD,+ FORWARDED_INVITATION_NOTE,GUEST_INVITES_RESTRICTED,GUEST_LIST_HIDDEN,guestInvitesRestrictedReason,} from '../utils/event-guest-editing';+import { useCalendarPreferences } from '../utils/preferences';/** Guests an editor sends an invitation to, with the names its toast uses. */export interface GuestInvitation {@@ -28,20 +37,41 @@ export function invitationSentMessage(guests: readonly { name: string }[]) {: `Invitations sent to ${guests.length} people`;}+/** People a guest forwards the invitation to, with the names its toast uses. */+export interface InvitationForward {+ recipients: { email: string; name: string }[];+}++export function invitationForwardedMessage(+ recipients: readonly { name: string }[]+) {+ return recipients.length === 1+ ? `Invitation forwarded to ${recipients[0]?.name}`+ : `Invitation forwarded to ${recipients.length} people`;+}+/*** Inviting guests from event details. The editor closes as soon as the* invitation goes out, while the mutation shows the new guests as unanswered.* The outcome is announced once the provider answers, since that takes* seconds. A refusal means the organizer does not let guests invite, or* hides the guest list, which switches the details to that explanation.+ * A guest who cannot invite forwards the invitation instead: its editor+ * closes the same way, and the outcome is announced once the email is+ * accepted for sending, with Retry when it failed for another reason than+ * its recipients.*/export function createGuestInviteController(event: Accessor<CalendarEvent>,- enabled: Accessor<boolean>+ enabled: Accessor<boolean>,+ forwardEnabled: Accessor<boolean>) {const [editorOpen, setEditorOpen] = createSignal(false);+ const [forwardEditorOpen, setForwardEditorOpen] = createSignal(false);const [refusal, setRefusal] = createSignal<string>();const mutation = useInviteCalendarEventGuestsMutation();+ const forwardMutation = useForwardCalendarEventMutation();+ const [preferences] = useCalendarPreferences();const deliver = async (args: InviteCalendarEventGuestsArgs,@@ -74,9 +104,79 @@ export function createGuestInviteController(});};+ /**+ * A refused invitation means the guest list cannot grow after all, even+ * before the synced event says so.+ */+ const canForward = () => {+ const current = event();+ if (!forwardEnabled() || current.isCancelled) return false;+ if (canForwardInvitation(current)) return true;+ return (+ refusal() !== undefined &&+ !current.isReadOnly &&+ !current.teamProjection &&+ !current.isSnapshot+ );+ };++ const deliverForward = async (+ current: CalendarEvent,+ forward: InvitationForward+ ) => {+ const result = await ResultAsync.fromPromise(+ forwardMutation.mutateAsync({+ eventId: current.eventId,+ recipients: forward.recipients.map(({ email, name }) => ({+ email,+ name: name === email ? undefined : name,+ })),+ bodyText: `${eventForwardSummary(current, preferences.timeFormat)}\n\n${FORWARDED_INVITATION_NOTE}`,+ }),+ (error) => error+ );+ if (result.isOk()) {+ toast.success(invitationForwardedMessage(forward.recipients));+ return;+ }+ if (isForwardRecipientRefusal(result.error)) {+ toast.failure('Could not forward the invitation', {+ subtext:+ result.error instanceof Error ? result.error.message : undefined,+ });+ return;+ }+ toast.failure('Could not forward the invitation', {+ actions: [+ {+ label: 'Retry',+ onClick: () => sendForward(current, forward),+ },+ ],+ });+ };++ const sendForward = (current: CalendarEvent, forward: InvitationForward) => {+ if (forward.recipients.length === 0) return;+ if (!navigator.onLine) {+ toast.failure('You are offline. Reconnect to forward the invitation.');+ return;+ }+ setForwardEditorOpen(false);+ fireAndForget(+ deliverForward(current, forward),+ 'calendar-invitation-forward'+ );+ };+return {editorOpen,setEditorOpen,+ forwardEditorOpen,+ setForwardEditorOpen,+ canForward,+ /** Forward the invitation to people the guest list won't name. */+ forward: (forward: InvitationForward) => sendForward(event(), forward),canInvite: () => {const current = event();return (@@ -88,8 +188,15 @@ export function createGuestInviteController(current.viewerCan.inviteGuests);},- /** Why the viewer cannot add guests, shown above the guest list. */- restrictedReason: () => refusal() ?? guestInvitesRestrictedReason(event()),+ /**+ * Why the viewer cannot add guests, shown above the guest list, and+ * what they can do instead when the invitation can be forwarded.+ */+ restrictedReason: () => {+ const reason = refusal() ?? guestInvitesRestrictedReason(event());+ if (!reason) return undefined;+ return canForward() ? `${reason} ${FORWARD_INVITATION_INSTEAD}` : reason;+ },send: (invitation: GuestInvitation) => {if (invitation.guests.length === 0) return;if (!navigator.onLine) {diff --git a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.tsindex 4a29850894..4c670385c2 100644--- a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts+++ b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts@@ -2,6 +2,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import {enableCalendarAddSharedEvent,enableCalendarGuestInvites,+ enableCalendarInvitationForward,enableCalendarMeetingNotes,enableCalendarPromptMobile,enableCalendarPromptWeb,@@ -63,6 +64,12 @@ export function useCalendarGuestInvitesFlag(): Accessor<boolean> {return () => flag().enabled;}+/** Whether a guest who cannot add guests may forward the invitation instead. */+export function useCalendarInvitationForwardFlag(): Accessor<boolean> {+ const flag = useFeatureFlag(enableCalendarInvitationForward);+ return () => flag().enabled;+}+/** Whether a channel member may add a shared event to their own calendar. */export function useCalendarAddSharedEventFlag(): Accessor<boolean> {const flag = useFeatureFlag(enableCalendarAddSharedEvent);diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts b/apps/web/src/features/calendar/hooks/use-event-editor.test.tsindex f580a8c263..5d51755eb0 100644--- a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts+++ b/apps/web/src/features/calendar/hooks/use-event-editor.test.ts@@ -1066,7 +1066,8 @@ describe('guests of an event the viewer was invited to', () => {event: CalendarEvent,invitesEnabled: boolean,onDetailsLocked?: () => void,- syncedEvent?: () => CalendarEvent | undefined+ syncedEvent?: () => CalendarEvent | undefined,+ forwardEnabled = invitesEnabled) {return createRoot((dispose) => ({editor: useEventEditor({@@ -1075,6 +1076,7 @@ describe('guests of an event the viewer was invited to', () => {onSaved: vi.fn(),macroCallsEnabled: () => false,guestInvitesEnabled: () => invitesEnabled,+ invitationForwardEnabled: () => forwardEnabled,onDetailsLocked,}),dispose,@@ -1183,10 +1185,21 @@ describe('guests of an event the viewer was invited to', () => {}});- it('explains why a guest the organizer does not let invite cannot add guests', () => {+ it('explains why a guest the organizer does not let invite cannot add guests, and offers the forward', () => {const { editor, dispose } = editorFor(invitedEvent(mayNotInvite), true);try {expect(editor.disabledFields()?.guests).toBe(true);+ expect(editor.guestsReadOnlyReason()).toBe(+ "Only the organizer can invite guests. You can forward the invitation instead. The people you send it to can add the event to their calendar but won't be on the guest list."+ );+ } finally {+ dispose();+ }+ });++ it('explains without offering the forward while forwarding is off', () => {+ const { editor, dispose } = editorFor(invitedEvent(mayNotInvite), false);+ try {expect(editor.guestsReadOnlyReason()).toBe('Only the organizer can invite guests.');diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.ts b/apps/web/src/features/calendar/hooks/use-event-editor.tsindex 8338319488..250f7f6a36 100644--- a/apps/web/src/features/calendar/hooks/use-event-editor.ts+++ b/apps/web/src/features/calendar/hooks/use-event-editor.ts@@ -40,8 +40,10 @@ import {} from '../utils/calendar-label';import {addedGuestEmails,+ canForwardInvitation,type EventGuestEditing,eventGuestEditing,+ FORWARD_INVITATION_INSTEAD,GUEST_EDITS_RESTRICTED,guestEditsRestricted,guestInvitesRestrictedReason,@@ -116,6 +118,8 @@ interface UseEventEditorProps {* when omitted.*/guestInvitesEnabled?: Accessor<boolean>;+ /** Whether a guest who cannot add guests may forward the invitation. */+ invitationForwardEnabled?: Accessor<boolean>;/*** The edited event as the calendar now holds it. The lock on its details* follows this copy, so a guest whose organizer stops letting guests@@ -202,7 +206,12 @@ export function useEventEditor(props: UseEventEditorProps) {});const guestsReadOnlyReason = () => {const event = props.event();- return event && guestInvitesRestrictedReason(event);+ const reason = event && guestInvitesRestrictedReason(event);+ if (!reason) return undefined;+ return (props.invitationForwardEnabled?.() ?? false) &&+ canForwardInvitation(event)+ ? `${reason} ${FORWARD_INVITATION_INSTEAD}`+ : reason;};// A refusal means the stored guest policy was newer than the event shown,// so the details lock without waiting for the refetch.diff --git a/apps/web/src/features/calendar/utils/event-guest-editing.test.ts b/apps/web/src/features/calendar/utils/event-guest-editing.test.tsindex b3fc668b2d..7db719f514 100644--- a/apps/web/src/features/calendar/utils/event-guest-editing.test.ts+++ b/apps/web/src/features/calendar/utils/event-guest-editing.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import type { CalendarEvent } from '../types';import {addedGuestEmails,+ canForwardInvitation,eventGuestEditing,GUEST_INVITES_RESTRICTED,GUEST_LIST_HIDDEN,@@ -168,6 +169,39 @@ describe('guestInvitesRestricted', () => {});});+describe('canForwardInvitation', () => {+ it('lets a guest who cannot invite forward instead, hidden list or not', () => {+ expect(canForwardInvitation(invited(GUEST))).toBe(true);+ expect(+ canForwardInvitation({+ ...invited(GUEST),+ guestPolicy: {+ canModify: false,+ canInviteOthers: true,+ canSeeOtherGuests: false,+ },+ })+ ).toBe(true);+ });++ it('is not offered to someone who can invite, or on a copy that cannot change', () => {+ expect(canForwardInvitation(invited(INVITING_GUEST))).toBe(false);+ expect(canForwardInvitation(invited(ORGANIZER))).toBe(false);+ expect(canForwardInvitation({ ...invited(GUEST), isCancelled: true })).toBe(+ false+ );+ expect(canForwardInvitation({ ...invited(GUEST), isReadOnly: true })).toBe(+ false+ );+ expect(+ canForwardInvitation({+ ...invited({ ...GUEST, rsvp: false }),+ isSnapshot: true,+ })+ ).toBe(false);+ });+});+describe('guestInvitesRestrictedReason', () => {const policy = (canSeeOtherGuests: boolean,diff --git a/apps/web/src/features/calendar/utils/event-guest-editing.ts b/apps/web/src/features/calendar/utils/event-guest-editing.tsindex 6eb4b1c918..719fd8ff1c 100644--- a/apps/web/src/features/calendar/utils/event-guest-editing.ts+++ b/apps/web/src/features/calendar/utils/event-guest-editing.ts@@ -11,6 +11,21 @@ export const GUEST_INVITES_RESTRICTED = 'Only the organizer can invite guests.';export const GUEST_LIST_HIDDEN ='Guests cannot be added while the organizer hides the guest list.';+/**+ * Follows why a guest cannot add guests, where they may forward the+ * invitation instead: forwarded people get the event to add to their own+ * calendar, as Google says of its own forward, and stay off the guest list.+ */+export const FORWARD_INVITATION_INSTEAD =+ "You can forward the invitation instead. The people you send it to can add the event to their calendar but won't be on the guest list.";++/**+ * Ends a forwarded invitation's email, for the people it goes to; the+ * server's default body says the same.+ */+export const FORWARDED_INVITATION_NOTE =+ "This invitation was forwarded to you. Add the event to your calendar from the attached file. You won't be on the organizer's guest list.";+/** Shown where a guest would change the event when the organizer does not allow it. */export const GUEST_EDITS_RESTRICTED ='Only the organizer can change this event.';@@ -101,6 +116,16 @@ export function guestInvitesRestricted(event: CalendarEvent): boolean {);}+/**+ * Whether the viewer may forward the invitation instead of inviting: a+ * guest whose guest list cannot grow, on a live copy of their own. The+ * forward emails the event's file from the copy's inbox, so it needs no+ * provider support and reaches nobody on the guest list.+ */+export function canForwardInvitation(event: CalendarEvent): boolean {+ return !event.isCancelled && guestInvitesRestricted(event);+}+/*** Whether the organizer hides the guest list from the viewer, a guest on* their own copy. Google then gives that copy only the viewer and perhaps thediff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex c0739b56c9..a78b083729 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -721,6 +721,17 @@ export const enableCalendarGuestInvites = defineFlag({default: onInDev,});+// Forwarding an invitation: event details' and the editor's "Forward+// invitation", offered where a guest cannot add guests, which emails the+// event's .ics from the inbox holding the viewer's copy. On in dev only until+// a real send has passed on dev; there is no PostHog flag yet, so it stays off+// in production. Override with VITE_ENABLE_CALENDAR_INVITATION_FORWARD.+export const enableCalendarInvitationForward = defineFlag({+ key: 'enable-calendar-invitation-forward',+ env: 'ENABLE_CALENDAR_INVITATION_FORWARD',+ default: onInDev,+});+// Adding a channel-shared event to your own calendar: the "Add to calendar"// action on a shared event's mention card. On in dev only until a real Google// import has passed on dev; there is no PostHog flag yet, so it stays off indiff --git a/apps/web/src/lib/queries/calendar/forward.ts b/apps/web/src/lib/queries/calendar/forward.tsnew file mode 100644index 0000000000..a2e98aa207--- /dev/null+++ b/apps/web/src/lib/queries/calendar/forward.ts@@ -0,0 +1,83 @@+import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';+import { Telemetry } from '@macro-inc/observability';+import type { MutationCallbacks } from '@queries/utils';+import { emailClient } from '@service-email/client';+import { ForwardCalendarEventErrorCode } from '@service-email/generated/schemas/forwardCalendarEventErrorCode';+import type { ForwardCalendarEventResponse } from '@service-email/generated/schemas/forwardCalendarEventResponse';+import { useMutation } from '@tanstack/solid-query';++export interface ForwardCalendarEventArgs {+ /** The viewer's own copy of the event. */+ eventId: string;+ recipients: { email: string; name?: string }[];+ /** The email's plain-text body. */+ bodyText: string;+}++/** Whether the server refused the recipients, so retrying cannot help. */+export function isForwardRecipientRefusal(error: unknown): boolean {+ return thrownResultErrorHasCode(+ error,+ ForwardCalendarEventErrorCode.invalid_recipients+ );+}++/** Span outcome of a failed forward. */+function forwardFailureOutcome(error: unknown) {+ if (isForwardRecipientRefusal(error)) return 'invalid_recipients';+ if (thrownResultErrorHasCode(error, ForwardCalendarEventErrorCode.not_found))+ return 'not_found';+ if (+ thrownResultErrorHasCode(+ error,+ ForwardCalendarEventErrorCode.inbox_unavailable+ )+ )+ return 'inbox_unavailable';+ return 'failed';+}++async function forwardCalendarEvent(+ args: ForwardCalendarEventArgs+): Promise<ForwardCalendarEventResponse> {+ return Telemetry.span('calendar.forward_invitation', async (span) => {+ span.setAttr('calendar.event_id', args.eventId);+ span.setAttr('calendar.forward.recipient_count', args.recipients.length);+ try {+ const sent = await throwOnErr(() =>+ emailClient.forwardCalendarEvent(args.eventId, {+ to: args.recipients,+ bodyText: args.bodyText,+ })+ );+ span.setAttr('email.message_id', sent.messageId);+ span.setAttr('calendar.forward.outcome', 'sent');+ return sent;+ } catch (error) {+ const outcome = forwardFailureOutcome(error);+ span.setAttr('calendar.forward.outcome', outcome);+ // Provider messages can quote addresses; record only the category.+ span.error('Forwarding the invitation failed');+ throw error;+ }+ });+}++type ForwardCallbacks = MutationCallbacks<+ ForwardCalendarEventResponse,+ Error,+ ForwardCalendarEventArgs,+ unknown+>;++/**+ * Emails the event's .ics to people the organizer's guest list does not+ * name, from the inbox holding the viewer's copy. Nothing about the event+ * changes, so no cache needs refreshing.+ */+export function useForwardCalendarEventMutation(callbacks?: ForwardCallbacks) {+ return useMutation(() => ({+ mutationFn: forwardCalendarEvent,+ ...callbacks,+ }));+}diff --git a/apps/web/src/lib/queries/calendar/tests/forward.test.tsx b/apps/web/src/lib/queries/calendar/tests/forward.test.tsxnew file mode 100644index 0000000000..89665d9b82--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/forward.test.tsx@@ -0,0 +1,102 @@+import { ThrownResultError } from '@core/util/result';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import type { JSX } from 'solid-js';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import {+ isForwardRecipientRefusal,+ useForwardCalendarEventMutation,+} from '../forward';++const forwardCalendarEventMock = vi.hoisted(() => vi.fn());++vi.mock('@service-email/client', () => ({+ emailClient: { forwardCalendarEvent: forwardCalendarEventMock },+}));++let testQueryClient: QueryClient;+let dispose: (() => void) | undefined;++function renderHook<T>(factory: () => T): T {+ let hook!: T;+ dispose = render(+ () => (+ <QueryClientProvider client={testQueryClient}>+ {(() => {+ hook = factory();+ return null as unknown as JSX.Element;+ })()}+ </QueryClientProvider>+ ),+ document.body+ );+ return hook;+}++beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+ testQueryClient.clear();+});++it('sends the recipients and body for the viewer’s copy', async () => {+ forwardCalendarEventMock.mockResolvedValue(+ ok({ messageId: 'message-1', threadId: 'thread-1' })+ );+ const forward = renderHook(() => useForwardCalendarEventMutation());++ const sent = await forward.mutateAsync({+ eventId: 'event-1',+ recipients: [{ email: '[email protected]', name: 'Friend' }],+ bodyText: 'Office tour',+ });++ expect(sent.messageId).toBe('message-1');+ expect(forwardCalendarEventMock).toHaveBeenCalledWith('event-1', {+ to: [{ email: '[email protected]', name: 'Friend' }],+ bodyText: 'Office tour',+ });+});++it('reports a refusal of the recipients by its code', async () => {+ forwardCalendarEventMock.mockResolvedValue(+ err([{ code: 'invalid_recipients', message: 'bad address' }])+ );+ const forward = renderHook(() => useForwardCalendarEventMutation());++ const error = await forward+ .mutateAsync({+ eventId: 'event-1',+ recipients: [{ email: '[email protected]' }],+ bodyText: 'Office tour',+ })+ .catch((error: unknown) => error);++ expect(error).toBeInstanceOf(ThrownResultError);+ expect(isForwardRecipientRefusal(error)).toBe(true);+});++it('does not treat a failed send as a recipient refusal', async () => {+ forwardCalendarEventMock.mockResolvedValue(+ err([{ code: 'send_failed', message: 'try again' }])+ );+ const forward = renderHook(() => useForwardCalendarEventMutation());++ const error = await forward+ .mutateAsync({+ eventId: 'event-1',+ recipients: [{ email: '[email protected]' }],+ bodyText: 'Office tour',+ })+ .catch((error: unknown) => error);++ expect(isForwardRecipientRefusal(error)).toBe(false);+});diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.tsindex 7a64b17f98..7a60d437c9 100644--- a/apps/web/src/lib/service-clients/service-email/client.ts+++ b/apps/web/src/lib/service-clients/service-email/client.ts@@ -65,6 +65,9 @@ import type {UpsertScheduledResponse,} from './generated/schemas';import type { EmptyResponse } from './generated/schemas/emptyResponse';+import { ForwardCalendarEventErrorCode } from './generated/schemas/forwardCalendarEventErrorCode';+import type { ForwardCalendarEventRequest } from './generated/schemas/forwardCalendarEventRequest';+import type { ForwardCalendarEventResponse } from './generated/schemas/forwardCalendarEventResponse';import type { InvitationResolution } from './generated/schemas/invitationResolution';const emailHost: string = SERVER_HOSTS['email-service'];@@ -114,6 +117,24 @@ async function calendarMutationErrorHandler(response: Response) {};}+async function forwardCalendarEventErrorHandler(response: Response) {+ const body = (await response.json().catch(() => null)) as {+ code?: string;+ message?: string;+ } | null;+ const code =+ body?.code && body.code in ForwardCalendarEventErrorCode+ ? (body.code as ForwardCalendarEventErrorCode)+ : undefined;+ if (code) {+ return { code, message: body?.message ?? '' };+ }+ return {+ code: 'HTTP_ERROR' as const,+ message: `HTTP error! status: ${response.status}`,+ };+}+function emailFetch(url: string,init?: SafeFetchInit@@ -192,6 +213,19 @@ export const emailClient = {});},+ async forwardCalendarEvent(+ eventId: string,+ args: ForwardCalendarEventRequest+ ) {+ return fetchWithToken<+ ForwardCalendarEventResponse,+ ForwardCalendarEventErrorCode+ >(`${emailHost}/email/calendar-events/${eventId}/forward`, {+ method: 'POST',+ body: JSON.stringify(args),+ errorResponseHandler: forwardCalendarEventErrorHandler,+ });+ },async init(args?: { linkId?: string; forceShare?: boolean }) {const params = new URLSearchParams();if (args?.linkId) params.set('link_id', args.linkId);diff --git a/apps/web/src/lib/service-clients/service-email/generated/client.ts b/apps/web/src/lib/service-clients/service-email/generated/client.tsindex afef70abe1..8cf1400fd4 100644--- a/apps/web/src/lib/service-clients/service-email/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/client.ts@@ -29,6 +29,9 @@ import type {DeleteScheduledDraftParams,EmptyResponse,ErrorResponse,+ ForwardCalendarEventError,+ ForwardCalendarEventRequest,+ ForwardCalendarEventResponse,GetActiveBackfillJobResponse,GetAttachmentDocumentIDResponse,GetAttachmentResponse,@@ -483,6 +486,90 @@ export const getBackfillGmail = async (} as getBackfillGmailResponse;};+/**+ * @summary Email one of the viewer's events to people the organizer's guest list+does not name: the event's iCalendar file (`METHOD:PUBLISH`, no+attendees, no join link), sent from the inbox that holds the viewer's+copy, with the usual undo delay. Recipients can add the event to their+own calendar; they are not added to the guest list and the organizer is+not told.+ */+export type forwardCalendarEventResponse202 = {+ data: ForwardCalendarEventResponse;+ status: 202;+};++export type forwardCalendarEventResponse400 = {+ data: ForwardCalendarEventError;+ status: 400;+};++export type forwardCalendarEventResponse401 = {+ data: void;+ status: 401;+};++export type forwardCalendarEventResponse403 = {+ data: ForwardCalendarEventError;+ status: 403;+};++export type forwardCalendarEventResponse404 = {+ data: ForwardCalendarEventError;+ status: 404;+};++export type forwardCalendarEventResponse502 = {+ data: ForwardCalendarEventError;+ status: 502;+};++export type forwardCalendarEventResponseSuccess =+ forwardCalendarEventResponse202 & {+ headers: Headers;+ };+export type forwardCalendarEventResponseError = (+ | forwardCalendarEventResponse400+ | forwardCalendarEventResponse401+ | forwardCalendarEventResponse403+ | forwardCalendarEventResponse404+ | forwardCalendarEventResponse502+) & {+ headers: Headers;+};++export type forwardCalendarEventResponse =+ | forwardCalendarEventResponseSuccess+ | forwardCalendarEventResponseError;++export const getForwardCalendarEventUrl = (eventId: string) => {+ return `/email/calendar-events/${eventId}/forward`;+};++export const forwardCalendarEvent = async (+ eventId: string,+ forwardCalendarEventRequest: ForwardCalendarEventRequest,+ options?: RequestInit+): Promise<forwardCalendarEventResponse> => {+ const res = await fetch(getForwardCalendarEventUrl(eventId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(forwardCalendarEventRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: forwardCalendarEventResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as forwardCalendarEventResponse;+};+/*** @summary List all contacts belonging to the user, grouped by link.*/diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventError.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventError.tsnew file mode 100644index 0000000000..dc2cc459b4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventError.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ForwardCalendarEventErrorCode } from './forwardCalendarEventErrorCode';++/**+ * A refused or failed forward.+ */+export interface ForwardCalendarEventError {+ /** What went wrong. */+ code: ForwardCalendarEventErrorCode;+ /** A message fit to show the user. */+ message: string;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventErrorCode.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventErrorCode.tsnew file mode 100644index 0000000000..179566eb43--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventErrorCode.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Why a forward was not sent.+ */+export type ForwardCalendarEventErrorCode =+ (typeof ForwardCalendarEventErrorCode)[keyof typeof ForwardCalendarEventErrorCode];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ForwardCalendarEventErrorCode = {+ not_found: 'not_found',+ invalid_recipients: 'invalid_recipients',+ inbox_unavailable: 'inbox_unavailable',+ send_failed: 'send_failed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRecipient.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRecipient.tsnew file mode 100644index 0000000000..ae2e8eda25--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRecipient.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ForwardCalendarEventRecipientName } from './forwardCalendarEventRecipientName';++/**+ * One person a forwarded invitation goes to.+ */+export interface ForwardCalendarEventRecipient {+ /** Their email address. */+ email: string;+ /** Their display name. */+ name?: ForwardCalendarEventRecipientName;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRecipientName.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRecipientName.tsnew file mode 100644index 0000000000..9bc850d390--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRecipientName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Their display name.+ */+export type ForwardCalendarEventRecipientName = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRequest.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRequest.tsnew file mode 100644index 0000000000..d3c3c59d4a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRequest.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++import type { ForwardCalendarEventRecipient } from './forwardCalendarEventRecipient';+import type { ForwardCalendarEventRequestBodyText } from './forwardCalendarEventRequestBodyText';++/**+ * Who a forwarded invitation goes to, and what its email says.+ */+export interface ForwardCalendarEventRequest {+ /** The email's plain-text body. Without one, it names the event and+says the recipient won't be on the organizer's guest list. */+ bodyText?: ForwardCalendarEventRequestBodyText;+ /** The people it goes to, at most 50. */+ to: ForwardCalendarEventRecipient[];+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRequestBodyText.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRequestBodyText.tsnew file mode 100644index 0000000000..5f7b10b6ee--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventRequestBodyText.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The email's plain-text body. Without one, it names the event and+says the recipient won't be on the organizer's guest list.+ */+export type ForwardCalendarEventRequestBodyText = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventResponse.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventResponse.tsnew file mode 100644index 0000000000..0b721652c4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/forwardCalendarEventResponse.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The email the forward queued.+ */+export interface ForwardCalendarEventResponse {+ /** The sent message. */+ messageId: string;+ /** Its thread. */+ threadId: string;+}diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.tsindex 6423565917..d9e55083b9 100644--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts@@ -236,6 +236,13 @@ export * from './eventTimeOneOfTimeZone';export * from './eventTransparency';export * from './eventType';export * from './eventVisibility';+export * from './forwardCalendarEventError';+export * from './forwardCalendarEventErrorCode';+export * from './forwardCalendarEventRecipient';+export * from './forwardCalendarEventRecipientName';+export * from './forwardCalendarEventRequest';+export * from './forwardCalendarEventRequestBodyText';+export * from './forwardCalendarEventResponse';export * from './getActiveBackfillJobResponse';export * from './getAttachmentDocumentIDResponse';export * from './getAttachmentResponse';diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex 33a7040d88..ce54b9f137 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -388,6 +388,90 @@}}},+ "/email/calendar-events/{event_id}/forward": {+ "post": {+ "tags": ["email"],+ "summary": "Email one of the viewer's events to people the organizer's guest list\ndoes not name: the event's iCalendar file (`METHOD:PUBLISH`, no\nattendees, no join link), sent from the inbox that holds the viewer's\ncopy, with the usual undo delay. Recipients can add the event to their\nown calendar; they are not added to the guest list and the organizer is\nnot told.",+ "operationId": "forward_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "The viewer's copy of the event",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "202": {+ "description": "The email is queued to send",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventResponse"+ }+ }+ }+ },+ "400": {+ "description": "No, too many, or invalid recipients",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "The inbox holding the copy cannot send for the viewer",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ },+ "404": {+ "description": "No such event on one of the viewer's own inboxes",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ },+ "502": {+ "description": "The email could not be sent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ }+ }+ }+ },"/email/contacts": {"get": {"tags": ["Contacts"],@@ -5769,6 +5853,81 @@"description": "Visibility of event details.","enum": ["default", "public", "private", "confidential"]},+ "ForwardCalendarEventError": {+ "type": "object",+ "description": "A refused or failed forward.",+ "required": ["code", "message"],+ "properties": {+ "code": {+ "$ref": "#/components/schemas/ForwardCalendarEventErrorCode",+ "description": "What went wrong."+ },+ "message": {+ "type": "string",+ "description": "A message fit to show the user."+ }+ }+ },+ "ForwardCalendarEventErrorCode": {+ "type": "string",+ "description": "Why a forward was not sent.",+ "enum": [+ "not_found",+ "invalid_recipients",+ "inbox_unavailable",+ "send_failed"+ ]+ },+ "ForwardCalendarEventRecipient": {+ "type": "object",+ "description": "One person a forwarded invitation goes to.",+ "required": ["email"],+ "properties": {+ "email": {+ "type": "string",+ "description": "Their email address."+ },+ "name": {+ "type": ["string", "null"],+ "description": "Their display name."+ }+ }+ },+ "ForwardCalendarEventRequest": {+ "type": "object",+ "description": "Who a forwarded invitation goes to, and what its email says.",+ "required": ["to"],+ "properties": {+ "bodyText": {+ "type": ["string", "null"],+ "description": "The email's plain-text body. Without one, it names the event and\nsays the recipient won't be on the organizer's guest list."+ },+ "to": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ForwardCalendarEventRecipient"+ },+ "description": "The people it goes to, at most 50."+ }+ }+ },+ "ForwardCalendarEventResponse": {+ "type": "object",+ "description": "The email the forward queued.",+ "required": ["messageId", "threadId"],+ "properties": {+ "messageId": {+ "type": "string",+ "format": "uuid",+ "description": "The sent message."+ },+ "threadId": {+ "type": "string",+ "format": "uuid",+ "description": "Its thread."+ }+ }+ },"GetActiveBackfillJobResponse": {"type": "object","description": "The response returned from the get backfill job endpoint",diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex 2579bddde0..4b2f69da6d 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -234,6 +234,7 @@"email.listBackfillGmail": "List Backfill Gmail","email.getBackfillGmailActive": "Get Backfill Gmail Active","email.getBackfillGmail": "Get Backfill Gmail",+ "email.forwardCalendarEvent": "Forward Calendar Event","email.listContacts": "List Contacts","email.blockSender": "Block Sender","email.listBlockedSenders": "List Blocked Senders",diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 8ef1c70ae0..845105ee85 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -154,6 +154,12 @@ reminder dispatch, team availability, and provider/Postgres persistence.forwarded by email takes the same import through`CalendarSnapshotImporter::import_snapshot`, fed an `EventSnapshot` that`crates/email`'s `invitation_import` builds from the email's saved snapshot.+ The other direction, a guest forwarding their copy of an event, reads the+ same `.ics` through `CalendarEventForwardSource::event_forward`, which also+ names the inbox holding that copy (`meeting_copies`), and is `None` for a+ channel share or a delegated inbox's copy; `crates/email`'s+ `event_forward` sends it. The file names no attendees, so a recipient can+ only add it to their calendar and nothing reaches the organizer.- Asking to join a channel-shared event (`src/domain/join_requests.rs`) is aMacro-stored request, not an `entity_access` row: the grant is a provider guestwrite. Eligibility is the invite path's own `copy_capabilities` on thediff --git a/crates/calendar_events/src/domain/ics.rs b/crates/calendar_events/src/domain/ics.rsindex 1caa4bba2a..e46cb38eb9 100644--- a/crates/calendar_events/src/domain/ics.rs+++ b/crates/calendar_events/src/domain/ics.rs@@ -145,6 +145,17 @@ pub struct CalendarEventIcs {pub document: String,}+/// What forwarding one of the requester's events by email sends, and from+/// where: the same document the .ics export renders, and the inbox holding+/// the requester's own copy.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CalendarEventForward {+ /// The event as an iCalendar document, with its title.+ pub ics: CalendarEventIcs,+ /// Address of the requester's own inbox that holds the requested copy.+ pub inbox: String,+}+/// Render an event as a single-event `VCALENDAR` document.////// The UID is the meeting's own, so a client that already holds the meetingdiff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 08c62a7dd0..7f18de900f 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -7,7 +7,7 @@ use rootcause::Report;use uuid::Uuid;use super::copies::{CopyChange, CopyRefusal};-use super::ics::{CalendarEventExport, CalendarEventIcs, EventSnapshot};+use super::ics::{CalendarEventExport, CalendarEventForward, CalendarEventIcs, EventSnapshot};use super::join_requests::{CalendarJoinRequest, CalendarJoinRequestStatus};use super::meeting_links::{CreateEventWithMacroCallError, MeetingLink, MeetingLinkError, MeetingLinkRequest,@@ -1070,6 +1070,20 @@ pub trait CalendarSnapshotImporter: Send + Sync + 'static {) -> impl Future<Output = Result<CalendarEvent, CalendarMutationError>> + Send;}+/// Inbound service port reading what forwarding one of the requester's+/// events by email sends, for the host that sends the email.+pub trait CalendarEventForwardSource: Send + Sync + 'static {+ /// The requester's own copy of `event_id` as an iCalendar document,+ /// with the inbox holding that copy, which sends it. `None` when the+ /// event is cancelled, unknown, or not held through one of their own+ /// inboxes.+ fn event_forward(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Option<CalendarEventForward>, Report>> + Send;+}+/// Inbound service port creating events that carry a Macro call.////// The meeting is minted before the calendar write, so the one invitationdiff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex 33b1f60ba3..d7e9565868 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -9,7 +9,7 @@ use crate::domain::events::{CalendarEventMetadata, CalendarMacroEvent, CalendarTuse macro_event_broker::MacroEventBroker;use super::{- ics::{CalendarEventIcs, render_event_ics},+ ics::{CalendarEventExportAccess, CalendarEventForward, CalendarEventIcs, render_event_ics},models::{ActorInboxes, AppliedGoogleGrant, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,@@ -17,11 +17,11 @@ use super::{GoogleBackfillRunReport, GoogleCalendarSyncSnapshot, GoogleScopeSet, OccurrenceRange,},ports::{- CalendarBackfillRepository, CalendarEventChange, CalendarEventWrite,- CalendarEventWriteOutcome, CalendarOccurrenceService, CalendarProviderError,- CalendarProviderErrorKind, CalendarReauthNotifier, CalendarRepository,- GoogleCalendarProvider, GoogleCalendarSyncRepository, GoogleEventSyncContext,- RetiredCalendarEvent,+ CalendarBackfillRepository, CalendarEventChange, CalendarEventForwardSource,+ CalendarEventWrite, CalendarEventWriteOutcome, CalendarOccurrenceService,+ CalendarProviderError, CalendarProviderErrorKind, CalendarReauthNotifier,+ CalendarRepository, GoogleCalendarProvider, GoogleCalendarSyncRepository,+ GoogleEventSyncContext, RetiredCalendarEvent,},};@@ -237,6 +237,40 @@ where}))}+ /// The .ics a forward of the requester's own copy of an event carries,+ /// and that copy's inbox, which sends it. `None` unless `event_id` is a+ /// live copy held through one of the requester's own inboxes: a channel+ /// share or a delegated inbox's copy has no inbox of theirs to send from.+ #[tracing::instrument(skip(self, requester_id), err)]+ pub async fn event_forward(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> Result<Option<CalendarEventForward>, Report> {+ let copies = self+ .repository+ .meeting_copies(requester_id, event_id)+ .await?;+ let Some(copy) = copies.into_iter().find(|copy| copy.event_id == event_id) else {+ return Ok(None);+ };+ let Some(event) = self+ .repository+ .event_export(requester_id, event_id)+ .await?+ .filter(|event| event.access == CalendarEventExportAccess::OwnCopy)+ else {+ return Ok(None);+ };+ Ok(Some(CalendarEventForward {+ ics: CalendarEventIcs {+ document: render_event_ics(&event),+ title: event.title,+ },+ inbox: copy.inbox,+ }))+ }+/// Re-arm the watched inbox's sync job for a push notification whose/// channel token the adapter already verified. Returns whether the/// notification matched an active channel.@@ -260,6 +294,19 @@ where}}+impl<R> CalendarEventForwardSource for CalendarService<R>+where+ R: CalendarRepository,+{+ fn event_forward(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Option<CalendarEventForward>, Report>> + Send {+ CalendarService::event_forward(self, requester_id, event_id)+ }+}+impl<R> CalendarOccurrenceService for CalendarService<R>whereR: CalendarRepository,diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex afc09467dc..e3be8b4d5c 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -35,6 +35,10 @@ struct FakeRepo {recorded_sync_errors: Arc<Mutex<Vec<String>>>,/// Calendars recorded as refusing push channels, in order.recorded_watch_unsupported: Arc<Mutex<Vec<Uuid>>>,+ /// Copies `meeting_copies` reports for every event.+ meeting_copies: Vec<crate::domain::models::MeetingCopy>,+ /// What `event_export` resolves for every event.+ export: Option<crate::domain::ics::CalendarEventExport>,}impl CalendarRepository for FakeRepo {@@ -111,7 +115,7 @@ impl CalendarRepository for FakeRepo {_requester_id: &str,_event_id: Uuid,) -> Result<Vec<crate::domain::models::MeetingCopy>, Report> {- Ok(Vec::new())+ Ok(self.meeting_copies.clone())}async fn event_export(@@ -119,7 +123,7 @@ impl CalendarRepository for FakeRepo {_requester_id: &str,_event_id: Uuid,) -> Result<Option<crate::domain::ics::CalendarEventExport>, Report> {- unreachable!("event export is not exercised by sync tests")+ Ok(self.export.clone())}async fn open_join_request(@@ -1898,3 +1902,103 @@ async fn failure_to_persist_calendar_quarantine_fails_the_account_run() {assert!(lifecycle.completions.lock().unwrap().is_empty());assert_eq!(lifecycle.failures.lock().unwrap().len(), 1);}++fn forward_export(+ access: crate::domain::ics::CalendarEventExportAccess,+) -> crate::domain::ics::CalendarEventExport {+ crate::domain::ics::CalendarEventExport {+ access,+ owner_id: "macro|[email protected]".to_string(),+ event_type: EventType::Default,+ ical_uid: "[email protected]".to_string(),+ sequence: 2,+ title: "Office tour".to_string(),+ description: None,+ location: Some("12th floor".to_string()),+ time: EventTime::Timed {+ starts_at: Utc.with_ymd_and_hms(2026, 10, 30, 18, 0, 0).unwrap(),+ ends_at: Utc.with_ymd_and_hms(2026, 10, 30, 18, 30, 0).unwrap(),+ time_zone: None,+ },+ recurrence_lines: Vec::new(),+ organizer_email: Some("[email protected]".to_string()),+ organizer_name: None,+ updated_at: Utc.with_ymd_and_hms(2026, 10, 28, 12, 0, 0).unwrap(),+ }+}++fn forward_copy(event_id: Uuid, inbox: &str) -> crate::domain::models::MeetingCopy {+ crate::domain::models::MeetingCopy {+ event_id,+ inbox: inbox.to_string(),+ organizes: false,+ attends: true,+ }+}++#[tokio::test]+async fn event_forward_sends_the_export_from_the_requested_copys_inbox() {+ let requested = Uuid::now_v7();+ let other = Uuid::now_v7();+ let service = CalendarService::new(FakeRepo {+ meeting_copies: vec![+ forward_copy(other, "[email protected]"),+ forward_copy(requested, "[email protected]"),+ ],+ export: Some(forward_export(+ crate::domain::ics::CalendarEventExportAccess::OwnCopy,+ )),+ ..FakeRepo::default()+ });++ let forward = service+ .event_forward("macro|[email protected]", requested)+ .await+ .unwrap()+ .expect("the requester's own copy can be forwarded");++ assert_eq!(forward.inbox, "[email protected]");+ assert_eq!(forward.ics.title, "Office tour");+ assert!(forward.ics.document.contains("METHOD:PUBLISH"));+ assert!(forward.ics.document.contains("UID:[email protected]"));+ assert!(!forward.ics.document.contains("ATTENDEE"));+}++#[tokio::test]+async fn event_forward_refuses_an_event_none_of_the_requesters_inboxes_holds() {+ // A delegated inbox's copy or a channel share lists no copy of the+ // requester's own for the requested event.+ let service = CalendarService::new(FakeRepo {+ meeting_copies: vec![forward_copy(Uuid::now_v7(), "[email protected]")],+ export: Some(forward_export(+ crate::domain::ics::CalendarEventExportAccess::OwnCopy,+ )),+ ..FakeRepo::default()+ });++ let forward = service+ .event_forward("macro|[email protected]", Uuid::now_v7())+ .await+ .unwrap();++ assert_eq!(forward, None);+}++#[tokio::test]+async fn event_forward_refuses_a_copy_the_export_no_longer_resolves_as_owned() {+ let requested = Uuid::now_v7();+ let service = CalendarService::new(FakeRepo {+ meeting_copies: vec![forward_copy(requested, "[email protected]")],+ export: Some(forward_export(+ crate::domain::ics::CalendarEventExportAccess::ChannelShared,+ )),+ ..FakeRepo::default()+ });++ let forward = service+ .event_forward("macro|[email protected]", requested)+ .await+ .unwrap();++ assert_eq!(forward, None);+}diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex 11ed02f191..9e083116a2 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -29,7 +29,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=y.pop()??"";for(let a of y){let i=a.split(``),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Q5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(Y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=K5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},x0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=Q5(x),X=Object.entries(S).map(([K,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var J5=/\{[^{}]+\}/g,V5=({path:$,url:O})=>{let j=O,x=O.match(J5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,j0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,x0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},OS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=V5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Z1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var jS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var xS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var SS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=j0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=x0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=qO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},ZS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},W5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function XS($){for(let O of $.security??[]){if(W5($,O.name))continue;let j=await jS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var X1=($)=>OS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:SS($.querySerializer),url:$.url}),G1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Z0($.headers,O.headers),j},B5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Z0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class S0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var GS=()=>({error:new S0,request:new S0,response:new S0}),L5=SS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),N5={"Content-Type":"application/json"},Xj=($={})=>({...xS,headers:N5,parseAs:"auto",querySerializer:L5,...$});var K1=($={})=>{let O=G1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=G1(O,Q),j()},S=GS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Z0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await XS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=X1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:Z1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?ZS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return $S({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Z1(I),url:z})};return{buildUrl:(Q)=>X1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var KS=K1(Xj());class YS{client;constructor($){this.client=$?.client??KS}}class QS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class X0 extends YS{static __registry=new QS;constructor($){super($);X0.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function JS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Q5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(Y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=K5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},x0=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=Q5(x),X=Object.entries(S).map(([K,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var J5=/\{[^{}]+\}/g,V5=({path:$,url:O})=>{let j=O,x=O.match(J5);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,j0({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,x0({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},OS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=V5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Z1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var jS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var xS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var SS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=j0({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=x0({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=qO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},ZS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},W5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function XS($){for(let O of $.security??[]){if(W5($,O.name))continue;let j=await jS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var X1=($)=>OS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:SS($.querySerializer),url:$.url}),G1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Z0($.headers,O.headers),j},B5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Z0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B5(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class S0{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var GS=()=>({error:new S0,request:new S0,response:new S0}),L5=SS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),N5={"Content-Type":"application/json"},Xj=($={})=>({...xS,headers:N5,parseAs:"auto",querySerializer:L5,...$});var K1=($={})=>{let O=G1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=G1(O,Q),j()},S=GS(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Z0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await XS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=X1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:Z1(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?ZS(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return $S({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:Z1(I),url:z})};return{buildUrl:(Q)=>X1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var KS=K1(Xj());class YS{client;constructor($){this.client=$?.client??KS}}class QS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class X0 extends YS{static __registry=new QS;constructor($){super($);X0.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function JS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex 5c333bb683..4208260304 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -20,8 +20,10 @@ tools — hexagonal, heavily feature-gated.## Scope- Owns: email/thread domain logic, scheduled delivery, reminders/followups,- calendar invitation extraction and resolution, and adding a forwarded- event (`METHOD:PUBLISH`) to the viewer's calendar (`domain/invitation_import.rs`).+ calendar invitation extraction and resolution, adding a forwarded+ event (`METHOD:PUBLISH`) to the viewer's calendar (`domain/invitation_import.rs`),+ and forwarding one of the viewer's events as that same file from the inbox+ holding their copy (`domain/event_forward.rs`).- Not here: raw provider API calls → `email_api_client`; HTMLparsing/sanitization → `email_utils`; SQLx queries over email tables →`email_db_client`.@@ -61,6 +63,11 @@ tools — hexagonal, heavily feature-gated.- Forwarded attachments register through `domain/draft_attachments.rs` and resolvebytes through `domain/attachment_access.rs`; scheduled delivery also recheckssource inbox access in `domain/forwarded_attachments.rs`, including legacy jobs.+- A send with files staged before delivery goes through+ `StagedAttachmentSender` (`domain/service/attachments.rs`): draft, staged+ attachment rows, then the send. `DraftAttachmentSender` adds Macro documents+ as the source of those files for `SendEmail`; a caller that already holds+ the bytes, such as an event forward's `.ics`, uses `send_with_files`.- Saved invitation snapshots are JSONB and never re-extracted. `recurrence`is `None` on snapshots saved before it was recorded, where a series lookslike a single event, so those cannot be added to a calendar.diff --git a/crates/email/src/domain.rs b/crates/email/src/domain.rsindex 48cfca2571..5e3b191ed8 100644--- a/crates/email/src/domain.rs+++ b/crates/email/src/domain.rs@@ -2,6 +2,8 @@pub mod activity;#[cfg(feature = "calendar_invitations")]pub mod calendar_invitation_parser;+#[cfg(all(feature = "calendar_invitations", feature = "ports"))]+pub mod event_forward;pub mod events;#[cfg(feature = "ports")]pub mod followup;diff --git a/crates/email/src/domain/event_forward.rs b/crates/email/src/domain/event_forward.rsnew file mode 100644index 0000000000..0aa7cf2374--- /dev/null+++ b/crates/email/src/domain/event_forward.rs@@ -0,0 +1,250 @@+//! Forward one of the viewer's calendar events by email, as a guest whose+//! organizer does not let them add guests forwards the invitation instead:+//! the event's iCalendar file, the one the .ics export renders, sent from+//! the inbox that holds their copy.+//!+//! The file is `METHOD:PUBLISH` and names no attendees, so a recipient can+//! add the event to their own calendar but has nothing to answer: nothing+//! reaches the organizer and the guest list stays as the organizer keeps+//! it. A Macro recipient sees it as a shared event with Add to calendar+//! ([`super::invitation_import`]).++#[cfg(test)]+mod test;++use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use calendar_events::domain::ports::CalendarEventForwardSource;+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};+use uuid::Uuid;++use super::{+ models::{+ ContactInfo, CreateDraftInput, CreatedDraft, EmailErr, SendingInboxRequest,+ SourcedAttachment,+ },+ ports::{EmailFileSendService, SendingInboxResolver},+};++/// The most people one forward goes to.+pub const MAX_FORWARD_RECIPIENTS: usize = 50;++/// The type the event file is attached with, as Forward by email attaches it.+const ICS_CONTENT_TYPE: &str = "text/calendar";++/// What a forward sends besides the event file.+#[derive(Debug, Clone)]+pub struct EventForwardRequest {+ /// The people it goes to.+ pub to: Vec<ContactInfo>,+ /// The plain-text body; a short note names the event when absent.+ pub body_text: Option<String>,+}++/// Why a forward was not sent.+#[derive(Debug, thiserror::Error)]+pub enum EventForwardError {+ /// The event is unknown, cancelled, or not held through one of the+ /// requester's own inboxes.+ #[error("event not found")]+ NotFound,+ /// The recipients are missing, too many, or not email addresses.+ #[error("{0}")]+ InvalidRecipients(&'static str),+ /// The inbox holding the copy cannot send for the requester.+ #[error("the inbox holding this event cannot send email")]+ InboxUnavailable,+ /// The send failed.+ #[error(transparent)]+ Email(EmailErr),+ /// Reading the event failed.+ #[error("failed to read the event")]+ Internal(rootcause::Report),+}++impl EventForwardError {+ fn outcome(&self) -> &'static str {+ match self {+ Self::NotFound => "not_found",+ Self::InvalidRecipients(_) => "invalid_recipients",+ Self::InboxUnavailable => "inbox_unavailable",+ Self::Email(_) | Self::Internal(_) => "failed",+ }+ }+}++/// Send `event_id`'s iCalendar file to the requested people from the inbox+/// holding the actor's copy of it. The send is queued like any other, so it+/// leaves after the usual undo delay.+#[tracing::instrument(+ name = "email.forward_calendar_event",+ skip(calendar, email, sender, actor, request),+ fields(%event_id, recipient_count = request.to.len(), link_id, outcome),+ err+)]+pub async fn forward_event<C, E, F>(+ calendar: &C,+ email: &E,+ sender: &F,+ actor: MacroUserIdStr<'static>,+ event_id: Uuid,+ request: EventForwardRequest,+) -> Result<CreatedDraft, EventForwardError>+where+ C: CalendarEventForwardSource,+ E: SendingInboxResolver,+ F: EmailFileSendService,+{+ let result = send_forward(calendar, email, sender, actor, event_id, request).await;+ let span = tracing::Span::current();+ match &result {+ Ok(sent) => {+ span.record("link_id", tracing::field::display(sent.link_id));+ span.record("outcome", "sent");+ }+ Err(error) => {+ span.record("outcome", error.outcome());+ }+ }+ result+}++async fn send_forward<C, E, F>(+ calendar: &C,+ email: &E,+ sender: &F,+ actor: MacroUserIdStr<'static>,+ event_id: Uuid,+ request: EventForwardRequest,+) -> Result<CreatedDraft, EventForwardError>+where+ C: CalendarEventForwardSource,+ E: SendingInboxResolver,+ F: EmailFileSendService,+{+ let to = recipients(request.to)?;+ let forward = calendar+ .event_forward(&actor.to_string(), event_id)+ .await+ .map_err(EventForwardError::Internal)?+ .ok_or(EventForwardError::NotFound)?;+ let inbox = email+ .resolve_sending_inbox(+ actor.clone(),+ SendingInboxRequest {+ requested_address: Some(&forward.inbox),+ replying_to_id: None,+ },+ )+ .await+ .map_err(|error| match error {+ EmailErr::InboxNotFound | EmailErr::UnknownSendingInbox { .. } => {+ EventForwardError::InboxUnavailable+ }+ other => EventForwardError::Email(other),+ })?;++ let title = match forward.ics.title.trim() {+ "" => "Untitled event",+ title => title,+ };+ let body_text = request+ .body_text+ .filter(|body| !body.trim().is_empty())+ .unwrap_or_else(|| default_body(title));+ let input = CreateDraftInput {+ frozen_signature_html: None,+ draft_generation: 0,+ sender_email: None,+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: None,+ subject: title.to_owned(),+ to,+ cc: Vec::new(),+ bcc: Vec::new(),+ body_html: Some(URL_SAFE_NO_PAD.encode(text_html(&body_text))),+ body_text: Some(body_text),+ body_macro: None,+ headers_json: None,+ send_time: None,+ include_signature: None,+ actor: Some(actor),+ draft_client_binding: None,+ thread_client_binding: None,+ };+ let file = SourcedAttachment {+ file_name: format!("{}.ics", file_stem(title)),+ content_type: ICS_CONTENT_TYPE.to_owned(),+ bytes: forward.ics.document.into_bytes(),+ };+ sender+ .send_message_with_files(&inbox.link, &inbox.accessible_inboxes, input, vec![file])+ .await+ .map_err(EventForwardError::Email)+}++/// The requested recipients as valid, distinct addresses, in the order given.+fn recipients(requested: Vec<ContactInfo>) -> Result<Vec<ContactInfo>, EventForwardError> {+ let mut seen = std::collections::HashSet::new();+ let mut to = Vec::with_capacity(requested.len());+ for contact in requested {+ let email = contact.email.trim().to_owned();+ EmailStr::parse_from_str(&email).map_err(|_| {+ EventForwardError::InvalidRecipients("a recipient is not an email address")+ })?;+ if seen.insert(email.to_lowercase()) {+ to.push(ContactInfo { email, ..contact });+ }+ }+ if to.is_empty() {+ return Err(EventForwardError::InvalidRecipients(+ "choose at least one person to forward the invitation to",+ ));+ }+ if to.len() > MAX_FORWARD_RECIPIENTS {+ return Err(EventForwardError::InvalidRecipients(+ "an invitation can be forwarded to at most 50 people at once",+ ));+ }+ Ok(to)+}++fn default_body(title: &str) -> String {+ format!(+ "{title}\n\nThis invitation was forwarded to you. Add the event to your calendar \+ from the attached file. You won't be on the organizer's guest list."+ )+}++/// The plain body as HTML: escaped, one line per line.+fn text_html(text: &str) -> String {+ let mut html = String::with_capacity(text.len() + 16);+ html.push_str("<div>");+ for character in text.chars() {+ match character {+ '&' => html.push_str("&"),+ '<' => html.push_str("<"),+ '>' => html.push_str(">"),+ '"' => html.push_str("""),+ '\n' => html.push_str("<br>"),+ '\r' => {}+ other => html.push(other),+ }+ }+ html.push_str("</div>");+ html+}++/// The title as a file name: no path separators or control characters.+fn file_stem(title: &str) -> String {+ title+ .chars()+ .map(|character| match character {+ '/' | '\\' => '-',+ character if character.is_control() => ' ',+ character => character,+ })+ .collect()+}diff --git a/crates/email/src/domain/event_forward/test.rs b/crates/email/src/domain/event_forward/test.rsnew file mode 100644index 0000000000..ac84edd55c--- /dev/null+++ b/crates/email/src/domain/event_forward/test.rs@@ -0,0 +1,320 @@+use super::*;+use crate::domain::models::{Link, ResolvedSendingInbox, UserProvider};+use calendar_events::domain::ics::{CalendarEventForward, CalendarEventIcs};+use rootcause::Report;+use std::sync::Mutex;++const EVENT_ICS: &str = "BEGIN:VCALENDAR\r\nMETHOD:PUBLISH\r\nEND:VCALENDAR\r\n";++fn actor() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn link(address: &str) -> Link {+ Link {+ id: Uuid::from_u128(0x11),+ macro_id: actor(),+ fusionauth_user_id: String::new(),+ email_address: EmailStr::try_from(address.to_owned()).unwrap(),+ provider: UserProvider::Gmail,+ is_sync_active: true,+ is_primary: false,+ created_at: Default::default(),+ updated_at: Default::default(),+ }+}++fn contact(email: &str) -> ContactInfo {+ ContactInfo {+ email: email.to_owned(),+ name: None,+ photo_url: None,+ }+}++/// One fake behind every port, recording what the use case asked of each.+#[derive(Default)]+struct Fake {+ /// What the calendar answers; `None` is an event the requester cannot forward.+ forward: Option<CalendarEventForward>,+ /// Inboxes the requester can send from.+ inboxes: Vec<&'static str>,+ resolved_addresses: Mutex<Vec<Option<String>>>,+ sent: Mutex<Vec<(Uuid, CreateDraftInput, Vec<SourcedAttachment>)>>,+}++impl CalendarEventForwardSource for Fake {+ async fn event_forward(+ &self,+ requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Option<CalendarEventForward>, Report> {+ assert_eq!(requester_id, "macro|[email protected]");+ Ok(self.forward.clone())+ }+}++impl SendingInboxResolver for Fake {+ async fn resolve_sending_inbox(+ &self,+ _macro_id: MacroUserIdStr<'_>,+ request: SendingInboxRequest<'_>,+ ) -> Result<ResolvedSendingInbox, EmailErr> {+ let requested = request.requested_address.map(str::to_owned);+ self.resolved_addresses+ .lock()+ .unwrap()+ .push(requested.clone());+ let requested = requested.unwrap_or_default();+ if !self.inboxes.contains(&requested.as_str()) {+ return Err(EmailErr::UnknownSendingInbox {+ requested,+ available: self.inboxes.iter().map(|inbox| inbox.to_string()).collect(),+ });+ }+ Ok(ResolvedSendingInbox {+ link: link(&requested),+ accessible_inboxes: self.inboxes.iter().map(|inbox| link(inbox)).collect(),+ })+ }+}++impl EmailFileSendService for Fake {+ async fn send_message_with_files(+ &self,+ link: &Link,+ _accessible_inboxes: &[Link],+ input: CreateDraftInput,+ files: Vec<SourcedAttachment>,+ ) -> Result<CreatedDraft, EmailErr> {+ let created = CreatedDraft {+ draft_generation: 0,+ db_id: Uuid::from_u128(0xd1),+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: Uuid::from_u128(0x7a),+ link_id: link.id,+ subject: input.subject.clone(),+ to: input.to.clone(),+ cc: Vec::new(),+ bcc: Vec::new(),+ body_text: input.body_text.clone(),+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: None,+ };+ self.sent.lock().unwrap().push((link.id, input, files));+ Ok(created)+ }+}++fn guest_copy(title: &str) -> Fake {+ Fake {+ forward: Some(CalendarEventForward {+ ics: CalendarEventIcs {+ title: title.to_owned(),+ document: EVENT_ICS.to_owned(),+ },+ inbox: "[email protected]".to_owned(),+ }),+ inboxes: vec!["[email protected]", "[email protected]"],+ ..Fake::default()+ }+}++async fn forward(+ fake: &Fake,+ request: EventForwardRequest,+) -> Result<CreatedDraft, EventForwardError> {+ forward_event(fake, fake, fake, actor(), Uuid::from_u128(0xe1), request).await+}++#[tokio::test]+async fn sends_the_event_file_from_the_inbox_holding_the_copy() {+ let fake = guest_copy("Office tour");+ let sent = forward(+ &fake,+ EventForwardRequest {+ to: vec![contact("[email protected]")],+ body_text: Some("Office tour\nWhen: Friday".to_owned()),+ },+ )+ .await+ .unwrap();++ assert_eq!(sent.db_id, Uuid::from_u128(0xd1));+ assert_eq!(+ *fake.resolved_addresses.lock().unwrap(),+ [Some("[email protected]".to_owned())],+ "the copy's own inbox sends, not the requester's default one"+ );+ let sent = fake.sent.lock().unwrap();+ let (_, input, files) = &sent[0];+ assert_eq!(input.subject, "Office tour");+ assert_eq!(input.to.len(), 1);+ assert_eq!(input.to[0].email, "[email protected]");+ assert!(input.cc.is_empty() && input.bcc.is_empty());+ assert_eq!(input.replying_to_id, None);+ assert_eq!(+ input.body_text.as_deref(),+ Some("Office tour\nWhen: Friday")+ );+ let html = URL_SAFE_NO_PAD+ .decode(input.body_html.as_deref().unwrap())+ .unwrap();+ assert_eq!(+ String::from_utf8(html).unwrap(),+ "<div>Office tour<br>When: Friday</div>"+ );+ assert_eq!(+ input.actor.as_ref().map(ToString::to_string).as_deref(),+ Some("macro|[email protected]")+ );+ assert_eq!(files.len(), 1);+ assert_eq!(files[0].file_name, "Office tour.ics");+ assert_eq!(files[0].content_type, "text/calendar");+ assert_eq!(files[0].bytes, EVENT_ICS.as_bytes());+}++#[tokio::test]+async fn a_missing_body_names_the_event_and_says_the_guest_list_is_unchanged() {+ let fake = guest_copy(" ");+ forward(+ &fake,+ EventForwardRequest {+ to: vec![contact("[email protected]")],+ body_text: Some(" ".to_owned()),+ },+ )+ .await+ .unwrap();++ let sent = fake.sent.lock().unwrap();+ let (_, input, files) = &sent[0];+ assert_eq!(input.subject, "Untitled event");+ let body = input.body_text.as_deref().unwrap();+ assert!(body.starts_with("Untitled event\n\n"), "{body}");+ assert!(+ body.contains("You won't be on the organizer's guest list."),+ "{body}"+ );+ assert_eq!(files[0].file_name, "Untitled event.ics");+}++#[tokio::test]+async fn markup_in_the_body_is_escaped_and_the_title_cannot_name_a_path() {+ let fake = guest_copy("Q3/Q4 <review>");+ forward(+ &fake,+ EventForwardRequest {+ to: vec![contact("[email protected]")],+ body_text: Some("<b>&</b>".to_owned()),+ },+ )+ .await+ .unwrap();++ let sent = fake.sent.lock().unwrap();+ let (_, input, files) = &sent[0];+ let html = URL_SAFE_NO_PAD+ .decode(input.body_html.as_deref().unwrap())+ .unwrap();+ assert_eq!(+ String::from_utf8(html).unwrap(),+ "<div><b>&</b></div>"+ );+ assert_eq!(files[0].file_name, "Q3-Q4 <review>.ics");+}++#[tokio::test]+async fn recipients_are_trimmed_and_deduplicated_in_order() {+ let fake = guest_copy("Office tour");+ forward(+ &fake,+ EventForwardRequest {+ to: vec![+ contact(" [email protected] "),+ contact("[email protected]"),+ contact("[email protected]"),+ ],+ body_text: None,+ },+ )+ .await+ .unwrap();++ let sent = fake.sent.lock().unwrap();+ let emails: Vec<_> = sent[0].1.to.iter().map(|to| to.email.as_str()).collect();+ assert_eq!(emails, ["[email protected]", "[email protected]"]);+}++#[tokio::test]+async fn invalid_recipients_are_refused_before_anything_is_read() {+ for to in [+ vec![],+ vec![contact("not an address")],+ (0..=MAX_FORWARD_RECIPIENTS)+ .map(|index| contact(&format!("person{index}@example.org")))+ .collect(),+ ] {+ let fake = guest_copy("Office tour");+ let error = forward(+ &fake,+ EventForwardRequest {+ to,+ body_text: None,+ },+ )+ .await+ .unwrap_err();+ assert!(+ matches!(error, EventForwardError::InvalidRecipients(_)),+ "{error:?}"+ );+ assert!(fake.resolved_addresses.lock().unwrap().is_empty());+ assert!(fake.sent.lock().unwrap().is_empty());+ }+}++#[tokio::test]+async fn an_event_the_requester_cannot_forward_is_not_found() {+ let fake = Fake {+ inboxes: vec!["[email protected]"],+ ..Fake::default()+ };+ let error = forward(+ &fake,+ EventForwardRequest {+ to: vec![contact("[email protected]")],+ body_text: None,+ },+ )+ .await+ .unwrap_err();+ assert!(matches!(error, EventForwardError::NotFound), "{error:?}");+ assert!(fake.sent.lock().unwrap().is_empty());+}++#[tokio::test]+async fn an_inbox_that_cannot_send_is_refused_rather_than_replaced() {+ let fake = Fake {+ inboxes: vec!["[email protected]"],+ ..guest_copy("Office tour")+ };+ let error = forward(+ &fake,+ EventForwardRequest {+ to: vec![contact("[email protected]")],+ body_text: None,+ },+ )+ .await+ .unwrap_err();+ assert!(+ matches!(error, EventForwardError::InboxUnavailable),+ "{error:?}"+ );+ assert!(fake.sent.lock().unwrap().is_empty());+}diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rsindex 8feb542004..a3f514fb27 100644--- a/crates/email/src/domain/ports.rs+++ b/crates/email/src/domain/ports.rs@@ -1118,6 +1118,41 @@ impl<T: EmailService> DraftSendService for T {}}+/// Narrow port choosing the inbox a composed email is sent from, for use+/// cases that need nothing else of the [`EmailService`].+pub trait SendingInboxResolver: Send + Sync + 'static {+ /// See [`EmailService::resolve_sending_inbox`].+ fn resolve_sending_inbox(+ &self,+ macro_id: MacroUserIdStr<'_>,+ request: SendingInboxRequest<'_>,+ ) -> impl Future<Output = Result<ResolvedSendingInbox, EmailErr>> + Send;+}++impl<T: EmailService> SendingInboxResolver for T {+ fn resolve_sending_inbox(+ &self,+ macro_id: MacroUserIdStr<'_>,+ request: SendingInboxRequest<'_>,+ ) -> impl Future<Output = Result<ResolvedSendingInbox, EmailErr>> + Send {+ EmailService::resolve_sending_inbox(self, macro_id, request)+ }+}++/// Use case: send a message carrying files the caller already holds, such+/// as an event's iCalendar file.+pub trait EmailFileSendService: Send + Sync + 'static {+ /// Like [`EmailService::send_message`], with every file staged on the+ /// message before delivery is queued. With no files it is exactly a send.+ fn send_message_with_files(+ &self,+ link: &Link,+ accessible_inboxes: &[Link],+ input: CreateDraftInput,+ files: Vec<SourcedAttachment>,+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;+}+/// Use case: send a message carrying Macro documents as attachments.////// Object-safe (boxed future) so a tool context can hold any implementationdiff --git a/crates/email/src/domain/service/attachments.rs b/crates/email/src/domain/service/attachments.rsindex 2b0cace4f2..45e58a3f01 100644--- a/crates/email/src/domain/service/attachments.rs+++ b/crates/email/src/domain/service/attachments.rs@@ -1,4 +1,5 @@-//! Sending an email with Macro documents attached.+//! Sending an email with files attached: Macro documents, or files the+//! caller produced itself, such as an event's iCalendar file.//!//! The scheduled sender attaches whatever `email_attachments_drafts` rows a//! message has when its delivery runs, so attachments must be staged on a@@ -22,27 +23,43 @@ use crate::domain::{},ports::{DraftAttachmentRepo, DraftAttachmentSource, DraftAttachmentStorage, DraftSendService,- EmailAttachmentSendService,+ EmailAttachmentSendService, EmailFileSendService,},};-/// [`EmailAttachmentSendService`] over a [`DraftSendService`] (any-/// `EmailService`) for the draft and the send, plus the three attachment ports.-pub struct DraftAttachmentSender<Svc, R, S, St> {+/// [`EmailFileSendService`] over a [`DraftSendService`] (any+/// `EmailService`) for the draft and the send, plus the draft attachment+/// record and its object store: sends files the caller already holds.+pub struct StagedAttachmentSender<Svc, R, St> {email: Arc<Svc>,repo: R,- source: S,storage: St,}+impl<Svc, R, St> StagedAttachmentSender<Svc, R, St> {+ /// Compose the sender from the email service and the staging ports.+ pub fn new(email: Arc<Svc>, repo: R, storage: St) -> Self {+ Self {+ email,+ repo,+ storage,+ }+ }+}++/// [`EmailAttachmentSendService`] over a [`StagedAttachmentSender`], with+/// the documents a send names resolved into files through `source`.+pub struct DraftAttachmentSender<Svc, R, S, St> {+ staged: StagedAttachmentSender<Svc, R, St>,+ source: S,+}+impl<Svc, R, S, St> DraftAttachmentSender<Svc, R, S, St> {/// Compose the sender from the email service and the attachment ports.pub fn new(email: Arc<Svc>, repo: R, source: S, storage: St) -> Self {Self {- email,- repo,+ staged: StagedAttachmentSender::new(email, repo, storage),source,- storage,}}}@@ -80,11 +97,10 @@ pub(crate) fn input_for_staged_draft(input}-impl<Svc, R, S, St> DraftAttachmentSender<Svc, R, S, St>+impl<Svc, R, St> StagedAttachmentSender<Svc, R, St>whereSvc: DraftSendService,R: DraftAttachmentRepo,- S: DraftAttachmentSource,St: DraftAttachmentStorage,anyhow::Error: From<R::Err>,{@@ -142,28 +158,24 @@ where}}- async fn send_with_attachments(+ /// Send `input` with `files` staged on its draft first; with no files+ /// it is exactly a send. An oversized set is refused before any draft+ /// exists.+ pub async fn send_with_files(&self,link: &Link,accessible_inboxes: &[Link],input: CreateDraftInput,- attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,+ files: Vec<SourcedAttachment>,) -> Result<CreatedDraft, EmailErr> {- if attachments.is_empty() {+ if files.is_empty() {return self.send_message(link, accessible_inboxes, input).await;}-- // Check the running total after each download, so an oversized set- // fails as soon as it crosses the limit rather than after every file- // is held in memory.- let mut sourced = Vec::with_capacity(attachments.len());- for receipt in attachments {- sourced.push(self.source.fetch_attachment(receipt).await?);- total_attachment_bytes(&sourced)?;- }+ total_attachment_bytes(&files)?;+ let sourced = files;let mut draft_input = input.clone();draft_input.send_time = None;@@ -184,6 +196,53 @@ where}}+impl<Svc, R, St> EmailFileSendService for StagedAttachmentSender<Svc, R, St>+where+ Svc: DraftSendService,+ R: DraftAttachmentRepo,+ St: DraftAttachmentStorage,+ anyhow::Error: From<R::Err>,+{+ fn send_message_with_files(+ &self,+ link: &Link,+ accessible_inboxes: &[Link],+ input: CreateDraftInput,+ files: Vec<SourcedAttachment>,+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send {+ self.send_with_files(link, accessible_inboxes, input, files)+ }+}++impl<Svc, R, S, St> DraftAttachmentSender<Svc, R, S, St>+where+ Svc: DraftSendService,+ R: DraftAttachmentRepo,+ S: DraftAttachmentSource,+ St: DraftAttachmentStorage,+ anyhow::Error: From<R::Err>,+{+ async fn send_with_attachments(+ &self,+ link: &Link,+ accessible_inboxes: &[Link],+ input: CreateDraftInput,+ attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,+ ) -> Result<CreatedDraft, EmailErr> {+ // Check the running total after each download, so an oversized set+ // fails as soon as it crosses the limit rather than after every file+ // is held in memory.+ let mut sourced = Vec::with_capacity(attachments.len());+ for receipt in attachments {+ sourced.push(self.source.fetch_attachment(receipt).await?);+ total_attachment_bytes(&sourced)?;+ }+ self.staged+ .send_with_files(link, accessible_inboxes, input, sourced)+ .await+ }+}+impl<Svc, R, S, St> EmailAttachmentSendService for DraftAttachmentSender<Svc, R, S, St>whereSvc: DraftSendService,diff --git a/crates/email/src/domain/service/attachments/test.rs b/crates/email/src/domain/service/attachments/test.rsindex af81e638cc..94e9e394fe 100644--- a/crates/email/src/domain/service/attachments/test.rs+++ b/crates/email/src/domain/service/attachments/test.rs@@ -347,3 +347,56 @@ fn the_attachment_key_matches_the_draft_attachment_api_layout() {format!("draft/{draft}/{attachment}"));}++#[tokio::test]+async fn a_file_the_caller_holds_is_staged_on_the_draft_then_sent() {+ let fake = fake_with(vec![]);+ let sent = StagedAttachmentSender::new(fake.clone(), fake.clone(), fake.clone())+ .send_message_with_files(+ &link(),+ &[link()],+ input(),+ vec![SourcedAttachment {+ file_name: "Office tour.ics".to_owned(),+ content_type: "text/calendar".to_owned(),+ bytes: vec![1, 2],+ }],+ )+ .await+ .unwrap();+ assert_eq!(sent.db_id, fake.draft_id);++ let calls = fake.calls.take();+ assert_eq!(calls[0], "create_draft");+ assert!(calls[1].starts_with(&format!("put:draft/{}/", fake.draft_id)));+ assert!(calls[1].ends_with(":text/calendar"));+ assert_eq!(calls[2], "record:Office tour.ics:text/calendar:2");+ assert_eq!(+ calls[3],+ format!("send:{}:{}", fake.draft_id, fake.thread_id)+ );+ assert_eq!(calls.len(), 4);+}++#[tokio::test]+async fn oversized_files_are_refused_before_any_draft_exists() {+ let fake = fake_with(vec![]);+ let error = StagedAttachmentSender::new(fake.clone(), fake.clone(), fake.clone())+ .send_message_with_files(+ &link(),+ &[link()],+ input(),+ vec![SourcedAttachment {+ file_name: "big.ics".to_owned(),+ content_type: "text/calendar".to_owned(),+ bytes: vec![0; MAX_DRAFT_ATTACHMENTS_BYTES + 1],+ }],+ )+ .await+ .unwrap_err();+ assert!(+ matches!(error, EmailErr::AttachmentsTooLarge { .. }),+ "got {error:?}"+ );+ assert!(fake.calls.take().is_empty());+}diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 690d3236b7..12f4486946 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -617,6 +617,29 @@ cannot be added while the organizer hides the guest list.` instead. To check thestates without a Google account, answer `POST /events/{id}/guests` with HTTP 403 and code`guests_cannot_invite` or `guest_list_hidden`; each switches the guest list to its ownexplanation and toast.+In each of those cases (inviting off, a hidden guest list, an Outlook guest copy, and after+a refusal), the `enable-calendar-invitation-forward` flag (on in dev, with no PostHog flag+yet, so off in production) puts `Forward invitation` (a paper-plane icon) where `Add guests`+would be, whether or not guest invites are on, and the explanation goes on: `You can forward the invitation instead. The people+you send it to can add the event to their calendar but won't be on the guest list.` It opens+the same add-only editor (current guests under `Invited`, the picker adds people listed as+`Forward to`), says `They can add the event to their calendar but won't appear in the guest+list.`, and `Forward` (or Cmd/Ctrl+Enter) sends; there is no Optional box or occurrence+choice, since the forward always carries the whole series. It posts+`POST /email/calendar-events/{event_id}/forward` with the recipients and a body made of+`Forward by email`'s summary plus `This invitation was forwarded to you. Add the event to+your calendar from the attached file. You won't be on the organizer's guest list.`; email-service sends it from the inbox+holding the copy, with the event's `.ics` (`METHOD:PUBLISH`, no guests or join link)+attached, so recipients can add the event to their calendar and nothing reaches the+organizer or the guest list. The toast reads `Invitation forwarded to <name>` (or `to N+people`) once the send is accepted; a failure reads `Could not forward the invitation`, with+`Retry` unless the server refused the recipients (400 `invalid_recipients`, whose reason+shows instead). The editor offers the same `Forward invitation` beside its read-only guests+pill, whose tooltip carries the longer explanation. Event details stay open while the+forward editor is, as they do for `Add guests`. Snapshots, cancelled events, read-only+copies and team projections offer nothing. To check the toasts without sending mail, answer+the route with 202 `{messageId, threadId}`, or with 502 `send_failed` or 400+`invalid_recipients`.An event that reached several connected inboxes shows one chip per inbox (overlapping;tell them apart by calendar color), and each copy answers only for its own inbox: aguest copy stays a guest copy, marked `(you)` on that inbox's row alone, even when@@ -665,7 +688,8 @@ switches (`Guest permissions apply to all events. Choose All events to change thchoosing `This event` returns it to the stored values. Save sends `guestPolicy` only when itchanged. Guests whose copies Macro holds follow at once, since the organizer's stored copyhands its policy to theirs; others follow once Google syncs their copies. Turning `Invite others`-off replaces a guest's `Add guests` with `Only the organizer can invite guests.` The update+off replaces a guest's `Add guests` with `Only the organizer can invite guests.` (and, with+the forward flag on, `Forward invitation`). The updaterefuses a policy change from anyone but the organizer with 403 `not_organizer`, and on anOutlook event with`provider_rejected`. `viewerCan.organize` marks the organizer of the displayed copy, including@@ -1355,7 +1379,8 @@ Plain-text line breaks and literal angle brackets (such as `<[email protected]>`)remain readable. Use `Show more` / `Show less` to expand or collapse the description;description links use the host's normal link-opening behavior.-A published event file (`METHOD:PUBLISH`, what `Forward by email` attaches) is a shared+A published event file (`METHOD:PUBLISH`, what `Forward by email` and `Forward invitation`+attach) is a sharedevent, not an invitation: the card reads `Shared event organized by <organizer>` and nevershows Yes / Maybe / No, a last response, or a waiting-for-sync line. When the viewer alreadyholds the meeting it says `On your calendar.` with `Open in calendar` and `View your day`;diff --git a/packages/sdk-docs/reference/generated/email/types.gen/README.md b/packages/sdk-docs/reference/generated/email/types.gen/README.mdindex 14ed4922e2..ab8bd3fa43 100644--- a/packages/sdk-docs/reference/generated/email/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/email/types.gen/README.md@@ -164,6 +164,16 @@- [EventTransparency](type-aliases/EventTransparency.md)- [EventType](type-aliases/EventType.md)- [EventVisibility](type-aliases/EventVisibility.md)+- [ForwardCalendarEventData](type-aliases/ForwardCalendarEventData.md)+- [ForwardCalendarEventError](type-aliases/ForwardCalendarEventError.md)+- [ForwardCalendarEventError2](type-aliases/ForwardCalendarEventError2.md)+- [ForwardCalendarEventErrorCode](type-aliases/ForwardCalendarEventErrorCode.md)+- [ForwardCalendarEventErrors](type-aliases/ForwardCalendarEventErrors.md)+- [ForwardCalendarEventRecipient](type-aliases/ForwardCalendarEventRecipient.md)+- [ForwardCalendarEventRequest](type-aliases/ForwardCalendarEventRequest.md)+- [ForwardCalendarEventResponse](type-aliases/ForwardCalendarEventResponse.md)+- [ForwardCalendarEventResponse2](type-aliases/ForwardCalendarEventResponse2.md)+- [ForwardCalendarEventResponses](type-aliases/ForwardCalendarEventResponses.md)- [GetActiveBackfillJobResponse](type-aliases/GetActiveBackfillJobResponse.md)- [GetAttachmentData](type-aliases/GetAttachmentData.md)- [GetAttachmentDocumentIdData](type-aliases/GetAttachmentDocumentIdData.md)diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventData.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventData.mdnew file mode 100644index 0000000000..106076ad03--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventData.md@@ -0,0 +1,13 @@+# Type Alias: ForwardCalendarEventData++> **ForwardCalendarEventData** = \{ `body`: [`ForwardCalendarEventRequest`](ForwardCalendarEventRequest.md); `path`: \{ `event_id`: `string`; \}; `query?`: `never`; `url`: `"/email/calendar-events/{event_id}/forward"`; \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-body"></a> `body` | [`ForwardCalendarEventRequest`](ForwardCalendarEventRequest.md) | - |+| <a id="property-path"></a> `path` | \{ `event_id`: `string`; \} | - |+| `path.event_id` | `string` | The viewer's copy of the event |+| <a id="property-query"></a> `query?` | `never` | - |+| <a id="property-url"></a> `url` | `"/email/calendar-events/{event_id}/forward"` | - |diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventError.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventError.mdnew file mode 100644index 0000000000..5c5ea64ee8--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventError.md@@ -0,0 +1,12 @@+# Type Alias: ForwardCalendarEventError++> **ForwardCalendarEventError** = \{ `code`: [`ForwardCalendarEventErrorCode`](ForwardCalendarEventErrorCode.md); `message`: `string`; \}++A refused or failed forward.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-code"></a> `code` | [`ForwardCalendarEventErrorCode`](ForwardCalendarEventErrorCode.md) | What went wrong. |+| <a id="property-message"></a> `message` | `string` | A message fit to show the user. |diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventError2.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventError2.mdnew file mode 100644index 0000000000..2ee34da399--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventError2.md@@ -0,0 +1,3 @@+# Type Alias: ForwardCalendarEventError2++> **ForwardCalendarEventError2** = [`ForwardCalendarEventErrors`](ForwardCalendarEventErrors.md)\[keyof [`ForwardCalendarEventErrors`](ForwardCalendarEventErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventErrorCode.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventErrorCode.mdnew file mode 100644index 0000000000..1ab219e312--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventErrorCode.md@@ -0,0 +1,5 @@+# Type Alias: ForwardCalendarEventErrorCode++> **ForwardCalendarEventErrorCode** = `"not_found"` \| `"invalid_recipients"` \| `"inbox_unavailable"` \| `"send_failed"`++Why a forward was not sent.diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventErrors.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventErrors.mdnew file mode 100644index 0000000000..f15ff12263--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventErrors.md@@ -0,0 +1,13 @@+# Type Alias: ForwardCalendarEventErrors++> **ForwardCalendarEventErrors** = \{ `400`: [`ForwardCalendarEventError`](ForwardCalendarEventError.md); `401`: `unknown`; `403`: [`ForwardCalendarEventError`](ForwardCalendarEventError.md); `404`: [`ForwardCalendarEventError`](ForwardCalendarEventError.md); `502`: [`ForwardCalendarEventError`](ForwardCalendarEventError.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-400"></a> `400` | [`ForwardCalendarEventError`](ForwardCalendarEventError.md) | No, too many, or invalid recipients |+| <a id="property-401"></a> `401` | `unknown` | Authentication required |+| <a id="property-403"></a> `403` | [`ForwardCalendarEventError`](ForwardCalendarEventError.md) | The inbox holding the copy cannot send for the viewer |+| <a id="property-404"></a> `404` | [`ForwardCalendarEventError`](ForwardCalendarEventError.md) | No such event on one of the viewer's own inboxes |+| <a id="property-502"></a> `502` | [`ForwardCalendarEventError`](ForwardCalendarEventError.md) | The email could not be sent |diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventRecipient.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventRecipient.mdnew file mode 100644index 0000000000..ad8c79a261--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventRecipient.md@@ -0,0 +1,12 @@+# Type Alias: ForwardCalendarEventRecipient++> **ForwardCalendarEventRecipient** = \{ `email`: `string`; `name?`: `string` \| `null`; \}++One person a forwarded invitation goes to.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-email"></a> `email` | `string` | Their email address. |+| <a id="property-name"></a> `name?` | `string` \| `null` | Their display name. |diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventRequest.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventRequest.mdnew file mode 100644index 0000000000..a51eb7b7b3--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventRequest.md@@ -0,0 +1,12 @@+# Type Alias: ForwardCalendarEventRequest++> **ForwardCalendarEventRequest** = \{ `bodyText?`: `string` \| `null`; `to`: [`ForwardCalendarEventRecipient`](ForwardCalendarEventRecipient.md)[]; \}++Who a forwarded invitation goes to, and what its email says.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-bodytext"></a> `bodyText?` | `string` \| `null` | The email's plain-text body. Without one, it names the event and says the recipient won't be on the organizer's guest list. |+| <a id="property-to"></a> `to` | [`ForwardCalendarEventRecipient`](ForwardCalendarEventRecipient.md)[] | The people it goes to, at most 50. |diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponse.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponse.mdnew file mode 100644index 0000000000..011f19e283--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponse.md@@ -0,0 +1,12 @@+# Type Alias: ForwardCalendarEventResponse++> **ForwardCalendarEventResponse** = \{ `messageId`: `string`; `threadId`: `string`; \}++The email the forward queued.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-messageid"></a> `messageId` | `string` | The sent message. |+| <a id="property-threadid"></a> `threadId` | `string` | Its thread. |diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponse2.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponse2.mdnew file mode 100644index 0000000000..b491748dad--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponse2.md@@ -0,0 +1,3 @@+# Type Alias: ForwardCalendarEventResponse2++> **ForwardCalendarEventResponse2** = [`ForwardCalendarEventResponses`](ForwardCalendarEventResponses.md)\[keyof [`ForwardCalendarEventResponses`](ForwardCalendarEventResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponses.md b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponses.mdnew file mode 100644index 0000000000..1ac2fb9267--- /dev/null+++ b/packages/sdk-docs/reference/generated/email/types.gen/type-aliases/ForwardCalendarEventResponses.md@@ -0,0 +1,9 @@+# Type Alias: ForwardCalendarEventResponses++> **ForwardCalendarEventResponses** = \{ `202`: [`ForwardCalendarEventResponse`](ForwardCalendarEventResponse.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-202"></a> `202` | [`ForwardCalendarEventResponse`](ForwardCalendarEventResponse.md) | The email is queued to send |diff --git a/packages/sdk/generated/email/index.ts b/packages/sdk/generated/email/index.tsindex 830db354ba..262de30b66 100644--- a/packages/sdk/generated/email/index.ts+++ b/packages/sdk/generated/email/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiMessageOperation, ApiMessageOperationIssue, ApiMessageOperationState, ApiMessageResolutionAction, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsError, ArchiveThreadsErrors, ArchiveThreadsRequest, ArchiveThreadsResponse, ArchiveThreadsResponse2, ArchiveThreadsResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarEvent, CalendarEventSourceContent, CalendarInvitation, CalendarMutationApiError, CalendarMutationErrorCode, CalendarOccurrence, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponse, CompleteDraftAttachmentResponses, ConferenceProvider, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CopyCalendarEventRequest, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationError, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponse, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarError, DisableLinkCalendarErrors, DisableLinkCalendarResponse, DisableLinkCalendarResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponse, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, GuestPolicy, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, InvitationDateTime, InvitationMethod, InvitationParticipant, InvitationResolution, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, MailboxAction, MailboxOperation, MailboxOperationState, MailboxSettingsChange, MailboxSettingsOperation, MailboxSettingsOperationsData, MailboxSettingsOperationsResponse, MailboxSettingsOperationsResponses, Message, MessageListVisibility, MessageOperationResponse, MessageOperationStatusData, MessageOperationStatusError, MessageOperationStatusErrors, MessageOperationStatusResponse, MessageOperationStatusResponses, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponse, RecoverDraftTransferResponses, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationError, ResolveMessageOperationErrors, ResolveMessageOperationRequest, ResolveMessageOperationResponse, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, ScheduledSendStatus, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadOperationsData, ThreadOperationsError, ThreadOperationsErrors, ThreadOperationsResponse, ThreadOperationsResponses, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadStateField, ThreadSummary, TransferDraftData, TransferDraftErrors, TransferDraftRequest, TransferDraftResponse, TransferDraftResponse2, TransferDraftResponses, TransferRecoveryResponse, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateError, UpdateThreadStateErrors, UpdateThreadStateRequest, UpdateThreadStateResponse, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, ViewerCapabilities } from './types.gen';+export type { AccessLevel, AddDraftAttachmentData, AddDraftAttachmentError, AddDraftAttachmentErrors, AddDraftAttachmentRequest, AddDraftAttachmentResponse, AddDraftAttachmentResponse2, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentError, AddForwardedAttachmentErrors, AddForwardedAttachmentRequest, AddForwardedAttachmentResponse, AddForwardedAttachmentResponse2, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelError, AddRemoveLabelErrors, AddRemoveLabelResponse, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelError, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponse, AddRemoveThreadLabelResponses, ApiAttachment, ApiAttachmentDraft, ApiAttachmentForwarded, ApiContact, ApiContactInfo, ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiEmailFilter, ApiLabel, ApiLabelListVisibility, ApiLabelType, ApiMessage, ApiMessageAttachment, ApiMessageLabel, ApiMessageListVisibility, ApiMessageOperation, ApiMessageOperationIssue, ApiMessageOperationState, ApiMessageResolutionAction, ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, ApiThreadPreviewCursor, ApiThreadPreviewCursorInner, ArchiveThreadData, ArchiveThreadError, ArchiveThreadErrors, ArchiveThreadRequest, ArchiveThreadResponse, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsError, ArchiveThreadsErrors, ArchiveThreadsRequest, ArchiveThreadsResponse, ArchiveThreadsResponse2, ArchiveThreadsResponses, Attachment, AttachmentDraft, AttachmentForwarded, AttendeeResponseStatus, BackfillJob, BackfillJobStatus, BackfillStatus, BlockSenderData, BlockSenderError, BlockSenderErrors, BlockSenderRequest, BlockSenderResponses, CalendarAttendee, CalendarEvent, CalendarEventSourceContent, CalendarInvitation, CalendarMutationApiError, CalendarMutationErrorCode, CalendarOccurrence, CancelBackfillGmailData, CancelBackfillGmailError, CancelBackfillGmailErrors, CancelBackfillGmailResponse, CancelBackfillGmailResponses, CancelBackfillParams, ClientOptions, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponse, CompleteDraftAttachmentResponses, ConferenceProvider, Contact, ContactInfo, ContactInfoLegacy, ContactInfoWithInteraction, CopyCalendarEventRequest, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationError, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponse, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftError, CreateDraftErrors, CreateDraftRequest, CreateDraftResponse, CreateDraftResponse2, CreateDraftResponses, CreateLabelData, CreateLabelError, CreateLabelErrors, CreateLabelRequest, CreateLabelResponse, CreateLabelResponse2, CreateLabelResponses, DeleteDraftData, DeleteDraftError, DeleteDraftErrors, DeleteDraftResponse, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterError, DeleteEmailFilterErrors, DeleteEmailFilterResponse, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelError, DeleteLabelErrors, DeleteLabelResponse, DeleteLabelResponses, DeleteLinkData, DeleteLinkError, DeleteLinkErrors, DeleteLinkResponse, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftError, DeleteScheduledDraftErrors, DeleteScheduledDraftResponse, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarError, DisableLinkCalendarErrors, DisableLinkCalendarResponse, DisableLinkCalendarResponses, DisableSyncData, DisableSyncError, DisableSyncErrors, DisableSyncResponse, DisableSyncResponses, EmptyResponse, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ForwardCalendarEventData, ForwardCalendarEventError, ForwardCalendarEventError2, ForwardCalendarEventErrorCode, ForwardCalendarEventErrors, ForwardCalendarEventRecipient, ForwardCalendarEventRequest, ForwardCalendarEventResponse, ForwardCalendarEventResponse2, ForwardCalendarEventResponses, GetActiveBackfillJobResponse, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdError, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponse, GetAttachmentDocumentIdResponse2, GetAttachmentDocumentIdResponses, GetAttachmentError, GetAttachmentErrors, GetAttachmentResponse, GetAttachmentResponse2, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveError, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponse, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailError, GetBackfillGmailErrors, GetBackfillGmailResponse, GetBackfillGmailResponses, GetBackfillJobResponse, GetMessageData, GetMessageError, GetMessageErrors, GetMessageResponse, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchError, GetMessagesBatchErrors, GetMessagesBatchResponse, GetMessagesBatchResponses, GetPreviewsCursorParams, GetScheduledMessagesData, GetScheduledMessagesError, GetScheduledMessagesErrors, GetScheduledMessagesResponse, GetScheduledMessagesResponses, GetScheduledResponse, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponse, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadError, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerError, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponse, GetThreadMessagesHandlerResponses, GetThreadResponse, GetThreadResponse2, GetThreadResponses, GuestPolicy, HealthCheckLinksData, HealthCheckLinksError, HealthCheckLinksErrors, HealthCheckLinksResponse, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitErrorCodeResponse, InitResponse, InitUserData, InitUserError, InitUserErrors, InitUserResponse, InitUserResponses, InvitationDateTime, InvitationMethod, InvitationParticipant, InvitationResolution, Label, LabelInfo, LabelListVisibility, LabelType, Link, ListBackfillGmailData, ListBackfillGmailError, ListBackfillGmailErrors, ListBackfillGmailResponse, ListBackfillGmailResponses, ListBackfillJobsResponse, ListBlockedResponse, ListBlockedSendersData, ListBlockedSendersError, ListBlockedSendersErrors, ListBlockedSendersResponse, ListBlockedSendersResponses, ListContactsData, ListContactsError, ListContactsErrors, ListContactsResponse, ListContactsResponse2, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersError, ListEmailFiltersErrors, ListEmailFiltersResponse, ListEmailFiltersResponse2, ListEmailFiltersResponses, ListLabelsData, ListLabelsError, ListLabelsErrors, ListLabelsResponse, ListLabelsResponse2, ListLabelsResponses, ListLinksData, ListLinksError, ListLinksErrors, ListLinksResponse, ListLinksResponse2, ListLinksResponses, MailboxAction, MailboxOperation, MailboxOperationState, MailboxSettingsChange, MailboxSettingsOperation, MailboxSettingsOperationsData, MailboxSettingsOperationsResponse, MailboxSettingsOperationsResponses, Message, MessageListVisibility, MessageOperationResponse, MessageOperationStatusData, MessageOperationStatusError, MessageOperationStatusErrors, MessageOperationStatusResponse, MessageOperationStatusResponses, ParsedMessage, PatchSettingsData, PatchSettingsError, PatchSettingsErrors, PatchSettingsRequest, PatchSettingsResponse, PatchSettingsResponse2, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorError, PreviewsInboxCursorErrors, PreviewsInboxCursorResponse, PreviewsInboxCursorResponses, PreviewView, PreviewViewStandardLabel, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponse, RecoverDraftTransferResponses, RefreshEmailEvent, RemoveDraftAttachmentData, RemoveDraftAttachmentError, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponse, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentError, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponse, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationError, ResolveMessageOperationErrors, ResolveMessageOperationRequest, ResolveMessageOperationResponse, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkError, ResyncLinkErrors, ResyncLinkResponse, ResyncLinkResponses, ResyncResponse, ScheduledSendStatus, SendMessageData, SendMessageError, SendMessageErrors, SendMessageRequest, SendMessageResponse, SendMessageResponse2, SendMessageResponses, Settings, SharedInboxConflictResponse, SyncStatus, Thread, ThreadList, ThreadOperationsData, ThreadOperationsError, ThreadOperationsErrors, ThreadOperationsResponse, ThreadOperationsResponses, ThreadPreviewCursor, ThreadSeenData, ThreadSeenError, ThreadSeenErrors, ThreadSeenResponse, ThreadSeenResponses, ThreadStateField, ThreadSummary, TransferDraftData, TransferDraftErrors, TransferDraftRequest, TransferDraftResponse, TransferDraftResponse2, TransferDraftResponses, TransferRecoveryResponse, UnblockSenderData, UnblockSenderError, UnblockSenderErrors, UnblockSenderRequest, UnblockSenderResponse, UnblockSenderResponses, UnresolvedSignatureImagesError, UpdateLabelBatchRequest, UpdateLabelBatchResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectData, UpdateThreadProjectError, UpdateThreadProjectErrors, UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpdateThreadProjectResponse2, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateError, UpdateThreadStateErrors, UpdateThreadStateRequest, UpdateThreadStateResponse, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterError, UpsertEmailFilterErrors, UpsertEmailFilterRequest, UpsertEmailFilterResponse, UpsertEmailFilterResponse2, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageError, UpsertScheduledMessageErrors, UpsertScheduledMessageResponse, UpsertScheduledMessageResponses, UpsertScheduledRequest, UpsertScheduledResponse, UserProvider, Value, ViewerCapabilities } from './types.gen';diff --git a/packages/sdk/generated/email/sdk.gen.ts b/packages/sdk/generated/email/sdk.gen.tsindex 5b34fbfd58..bde961a787 100644--- a/packages/sdk/generated/email/sdk.gen.ts+++ b/packages/sdk/generated/email/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsErrors, ArchiveThreadsResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponses, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarErrors, DisableLinkCalendarResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, MailboxSettingsOperationsData, MailboxSettingsOperationsResponses, MessageOperationStatusData, MessageOperationStatusErrors, MessageOperationStatusResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationErrors, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadOperationsData, ThreadOperationsErrors, ThreadOperationsResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, TransferDraftData, TransferDraftErrors, TransferDraftResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateErrors, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';+import type { AddDraftAttachmentData, AddDraftAttachmentErrors, AddDraftAttachmentResponses, AddForwardedAttachmentData, AddForwardedAttachmentErrors, AddForwardedAttachmentResponses, AddRemoveLabelData, AddRemoveLabelErrors, AddRemoveLabelResponses, AddRemoveThreadLabelData, AddRemoveThreadLabelErrors, AddRemoveThreadLabelResponses, ArchiveThreadData, ArchiveThreadErrors, ArchiveThreadResponses, ArchiveThreadsData, ArchiveThreadsErrors, ArchiveThreadsResponses, BlockSenderData, BlockSenderErrors, BlockSenderResponses, CancelBackfillGmailData, CancelBackfillGmailErrors, CancelBackfillGmailResponses, CompleteDraftAttachmentData, CompleteDraftAttachmentErrors, CompleteDraftAttachmentResponses, CopyThreadCalendarInvitationData, CopyThreadCalendarInvitationErrors, CopyThreadCalendarInvitationResponses, CreateDraftData, CreateDraftErrors, CreateDraftResponses, CreateLabelData, CreateLabelErrors, CreateLabelResponses, DeleteDraftData, DeleteDraftErrors, DeleteDraftResponses, DeleteEmailFilterData, DeleteEmailFilterErrors, DeleteEmailFilterResponses, DeleteLabelData, DeleteLabelErrors, DeleteLabelResponses, DeleteLinkData, DeleteLinkErrors, DeleteLinkResponses, DeleteScheduledDraftData, DeleteScheduledDraftErrors, DeleteScheduledDraftResponses, DisableLinkCalendarData, DisableLinkCalendarErrors, DisableLinkCalendarResponses, DisableSyncData, DisableSyncErrors, DisableSyncResponses, ForwardCalendarEventData, ForwardCalendarEventErrors, ForwardCalendarEventResponses, GetAttachmentData, GetAttachmentDocumentIdData, GetAttachmentDocumentIdErrors, GetAttachmentDocumentIdResponses, GetAttachmentErrors, GetAttachmentResponses, GetBackfillGmailActiveData, GetBackfillGmailActiveErrors, GetBackfillGmailActiveResponses, GetBackfillGmailData, GetBackfillGmailErrors, GetBackfillGmailResponses, GetMessageData, GetMessageErrors, GetMessageResponses, GetMessagesBatchData, GetMessagesBatchErrors, GetMessagesBatchResponses, GetScheduledMessagesData, GetScheduledMessagesErrors, GetScheduledMessagesResponses, GetThreadCalendarInvitationsData, GetThreadCalendarInvitationsErrors, GetThreadCalendarInvitationsResponses, GetThreadData, GetThreadErrors, GetThreadMessagesHandlerData, GetThreadMessagesHandlerErrors, GetThreadMessagesHandlerResponses, GetThreadResponses, HealthCheckLinksData, HealthCheckLinksErrors, HealthCheckLinksResponses, HealthHandlerData, HealthHandlerResponses, InitUserData, InitUserErrors, InitUserResponses, ListBackfillGmailData, ListBackfillGmailErrors, ListBackfillGmailResponses, ListBlockedSendersData, ListBlockedSendersErrors, ListBlockedSendersResponses, ListContactsData, ListContactsErrors, ListContactsResponses, ListEmailFiltersData, ListEmailFiltersErrors, ListEmailFiltersResponses, ListLabelsData, ListLabelsErrors, ListLabelsResponses, ListLinksData, ListLinksErrors, ListLinksResponses, MailboxSettingsOperationsData, MailboxSettingsOperationsResponses, MessageOperationStatusData, MessageOperationStatusErrors, MessageOperationStatusResponses, PatchSettingsData, PatchSettingsErrors, PatchSettingsResponses, PreviewsInboxCursorData, PreviewsInboxCursorErrors, PreviewsInboxCursorResponses, RecoverDraftTransferData, RecoverDraftTransferErrors, RecoverDraftTransferResponses, RemoveDraftAttachmentData, RemoveDraftAttachmentErrors, RemoveDraftAttachmentResponses, RemoveForwardedAttachmentData, RemoveForwardedAttachmentErrors, RemoveForwardedAttachmentResponses, ResolveMessageOperationData, ResolveMessageOperationErrors, ResolveMessageOperationResponses, ResyncLinkData, ResyncLinkErrors, ResyncLinkResponses, SendMessageData, SendMessageErrors, SendMessageResponses, ThreadOperationsData, ThreadOperationsErrors, ThreadOperationsResponses, ThreadSeenData, ThreadSeenErrors, ThreadSeenResponses, TransferDraftData, TransferDraftErrors, TransferDraftResponses, UnblockSenderData, UnblockSenderErrors, UnblockSenderResponses, UpdateThreadProjectData, UpdateThreadProjectErrors, UpdateThreadProjectResponses, UpdateThreadStateData, UpdateThreadStateErrors, UpdateThreadStateResponses, UpsertEmailFilterData, UpsertEmailFilterErrors, UpsertEmailFilterResponses, UpsertScheduledMessageData, UpsertScheduledMessageErrors, UpsertScheduledMessageResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -108,6 +108,25 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).get<GetBackfillGmailResponses, GetBackfillGmailErrors, ThrowOnError>({ url: '/email/backfill/gmail/{id}', ...options });}+ /**+ * Email one of the viewer's events to people the organizer's guest list+ * does not name: the event's iCalendar file (`METHOD:PUBLISH`, no+ * attendees, no join link), sent from the inbox that holds the viewer's+ * copy, with the usual undo delay. Recipients can add the event to their+ * own calendar; they are not added to the guest list and the organizer is+ * not told.+ */+ public forwardCalendarEvent<ThrowOnError extends boolean = false>(options: Options<ForwardCalendarEventData, ThrowOnError>): RequestResult<ForwardCalendarEventResponses, ForwardCalendarEventErrors, ThrowOnError> {+ return (options.client ?? this.client).post<ForwardCalendarEventResponses, ForwardCalendarEventErrors, ThrowOnError>({+ url: '/email/calendar-events/{event_id}/forward',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** List all contacts belonging to the user, grouped by link.*/diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex 361ce8ec2d..5c70b60022 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -1153,6 +1153,68 @@ export type EventType = 'default' | 'out_of_office' | 'focus_time' | 'working_lo*/export type EventVisibility = 'default' | 'public' | 'private' | 'confidential';+/**+ * A refused or failed forward.+ */+export type ForwardCalendarEventError = {+ /**+ * What went wrong.+ */+ code: ForwardCalendarEventErrorCode;+ /**+ * A message fit to show the user.+ */+ message: string;+};++/**+ * Why a forward was not sent.+ */+export type ForwardCalendarEventErrorCode = 'not_found' | 'invalid_recipients' | 'inbox_unavailable' | 'send_failed';++/**+ * One person a forwarded invitation goes to.+ */+export type ForwardCalendarEventRecipient = {+ /**+ * Their email address.+ */+ email: string;+ /**+ * Their display name.+ */+ name?: string | null;+};++/**+ * Who a forwarded invitation goes to, and what its email says.+ */+export type ForwardCalendarEventRequest = {+ /**+ * The email's plain-text body. Without one, it names the event and+ * says the recipient won't be on the organizer's guest list.+ */+ bodyText?: string | null;+ /**+ * The people it goes to, at most 50.+ */+ to: Array<ForwardCalendarEventRecipient>;+};++/**+ * The email the forward queued.+ */+export type ForwardCalendarEventResponse = {+ /**+ * The sent message.+ */+ messageId: string;+ /**+ * Its thread.+ */+ threadId: string;+};+/*** The response returned from the get backfill job endpoint*/@@ -2116,6 +2178,52 @@ export type GetBackfillGmailResponses = {export type GetBackfillGmailResponse = GetBackfillGmailResponses[keyof GetBackfillGmailResponses];+export type ForwardCalendarEventData = {+ body: ForwardCalendarEventRequest;+ path: {+ /**+ * The viewer's copy of the event+ */+ event_id: string;+ };+ query?: never;+ url: '/email/calendar-events/{event_id}/forward';+};++export type ForwardCalendarEventErrors = {+ /**+ * No, too many, or invalid recipients+ */+ 400: ForwardCalendarEventError;+ /**+ * Authentication required+ */+ 401: unknown;+ /**+ * The inbox holding the copy cannot send for the viewer+ */+ 403: ForwardCalendarEventError;+ /**+ * No such event on one of the viewer's own inboxes+ */+ 404: ForwardCalendarEventError;+ /**+ * The email could not be sent+ */+ 502: ForwardCalendarEventError;+};++export type ForwardCalendarEventError2 = ForwardCalendarEventErrors[keyof ForwardCalendarEventErrors];++export type ForwardCalendarEventResponses = {+ /**+ * The email is queued to send+ */+ 202: ForwardCalendarEventResponse;+};++export type ForwardCalendarEventResponse2 = ForwardCalendarEventResponses[keyof ForwardCalendarEventResponses];+export type ListContactsData = {body?: never;path?: never;diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex 33a7040d88..ce54b9f137 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -388,6 +388,90 @@}}},+ "/email/calendar-events/{event_id}/forward": {+ "post": {+ "tags": ["email"],+ "summary": "Email one of the viewer's events to people the organizer's guest list\ndoes not name: the event's iCalendar file (`METHOD:PUBLISH`, no\nattendees, no join link), sent from the inbox that holds the viewer's\ncopy, with the usual undo delay. Recipients can add the event to their\nown calendar; they are not added to the guest list and the organizer is\nnot told.",+ "operationId": "forward_calendar_event",+ "parameters": [+ {+ "name": "event_id",+ "in": "path",+ "description": "The viewer's copy of the event",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "202": {+ "description": "The email is queued to send",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventResponse"+ }+ }+ }+ },+ "400": {+ "description": "No, too many, or invalid recipients",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ },+ "401": {+ "description": "Authentication required"+ },+ "403": {+ "description": "The inbox holding the copy cannot send for the viewer",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ },+ "404": {+ "description": "No such event on one of the viewer's own inboxes",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ },+ "502": {+ "description": "The email could not be sent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ForwardCalendarEventError"+ }+ }+ }+ }+ }+ }+ },"/email/contacts": {"get": {"tags": ["Contacts"],@@ -5769,6 +5853,81 @@"description": "Visibility of event details.","enum": ["default", "public", "private", "confidential"]},+ "ForwardCalendarEventError": {+ "type": "object",+ "description": "A refused or failed forward.",+ "required": ["code", "message"],+ "properties": {+ "code": {+ "$ref": "#/components/schemas/ForwardCalendarEventErrorCode",+ "description": "What went wrong."+ },+ "message": {+ "type": "string",+ "description": "A message fit to show the user."+ }+ }+ },+ "ForwardCalendarEventErrorCode": {+ "type": "string",+ "description": "Why a forward was not sent.",+ "enum": [+ "not_found",+ "invalid_recipients",+ "inbox_unavailable",+ "send_failed"+ ]+ },+ "ForwardCalendarEventRecipient": {+ "type": "object",+ "description": "One person a forwarded invitation goes to.",+ "required": ["email"],+ "properties": {+ "email": {+ "type": "string",+ "description": "Their email address."+ },+ "name": {+ "type": ["string", "null"],+ "description": "Their display name."+ }+ }+ },+ "ForwardCalendarEventRequest": {+ "type": "object",+ "description": "Who a forwarded invitation goes to, and what its email says.",+ "required": ["to"],+ "properties": {+ "bodyText": {+ "type": ["string", "null"],+ "description": "The email's plain-text body. Without one, it names the event and\nsays the recipient won't be on the organizer's guest list."+ },+ "to": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ForwardCalendarEventRecipient"+ },+ "description": "The people it goes to, at most 50."+ }+ }+ },+ "ForwardCalendarEventResponse": {+ "type": "object",+ "description": "The email the forward queued.",+ "required": ["messageId", "threadId"],+ "properties": {+ "messageId": {+ "type": "string",+ "format": "uuid",+ "description": "The sent message."+ },+ "threadId": {+ "type": "string",+ "format": "uuid",+ "description": "Its thread."+ }+ }+ },"GetActiveBackfillJobResponse": {"type": "object","description": "The response returned from the get backfill job endpoint",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex d1d922da0b..195069a3fb 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -240,7 +240,11 @@ export const emailExcluded = ['resyncLink',] as const satisfies readonly (keyof EmailSdk)[];-export const emailBacklog = [] as const satisfies readonly (keyof EmailSdk)[];+export const emailBacklog = [+ // Belongs on CalendarEvent beside inviteGuests; the first release keeps+ // forwarding to the app's own surfaces, since the SDK also reaches agents.+ 'forwardCalendarEvent',+] as const satisfies readonly (keyof EmailSdk)[];export const notificationExcluded = ['bulkGetTypedNotificationsByEventItemIds',diff --git a/services/email_service/AGENTS.md b/services/email_service/AGENTS.mdindex 04cd301407..f4caa9b05d 100644--- a/services/email_service/AGENTS.md+++ b/services/email_service/AGENTS.md@@ -33,7 +33,8 @@ the gateway `/email` prefix.## Recipes- Add an email API route: `src/api/email.rs` (or `src/api/gmail.rs`,- `src/api/calendar_invitations.rs`) → `src/api/context.rs` → `src/openapi.rs`.+ `src/api/calendar_invitations.rs`, `src/api/calendar_event_forward.rs`) →+ `src/api/context.rs` → `src/api/swagger.rs`.- Add a pubsub consumer: new module under `src/pubsub/` → wire into`src/pubsub/mod.rs` and the `pubsub_workers` binary.- Add a backfill step: `src/backfill_init_service.rs` →diff --git a/services/email_service/src/api.rs b/services/email_service/src/api.rsindex d0c6bbe658..8990473282 100644--- a/services/email_service/src/api.rs+++ b/services/email_service/src/api.rs@@ -1,3 +1,4 @@+mod calendar_event_forward;mod calendar_invitations;use anyhow::Context;use axum::Router;@@ -76,6 +77,10 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",axum::routing::post(calendar_invitations::copy_handler),)+ .route(+ "/email/calendar-events/{event_id}/forward",+ axum::routing::post(calendar_event_forward::handler),+ ).nest("/email", email::router(state)).nest("/gmail", gmail::router()).nest("/outlook", outlook::router())diff --git a/services/email_service/src/api/calendar_event_forward.rs b/services/email_service/src/api/calendar_event_forward.rsnew file mode 100644index 0000000000..39a5284bbc--- /dev/null+++ b/services/email_service/src/api/calendar_event_forward.rs@@ -0,0 +1,173 @@+//! Forward one of the viewer's calendar events by email, for a guest whose+//! organizer does not let them add guests.+#[cfg(test)]+mod test;++use super::context::{ApiContext, AuthorizationService};+use axum::{+ Json,+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use email::domain::{+ event_forward::{EventForwardError, EventForwardRequest, forward_event},+ models::ContactInfo,+};+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;+use uuid::Uuid;++/// Who a forwarded invitation goes to, and what its email says.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub(crate) struct ForwardCalendarEventRequest {+ /// The people it goes to, at most 50.+ pub to: Vec<ForwardCalendarEventRecipient>,+ /// The email's plain-text body. Without one, it names the event and+ /// says the recipient won't be on the organizer's guest list.+ #[serde(default)]+ pub body_text: Option<String>,+}++/// One person a forwarded invitation goes to.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub(crate) struct ForwardCalendarEventRecipient {+ /// Their email address.+ pub email: String,+ /// Their display name.+ #[serde(default)]+ pub name: Option<String>,+}++/// The email the forward queued.+#[derive(Debug, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub(crate) struct ForwardCalendarEventResponse {+ /// The sent message.+ pub message_id: Uuid,+ /// Its thread.+ pub thread_id: Uuid,+}++/// Why a forward was not sent.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub(crate) enum ForwardCalendarEventErrorCode {+ /// The event is unknown, cancelled, or not on one of the viewer's own+ /// inboxes.+ NotFound,+ /// The recipients are missing, too many, or not email addresses.+ InvalidRecipients,+ /// The inbox holding the viewer's copy cannot send email for them.+ InboxUnavailable,+ /// The email could not be sent; trying again may work.+ SendFailed,+}++/// A refused or failed forward.+#[derive(Debug, Serialize, ToSchema)]+pub(crate) struct ForwardCalendarEventError {+ /// What went wrong.+ pub code: ForwardCalendarEventErrorCode,+ /// A message fit to show the user.+ pub message: String,+}++impl IntoResponse for ForwardCalendarEventError {+ fn into_response(self) -> Response {+ let status = match self.code {+ ForwardCalendarEventErrorCode::NotFound => StatusCode::NOT_FOUND,+ ForwardCalendarEventErrorCode::InvalidRecipients => StatusCode::BAD_REQUEST,+ ForwardCalendarEventErrorCode::InboxUnavailable => StatusCode::FORBIDDEN,+ ForwardCalendarEventErrorCode::SendFailed => StatusCode::BAD_GATEWAY,+ };+ (status, Json(self)).into_response()+ }+}++impl From<EventForwardError> for ForwardCalendarEventError {+ fn from(error: EventForwardError) -> Self {+ let (code, message) = match &error {+ EventForwardError::NotFound => (+ ForwardCalendarEventErrorCode::NotFound,+ "Event not found".to_owned(),+ ),+ EventForwardError::InvalidRecipients(reason) => (+ ForwardCalendarEventErrorCode::InvalidRecipients,+ (*reason).to_owned(),+ ),+ EventForwardError::InboxUnavailable => (+ ForwardCalendarEventErrorCode::InboxUnavailable,+ error.to_string(),+ ),+ EventForwardError::Email(_) | EventForwardError::Internal(_) => {+ tracing::error!(error=?error, "calendar event forward failed");+ (+ ForwardCalendarEventErrorCode::SendFailed,+ "The invitation could not be forwarded".to_owned(),+ )+ }+ };+ Self { code, message }+ }+}++/// Email one of the viewer's events to people the organizer's guest list+/// does not name: the event's iCalendar file (`METHOD:PUBLISH`, no+/// attendees, no join link), sent from the inbox that holds the viewer's+/// copy, with the usual undo delay. Recipients can add the event to their+/// own calendar; they are not added to the guest list and the organizer is+/// not told.+#[utoipa::path(post,+ path = "/email/calendar-events/{event_id}/forward",+ tag = "email",+ operation_id = "forward_calendar_event",+ params(("event_id" = Uuid, Path, description = "The viewer's copy of the event")),+ request_body = ForwardCalendarEventRequest,+ responses(+ (status = 202, description = "The email is queued to send", body = ForwardCalendarEventResponse),+ (status = 400, description = "No, too many, or invalid recipients", body = ForwardCalendarEventError),+ (status = 401, description = "Authentication required"),+ (status = 403, description = "The inbox holding the copy cannot send for the viewer", body = ForwardCalendarEventError),+ (status = 404, description = "No such event on one of the viewer's own inboxes", body = ForwardCalendarEventError),+ (status = 502, description = "The email could not be sent", body = ForwardCalendarEventError),+ ))]+pub(crate) async fn handler(+ State(state): State<ApiContext>,+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+ Path(event_id): Path<Uuid>,+ Json(request): Json<ForwardCalendarEventRequest>,+) -> Result<(StatusCode, Json<ForwardCalendarEventResponse>), ForwardCalendarEventError> {+ let actor = authorization.authorization.user.macro_user_id.clone();+ let email = state.email_service.service();+ let sent = forward_event(+ state.calendar_service.as_ref(),+ email.as_ref(),+ state.event_forward_sender.as_ref(),+ actor,+ event_id,+ EventForwardRequest {+ to: request+ .to+ .into_iter()+ .map(|recipient| ContactInfo {+ email: recipient.email,+ name: recipient.name,+ photo_url: None,+ })+ .collect(),+ body_text: request.body_text,+ },+ )+ .await?;+ Ok((+ StatusCode::ACCEPTED,+ Json(ForwardCalendarEventResponse {+ message_id: sent.db_id,+ thread_id: sent.thread_db_id,+ }),+ ))+}diff --git a/services/email_service/src/api/calendar_event_forward/test.rs b/services/email_service/src/api/calendar_event_forward/test.rsnew file mode 100644index 0000000000..e4f1cdfee2--- /dev/null+++ b/services/email_service/src/api/calendar_event_forward/test.rs@@ -0,0 +1,49 @@+use super::*;+use email::domain::models::EmailErr;++fn status_and_code(error: EventForwardError) -> (StatusCode, ForwardCalendarEventErrorCode) {+ let error = ForwardCalendarEventError::from(error);+ let code = error.code;+ (error.into_response().status(), code)+}++#[test]+fn refusals_map_to_their_status_and_code() {+ assert_eq!(+ status_and_code(EventForwardError::NotFound),+ (+ StatusCode::NOT_FOUND,+ ForwardCalendarEventErrorCode::NotFound+ )+ );+ assert_eq!(+ status_and_code(EventForwardError::InvalidRecipients("no recipients")),+ (+ StatusCode::BAD_REQUEST,+ ForwardCalendarEventErrorCode::InvalidRecipients+ )+ );+ assert_eq!(+ status_and_code(EventForwardError::InboxUnavailable),+ (+ StatusCode::FORBIDDEN,+ ForwardCalendarEventErrorCode::InboxUnavailable+ )+ );+}++#[test]+fn a_failed_send_is_retryable_and_keeps_its_cause_out_of_the_message() {+ let error = ForwardCalendarEventError::from(EventForwardError::Email(EmailErr::InboxNotFound));+ assert_eq!(error.code, ForwardCalendarEventErrorCode::SendFailed);+ assert_eq!(error.message, "The invitation could not be forwarded");+ assert_eq!(error.into_response().status(), StatusCode::BAD_GATEWAY);+}++#[test]+fn the_reason_for_invalid_recipients_reaches_the_user() {+ let error = ForwardCalendarEventError::from(EventForwardError::InvalidRecipients(+ "a recipient is not an email address",+ ));+ assert_eq!(error.message, "a recipient is not an email address");+}diff --git a/services/email_service/src/api/context.rs b/services/email_service/src/api/context.rsindex 58975b1c63..b8f76d7fb8 100644--- a/services/email_service/src/api/context.rs+++ b/services/email_service/src/api/context.rs@@ -67,6 +67,12 @@ pub(crate) type EmailSvc = EmailServiceImpl<EmailEventBroker,>;+pub(crate) type EventForwardSender = email::domain::service::attachments::StagedAttachmentSender<+ EmailSvc,+ EmailPgRepo,+ crate::outbound::draft_attachment_storage::DraftAttachmentS3,+>;+pub(crate) type DraftAttachmentSvc = email::domain::draft_attachments::DraftAttachmentService<EmailPgRepo,crate::outbound::draft_attachment_storage::DraftAttachmentS3,@@ -124,6 +130,7 @@ pub(crate) struct ApiContext {pub inbox_health: Arc<crate::composition::InboxHealth>,pub attachment_reads: Arc<AttachmentReadSvc>,pub draft_attachments: Arc<DraftAttachmentSvc>,+ pub event_forward_sender: Arc<EventForwardSender>,pub draft_transfers: Arc<email::domain::draft_transfer::DraftTransferService<EmailPgRepo,diff --git a/services/email_service/src/api/swagger.rs b/services/email_service/src/api/swagger.rsindex 7c81e30cfe..37625642fb 100644--- a/services/email_service/src/api/swagger.rs+++ b/services/email_service/src/api/swagger.rs@@ -65,6 +65,7 @@ use utoipa::OpenApi;paths(crate::api::calendar_invitations::handler,crate::api::calendar_invitations::copy_handler,+ crate::api::calendar_event_forward::handler,health::health_handler,email::attachments::get::handler,email::attachments::get_document_id::handler,diff --git a/services/email_service/src/outbound/draft_attachment_storage.rs b/services/email_service/src/outbound/draft_attachment_storage.rsindex 4737ddeaec..c3340b6556 100644--- a/services/email_service/src/outbound/draft_attachment_storage.rs+++ b/services/email_service/src/outbound/draft_attachment_storage.rs@@ -61,3 +61,17 @@ impl email::domain::draft_transfer::DraftTransferFiles for DraftAttachmentS3 {.map_err(email::domain::models::EmailErr::RepoErr)}}++/// Stores a file the email domain produced itself, such as a forwarded+/// event's iCalendar file, as draft transfers store copied attachments: the+/// draft attachment row carries its type.+impl email::domain::ports::DraftAttachmentStorage for DraftAttachmentS3 {+ async fn put_attachment(+ &self,+ key: &str,+ _content_type: &str,+ bytes: &[u8],+ ) -> anyhow::Result<()> {+ self.s3.put(&self.bucket, key, bytes).await+ }+}diff --git a/services/email_service/src/server.rs b/services/email_service/src/server.rsindex 190ca9d6b6..85759834fe 100644--- a/services/email_service/src/server.rs+++ b/services/email_service/src/server.rs@@ -355,6 +355,16 @@ pub async fn run() -> anyhow::Result<()> {},access: entity_access_service.as_ref().clone(),}),+ event_forward_sender: Arc::new(+ email::domain::service::attachments::StagedAttachmentSender::new(+ email_service.service(),+ EmailPgRepo::new(db.clone()),+ crate::outbound::draft_attachment_storage::DraftAttachmentS3 {+ s3: s3_client.clone(),+ bucket: config.attachment_bucket.to_string(),+ },+ ),+ ),draft_attachments: Arc::new(email::domain::draft_attachments::DraftAttachmentService {repository: email::outbound::EmailPgRepo::new(db.clone()),storage: crate::outbound::draft_attachment_storage::DraftAttachmentS3 {