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 outside organizers as real invitations with the join link (#9068)
gbirmandce2ff484e32
diff --git a/.sqlx/query-28e3f84f2421bec4125d4852436ed2567d684f63c7eed1070806de1a05013d7d.json b/.sqlx/query-28e3f84f2421bec4125d4852436ed2567d684f63c7eed1070806de1a05013d7d.jsonnew file mode 100644index 0000000000..3979f35a7b--- /dev/null+++ b/.sqlx/query-28e3f84f2421bec4125d4852436ed2567d684f63c7eed1070806de1a05013d7d.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n event.conference_url,\n event.conference_provider,\n -- Google's own flag, kept in the payload it sent. Every source\n -- must be a Google private copy: an Outlook copy, or a source\n -- stored before Macro kept Google's whole payload, is no evidence.\n -- A source without the key counts as false, since bool_and skips\n -- NULLs.\n COALESCE(\n bool_and(\n COALESCE(\n source.source_kind = 'google'\n AND source.raw_payload->>'privateCopy' = 'true',\n false\n )\n ),\n false\n ) AS \"google_private_copy!\",\n event.is_snapshot\n OR COALESCE(\n bool_or(source.normalized_payload->'event'->>'isSnapshot' = 'true'),\n false\n ) AS \"is_snapshot!\"\n FROM calendar_events event\n LEFT JOIN calendar_event_sources source ON source.event_id = event.id\n WHERE event.id = $1\n AND event.owner_id = $2\n AND event.status <> 'cancelled'\n GROUP BY event.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "conference_url",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "conference_provider",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "google_private_copy!",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "is_snapshot!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ true,+ true,+ null,+ null+ ]+ },+ "hash": "28e3f84f2421bec4125d4852436ed2567d684f63c7eed1070806de1a05013d7d"+}diff --git a/apps/web/src/features/calendar-view/components/EventGuests.test.tsx b/apps/web/src/features/calendar-view/components/EventGuests.test.tsxindex 778ee535af..2bc9ac0578 100644--- a/apps/web/src/features/calendar-view/components/EventGuests.test.tsx+++ b/apps/web/src/features/calendar-view/components/EventGuests.test.tsx@@ -183,7 +183,7 @@ 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.";+ "You can forward the invitation instead. The people you send it to get the event by email but won't be on the guest list.";beforeEach(() => {vi.clearAllMocks();@@ -492,7 +492,7 @@ describe('forwarding the invitation from event details', () => {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."+ "They'll get the event by email but won't appear in the guest list.")).toBeTruthy();await user.click(@@ -509,12 +509,9 @@ describe('forwarding the invitation from event details', () => {expect(args.recipients).toEqual([{ email: '[email protected]', name: 'Ada Lovelace' },]);+ // The summary alone: the server adds the note for the kind it sends.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(args.bodyText).not.toContain('forwarded to you');expect(screen.getByRole('button', { name: 'Forward invitation' })diff --git a/apps/web/src/features/calendar-view/components/EventGuests.tsx b/apps/web/src/features/calendar-view/components/EventGuests.tsxindex f4ad9b3309..998f5b2e8d 100644--- a/apps/web/src/features/calendar-view/components/EventGuests.tsx+++ b/apps/web/src/features/calendar-view/components/EventGuests.tsx@@ -168,9 +168,13 @@ function InviteGuestsForm(props: {);}-/** Shown above the forward button; Google says the same of its own forward. */+/**+ * Shown above the forward button; Google says the same of its own forward.+ * The server decides whether recipients get an invitation to answer or a+ * file to add, so this says only what both share.+ */const FORWARD_FORM_NOTE =- "They can add the event to their calendar but won't appear in the guest list.";+ "They'll get the event by email but won't appear in the guest list.";/*** Forwarding the invitation, for a guest who cannot add guests: the samediff --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 0891196364..0ca355769e 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@@ -18,7 +18,6 @@ import { eventForwardSummary } from '../utils/event-forward-summary';import {canForwardInvitation,FORWARD_INVITATION_INSTEAD,- FORWARDED_INVITATION_NOTE,GUEST_INVITES_RESTRICTED,GUEST_LIST_HIDDEN,guestInvitesRestrictedReason,@@ -131,7 +130,9 @@ export function createGuestInviteController(email,name: name === email ? undefined : name,})),- bodyText: `${eventForwardSummary(current, preferences.timeFormat)}\n\n${FORWARDED_INVITATION_NOTE}`,+ // The server ends the email with what the recipient can do, which+ // depends on the kind of forward it decides to send.+ bodyText: eventForwardSummary(current, preferences.timeFormat),}),(error) => error);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 5d51755eb0..aa329ec79b 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@@ -1190,7 +1190,7 @@ describe('guests of an event the viewer was invited to', () => {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."+ "Only the organizer can invite guests. You can forward the invitation instead. The people you send it to get the event by email but won't be on the guest list.");} finally {dispose();diff --git a/apps/web/src/features/calendar/utils/event-guest-editing.ts b/apps/web/src/features/calendar/utils/event-guest-editing.tsindex 719fd8ff1c..45627ede5c 100644--- a/apps/web/src/features/calendar/utils/event-guest-editing.ts+++ b/apps/web/src/features/calendar/utils/event-guest-editing.ts@@ -13,18 +13,13 @@ export const GUEST_LIST_HIDDEN =/*** 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.+ * invitation instead: forwarded people get the event by email and stay off+ * the guest list, as Google says of its own forward. The server decides+ * whether that is an invitation they answer to an organizer outside Google+ * or a file they add to their calendar, so this says only what both share.*/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.";+ "You can forward the invitation instead. The people you send it to get the event by email but won't be on the guest list.";/** Shown where a guest would change the event when the organizer does not allow it. */export const GUEST_EDITS_RESTRICTED =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 8cf1400fd4..36067674df 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@@ -488,11 +488,14 @@ export const getBackfillGmail = async (/*** @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.+does not name, from the inbox that holds the viewer's copy, with the+usual undo delay, carrying the copy's join link. When the copy is Google's+private copy of an invitation from an organizer outside Google, it is a+real invitation (`METHOD:REQUEST`) naming the recipients, who answer it to+the organizer, who gets the email too. Otherwise it is the event's file+(`METHOD:PUBLISH`, no attendees): recipients can add the event to their+own calendar, are not added to the guest list, and the organizer is not+told.*/export type forwardCalendarEventResponse202 = {data: ForwardCalendarEventResponse;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.tsindex d3c3c59d4a..431e3d0ea2 100644--- 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.ts@@ -12,8 +12,9 @@ import type { ForwardCalendarEventRequestBodyText } from './forwardCalendarEvent* 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. */+ /** A plain-text summary of the event the email opens with; the title+when absent. The email ends with a note saying what the recipient+can do with the forward. */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.tsindex 5f7b10b6ee..cc9be2f464 100644--- 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.ts@@ -6,7 +6,8 @@*//**- * 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 plain-text summary of the event the email opens with; the title+when absent. The email ends with a note saying what the recipient+can do with the forward.*/export type ForwardCalendarEventRequestBodyText = string | null;diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.jsonindex ce54b9f137..3aa11f5bd5 100644--- a/apps/web/src/lib/service-clients/service-email/openapi.json+++ b/apps/web/src/lib/service-clients/service-email/openapi.json@@ -391,7 +391,7 @@"/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.",+ "summary": "Email one of the viewer's events to people the organizer's guest list\ndoes not name, from the inbox that holds the viewer's copy, with the\nusual undo delay, carrying the copy's join link. When the copy is Google's\nprivate copy of an invitation from an organizer outside Google, it is a\nreal invitation (`METHOD:REQUEST`) naming the recipients, who answer it to\nthe organizer, who gets the email too. Otherwise it is the event's file\n(`METHOD:PUBLISH`, no attendees): recipients can add the event to their\nown calendar, are not added to the guest list, and the organizer is not\ntold.","operationId": "forward_calendar_event","parameters": [{@@ -5900,7 +5900,7 @@"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."+ "description": "A plain-text summary of the event the email opens with; the title\nwhen absent. The email ends with a note saying what the recipient\ncan do with the forward."},"to": {"type": "array",diff --git a/crates/ai_tools/src/email_attachments.rs b/crates/ai_tools/src/email_attachments.rsindex 53040ca1ca..c2e76d682d 100644--- a/crates/ai_tools/src/email_attachments.rs+++ b/crates/ai_tools/src/email_attachments.rs@@ -176,6 +176,7 @@ impl<D: DocumentService> DraftAttachmentSource for DocumentAttachmentSource<D> {file_name: attachment_file_name(&name, extension),content_type,bytes,+ is_inline: false,})}}diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 845105ee85..129809464f 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -154,12 +154,27 @@ 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.+ Only the channel-share path strips the Macro call+ (`EventSnapshot::without_macro_call`); a forwarded file keeps the join link+ it carries.+ The other direction, a guest forwarding their copy of an event, renders it+ 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 copy decides the kind (`ForwardedCopy::outside_organizer`, read by+ `forwarded_copy` from every source of the copy): Google's private copy+ (`privateCopy` in the stored raw payload, which Google sets on every+ invitation from another calendar system) that is not a snapshot, whose UID+ Google did not mint (`…@google.com`), and that names its organizer becomes a+ `METHOD:REQUEST` invitation naming only the recipients, answered to that+ organizer, as Google's own Add guests sends there. Anything else, a Google+ organizer who turned inviting off above all, keeps the `METHOD:PUBLISH`+ file naming no attendees, so a recipient can only add it to their calendar+ and nothing reaches the organizer; missing evidence falls back to it. One+ renderer serves every use: `render_event_ics` takes an `IcsPurpose`, and+ only `Forward` keeps the Macro call and adds the copy's conference link+ (`JoinLink`), which `Share` (the .ics download) and channel shares never+ carry.- 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 e46cb38eb9..31141a0fb2 100644--- a/crates/calendar_events/src/domain/ics.rs+++ b/crates/calendar_events/src/domain/ics.rs@@ -1,5 +1,5 @@//! RFC 5545 export of one calendar event, for adding it to a calendar Macro-//! does not write to.+//! does not write to, or for a guest forwarding their copy by email.#[cfg(test)]mod test;@@ -9,7 +9,7 @@ use chrono_tz::Tz;use super::{meeting_links::{first_macro_call_url, strip_macro_call},- models::{EventTime, EventType},+ models::{ConferenceProvider, EventTime, EventType},};/// Longest content line, in octets, before RFC 5545 folding.@@ -32,7 +32,9 @@ pub enum CalendarEventExportAccess {/// Attendees and the conference link are deliberately absent: a channel/// share exposes the meeting, not its guest list or join link, and the export/// has one shape however the requester sees the event. A Macro call travels-/// in the description and location instead, so the renderer strips it there.+/// in the description and location instead, so the renderer strips it there+/// unless a guest is forwarding their own copy ([`IcsPurpose`]), which reads+/// the conference link from that copy ([`ForwardedCopy`]).#[derive(Clone, Debug, PartialEq, Eq)]pub struct CalendarEventExport {/// How the requester sees the event.@@ -83,8 +85,10 @@ impl CalendarEventExport {/// What a snapshot imported onto a requester's calendar carries: the/// meeting's identity, revision and series content, from a channel share or-/// from an event file someone sent them. Guests and the conference link are-/// left out, so importing it invites no one and opens no way into the call.+/// from an event file someone sent them. Guests are left out, so importing it+/// invites no one. A channel share also leaves out the join link+/// ([`Self::without_macro_call`]); a forwarded file keeps whatever link it+/// carries, since its sender meant to invite the recipient.#[derive(Clone, Debug, PartialEq, Eq)]pub struct EventSnapshot {/// RFC 5545 UID shared by every projection of the meeting.@@ -145,32 +149,177 @@ pub struct CalendarEventIcs {pub document: String,}+/// Someone an event file names: an attendee of an invitation, or the+/// organizer it is answered to.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct IcsParticipant {+ /// Email address.+ pub email: String,+ /// Display name, when known.+ pub name: Option<String>,+}++/// A copy's provider conference link, which the meeting's content does not+/// carry: Google Meet, Microsoft Teams, or a third party's such as Zoom.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct JoinLink {+ /// The URL that joins the call.+ pub url: String,+ /// Which system backs it, when known.+ pub provider: Option<ConferenceProvider>,+}++/// What an event file is rendered for, which decides what it carries beyond+/// the meeting's content. One renderer serves every use, so they differ only+/// where this says so.+#[derive(Clone, Copy, Debug)]+pub enum IcsPurpose<'a> {+ /// Sharing the meeting without inviting anyone: the .ics download. It+ /// names no attendees and leaves out the join link, a Macro call's+ /// included, since it shares the meeting, not a way into its call.+ Share,+ /// A guest forwarding their copy by email, which deliberately invites the+ /// people it goes to: the join link stays, as it does in Google's own+ /// forward.+ Forward {+ /// The copy's provider conference.+ join_link: Option<&'a JoinLink>,+ /// The people it goes to, as the attendees of a `METHOD:REQUEST`+ /// invitation they answer to the organizer. `None` publishes the+ /// event (`METHOD:PUBLISH`) naming nobody, which a recipient can only+ /// add to their calendar.+ invitees: Option<&'a [IcsParticipant]>,+ },+}++/// How a forward reaches its recipients, decided from the forwarder's copy.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum CalendarEventForwardKind {+ /// The shared-event file (`METHOD:PUBLISH`, no attendees): recipients+ /// can add the event to their calendar, and nothing reaches the+ /// organizer. Used whenever the organizer could have a say in who is+ /// invited, and whenever that is unclear.+ EventFile,+ /// A real invitation (`METHOD:REQUEST`) from an organizer outside+ /// Google, as Google's own Add guests sends on such a copy: it names the+ /// recipients as attendees, they answer it to the organizer, and the+ /// email goes to the organizer too.+ Invitation {+ /// Who the answers go to.+ organizer: IcsParticipant,+ },+}++impl CalendarEventForwardKind {+ /// Span and log form.+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::EventFile => "event_file",+ Self::Invitation { .. } => "invitation",+ }+ }+}+/// 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.+/// where: the event's document, rendered for the kind of forward its copy+/// allows, 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,+ /// Whether the document is an invitation or the shared-event file.+ pub kind: CalendarEventForwardKind,+}++/// What a forwarded copy's stored source shows about where its invitation+/// came from, and the conference link it carries.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct ForwardedCopy {+ /// Whether the copy is Google's private copy of an invitation, in every+ /// Google calendar holding it: what Google keeps of an invitation from+ /// another calendar system, such as Exchange, and also of an imported+ /// event file. False for an Outlook copy, and for a Google source synced+ /// before Macro kept Google's whole payload.+ pub google_private_copy: bool,+ /// Whether the copy, or any calendar's projection of it, is a snapshot+ /// Macro imported.+ pub is_snapshot: bool,+ /// The copy's provider conference.+ pub join_link: Option<JoinLink>,+}++impl ForwardedCopy {+ /// The organizer an invitation forwarded from this copy is answered to,+ /// when the copy shows the organizer is outside Google; `None` keeps the+ /// shared-event file.+ ///+ /// The evidence is Google's private copy, which Google keeps of every+ /// invitation from another calendar system and reports as letting no+ /// guest invite, whatever the organizer chose. A snapshot is a private+ /// copy Macro imported, and so is any event file a user imported into+ /// Google; one whose UID Google minted (`…@google.com`) belongs to a+ /// Google organizer, whose own choice about guests stands. Anything+ /// short of that evidence, an organizer Macro cannot name included, falls+ /// back to the shared-event file: a wrong guess would notify an organizer+ /// who turned inviting off.+ pub fn outside_organizer(&self, event: &CalendarEventExport) -> Option<IcsParticipant> {+ if !self.google_private_copy || self.is_snapshot || is_google_uid(&event.ical_uid) {+ return None;+ }+ let email = event+ .organizer_email+ .as_deref()+ .map(str::trim)+ .filter(|email| email.contains('@'))?;+ Some(IcsParticipant {+ email: email.to_string(),+ name: event+ .organizer_name+ .clone()+ .filter(|name| !name.trim().is_empty()),+ })+ }+}++/// Whether Google minted `uid`, which it does for every event created in+/// Google Calendar, so the meeting has a Google organizer.+fn is_google_uid(uid: &str) -> bool {+ uid.trim().to_ascii_lowercase().ends_with(GOOGLE_UID_SUFFIX)}-/// Render an event as a single-event `VCALENDAR` document.+/// The domain Google gives the UIDs of events created in Google Calendar.+const GOOGLE_UID_SUFFIX: &str = "@google.com";++/// Render an event as a single-event `VCALENDAR` document for `purpose`.////// The UID is the meeting's own, so a client that already holds the meeting-/// updates it rather than duplicating it. A one-off timed event is written in+/// updates it rather than duplicating it, and an answer to an invitation+/// reaches the organizer's meeting. A one-off timed event is written in/// UTC. A recurring one keeps its original IANA zone when it is known, so the/// series holds its wall-clock time across daylight-saving changes; that/// `TZID` carries no `VTIMEZONE` block, which Google, Apple and Outlook/// resolve by name but strict importers may reject.-pub fn render_event_ics(event: &CalendarEventExport) -> String {+pub fn render_event_ics(event: &CalendarEventExport, purpose: IcsPurpose<'_>) -> String {+ let (join_link, invitees) = match purpose {+ IcsPurpose::Share => (None, None),+ IcsPurpose::Forward {+ join_link,+ invitees,+ } => (join_link, invitees),+ };+ let method = if invitees.is_some() {+ "METHOD:REQUEST"+ } else {+ "METHOD:PUBLISH"+ };let mut lines = vec!["BEGIN:VCALENDAR".to_string(),"VERSION:2.0".to_string(),"PRODID:-//Macro//Calendar//EN".to_string(),"CALSCALE:GREGORIAN".to_string(),- "METHOD:PUBLISH".to_string(),+ method.to_string(),"BEGIN:VEVENT".to_string(),format!("UID:{}", escape_text(&event.ical_uid)),format!("DTSTAMP:{}", utc_stamp(event.updated_at)),@@ -191,25 +340,48 @@ pub fn render_event_ics(event: &CalendarEventExport) -> String {.and_then(plain_text).unwrap_or_default();let location = event.location.clone().unwrap_or_default();- let (description, location) =- match first_macro_call_url(event.location.as_deref(), event.description.as_deref()) {- Some(url) => strip_macro_call(&description, &location, &url),- None => (description, location),- };+ let macro_call = first_macro_call_url(event.location.as_deref(), event.description.as_deref());+ let (description, location) = match (purpose, macro_call) {+ (IcsPurpose::Share, Some(url)) => strip_macro_call(&description, &location, &url),+ (IcsPurpose::Share, None) => (description, location),+ // The plain text shows the generated join line's link in brackets,+ // which some clients would make part of the link.+ (IcsPurpose::Forward { .. }, Some(url)) => (+ with_join_line(+ description.replace(&format!("[{url}]"), &url),+ &location,+ join_link,+ ),+ location,+ ),+ (IcsPurpose::Forward { .. }, None) => {+ (with_join_line(description, &location, join_link), location)+ }+ };if !description.is_empty() {lines.push(format!("DESCRIPTION:{}", escape_text(&description)));}if !location.is_empty() {lines.push(format!("LOCATION:{}", escape_text(&location)));}+ if let Some(link) = join_link.filter(|link| is_web_url(&link.url)) {+ if link.provider == Some(ConferenceProvider::GoogleMeet) {+ lines.push(format!("X-GOOGLE-CONFERENCE:{}", link.url));+ }+ lines.push(format!("CONFERENCE;VALUE=URI;FEATURE=VIDEO:{}", link.url));+ }if let Some(email) = event.organizer_email.as_deref() {- let name = event- .organizer_name- .as_deref()- .filter(|name| !name.is_empty())- .map(|name| format!(";CN={}", quote_param(name)))- .unwrap_or_default();- lines.push(format!("ORGANIZER{name}:mailto:{email}"));+ lines.push(format!(+ "ORGANIZER{}:mailto:{email}",+ common_name(event.organizer_name.as_deref())+ ));+ }+ for invitee in invitees.unwrap_or_default() {+ lines.push(format!(+ "ATTENDEE{};ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:mailto:{}",+ common_name(invitee.name.as_deref()),+ invitee.email+ ));}lines.push("END:VEVENT".to_string());lines.push("END:VCALENDAR".to_string());@@ -221,6 +393,43 @@ pub fn render_event_ics(event: &CalendarEventExport) -> String {document}+/// A participant's `CN` parameter, or nothing without a name.+fn common_name(name: Option<&str>) -> String {+ name.map(str::trim)+ .filter(|name| !name.is_empty())+ .map(|name| format!(";CN={}", quote_param(name)))+ .unwrap_or_default()+}++/// The description with a line naming the copy's conference link, as+/// Google's own invitations carry it, so every client shows it and a copy+/// added from the file keeps it. A link the description or location already+/// shows, as a Teams invitation's body does, is not repeated.+fn with_join_line(description: String, location: &str, join_link: Option<&JoinLink>) -> String {+ let Some(link) = join_link.filter(|link| is_web_url(&link.url)) else {+ return description;+ };+ if description.contains(&link.url) || location.contains(&link.url) {+ return description;+ }+ let label = match link.provider {+ Some(ConferenceProvider::GoogleMeet) => "Join with Google Meet",+ Some(ConferenceProvider::MicrosoftTeams) => "Join the Microsoft Teams meeting",+ Some(ConferenceProvider::Other) | None => "Join the meeting",+ };+ let line = format!("{label}: {}", link.url);+ if description.is_empty() {+ line+ } else {+ format!("{description}\n\n{line}")+ }+}++/// Whether `url` is a web link, the only kind a calendar can open as a call.+fn is_web_url(url: &str) -> bool {+ url.starts_with("https://") || url.starts_with("http://")+}+fn time_lines(time: &EventTime, is_recurring: bool) -> [String; 2] {match time {EventTime::Timed {diff --git a/crates/calendar_events/src/domain/ics/test.rs b/crates/calendar_events/src/domain/ics/test.rsindex 2906dbc0d1..8976efc715 100644--- a/crates/calendar_events/src/domain/ics/test.rs+++ b/crates/calendar_events/src/domain/ics/test.rs@@ -1,9 +1,12 @@use chrono::{NaiveDate, TimeZone, Utc};-use super::{CalendarEventExport, CalendarEventExportAccess, render_event_ics};+use super::{+ CalendarEventExport, CalendarEventExportAccess, ForwardedCopy, IcsParticipant, IcsPurpose,+ JoinLink, render_event_ics,+};use crate::domain::{meeting_links::attach_macro_call,- models::{EventTime, EventType},+ models::{ConferenceProvider, EventTime, EventType},};const CALL_URL: &str = "https://macro.com/app/meet/join/0123456789abcdef0123456789abcdef";@@ -51,7 +54,7 @@ fn a_recurring_timed_event_is_written_in_its_zones_wall_time() {});event.recurrence_lines = vec!["RRULE:FREQ=WEEKLY;BYDAY=TH".to_string()];- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.contains(&"DTSTART;TZID=America/New_York:20260924T193000".to_string()));assert!(lines.contains(&"DTEND;TZID=America/New_York:20260924T200000".to_string()));@@ -74,7 +77,7 @@ fn a_one_off_timed_event_is_written_in_utc() {time_zone: Some("America/New_York".to_string()),});- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.contains(&"DTSTART:20260924T233000Z".to_string()));assert!(lines.contains(&"DTEND:20260925T000000Z".to_string()));@@ -89,7 +92,7 @@ fn a_recurring_event_without_a_known_zone_is_written_in_utc() {});event.recurrence_lines = vec!["RRULE:FREQ=DAILY".to_string()];- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.contains(&"DTSTART:20260924T233000Z".to_string()));assert!(lines.contains(&"DTEND:20260925T000000Z".to_string()));@@ -97,7 +100,7 @@ fn a_recurring_event_without_a_known_zone_is_written_in_utc() {#[test]fn all_day_event_keeps_the_exclusive_end_date() {- let lines = unfolded(&render_event_ics(&export(all_day())));+ let lines = unfolded(&render_event_ics(&export(all_day()), IcsPurpose::Share));assert!(lines.contains(&"DTSTART;VALUE=DATE:20260924".to_string()));assert!(lines.contains(&"DTEND;VALUE=DATE:20260925".to_string()));@@ -112,7 +115,7 @@ fn html_description_is_reduced_to_escaped_plain_text() {.to_string(),);- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.contains(&"DESCRIPTION:Agenda:\\nBudget & hiring\\nNotes\\, too".to_string()),@@ -125,7 +128,7 @@ fn plain_text_description_keeps_its_line_breaks() {let mut event = export(all_day());event.description = Some("Dial in first\r\nthen share your screen\n".to_string());- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.contains(&"DESCRIPTION:Dial in first\\nthen share your screen".to_string()));}@@ -138,7 +141,7 @@ fn a_macro_call_leaves_neither_its_join_line_nor_its_link_as_the_location() {event.description = Some(description);event.location = Some(location);- let document = render_event_ics(&event);+ let document = render_event_ics(&event, IcsPurpose::Share);let lines = unfolded(&document);assert!(@@ -159,7 +162,7 @@ fn a_macro_call_keeps_a_physical_location_and_drops_an_empty_description() {event.description = Some(description);event.location = Some(location);- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.contains(&"LOCATION:Room 4".to_string()), "{lines:?}");assert!(@@ -180,7 +183,7 @@ fn the_join_line_goes_even_when_an_earlier_call_link_is_found_first() {event.description = Some(description);event.location = Some(location);- let document = render_event_ics(&event);+ let document = render_event_ics(&event, IcsPurpose::Share);let lines = unfolded(&document);assert!(@@ -202,7 +205,7 @@ fn stored_line_breaks_cannot_start_a_new_property() {event.organizer_email =Some("[email protected]\r\nATTENDEE:mailto:[email protected]".to_string());- let lines = unfolded(&render_event_ics(&event));+ let lines = unfolded(&render_event_ics(&event, IcsPurpose::Share));assert!(lines.iter().all(|line| !line.starts_with("ATTACH")@@ -218,10 +221,220 @@ fn long_lines_fold_at_75_octets_without_splitting_characters() {let mut event = export(all_day());event.title = "é".repeat(80);- let document = render_event_ics(&event);+ let document = render_event_ics(&event, IcsPurpose::Share);for line in document.split("\r\n") {assert!(line.len() <= 75, "line exceeds 75 octets: {line:?}");}assert!(unfolded(&document).contains(&format!("SUMMARY:{}", "é".repeat(80))));}++fn meet() -> JoinLink {+ JoinLink {+ url: "https://meet.google.com/abc-defg-hij".to_string(),+ provider: Some(ConferenceProvider::GoogleMeet),+ }+}++fn forward_file(join_link: Option<&JoinLink>) -> IcsPurpose<'_> {+ IcsPurpose::Forward {+ join_link,+ invitees: None,+ }+}++#[test]+fn a_share_never_carries_the_join_link() {+ // The .ics download has no conference to name: the export carries none.+ let mut event = export(all_day());+ let (description, location) = attach_macro_call(None, None, CALL_URL);+ event.description = Some(description);+ event.location = Some(location);++ let document = render_event_ics(&event, IcsPurpose::Share);++ assert!(!document.contains("CONFERENCE"));+ assert!(!document.contains("Join"));+ assert!(document.contains("METHOD:PUBLISH"));+}++#[test]+fn a_forward_keeps_the_macro_call_it_would_strip_from_a_share() {+ let mut event = export(all_day());+ let (description, location) =+ attach_macro_call(Some("<p>Bring the budget draft</p>"), None, CALL_URL);+ event.description = Some(description);+ event.location = Some(location);++ let document = render_event_ics(&event, forward_file(None));+ let lines = unfolded(&document);++ assert!(lines.contains(&format!("LOCATION:{CALL_URL}")), "{lines:?}");+ let description = lines+ .iter()+ .find(|line| line.starts_with("DESCRIPTION:"))+ .expect("the description stays");+ assert!(description.contains("Bring the budget draft"), "{lines:?}");+ assert!(+ description.ends_with(&format!("\\nJoin Macro call: {CALL_URL}")),+ "{lines:?}"+ );+ assert!(lines.contains(&"METHOD:PUBLISH".to_string()));+ assert!(!document.contains("ATTENDEE"));+}++#[test]+fn a_forward_names_its_conference_in_the_description_and_as_a_property() {+ let mut event = export(all_day());+ event.description = Some("Agenda".to_string());+ let link = meet();++ let lines = unfolded(&render_event_ics(&event, forward_file(Some(&link))));++ assert!(+ lines.contains(+ &"DESCRIPTION:Agenda\\n\\nJoin with Google Meet: https://meet.google.com/abc-defg-hij"+ .to_string()+ ),+ "{lines:?}"+ );+ assert!(+ lines.contains(&"X-GOOGLE-CONFERENCE:https://meet.google.com/abc-defg-hij".to_string())+ );+ assert!(lines.contains(+ &"CONFERENCE;VALUE=URI;FEATURE=VIDEO:https://meet.google.com/abc-defg-hij".to_string()+ ));+}++#[test]+fn a_forward_does_not_repeat_a_link_the_description_already_shows() {+ let mut event = export(all_day());+ event.description =+ Some("Microsoft Teams meeting\nJoin: https://teams.microsoft.com/l/meetup-join/abc".into());+ let link = JoinLink {+ url: "https://teams.microsoft.com/l/meetup-join/abc".to_string(),+ provider: Some(ConferenceProvider::MicrosoftTeams),+ };++ let document = render_event_ics(&event, forward_file(Some(&link)));+ let lines = unfolded(&document);++ assert!(+ lines.contains(+ &"DESCRIPTION:Microsoft Teams meeting\\nJoin: https://teams.microsoft.com/l/meetup-join/abc"+ .to_string()+ ),+ "{lines:?}"+ );+ assert!(!document.contains("X-GOOGLE-CONFERENCE"));+ assert!(+ lines.contains(+ &"CONFERENCE;VALUE=URI;FEATURE=VIDEO:https://teams.microsoft.com/l/meetup-join/abc"+ .to_string()+ )+ );+}++#[test]+fn a_conference_that_is_not_a_web_link_is_left_out() {+ let event = export(all_day());+ let link = JoinLink {+ url: "tel:+1-555-0100".to_string(),+ provider: Some(ConferenceProvider::Other),+ };++ let document = render_event_ics(&event, forward_file(Some(&link)));++ assert!(!document.contains("tel:"));+ assert!(!document.contains("CONFERENCE"));+}++#[test]+fn an_invitation_names_only_the_invitees_answerable_to_the_organizer() {+ let event = export(all_day());+ let invitees = [+ IcsParticipant {+ email: "[email protected]".to_string(),+ name: Some("Friend, \"Best\"".to_string()),+ },+ IcsParticipant {+ email: "[email protected]".to_string(),+ name: None,+ },+ ];++ let lines = unfolded(&render_event_ics(+ &event,+ IcsPurpose::Forward {+ join_link: None,+ invitees: Some(&invitees),+ },+ ));++ assert!(lines.contains(&"METHOD:REQUEST".to_string()));+ assert!(lines.contains(+ &"ORGANIZER;CN=\"Ada 'The' Organizer\":mailto:[email protected]".to_string()+ ));+ let attendees: Vec<&String> = lines+ .iter()+ .filter(|line| line.starts_with("ATTENDEE"))+ .collect();+ assert_eq!(+ attendees,+ [+ "ATTENDEE;CN=\"Friend, 'Best'\";ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:mailto:[email protected]",+ "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:mailto:[email protected]",+ ]+ );+}++fn outside_copy() -> ForwardedCopy {+ ForwardedCopy {+ google_private_copy: true,+ is_snapshot: false,+ join_link: None,+ }+}++#[test]+fn a_private_copy_of_an_outside_meeting_names_its_organizer() {+ let mut event = export(all_day());+ event.ical_uid = "040000008200E00074C5B7101A82E0080000000080F2".to_string();++ let organizer = outside_copy()+ .outside_organizer(&event)+ .expect("Google keeps an outside organizer's invitation as a private copy");++ assert_eq!(organizer.email, "[email protected]");+ assert_eq!(organizer.name.as_deref(), Some("Ada \"The\" Organizer"));+}++#[test]+fn anything_short_of_an_outside_private_copy_names_no_organizer() {+ let mut outside = export(all_day());+ outside.ical_uid = "[email protected]".to_string();+ let mut google_meeting = outside.clone();+ google_meeting.ical_uid = "[email protected]".to_string();+ let mut unnamed = outside.clone();+ unnamed.organizer_email = Some(" ".to_string());++ assert_eq!(+ ForwardedCopy {+ google_private_copy: false,+ ..outside_copy()+ }+ .outside_organizer(&outside),+ None+ );+ assert_eq!(+ ForwardedCopy {+ is_snapshot: true,+ ..outside_copy()+ }+ .outside_organizer(&outside),+ None+ );+ assert_eq!(outside_copy().outside_organizer(&google_meeting), None);+ assert_eq!(outside_copy().outside_organizer(&unnamed), None);+ assert!(outside_copy().outside_organizer(&outside).is_some());+}diff --git a/crates/calendar_events/src/domain/mutations/copy.rs b/crates/calendar_events/src/domain/mutations/copy.rsindex ea0a6cc8aa..87f0f71f45 100644--- a/crates/calendar_events/src/domain/mutations/copy.rs+++ b/crates/calendar_events/src/domain/mutations/copy.rs@@ -52,12 +52,15 @@ where"only regular events can be added to a calendar".to_string(),));}- self.add_snapshot(requester_id, source.snapshot(), calendar_id)- .await+ // A channel share shares the meeting, not a way into its call.+ let snapshot = source.snapshot().without_macro_call();+ self.add_snapshot(requester_id, snapshot, calendar_id).await}/// Import a snapshot into the selected calendar, or the requester's- /// primary inbox's primary calendar, and persist the provider echo.+ /// primary inbox's primary calendar, and persist the provider echo. The+ /// snapshot is imported as given: an event file someone forwarded keeps+ /// the join link it carries.async fn add_snapshot(&self,requester_id: &str,@@ -80,7 +83,6 @@ where"shared events can be added to Google calendars only".to_string(),));}- let snapshot = snapshot.without_macro_call();let access_token = self.fetch_token(&target.token_identity).await?;let outcome = self.providerdiff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex c374bec2e2..f8cc11e742 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -322,6 +322,14 @@ impl CalendarRepository for FakeRepo {Ok(self.export.clone())}+ async fn forwarded_copy(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Option<crate::domain::ics::ForwardedCopy>, rootcause::Report> {+ Ok(None)+ }+async fn open_join_request(&self,event_id: Uuid,diff --git a/crates/calendar_events/src/domain/mutations/test/copy.rs b/crates/calendar_events/src/domain/mutations/test/copy.rsindex bbe665e245..b5642bbf00 100644--- a/crates/calendar_events/src/domain/mutations/test/copy.rs+++ b/crates/calendar_events/src/domain/mutations/test/copy.rs@@ -85,11 +85,12 @@ async fn copy_leaves_the_meetings_macro_call_out() {}#[tokio::test]-async fn an_event_file_imports_onto_the_picked_calendar_without_its_macro_call() {+async fn an_event_file_imports_onto_the_picked_calendar_with_its_join_link() {+ // A forward is a guest deliberately inviting the recipient, so the copy+ // they add keeps the call the file names, unlike a channel share's.use crate::domain::ports::CalendarSnapshotImporter;let call = "https://macro.com/app/meet/join/0123456789abcdef0123456789abcdef";- let (description, location) =- crate::domain::meeting_links::attach_macro_call(Some("<p>Agenda</p>"), None, call);+ let description = format!("Agenda\n\nJoin Macro call: {call}");let applied_id = Uuid::now_v7();let repo = FakeRepo {persisted_event_id: Some(applied_id),@@ -100,8 +101,8 @@ async fn an_event_file_imports_onto_the_picked_calendar_without_its_macro_call()let provider = FakeProvider::new(FakeProviderBehavior::Echo);let imported = provider.imported.clone();let snapshot = CalendarEventExport {- description: Some(description),- location: Some(location),+ description: Some(description.clone()),+ location: Some(call.to_string()),..export(CalendarEventExportAccess::ChannelShared)}.snapshot();@@ -115,8 +116,11 @@ async fn an_event_file_imports_onto_the_picked_calendar_without_its_macro_call()assert_eq!(upserts.lock().unwrap().len(), 1);let imported = imported.lock().unwrap();assert_eq!(imported[0].1.ical_uid, "[email protected]");- assert_eq!(imported[0].1.description.as_deref(), Some("Agenda"));- assert_eq!(imported[0].1.location, None);+ assert_eq!(+ imported[0].1.description.as_deref(),+ Some(description.as_str())+ );+ assert_eq!(imported[0].1.location.as_deref(), Some(call));}#[tokio::test]diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 7f18de900f..8def7e6ad8 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -7,7 +7,10 @@ use rootcause::Report;use uuid::Uuid;use super::copies::{CopyChange, CopyRefusal};-use super::ics::{CalendarEventExport, CalendarEventForward, CalendarEventIcs, EventSnapshot};+use super::ics::{+ CalendarEventExport, CalendarEventForward, CalendarEventIcs, EventSnapshot, ForwardedCopy,+ IcsParticipant,+};use super::join_requests::{CalendarJoinRequest, CalendarJoinRequestStatus};use super::meeting_links::{CreateEventWithMacroCallError, MeetingLink, MeetingLinkError, MeetingLinkRequest,@@ -631,6 +634,15 @@ pub trait CalendarRepository: Send + Sync + 'static {event_id: Uuid,) -> impl Future<Output = Result<Option<CalendarEventExport>, Report>> + Send;+ /// What the requester's own `event_id` copy shows about where its+ /// invitation came from, and its conference link, for forwarding it.+ /// `None` when the requester owns no live copy by that id.+ fn forwarded_copy(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Option<ForwardedCopy>, Report>> + Send;+/// Record a pending request from the requester to join `event_id`,/// leaving an existing one, whatever its status, as it is. Returns the/// request and whether this call created it, so a repeated ask does not@@ -1073,14 +1085,16 @@ pub trait CalendarSnapshotImporter: Send + Sync + 'static {/// 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.+ /// The requester's own copy of `event_id` as an iCalendar document for+ /// a forward to `invitees`, with the inbox holding that copy, which+ /// sends it, and whether the document is an invitation naming them or+ /// the shared-event file. `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,+ invitees: &[IcsParticipant],) -> impl Future<Output = Result<Option<CalendarEventForward>, Report>> + Send;}diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex d7e9565868..e65606e36f 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -9,7 +9,10 @@ use crate::domain::events::{CalendarEventMetadata, CalendarMacroEvent, CalendarTuse macro_event_broker::MacroEventBroker;use super::{- ics::{CalendarEventExportAccess, CalendarEventForward, CalendarEventIcs, render_event_ics},+ ics::{+ CalendarEventExportAccess, CalendarEventForward, CalendarEventForwardKind,+ CalendarEventIcs, IcsParticipant, IcsPurpose, render_event_ics,+ },models::{ActorInboxes, AppliedGoogleGrant, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,@@ -232,20 +235,31 @@ where) -> Result<Option<CalendarEventIcs>, Report> {let event = self.repository.event_export(requester_id, event_id).await?;Ok(event.map(|event| CalendarEventIcs {- document: render_event_ics(&event),+ document: render_event_ics(&event, IcsPurpose::Share),title: event.title,}))}- /// 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)]+ /// What a forward of the requester's own copy of an event to `invitees`+ /// sends, and that copy's inbox, which sends it. The copy decides the+ /// kind ([`ForwardedCopy::outside_organizer`]): an invitation naming+ /// `invitees` when its organizer is outside Google, else the+ /// shared-event file. Both carry the copy's join link. `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.+ ///+ /// [`ForwardedCopy::outside_organizer`]: super::ics::ForwardedCopy::outside_organizer+ #[tracing::instrument(+ skip(self, requester_id, invitees),+ fields(invitee_count = invitees.len(), kind = tracing::field::Empty),+ err+ )]pub async fn event_forward(&self,requester_id: &str,event_id: Uuid,+ invitees: &[IcsParticipant],) -> Result<Option<CalendarEventForward>, Report> {let copies = self.repository@@ -262,12 +276,30 @@ whereelse {return Ok(None);};+ let Some(forwarded) = self+ .repository+ .forwarded_copy(requester_id, event_id)+ .await?+ else {+ return Ok(None);+ };+ let kind = match forwarded.outside_organizer(&event) {+ Some(organizer) => CalendarEventForwardKind::Invitation { organizer },+ None => CalendarEventForwardKind::EventFile,+ };+ tracing::Span::current().record("kind", kind.as_str());+ let purpose = IcsPurpose::Forward {+ join_link: forwarded.join_link.as_ref(),+ invitees: matches!(kind, CalendarEventForwardKind::Invitation { .. })+ .then_some(invitees),+ };Ok(Some(CalendarEventForward {ics: CalendarEventIcs {- document: render_event_ics(&event),+ document: render_event_ics(&event, purpose),title: event.title,},inbox: copy.inbox,+ kind,}))}@@ -302,8 +334,9 @@ where&self,requester_id: &str,event_id: Uuid,+ invitees: &[IcsParticipant],) -> impl Future<Output = Result<Option<CalendarEventForward>, Report>> + Send {- CalendarService::event_forward(self, requester_id, event_id)+ CalendarService::event_forward(self, requester_id, event_id, invitees)}}diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex e3be8b4d5c..b3de729c20 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -39,6 +39,8 @@ struct FakeRepo {meeting_copies: Vec<crate::domain::models::MeetingCopy>,/// What `event_export` resolves for every event.export: Option<crate::domain::ics::CalendarEventExport>,+ /// What `forwarded_copy` reads for every event.+ forwarded: Option<crate::domain::ics::ForwardedCopy>,}impl CalendarRepository for FakeRepo {@@ -126,6 +128,14 @@ impl CalendarRepository for FakeRepo {Ok(self.export.clone())}+ async fn forwarded_copy(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Option<crate::domain::ics::ForwardedCopy>, Report> {+ Ok(self.forwarded.clone())+ }+async fn open_join_request(&self,_event_id: Uuid,@@ -1936,32 +1946,172 @@ fn forward_copy(event_id: Uuid, inbox: &str) -> crate::domain::models::MeetingCo}}-#[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 {+fn invitees() -> Vec<crate::domain::ics::IcsParticipant> {+ vec![crate::domain::ics::IcsParticipant {+ email: "[email protected]".to_string(),+ name: Some("A Friend".to_string()),+ }]+}++/// Google's private copy of an invitation from an organizer outside Google.+fn outside_invitation() -> crate::domain::ics::ForwardedCopy {+ crate::domain::ics::ForwardedCopy {+ google_private_copy: true,+ is_snapshot: false,+ join_link: Some(crate::domain::ics::JoinLink {+ url: "https://teams.microsoft.com/l/meetup-join/abc".to_string(),+ provider: Some(crate::domain::models::ConferenceProvider::MicrosoftTeams),+ }),+ }+}++fn forward_service(+ export: crate::domain::ics::CalendarEventExport,+ forwarded: crate::domain::ics::ForwardedCopy,+ requested: Uuid,+) -> CalendarService<FakeRepo> {+ CalendarService::new(FakeRepo {meeting_copies: vec![- forward_copy(other, "[email protected]"),+ forward_copy(Uuid::now_v7(), "[email protected]"),forward_copy(requested, "[email protected]"),],- export: Some(forward_export(- crate::domain::ics::CalendarEventExportAccess::OwnCopy,- )),+ export: Some(export),+ forwarded: Some(forwarded),..FakeRepo::default()- });+ })+}- let forward = service- .event_forward("macro|[email protected]", requested)+#[tokio::test]+async fn event_forward_publishes_a_google_organizers_event_from_the_requested_copys_inbox() {+ let requested = Uuid::now_v7();+ let export = crate::domain::ics::CalendarEventExport {+ ical_uid: "[email protected]".to_string(),+ ..forward_export(crate::domain::ics::CalendarEventExportAccess::OwnCopy)+ };+ let forwarded = crate::domain::ics::ForwardedCopy {+ google_private_copy: false,+ is_snapshot: false,+ join_link: Some(crate::domain::ics::JoinLink {+ url: "https://meet.google.com/abc-defg-hij".to_string(),+ provider: Some(crate::domain::models::ConferenceProvider::GoogleMeet),+ }),+ };++ let forward = forward_service(export, forwarded, requested)+ .event_forward("macro|[email protected]", requested, &invitees()).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"));+ assert_eq!(+ forward.kind,+ crate::domain::ics::CalendarEventForwardKind::EventFile+ );+ let document = forward.ics.document.replace("\r\n ", "");+ assert!(document.contains("METHOD:PUBLISH"));+ assert!(document.contains("UID:[email protected]"));+ assert!(!document.contains("ATTENDEE"));+ assert!(document.contains("X-GOOGLE-CONFERENCE:https://meet.google.com/abc-defg-hij"));+ assert!(document.contains("Join with Google Meet: https://meet.google.com/abc-defg-hij"));+}++#[tokio::test]+async fn event_forward_invites_the_recipients_to_an_outside_organizers_meeting() {+ let requested = Uuid::now_v7();+ let export = crate::domain::ics::CalendarEventExport {+ ical_uid: "040000008200E00074C5B7101A82E008000000001".to_string(),+ organizer_name: Some("Outside Organizer".to_string()),+ ..forward_export(crate::domain::ics::CalendarEventExportAccess::OwnCopy)+ };++ let forward = forward_service(export, outside_invitation(), requested)+ .event_forward("macro|[email protected]", requested, &invitees())+ .await+ .unwrap()+ .expect("the requester's own copy can be forwarded");++ assert_eq!(+ forward.kind,+ crate::domain::ics::CalendarEventForwardKind::Invitation {+ organizer: crate::domain::ics::IcsParticipant {+ email: "[email protected]".to_string(),+ name: Some("Outside Organizer".to_string()),+ },+ }+ );+ let document = forward.ics.document.replace("\r\n ", "");+ assert!(document.contains("METHOD:REQUEST"));+ assert!(document.contains("ORGANIZER;CN=\"Outside Organizer\":mailto:[email protected]"));+ assert!(document.contains(+ "ATTENDEE;CN=\"A Friend\";ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:mailto:[email protected]"+ ));+ assert_eq!(document.matches("ATTENDEE").count(), 1);+ assert!(!document.contains("[email protected]"));+ assert!(document.contains(+ "CONFERENCE;VALUE=URI;FEATURE=VIDEO:https://teams.microsoft.com/l/meetup-join/abc"+ ));+ assert!(!document.contains("X-GOOGLE-CONFERENCE"));+}++#[tokio::test]+async fn event_forward_falls_back_to_the_event_file_without_evidence_of_an_outside_organizer() {+ let exchange = crate::domain::ics::CalendarEventExport {+ ical_uid: "040000008200E00074C5B7101A82E008000000001".to_string(),+ ..forward_export(crate::domain::ics::CalendarEventExportAccess::OwnCopy)+ };+ let cases = [+ (+ "a copy Google does not mark private",+ exchange.clone(),+ crate::domain::ics::ForwardedCopy {+ google_private_copy: false,+ ..outside_invitation()+ },+ ),+ (+ "a snapshot Macro imported",+ exchange.clone(),+ crate::domain::ics::ForwardedCopy {+ is_snapshot: true,+ ..outside_invitation()+ },+ ),+ (+ "an imported copy of a Google meeting",+ crate::domain::ics::CalendarEventExport {+ ical_uid: "[email protected]".to_string(),+ ..exchange.clone()+ },+ outside_invitation(),+ ),+ (+ "a copy naming no organizer",+ crate::domain::ics::CalendarEventExport {+ organizer_email: None,+ ..exchange.clone()+ },+ outside_invitation(),+ ),+ ];++ for (case, export, forwarded) in cases {+ let requested = Uuid::now_v7();+ let forward = forward_service(export, forwarded, requested)+ .event_forward("macro|[email protected]", requested, &invitees())+ .await+ .unwrap()+ .expect("the requester's own copy can be forwarded");++ assert_eq!(+ forward.kind,+ crate::domain::ics::CalendarEventForwardKind::EventFile,+ "{case}"+ );+ assert!(forward.ics.document.contains("METHOD:PUBLISH"), "{case}");+ assert!(!forward.ics.document.contains("ATTENDEE"), "{case}");+ }}#[tokio::test]@@ -1973,11 +2123,12 @@ async fn event_forward_refuses_an_event_none_of_the_requesters_inboxes_holds() {export: Some(forward_export(crate::domain::ics::CalendarEventExportAccess::OwnCopy,)),+ forwarded: Some(outside_invitation()),..FakeRepo::default()});let forward = service- .event_forward("macro|[email protected]", Uuid::now_v7())+ .event_forward("macro|[email protected]", Uuid::now_v7(), &invitees()).await.unwrap();@@ -1992,11 +2143,12 @@ async fn event_forward_refuses_a_copy_the_export_no_longer_resolves_as_owned() {export: Some(forward_export(crate::domain::ics::CalendarEventExportAccess::ChannelShared,)),+ forwarded: Some(outside_invitation()),..FakeRepo::default()});let forward = service- .event_forward("macro|[email protected]", requested)+ .event_forward("macro|[email protected]", requested, &invitees()).await.unwrap();diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex 943f7e9a7f..4e7246cf74 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -1644,6 +1644,15 @@ impl CalendarRepository for PgCalendarRepository {export::event_export(&self.pool, requester_id, event_id).await}+ #[tracing::instrument(skip(self, requester_id), err)]+ async fn forwarded_copy(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> Result<Option<crate::domain::ics::ForwardedCopy>, Report> {+ export::forwarded_copy(&self.pool, requester_id, event_id).await+ }+#[tracing::instrument(skip(self, requester_id, requester_email), err)]async fn open_join_request(&self,diff --git a/crates/calendar_events/src/outbound/pg/export.rs b/crates/calendar_events/src/outbound/pg/export.rsindex 65021b5154..ec8784ced8 100644--- a/crates/calendar_events/src/outbound/pg/export.rs+++ b/crates/calendar_events/src/outbound/pg/export.rs@@ -1,8 +1,9 @@//! Series content of one event the requester can see, for iCalendar export-//! and for copying onto their own calendar.+//! and for copying onto their own calendar, and what forwarding their own+//! copy needs besides.use super::*;-use crate::domain::ics::{CalendarEventExport, CalendarEventExportAccess};+use crate::domain::ics::{CalendarEventExport, CalendarEventExportAccess, ForwardedCopy, JoinLink};struct ExportRow {is_channel_shared: bool,@@ -171,3 +172,58 @@ pub(super) async fn event_export(}).transpose()}++/// What the requester's own `event_id` copy shows about its invitation's+/// origin, read from every calendar's source of it, and its conference link.+pub(super) async fn forwarded_copy(+ pool: &PgPool,+ requester_id: &str,+ event_id: Uuid,+) -> Result<Option<ForwardedCopy>, Report> {+ let row = sqlx::query!(+ r#"+ SELECT+ event.conference_url,+ event.conference_provider,+ -- Google's own flag, kept in the payload it sent. Every source+ -- must be a Google private copy: an Outlook copy, or a source+ -- stored before Macro kept Google's whole payload, is no evidence.+ -- A source without the key counts as false, since bool_and skips+ -- NULLs.+ COALESCE(+ bool_and(+ COALESCE(+ source.source_kind = 'google'+ AND source.raw_payload->>'privateCopy' = 'true',+ false+ )+ ),+ false+ ) AS "google_private_copy!",+ event.is_snapshot+ OR COALESCE(+ bool_or(source.normalized_payload->'event'->>'isSnapshot' = 'true'),+ false+ ) AS "is_snapshot!"+ FROM calendar_events event+ LEFT JOIN calendar_event_sources source ON source.event_id = event.id+ WHERE event.id = $1+ AND event.owner_id = $2+ AND event.status <> 'cancelled'+ GROUP BY event.id+ "#,+ event_id,+ requester_id,+ )+ .fetch_optional(pool)+ .await+ .map_err(report)?;+ Ok(row.map(|row| ForwardedCopy {+ google_private_copy: row.google_private_copy,+ is_snapshot: row.is_snapshot,+ join_link: row.conference_url.map(|url| JoinLink {+ url,+ provider: row.conference_provider.as_deref().map(conference_provider),+ }),+ }))+}diff --git a/crates/calendar_events/src/outbound/pg/test/export.rs b/crates/calendar_events/src/outbound/pg/test/export.rsindex 7544a5cc98..27d9f838d8 100644--- a/crates/calendar_events/src/outbound/pg/test/export.rs+++ b/crates/calendar_events/src/outbound/pg/test/export.rs@@ -126,3 +126,170 @@ async fn event_export_resolves_own_copies_before_channel_shares(pool: PgPool) {None);}++fn with_raw_payload(+ mut upsert: CalendarEventUpsert,+ raw: serde_json::Value,+) -> CalendarEventUpsert {+ if let CalendarEventSource::Google(source) = &mut upsert.source {+ source.raw_payload = raw;+ }+ upsert+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn forwarded_copy_reads_googles_private_copy_flag_and_the_conference(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, link).await;++ let mut outside = with_raw_payload(+ timed_upsert(+ owner_id,+ link,+ provider,+ "040000008200E000-outside",+ "Outside",+ 1,+ ),+ serde_json::json!({ "privateCopy": true, "guestsCanInviteOthers": false }),+ );+ outside.event.conference_url = Some("https://teams.microsoft.com/l/meetup-join/abc".into());+ outside.event.conference_provider = Some(ConferenceProvider::MicrosoftTeams);+ let outside_id = outside.event.id;+ repo.upsert_event_fixture(outside).await.unwrap();++ let invited = with_raw_payload(+ timed_upsert(owner_id, link, provider, "[email protected]", "Invited", 1),+ serde_json::json!({ "guestsCanInviteOthers": false }),+ );+ let invited_id = invited.event.id;+ repo.upsert_event_fixture(invited).await.unwrap();++ let mut snapshot = with_raw_payload(+ timed_upsert(+ owner_id,+ link,+ provider,+ "[email protected]",+ "Snapshot",+ 1,+ ),+ serde_json::json!({ "privateCopy": true }),+ );+ snapshot.event.is_snapshot = true;+ let snapshot_id = snapshot.event.id;+ repo.upsert_event_fixture(snapshot).await.unwrap();++ let outside = repo+ .forwarded_copy(owner_id, outside_id)+ .await+ .unwrap()+ .expect("the guest owns the copy");+ assert!(outside.google_private_copy);+ assert!(!outside.is_snapshot);+ assert_eq!(+ outside.join_link,+ Some(crate::domain::ics::JoinLink {+ url: "https://teams.microsoft.com/l/meetup-join/abc".to_string(),+ provider: Some(ConferenceProvider::MicrosoftTeams),+ })+ );++ let invited = repo+ .forwarded_copy(owner_id, invited_id)+ .await+ .unwrap()+ .expect("the guest owns the copy");+ assert!(!invited.google_private_copy);+ assert_eq!(invited.join_link, None);++ let snapshot = repo+ .forwarded_copy(owner_id, snapshot_id)+ .await+ .unwrap()+ .expect("the guest owns the copy");+ assert!(snapshot.google_private_copy);+ assert!(snapshot.is_snapshot);++ assert_eq!(+ repo.forwarded_copy("macro|[email protected]", outside_id)+ .await+ .unwrap(),+ None+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_copy_is_private_only_when_every_calendar_holding_it_says_so(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = provider_ids(&repo, link).await;+ let team_id = repo+ .upsert_calendar_fixture(+ account_id,+ ProviderCalendar {+ provider_calendar_id: "team".to_string(),+ name: "Team".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some("writer".to_string()),+ is_primary: false,+ is_selected: true,+ default_reminders: Vec::new(),+ },+ )+ .await+ .unwrap();+ let primary = with_raw_payload(+ timed_upsert(+ owner_id,+ link,+ (account_id, primary_id),+ "040000008200E000-two-calendars",+ "Outside",+ 1,+ ),+ serde_json::json!({ "privateCopy": true }),+ );+ let event_id = primary.event.id;+ repo.upsert_event_fixture(primary).await.unwrap();+ let mut team = with_raw_payload(+ timed_upsert(+ owner_id,+ link,+ (account_id, team_id),+ "040000008200E000-two-calendars",+ "Outside",+ 1,+ ),+ serde_json::json!({}),+ );+ team.event.id = event_id;+ if let CalendarEventSource::Google(source) = &mut team.source {+ source.provider_event_id = "team-copy".to_string();+ }+ repo.upsert_event_fixture(team).await.unwrap();+ let sources = sqlx::query_scalar!(+ "SELECT count(*) FROM calendar_event_sources WHERE event_id = $1",+ event_id+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(sources, Some(2), "both calendars hold the one entity");++ let forwarded = repo+ .forwarded_copy(owner_id, event_id)+ .await+ .unwrap()+ .expect("the owner holds the copy");++ assert!(+ !forwarded.google_private_copy,+ "a calendar whose source lacks the flag is no evidence"+ );+}diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex 1556967206..dfe8f29c7c 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -22,8 +22,10 @@ tools — hexagonal, heavily feature-gated.- Owns: email/thread domain logic, scheduled delivery, reminders/followups,calendar invitation extraction and resolution, adding a forwardedevent (`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`).+ and forwarding one of the viewer's events from the inbox holding their copy+ (`domain/event_forward.rs`): that same file, or, for an organizer outside+ Google, a real invitation (`METHOD:REQUEST`) sent as the message's calendar+ body to the recipients and the organizer, whichever the calendar decides.- Not here: raw provider API calls → `email_api_client`; HTMLparsing/sanitization → `email_utils`; SQLx queries over email tables →`email_db_client`.@@ -67,7 +69,11 @@ tools — hexagonal, heavily feature-gated.`StagedAttachmentSender` (`domain/service/attachments.rs`): draft, stagedattachment rows, then the send. `DraftAttachmentSender` adds Macro documentsas 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`.+ the bytes, such as an event forward's `.ics`, uses `send_with_files`. A+ `SourcedAttachment` with `is_inline` (no Content-ID) is staged inline and+ becomes the message's `text/calendar` body at delivery (see+ `email_api_client`'s `SendRequest::build_mime`); use it only for an+ invitation's calendar part.- 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/event_forward.rs b/crates/email/src/domain/event_forward.rsindex 0aa7cf2374..2348625056 100644--- a/crates/email/src/domain/event_forward.rs+++ b/crates/email/src/domain/event_forward.rs@@ -1,19 +1,33 @@//! 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.+//! organizer does not let them add guests forwards the invitation instead,+//! sent from the inbox that holds their copy. Both kinds carry the copy's+//! join link, since a forward deliberately invites the people it goes to.//!-//! 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`]).+//! The calendar decides the kind from the copy+//! ([`CalendarEventForwardKind`]):+//!+//! - An organizer outside Google: Google keeps such an invitation as a+//! private copy and offers its own Add guests there as a forward, so this+//! sends what that does: a real invitation (`METHOD:REQUEST`) naming the+//! recipients as attendees, as the message's calendar body, addressed to+//! them and to the organizer, as Google addresses its own. Recipients+//! answer it to the organizer with Yes, Maybe or No; the forwarder's own+//! copy and answer are untouched.+//! - Anything else, notably a Google organizer who turned inviting off: the+//! shared-event file (`METHOD:PUBLISH`) naming 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 calendar_events::domain::{+ ics::{CalendarEventForwardKind, IcsParticipant},+ ports::CalendarEventForwardSource,+};use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};use uuid::Uuid;@@ -31,12 +45,30 @@ 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.+/// The type of an invitation's calendar body, which makes it answerable.+const INVITATION_BODY_CONTENT_TYPE: &str = "text/calendar; method=REQUEST";++/// The type and name of the copy of the invitation attached for clients+/// that read only attachments, as Google's own invitations attach it.+const INVITATION_FILE_CONTENT_TYPE: &str = "application/ics";+const INVITATION_FILE_NAME: &str = "invite.ics";++/// Ends a forwarded event file's body: what the recipient can do with it.+const EVENT_FILE_NOTE: &str = "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.";++/// Ends a forwarded invitation's body: who hears the recipient's answer.+const INVITATION_NOTE: &str =+ "This invitation was forwarded to you. Your answer goes to the organizer.";++/// What a forward sends besides the event.#[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.+ /// The plain-text summary of the event the body opens with; the title+ /// when absent. A note saying what the recipient can do follows it.pub body_text: Option<String>,}@@ -72,13 +104,14 @@ impl EventForwardError {}}-/// 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.+/// Send `event_id` to the requested people from the inbox holding the+/// actor's copy of it, as an invitation or the shared-event file, whichever+/// the copy allows. 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),+ fields(%event_id, recipient_count = request.to.len(), link_id, kind, outcome),err)]pub async fn forward_event<C, E, F>(@@ -122,11 +155,19 @@ whereF: EmailFileSendService,{let to = recipients(request.to)?;+ let invitees: Vec<IcsParticipant> = to+ .iter()+ .map(|contact| IcsParticipant {+ email: contact.email.clone(),+ name: contact.name.clone().filter(|name| !name.trim().is_empty()),+ })+ .collect();let forward = calendar- .event_forward(&actor.to_string(), event_id)+ .event_forward(&actor.to_string(), event_id, &invitees).await.map_err(EventForwardError::Internal)?.ok_or(EventForwardError::NotFound)?;+ tracing::Span::current().record("kind", forward.kind.as_str());let inbox = email.resolve_sending_inbox(actor.clone(),@@ -147,10 +188,42 @@ where"" => "Untitled event",title => title,};- let body_text = request+ let document = forward.ics.document.into_bytes();+ let (note, to, files) = match forward.kind {+ CalendarEventForwardKind::EventFile => (+ EVENT_FILE_NOTE,+ to,+ vec![SourcedAttachment {+ file_name: format!("{}.ics", file_stem(title)),+ content_type: ICS_CONTENT_TYPE.to_owned(),+ bytes: document,+ is_inline: false,+ }],+ ),+ CalendarEventForwardKind::Invitation { organizer } => (+ INVITATION_NOTE,+ with_organizer(to, organizer),+ vec![+ SourcedAttachment {+ file_name: INVITATION_FILE_NAME.to_owned(),+ content_type: INVITATION_BODY_CONTENT_TYPE.to_owned(),+ bytes: document.clone(),+ is_inline: true,+ },+ SourcedAttachment {+ file_name: INVITATION_FILE_NAME.to_owned(),+ content_type: INVITATION_FILE_CONTENT_TYPE.to_owned(),+ bytes: document,+ is_inline: false,+ },+ ],+ ),+ };+ let summary = request.body_text.filter(|body| !body.trim().is_empty())- .unwrap_or_else(|| default_body(title));+ .unwrap_or_else(|| title.to_owned());+ let body_text = format!("{}\n\n{note}", summary.trim_end());let input = CreateDraftInput {frozen_signature_html: None,draft_generation: 0,@@ -174,17 +247,29 @@ wheredraft_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])+ .send_message_with_files(&inbox.link, &inbox.accessible_inboxes, input, files).await.map_err(EventForwardError::Email)}+/// The recipients followed by the organizer, who gets the answers, as+/// Google addresses its own forward; an organizer already among the+/// recipients is not added twice.+fn with_organizer(mut to: Vec<ContactInfo>, organizer: IcsParticipant) -> Vec<ContactInfo> {+ if !to+ .iter()+ .any(|contact| contact.email.eq_ignore_ascii_case(&organizer.email))+ {+ to.push(ContactInfo {+ email: organizer.email,+ name: organizer.name,+ photo_url: None,+ });+ }+ to+}+/// 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();@@ -211,13 +296,6 @@ fn recipients(requested: Vec<ContactInfo>) -> Result<Vec<ContactInfo>, EventForwOk(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);diff --git a/crates/email/src/domain/event_forward/test.rs b/crates/email/src/domain/event_forward/test.rsindex ac84edd55c..fb30f8cbd5 100644--- a/crates/email/src/domain/event_forward/test.rs+++ b/crates/email/src/domain/event_forward/test.rs@@ -1,5 +1,6 @@use super::*;use crate::domain::models::{Link, ResolvedSendingInbox, UserProvider};+use calendar_events::domain::ics::CalendarEventForwardKind;use calendar_events::domain::ics::{CalendarEventForward, CalendarEventIcs};use rootcause::Report;use std::sync::Mutex;@@ -40,6 +41,8 @@ struct Fake {/// Inboxes the requester can send from.inboxes: Vec<&'static str>,resolved_addresses: Mutex<Vec<Option<String>>>,+ /// The invitees each calendar read was asked to name.+ invitees: Mutex<Vec<Vec<IcsParticipant>>>,sent: Mutex<Vec<(Uuid, CreateDraftInput, Vec<SourcedAttachment>)>>,}@@ -48,8 +51,10 @@ impl CalendarEventForwardSource for Fake {&self,requester_id: &str,_event_id: Uuid,+ invitees: &[IcsParticipant],) -> Result<Option<CalendarEventForward>, Report> {assert_eq!(requester_id, "macro|[email protected]");+ self.invitees.lock().unwrap().push(invitees.to_vec());Ok(self.forward.clone())}}@@ -97,7 +102,7 @@ impl EmailFileSendService for Fake {link_id: link.id,subject: input.subject.clone(),to: input.to.clone(),- cc: Vec::new(),+ cc: input.cc.clone(),bcc: Vec::new(),body_text: input.body_text.clone(),body_html: None,@@ -118,12 +123,35 @@ fn guest_copy(title: &str) -> Fake {document: EVENT_ICS.to_owned(),},inbox: "[email protected]".to_owned(),+ kind: CalendarEventForwardKind::EventFile,}),inboxes: vec!["[email protected]", "[email protected]"],..Fake::default()}}+const INVITATION_ICS: &str = "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nEND:VCALENDAR\r\n";++/// A guest's copy of an invitation from an organizer outside Google.+fn outside_invitation() -> Fake {+ Fake {+ forward: Some(CalendarEventForward {+ ics: CalendarEventIcs {+ title: "Board review".to_owned(),+ document: INVITATION_ICS.to_owned(),+ },+ inbox: "[email protected]".to_owned(),+ kind: CalendarEventForwardKind::Invitation {+ organizer: IcsParticipant {+ email: "[email protected]".to_owned(),+ name: Some("The Organizer".to_owned()),+ },+ },+ }),+ ..guest_copy("Board review")+ }+}+async fn forward(fake: &Fake,request: EventForwardRequest,@@ -157,16 +185,19 @@ async fn sends_the_event_file_from_the_inbox_holding_the_copy() {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 body = input.body_text.as_deref().unwrap();+ assert!(body.starts_with("Office tour\nWhen: Friday\n\n"), "{body}");+ assert!(+ body.ends_with("You won't be on the organizer's guest list."),+ "{body}");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>"+ let html = String::from_utf8(html).unwrap();+ assert!(+ html.starts_with("<div>Office tour<br>When: Friday<br><br>This invitation"),+ "{html}");assert_eq!(input.actor.as_ref().map(ToString::to_string).as_deref(),@@ -176,6 +207,89 @@ async fn sends_the_event_file_from_the_inbox_holding_the_copy() {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());+ assert!(!files[0].is_inline);+}++#[tokio::test]+async fn an_outside_organizers_invitation_goes_out_answerable_to_the_recipients_and_organizer() {+ let fake = outside_invitation();+ forward(+ &fake,+ EventForwardRequest {+ to: vec![ContactInfo {+ name: Some("A Friend".to_owned()),+ ..contact(" [email protected] ")+ }],+ body_text: Some("Board review\nWhen: Friday".to_owned()),+ },+ )+ .await+ .unwrap();++ assert_eq!(+ *fake.invitees.lock().unwrap(),+ [vec![IcsParticipant {+ email: "[email protected]".to_owned(),+ name: Some("A Friend".to_owned()),+ }]],+ "the calendar names exactly the validated recipients"+ );+ let sent = fake.sent.lock().unwrap();+ let (_, input, files) = &sent[0];+ let to: Vec<_> = input+ .to+ .iter()+ .map(|to| (to.email.as_str(), to.name.as_deref()))+ .collect();+ assert_eq!(+ to,+ [+ ("[email protected]", Some("A Friend")),+ ("[email protected]", Some("The Organizer")),+ ],+ "the organizer is addressed beside the recipients, as Google does"+ );+ assert!(input.cc.is_empty() && input.bcc.is_empty());+ let body = input.body_text.as_deref().unwrap();+ assert!(body.starts_with("Board review\nWhen: Friday\n\n"), "{body}");+ assert!(+ body.ends_with("Your answer goes to the organizer."),+ "{body}"+ );+ assert!(+ !body.contains("attached file") && !body.contains("copied"),+ "{body}"+ );+ assert_eq!(files.len(), 2);+ assert_eq!(files[0].content_type, "text/calendar; method=REQUEST");+ assert!(+ files[0].is_inline,+ "the invitation is the message's calendar body"+ );+ assert_eq!(files[0].bytes, INVITATION_ICS.as_bytes());+ assert_eq!(files[1].file_name, "invite.ics");+ assert_eq!(files[1].content_type, "application/ics");+ assert!(!files[1].is_inline);+ assert_eq!(files[1].bytes, INVITATION_ICS.as_bytes());+}++#[tokio::test]+async fn an_organizer_among_the_recipients_is_not_addressed_twice() {+ let fake = outside_invitation();+ forward(+ &fake,+ EventForwardRequest {+ to: vec![contact("[email protected]")],+ body_text: None,+ },+ )+ .await+ .unwrap();++ let sent = fake.sent.lock().unwrap();+ let to: Vec<_> = sent[0].1.to.iter().map(|to| to.email.as_str()).collect();+ assert_eq!(to, ["[email protected]"]);+ assert!(sent[0].1.cc.is_empty());}#[tokio::test]@@ -221,9 +335,10 @@ async fn markup_in_the_body_is_escaped_and_the_title_cannot_name_a_path() {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>"+ let html = String::from_utf8(html).unwrap();+ assert!(+ html.starts_with("<div><b>&</b><br><br>"),+ "{html}");assert_eq!(files[0].file_name, "Q3-Q4 <review>.ics");}diff --git a/crates/email/src/domain/models/attachment.rs b/crates/email/src/domain/models/attachment.rsindex e1427fe747..aec7de77e7 100644--- a/crates/email/src/domain/models/attachment.rs+++ b/crates/email/src/domain/models/attachment.rs@@ -92,6 +92,10 @@ pub struct SourcedAttachment {pub content_type: String,/// The file's raw bytes.pub bytes: Vec<u8>,+ /// Sent as part of the message body instead of as a file. The only such+ /// part is an invitation's `text/calendar` body (RFC 6047), which Gmail+ /// and Outlook answer with Yes, Maybe and No.+ pub is_inline: bool,}/// A forwarded attachment linking a draft to an original message's attachment.diff --git a/crates/email/src/domain/service/attachments.rs b/crates/email/src/domain/service/attachments.rsindex 45e58a3f01..45c755b2b6 100644--- a/crates/email/src/domain/service/attachments.rs+++ b/crates/email/src/domain/service/attachments.rs@@ -128,7 +128,7 @@ wheres3_key,upload_pending: false,content_id: None,- is_inline: false,+ is_inline: sourced.is_inline,};self.repo.insert_draft_attachment(link.id, &record)diff --git a/crates/email/src/domain/service/attachments/test.rs b/crates/email/src/domain/service/attachments/test.rsindex 94e9e394fe..ce4d038278 100644--- a/crates/email/src/domain/service/attachments/test.rs+++ b/crates/email/src/domain/service/attachments/test.rs@@ -112,6 +112,7 @@ impl DraftAttachmentSource for Fake {file_name: format!("{id}.pdf"),content_type: "application/pdf".to_owned(),bytes: bytes.clone(),+ is_inline: false,})}}@@ -140,11 +141,13 @@ impl DraftAttachmentRepo for Fake {);assert_eq!(attachment.sha.len(), 64);assert!(!attachment.upload_pending);- assert!(!attachment.is_inline);assert!(attachment.content_id.is_none());self.calls.push(format!(- "record:{}:{}:{}",- attachment.file_name, attachment.content_type, attachment.size+ "record:{}:{}:{}{}",+ attachment.file_name,+ attachment.content_type,+ attachment.size,+ if attachment.is_inline { ":inline" } else { "" }));Ok(())}@@ -360,6 +363,7 @@ async fn a_file_the_caller_holds_is_staged_on_the_draft_then_sent() {file_name: "Office tour.ics".to_owned(),content_type: "text/calendar".to_owned(),bytes: vec![1, 2],+ is_inline: false,}],).await@@ -378,6 +382,40 @@ async fn a_file_the_caller_holds_is_staged_on_the_draft_then_sent() {assert_eq!(calls.len(), 4);}+#[tokio::test]+async fn an_invitations_calendar_body_is_staged_inline_beside_its_file() {+ let fake = fake_with(vec![]);+ StagedAttachmentSender::new(fake.clone(), fake.clone(), fake.clone())+ .send_message_with_files(+ &link(),+ &[link()],+ input(),+ vec![+ SourcedAttachment {+ file_name: "invite.ics".to_owned(),+ content_type: "text/calendar; method=REQUEST".to_owned(),+ bytes: vec![1, 2],+ is_inline: true,+ },+ SourcedAttachment {+ file_name: "invite.ics".to_owned(),+ content_type: "application/ics".to_owned(),+ bytes: vec![1, 2],+ is_inline: false,+ },+ ],+ )+ .await+ .unwrap();++ let calls = fake.calls.take();+ assert_eq!(+ calls[2],+ "record:invite.ics:text/calendar; method=REQUEST:2:inline"+ );+ assert_eq!(calls[4], "record:invite.ics:application/ics:2");+}+#[tokio::test]async fn oversized_files_are_refused_before_any_draft_exists() {let fake = fake_with(vec![]);@@ -390,6 +428,7 @@ async fn oversized_files_are_refused_before_any_draft_exists() {file_name: "big.ics".to_owned(),content_type: "text/calendar".to_owned(),bytes: vec![0; MAX_DRAFT_ATTACHMENTS_BYTES + 1],+ is_inline: false,}],).awaitdiff --git a/crates/email_api_client/AGENTS.md b/crates/email_api_client/AGENTS.mdindex e763fd1f83..1e1bff78e7 100644--- a/crates/email_api_client/AGENTS.md+++ b/crates/email_api_client/AGENTS.md@@ -70,6 +70,11 @@ Outlook (Microsoft Graph) outbound adapters.the link for reauthorization. Contact listings use `retry_with_fresh_token`to keep their WARN-level logging. Writes use `call_with_token` and do notretry.+- `SendRequest::build_mime` (Gmail sends) turns an inline `text/calendar`+ attachment with no Content-ID into the message's calendar body, the last+ alternative after the text and HTML, which is how an answerable invitation+ (RFC 6047) is sent; other files stay attachments. Outlook sends do not go+ through it.- Graph answers a bodyless POST or PATCH without `Content-Length: 0` with 411Length Required. `transport.rs` adds the header, so new Graph calls must gothrough `request`/`conditional_request` rather than the raw client.diff --git a/crates/email_api_client/src/domain/models/send.rs b/crates/email_api_client/src/domain/models/send.rsindex 18b38c86bf..17bbd4ce04 100644--- a/crates/email_api_client/src/domain/models/send.rs+++ b/crates/email_api_client/src/domain/models/send.rs@@ -1,6 +1,8 @@use mail_builder::MessageBuilder;use mail_builder::headers::address::Address;+use mail_builder::mime::{BodyPart, MimePart};use models_email::email::service::address::ContactInfo;+use models_email::email::service::attachment::AttachmentToSend;use models_email::email::service::message::MessageToSend;#[cfg(feature = "ports")]@@ -52,8 +54,16 @@ impl SendRequest {if let Some(html_body) = &self.message.body_html {builder = builder.html_body(html_body);}+ let mut calendar_body = None;if let Some(attachments) = &self.message.attachments {for attachment in attachments {+ if is_calendar_body(attachment) {+ calendar_body = Some(MimePart::new(+ attachment.content_type.as_str(),+ BodyPart::Text(String::from_utf8_lossy(&attachment.data)),+ ));+ continue;+ }// Borrow the attachment buffers: cloning them would double// peak memory for large-attachment sends.builder = if attachment.is_inline {@@ -76,6 +86,10 @@ impl SendRequest {}}+ if let Some(calendar) = calendar_body {+ builder.body = Some(with_calendar_body(&mut builder, calendar));+ }+builder.write_to_vec().map_err(|error| EmailApiError::Permanent {@@ -84,6 +98,44 @@ impl SendRequest {}}+/// Whether `attachment` is the message's calendar body rather than a file:+/// an inline `text/calendar` part with no Content-ID, which no HTML body+/// can reference. That is how an invitation (RFC 6047) is sent, and the+/// form Gmail and Outlook answer with Yes, Maybe and No.+fn is_calendar_body(attachment: &AttachmentToSend) -> bool {+ attachment.is_inline+ && attachment.content_id.is_none()+ && attachment+ .content_type+ .trim_start()+ .to_ascii_lowercase()+ .starts_with("text/calendar")+}++/// The body of a message carrying a calendar part: the calendar is the last+/// alternative to the text and HTML bodies, as Google's own invitations+/// send it, with any files after them.+fn with_calendar_body<'x>(+ builder: &mut MessageBuilder<'x>,+ calendar: MimePart<'x>,+) -> MimePart<'x> {+ let mut alternatives: Vec<MimePart<'x>> = [builder.text_body.take(), builder.html_body.take()]+ .into_iter()+ .flatten()+ .collect();+ alternatives.push(calendar);+ let alternative = MimePart::new("multipart/alternative", alternatives);+ match builder.attachments.take() {+ Some(files) if !files.is_empty() => {+ let mut parts = Vec::with_capacity(files.len() + 1);+ parts.push(alternative);+ parts.extend(files);+ MimePart::new("multipart/mixed", parts)+ }+ _ => alternative,+ }+}+/// Locally prepared delivery. Tokens and message contents cannot be logged via/// `Debug`, and callers cannot construct it without completing preparation.///diff --git a/crates/email_api_client/src/domain/models/send/test.rs b/crates/email_api_client/src/domain/models/send/test.rsindex 44a4a81748..2a95198b69 100644--- a/crates/email_api_client/src/domain/models/send/test.rs+++ b/crates/email_api_client/src/domain/models/send/test.rs@@ -83,3 +83,120 @@ fn stable_message_id_rejects_header_or_query_injection() {}assert!(super::validate_message_id("[email protected]").is_ok());}++fn message(attachments: Vec<AttachmentToSend>) -> SendRequest {+ SendRequest {+ message_id: Some("[email protected]".to_string()),+ message: MessageToSend {+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: None,+ link_id: Uuid::nil(),+ subject: "Office tour".to_string(),+ to: Some(vec![contact("[email protected]", "To Recipient")]),+ cc: None,+ bcc: None,+ body_text: Some("Plain body".to_string()),+ body_html: Some("<div>HTML body</div>".to_string()),+ body_macro: None,+ attachments: Some(attachments),+ headers_json: None,+ send_time: None,+ },+ from: contact("[email protected]", "Sender"),+ parent_message_id: None,+ references: None,+ }+}++const INVITATION: &str = "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nBEGIN:VEVENT\r\nUID:[email protected]\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";++fn calendar_body() -> AttachmentToSend {+ AttachmentToSend {+ content_id: None,+ is_inline: true,+ file_name: "invite.ics".to_string(),+ content_type: "text/calendar; method=REQUEST".to_string(),+ data: INVITATION.as_bytes().to_vec(),+ }+}++/// The parts of `mime` in order, as their Content-Type lines.+fn content_types(mime: &str) -> Vec<String> {+ mime.split("\r\n")+ .filter(|line| line.to_ascii_lowercase().starts_with("content-type:"))+ .map(|line| line["content-type:".len()..].trim().to_string())+ .collect()+}++#[test]+fn an_inline_calendar_part_is_the_last_alternative_and_the_file_follows() {+ let request = message(vec![+ calendar_body(),+ AttachmentToSend {+ content_id: None,+ is_inline: false,+ file_name: "invite.ics".to_string(),+ content_type: "application/ics".to_string(),+ data: INVITATION.as_bytes().to_vec(),+ },+ ]);++ let mime = String::from_utf8(request.build_mime().unwrap()).unwrap();+ let types = content_types(&mime);++ assert!(types[0].starts_with("multipart/mixed"), "{types:?}");+ assert!(types[1].starts_with("multipart/alternative"), "{types:?}");+ assert!(types[2].starts_with("text/plain"), "{types:?}");+ assert!(types[3].starts_with("text/html"), "{types:?}");+ assert!(+ types[4].starts_with("text/calendar; method=REQUEST"),+ "{types:?}"+ );+ assert!(types[5].starts_with("application/ics"), "{types:?}");+ assert_eq!(types.len(), 6, "{types:?}");+ assert_eq!(mime.matches("filename=\"invite.ics\"").count(), 1, "{mime}");+ assert!(mime.contains("UID:[email protected]"), "{mime}");+}++#[test]+fn a_calendar_body_without_files_is_the_whole_message() {+ let mime = String::from_utf8(message(vec![calendar_body()]).build_mime().unwrap()).unwrap();+ let types = content_types(&mime);++ assert!(types[0].starts_with("multipart/alternative"), "{types:?}");+ assert_eq!(types.len(), 4, "{types:?}");+}++#[test]+fn a_calendar_file_or_an_inline_image_stays_an_attachment() {+ let mime = String::from_utf8(+ message(vec![+ AttachmentToSend {+ content_id: None,+ is_inline: false,+ file_name: "Office tour.ics".to_string(),+ content_type: "text/calendar".to_string(),+ data: INVITATION.as_bytes().to_vec(),+ },+ AttachmentToSend {+ content_id: Some("[email protected]".to_string()),+ is_inline: true,+ file_name: "logo.png".to_string(),+ content_type: "image/png".to_string(),+ data: vec![0x89, 0x50, 0x4e, 0x47],+ },+ ])+ .build_mime()+ .unwrap(),+ )+ .unwrap();+ let types = content_types(&mime);++ assert!(types[0].starts_with("multipart/mixed"), "{types:?}");+ assert!(types[1].starts_with("multipart/alternative"), "{types:?}");+ assert!(mime.contains("filename=\"Office tour.ics\""), "{mime}");+ assert!(mime.contains("Content-ID: <[email protected]>"), "{mime}");+}diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex bef30d9dc7..fceee970eb 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -636,17 +636,37 @@ In each of those cases (inviting off, a hidden guest list, an Outlook guest copya refusal), the `enable-calendar-invitation-forward` flag (on in dev, with no PostHog flagyet, 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+you send it to get the event by email but won't be on the guest list.` It opensthe 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+`Forward to`), says `They'll get the event by email but won't appear in the guest list.`,+and `Forward` (or Cmd/Ctrl+Enter) sends; there is no Optional box or occurrencechoice, 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+`POST /email/calendar-events/{event_id}/forward` with the recipients and `Forward by+email`'s summary as the body; email-service sends it from the inbox holding the copy, and+the server decides what it is from the stored copy, ending the body with the matching note:+- Google's private copy (`privateCopy` in the stored Google payload) of an invitation whose+ organizer is outside Google, such as Exchange (Google stores every such invitation that+ way and reports it as `guestsCanInviteOthers: false`): a real invitation, as Google's own+ Add guests sends there. The message's calendar body is `METHOD:REQUEST` with the original+ organizer and the recipients (only them) as attendees, an `invite.ics` copy is attached,+ and the email goes to the recipients and the organizer, as Google addresses its own.+ Recipients get Yes / Maybe / No in Gmail and Outlook and their answers go to the+ organizer; the forwarder's own copy and answer are untouched. The note reads `This+ invitation was forwarded to you. Your answer goes to the organizer.`+- Anything else, notably a Google organizer who turned inviting off, and whenever the+ evidence is missing (an Outlook copy, a snapshot, a private copy whose UID ends in+ `@google.com`, which is an imported Google meeting, an organizer Macro cannot name, or a+ source synced before Macro kept Google's whole payload): the event's `.ics`+ (`METHOD:PUBLISH`, no guests) attached, so recipients can add the event to their calendar+ and nothing reaches the organizer or the guest list. The note reads `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.`++Both carry the join link, unlike `Download .ics` and channel shares: a Macro call's+`Join Macro call` line and location stay, and the copy's Meet, Teams or Zoom link is added as+a `Join with Google Meet: <url>` (or `Join the Microsoft Teams meeting`, `Join the meeting`)+line unless the description already shows it, plus `CONFERENCE` (and, for Meet,+`X-GOOGLE-CONFERENCE`). The toast reads `Invitation forwarded to <name>` (or `to Npeople`) 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 reasonshows instead). The editor offers the same `Forward invitation` beside its read-only guests@@ -1394,8 +1414,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` and `Forward invitation`-attach) is a shared+A published event file (`METHOD:PUBLISH`, what `Forward by email` and, for a Google+organizer, `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`;@@ -1405,7 +1425,8 @@ When the calendar check confirms the viewer does not hold it, the card says`Not on your calendar.` and, behind the `enable-calendar-add-shared-event` flag, offers`Add to calendar`, which imports the same snapshot as the channel-share card(the viewer's only writable Google calendar, or one picked from a menu; the real organizer-kept, the viewer as the only guest, nobody notified) through email service's+kept, the viewer as the only guest, nobody notified), except that it keeps the join link the+file carries, through email service's`POST /email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy`.The server reads the event from the saved email, never from the request. The card thenresolves to the snapshot. A single occurrence, a cancelled event, a time that cannot be read,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.mdindex a51eb7b7b3..a477e251c0 100644--- 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.md@@ -8,5 +8,5 @@ Who a forwarded invitation goes to, and what its email says.| 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-bodytext"></a> `bodyText?` | `string` \| `null` | A plain-text summary of the event the email opens with; the title when absent. The email ends with a note saying what the recipient can do with the forward. || <a id="property-to"></a> `to` | [`ForwardCalendarEventRecipient`](ForwardCalendarEventRecipient.md)[] | The people it goes to, at most 50. |diff --git a/packages/sdk/generated/email/sdk.gen.ts b/packages/sdk/generated/email/sdk.gen.tsindex bde961a787..6777edcc1e 100644--- a/packages/sdk/generated/email/sdk.gen.ts+++ b/packages/sdk/generated/email/sdk.gen.ts@@ -110,11 +110,14 @@ export class Sdk extends HeyApiClient {/*** 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.+ * does not name, from the inbox that holds the viewer's copy, with the+ * usual undo delay, carrying the copy's join link. When the copy is Google's+ * private copy of an invitation from an organizer outside Google, it is a+ * real invitation (`METHOD:REQUEST`) naming the recipients, who answer it to+ * the organizer, who gets the email too. Otherwise it is the event's file+ * (`METHOD:PUBLISH`, no attendees): recipients can add the event to their+ * own calendar, 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>({diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.tsindex 5c70b60022..5c27545973 100644--- a/packages/sdk/generated/email/types.gen.ts+++ b/packages/sdk/generated/email/types.gen.ts@@ -1191,8 +1191,9 @@ export type ForwardCalendarEventRecipient = {*/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.+ * A plain-text summary of the event the email opens with; the title+ * when absent. The email ends with a note saying what the recipient+ * can do with the forward.*/bodyText?: string | null;/**diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.jsonindex ce54b9f137..3aa11f5bd5 100644--- a/packages/sdk/specs/email.json+++ b/packages/sdk/specs/email.json@@ -391,7 +391,7 @@"/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.",+ "summary": "Email one of the viewer's events to people the organizer's guest list\ndoes not name, from the inbox that holds the viewer's copy, with the\nusual undo delay, carrying the copy's join link. When the copy is Google's\nprivate copy of an invitation from an organizer outside Google, it is a\nreal invitation (`METHOD:REQUEST`) naming the recipients, who answer it to\nthe organizer, who gets the email too. Otherwise it is the event's file\n(`METHOD:PUBLISH`, no attendees): recipients can add the event to their\nown calendar, are not added to the guest list, and the organizer is not\ntold.","operationId": "forward_calendar_event","parameters": [{@@ -5900,7 +5900,7 @@"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."+ "description": "A plain-text summary of the event the email opens with; the title\nwhen absent. The email ends with a note saying what the recipient\ncan do with the forward."},"to": {"type": "array",diff --git a/services/email_service/src/api/calendar_event_forward.rs b/services/email_service/src/api/calendar_event_forward.rsindex 39a5284bbc..ddb94e14d0 100644--- a/services/email_service/src/api/calendar_event_forward.rs+++ b/services/email_service/src/api/calendar_event_forward.rs@@ -25,8 +25,9 @@ use uuid::Uuid;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.+ /// A plain-text summary of the event the email opens with; the title+ /// when absent. The email ends with a note saying what the recipient+ /// can do with the forward.#[serde(default)]pub body_text: Option<String>,}@@ -116,11 +117,14 @@ impl From<EventForwardError> for ForwardCalendarEventError {}/// 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.+/// does not name, from the inbox that holds the viewer's copy, with the+/// usual undo delay, carrying the copy's join link. When the copy is Google's+/// private copy of an invitation from an organizer outside Google, it is a+/// real invitation (`METHOD:REQUEST`) naming the recipients, who answer it to+/// the organizer, who gets the email too. Otherwise it is the event's file+/// (`METHOD:PUBLISH`, no attendees): recipients can add the event to their+/// own calendar, 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",