Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calendar): let a secondary calendar's owner edit the events made on it (#8830)
gbirmanebd942766cfb
diff --git a/.sqlx/query-1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa.json b/.sqlx/query-1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa.jsondeleted file mode 100644index 0ee045d44c..0000000000--- a/.sqlx/query-1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n id AS link_id,\n email_address::text AS \"email_address!\",\n provider::text AS \"provider!\"\n FROM email_links\n WHERE macro_id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "link_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "email_address!",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "provider!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- null,- null- ]- },- "hash": "1e940847546512da10cc8270591d9eb83caba353443c96fcfab9f37f9d33b0aa"-}diff --git a/.sqlx/query-ba2831f014bc1c20230c4fcfbe6fb3ae3f0a92d9d558f96b7143bb2e50f18051.json b/.sqlx/query-26673e0c63c49bdcc93d0413bebfb6e68ee2e7bfe58f59a932329a11f23cfdfe.jsonsimilarity index 54%rename from .sqlx/query-ba2831f014bc1c20230c4fcfbe6fb3ae3f0a92d9d558f96b7143bb2e50f18051.jsonrename to .sqlx/query-26673e0c63c49bdcc93d0413bebfb6e68ee2e7bfe58f59a932329a11f23cfdfe.jsonindex 21bfc689d8..b15b81c4fe 100644--- a/.sqlx/query-ba2831f014bc1c20230c4fcfbe6fb3ae3f0a92d9d558f96b7143bb2e50f18051.json+++ b/.sqlx/query-26673e0c63c49bdcc93d0413bebfb6e68ee2e7bfe58f59a932329a11f23cfdfe.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n event.id AS event_id,\n event.owner_id,\n event.organizer_email,\n event.guests_can_modify,\n event.guests_can_invite_others,\n event.guests_can_see_other_guests,\n -- A snapshot imported into one calendar can share its entity\n -- with the real meeting on another, so the addressed copy's\n -- own projection says whether it is a snapshot.\n COALESCE(\n source.normalized_payload->'event'->>'isSnapshot' = 'true',\n false\n ) AS \"is_snapshot!\",\n source.is_read_only,\n source.provider_event_id AS \"provider_event_id!\",\n source.provider_recurring_event_id,\n source.account_id AS \"account_id!\",\n source.calendar_id AS \"calendar_id!\",\n calendar.provider_calendar_id,\n calendar.access_role,\n account.email_link_id,\n link.fusionauth_user_id,\n link.email_address,\n link.provider::text AS \"provider!\",link.sync_generation,link.grant_generation\n FROM calendar_events event\n JOIN calendar_event_sources source\n ON source.event_id = event.id\n AND source.source_kind IN ('google','outlook')\n JOIN calendars calendar ON calendar.id = source.calendar_id\n AND calendar.account_id = source.account_id\n JOIN calendar_accounts account ON account.id = source.account_id\n JOIN email_links link ON link.id = account.email_link_id\n WHERE event.id = $1\n AND NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND CASE\n WHEN $3::uuid IS NULL\n THEN source.id = calendar_event_canonical_source_id(event.id)\n ELSE source.calendar_id = $3\n END\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = event.source_link_id\n AND delegation.primary_macro_id = $2\n )\n )\n ORDER BY\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.id DESC\n LIMIT 1\n ",+ "query": "\n SELECT\n event.id AS event_id,\n event.owner_id,\n event.organizer_email,\n event.guests_can_modify,\n event.guests_can_invite_others,\n event.guests_can_see_other_guests,\n -- A snapshot imported into one calendar can share its entity\n -- with the real meeting on another, so the addressed copy's\n -- own projection says whether it is a snapshot.\n COALESCE(\n source.normalized_payload->'event'->>'isSnapshot' = 'true',\n false\n ) AS \"is_snapshot!\",\n source.is_read_only,\n source.provider_event_id AS \"provider_event_id!\",\n source.provider_recurring_event_id,\n source.account_id AS \"account_id!\",\n source.calendar_id AS \"calendar_id!\",\n calendar.provider_calendar_id,\n calendar.access_role,\n -- Google names the calendar an event was made on as its\n -- organizer; the copy on it takes the organizer's changes.\n (\n SELECT organizer_source.calendar_id\n FROM calendar_event_sources organizer_source\n JOIN calendars organizer_calendar\n ON organizer_calendar.id = organizer_source.calendar_id\n AND organizer_calendar.account_id = organizer_source.account_id\n WHERE organizer_source.event_id = event.id\n AND organizer_source.source_kind IN ('google','outlook')\n AND organizer_source.calendar_id <> source.calendar_id\n AND NOT organizer_calendar.is_deleted\n AND organizer_calendar.access_role IN ('owner', 'writer')\n AND lower(organizer_calendar.provider_calendar_id)\n = lower(event.organizer_email)\n LIMIT 1\n ) AS organizer_copy_calendar_id,\n account.email_link_id,\n link.fusionauth_user_id,\n link.email_address,\n link.provider::text AS \"provider!\",link.sync_generation,link.grant_generation\n FROM calendar_events event\n JOIN calendar_event_sources source\n ON source.event_id = event.id\n AND source.source_kind IN ('google','outlook')\n JOIN calendars calendar ON calendar.id = source.calendar_id\n AND calendar.account_id = source.account_id\n JOIN calendar_accounts account ON account.id = source.account_id\n JOIN email_links link ON link.id = account.email_link_id\n WHERE event.id = $1\n AND NOT calendar.is_deleted\n AND account.sync_status <> 'disabled'\n AND CASE\n WHEN $3::uuid IS NULL\n THEN source.id = calendar_event_canonical_source_id(event.id)\n ELSE source.calendar_id = $3\n END\n AND (\n event.owner_id = $2\n OR EXISTS (\n SELECT 1\n FROM macro_user_links delegation\n WHERE delegation.link_id = event.source_link_id\n AND delegation.primary_macro_id = $2\n )\n )\n ORDER BY\n source.source_sequence DESC,\n source.source_updated_at DESC,\n source.id DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -75,31 +75,36 @@},{"ordinal": 14,- "name": "email_link_id",+ "name": "organizer_copy_calendar_id","type_info": "Uuid"},{"ordinal": 15,+ "name": "email_link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 16,"name": "fusionauth_user_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "email_address","type_info": "Varchar"},{- "ordinal": 17,+ "ordinal": 18,"name": "provider!","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "sync_generation","type_info": "Int8"},{- "ordinal": 19,+ "ordinal": 20,"name": "grant_generation","type_info": "Int8"}@@ -126,6 +131,7 @@true,false,true,+ null,false,false,false,@@ -134,5 +140,5 @@false]},- "hash": "ba2831f014bc1c20230c4fcfbe6fb3ae3f0a92d9d558f96b7143bb2e50f18051"+ "hash": "26673e0c63c49bdcc93d0413bebfb6e68ee2e7bfe58f59a932329a11f23cfdfe"}diff --git a/.sqlx/query-41c9b8b64954e28433337d9dcd878574dd0f831c81b7c5110b5f17fdb5cdca41.json b/.sqlx/query-41c9b8b64954e28433337d9dcd878574dd0f831c81b7c5110b5f17fdb5cdca41.jsondeleted file mode 100644index 3e9658ce69..0000000000--- a/.sqlx/query-41c9b8b64954e28433337d9dcd878574dd0f831c81b7c5110b5f17fdb5cdca41.json+++ /dev/null@@ -1,164 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n (mentioned.id IS NOT NULL) AS \"mention_exists!\",\n viewer_event.id AS \"resolved_event_id?\",\n viewer_event.is_channel_shared AS \"is_channel_shared?\",\n viewer_event.is_snapshot AS \"is_snapshot?\",\n viewer_event.inbox_organizes AS \"inbox_organizes?\",\n viewer_event.inbox_attends AS \"inbox_attends?\",\n COALESCE(occurrence_override.title, viewer_event.title) AS \"title?\",\n left(\n COALESCE(occurrence_override.description, viewer_event.description),\n $5\n ) AS \"description?\",\n COALESCE(occurrence_override.location, viewer_event.location) AS \"location?\",\n viewer_event.organizer_email AS \"organizer_email?\",\n viewer_event.organizer_name AS \"organizer_name?\",\n viewer_event.recurrence_lines AS \"recurrence_lines?\",\n viewer_event.starts_at AS \"event_starts_at?\",\n viewer_event.ends_at AS \"event_ends_at?\",\n viewer_event.start_date AS \"event_start_date?\",\n viewer_event.end_date AS \"event_end_date?\",\n viewer_event.time_zone AS \"time_zone?\",\n viewer_event.updated_at AS \"updated_at?\",\n occurrence.occurrence_key AS \"occurrence_key?\",\n occurrence.starts_at AS \"occurrence_starts_at?\",\n occurrence.ends_at AS \"occurrence_ends_at?\",\n occurrence.start_date AS \"occurrence_start_date?\",\n occurrence.end_date AS \"occurrence_end_date?\",\n attendees.attendee_count AS \"attendee_count?\"\n FROM unnest($2::uuid[], $3::text[])\n WITH ORDINALITY AS requested(event_id, occurrence_key, ord)\n LEFT JOIN calendar_events mentioned\n ON mentioned.id = requested.event_id\n AND mentioned.status <> 'cancelled'\n LEFT JOIN LATERAL (\n SELECT resolved.*\n FROM (\n SELECT\n candidate.id,\n false AS is_channel_shared,\n (candidate.owner_id = $1) AS is_owned,\n (candidate.id = mentioned.id) AS is_mentioned,\n candidate.is_snapshot,\n -- The copy's own inbox decides how the requester\n -- holds it, as it decides their capabilities: an\n -- inbox they own that organizes it or is on it.\n COALESCE(\n lower(copy_inbox.email_address) = lower(candidate.organizer_email)\n OR EXISTS (\n SELECT 1\n FROM calendar_event_attendees organizer\n WHERE organizer.event_id = candidate.id\n AND organizer.is_organizer\n AND lower(organizer.email) = lower(copy_inbox.email_address)\n ),\n false\n ) AS inbox_organizes,\n EXISTS (\n SELECT 1\n FROM calendar_event_attendees guest\n WHERE guest.event_id = candidate.id\n AND lower(guest.email) = lower(copy_inbox.email_address)\n ) AS inbox_attends,\n candidate.title,\n candidate.description,\n candidate.location,\n candidate.organizer_email,\n candidate.organizer_name,\n candidate.recurrence_lines,\n candidate.starts_at,\n candidate.ends_at,\n candidate.start_date,\n candidate.end_date,\n candidate.time_zone,\n candidate.updated_at\n FROM calendar_events candidate\n LEFT JOIN email_links copy_inbox\n ON copy_inbox.id = candidate.source_link_id\n AND copy_inbox.macro_id = $1\n WHERE calendar_meeting_uid(candidate.ical_uid)\n = calendar_meeting_uid(mentioned.ical_uid)\n AND candidate.status <> 'cancelled'\n AND (\n candidate.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = candidate.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n UNION ALL\n SELECT\n mentioned.id,\n true,\n false,\n true,\n false,\n false,\n false,\n mentioned.title,\n mentioned.description,\n mentioned.location,\n mentioned.organizer_email,\n mentioned.organizer_name,\n mentioned.recurrence_lines,\n mentioned.starts_at,\n mentioned.ends_at,\n mentioned.start_date,\n mentioned.end_date,\n mentioned.time_zone,\n mentioned.updated_at\n WHERE mentioned.visibility IN ('default', 'public')\n AND EXISTS (\n SELECT 1\n FROM entity_access grant_row\n JOIN comms_channel_participants participant\n ON participant.channel_id::text = grant_row.source_id\n AND participant.user_id = $1\n AND participant.left_at IS NULL\n WHERE grant_row.entity_id = mentioned.id\n AND grant_row.entity_type = 'calendar_event'\n AND grant_row.source_type = 'channel'\n )\n ) resolved\n ORDER BY\n resolved.is_channel_shared,\n resolved.is_owned DESC,\n resolved.is_mentioned DESC,\n resolved.updated_at DESC,\n resolved.id\n LIMIT 1\n ) viewer_event ON true\n LEFT JOIN LATERAL (\n SELECT\n instance.occurrence_key,\n instance.recurrence_id,\n instance.starts_at,\n instance.ends_at,\n instance.start_date,\n instance.end_date\n FROM calendar_event_occurrences instance\n CROSS JOIN LATERAL (\n SELECT COALESCE(\n instance.starts_at,\n instance.start_date::timestamp AT TIME ZONE 'UTC'\n ) AS at\n ) instance_start\n WHERE instance.event_id = viewer_event.id\n AND NOT instance.is_cancelled\n ORDER BY\n (instance.occurrence_key\n IS NOT DISTINCT FROM requested.occurrence_key) DESC,\n (instance_start.at >= $4) DESC,\n CASE WHEN instance_start.at >= $4 THEN instance_start.at END ASC,\n instance_start.at DESC,\n instance.occurrence_key\n LIMIT 1\n ) occurrence ON true\n -- An exception's content replaces the series content for the\n -- previewed occurrence alone, as it does in the event view.\n LEFT JOIN calendar_event_overrides occurrence_override\n ON occurrence_override.event_id = viewer_event.id\n AND occurrence_override.recurrence_id = occurrence.recurrence_id\n LEFT JOIN LATERAL (\n SELECT count(*) AS attendee_count\n FROM calendar_event_attendees attendee\n WHERE attendee.event_id = viewer_event.id\n ) attendees ON true\n ORDER BY requested.ord\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "mention_exists!",- "type_info": "Bool"- },- {- "ordinal": 1,- "name": "resolved_event_id?",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "is_channel_shared?",- "type_info": "Bool"- },- {- "ordinal": 3,- "name": "is_snapshot?",- "type_info": "Bool"- },- {- "ordinal": 4,- "name": "inbox_organizes?",- "type_info": "Bool"- },- {- "ordinal": 5,- "name": "inbox_attends?",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "title?",- "type_info": "Text"- },- {- "ordinal": 7,- "name": "description?",- "type_info": "Text"- },- {- "ordinal": 8,- "name": "location?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "organizer_email?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "organizer_name?",- "type_info": "Text"- },- {- "ordinal": 11,- "name": "recurrence_lines?",- "type_info": "TextArray"- },- {- "ordinal": 12,- "name": "event_starts_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 13,- "name": "event_ends_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 14,- "name": "event_start_date?",- "type_info": "Date"- },- {- "ordinal": 15,- "name": "event_end_date?",- "type_info": "Date"- },- {- "ordinal": 16,- "name": "time_zone?",- "type_info": "Text"- },- {- "ordinal": 17,- "name": "updated_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 18,- "name": "occurrence_key?",- "type_info": "Text"- },- {- "ordinal": 19,- "name": "occurrence_starts_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 20,- "name": "occurrence_ends_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 21,- "name": "occurrence_start_date?",- "type_info": "Date"- },- {- "ordinal": 22,- "name": "occurrence_end_date?",- "type_info": "Date"- },- {- "ordinal": 23,- "name": "attendee_count?",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Text",- "UuidArray",- "TextArray",- "Timestamptz",- "Int4"- ]- },- "nullable": [- null,- true,- true,- true,- true,- true,- null,- true,- null,- true,- true,- true,- true,- true,- true,- true,- true,- true,- true,- true,- true,- true,- true,- null- ]- },- "hash": "41c9b8b64954e28433337d9dcd878574dd0f831c81b7c5110b5f17fdb5cdca41"-}diff --git a/.sqlx/query-4516dcc374f177843056362d6ee78825fcd40ce8c536c97013ca815287a5c5c9.json b/.sqlx/query-4516dcc374f177843056362d6ee78825fcd40ce8c536c97013ca815287a5c5c9.jsonnew file mode 100644index 0000000000..b931800894--- /dev/null+++ b/.sqlx/query-4516dcc374f177843056362d6ee78825fcd40ce8c536c97013ca815287a5c5c9.json@@ -0,0 +1,164 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n (mentioned.id IS NOT NULL) AS \"mention_exists!\",\n viewer_event.id AS \"resolved_event_id?\",\n viewer_event.is_channel_shared AS \"is_channel_shared?\",\n viewer_event.is_snapshot AS \"is_snapshot?\",\n viewer_event.inbox_organizes AS \"inbox_organizes?\",\n viewer_event.inbox_attends AS \"inbox_attends?\",\n COALESCE(occurrence_override.title, viewer_event.title) AS \"title?\",\n left(\n COALESCE(occurrence_override.description, viewer_event.description),\n $5\n ) AS \"description?\",\n COALESCE(occurrence_override.location, viewer_event.location) AS \"location?\",\n viewer_event.organizer_email AS \"organizer_email?\",\n viewer_event.organizer_name AS \"organizer_name?\",\n viewer_event.recurrence_lines AS \"recurrence_lines?\",\n viewer_event.starts_at AS \"event_starts_at?\",\n viewer_event.ends_at AS \"event_ends_at?\",\n viewer_event.start_date AS \"event_start_date?\",\n viewer_event.end_date AS \"event_end_date?\",\n viewer_event.time_zone AS \"time_zone?\",\n viewer_event.updated_at AS \"updated_at?\",\n occurrence.occurrence_key AS \"occurrence_key?\",\n occurrence.starts_at AS \"occurrence_starts_at?\",\n occurrence.ends_at AS \"occurrence_ends_at?\",\n occurrence.start_date AS \"occurrence_start_date?\",\n occurrence.end_date AS \"occurrence_end_date?\",\n attendees.attendee_count AS \"attendee_count?\"\n FROM unnest($2::uuid[], $3::text[])\n WITH ORDINALITY AS requested(event_id, occurrence_key, ord)\n LEFT JOIN calendar_events mentioned\n ON mentioned.id = requested.event_id\n AND mentioned.status <> 'cancelled'\n LEFT JOIN LATERAL (\n SELECT resolved.*\n FROM (\n SELECT\n candidate.id,\n false AS is_channel_shared,\n (candidate.owner_id = $1) AS is_owned,\n (candidate.id = mentioned.id) AS is_mentioned,\n candidate.is_snapshot,\n -- The copy's own inbox decides how the requester\n -- holds it, as it decides their capabilities: an\n -- inbox they own that organizes it or is on it.\n COALESCE(\n lower(copy_inbox.email_address) = lower(candidate.organizer_email)\n OR EXISTS (\n SELECT 1\n FROM calendar_event_attendees organizer\n WHERE organizer.event_id = candidate.id\n AND organizer.is_organizer\n AND lower(organizer.email) = lower(copy_inbox.email_address)\n )\n -- A calendar the inbox can write organizes it,\n -- as Google names a secondary calendar.\n OR EXISTS (\n SELECT 1\n FROM calendar_accounts organizer_account\n JOIN calendars organizer_calendar\n ON organizer_calendar.account_id = organizer_account.id\n WHERE organizer_account.email_link_id = copy_inbox.id\n AND organizer_account.sync_status <> 'disabled'\n AND NOT organizer_calendar.is_deleted\n AND organizer_calendar.access_role IN ('owner', 'writer')\n AND lower(organizer_calendar.provider_calendar_id)\n = lower(candidate.organizer_email)\n ),\n false\n ) AS inbox_organizes,\n EXISTS (\n SELECT 1\n FROM calendar_event_attendees guest\n WHERE guest.event_id = candidate.id\n AND lower(guest.email) = lower(copy_inbox.email_address)\n ) AS inbox_attends,\n candidate.title,\n candidate.description,\n candidate.location,\n candidate.organizer_email,\n candidate.organizer_name,\n candidate.recurrence_lines,\n candidate.starts_at,\n candidate.ends_at,\n candidate.start_date,\n candidate.end_date,\n candidate.time_zone,\n candidate.updated_at\n FROM calendar_events candidate\n LEFT JOIN email_links copy_inbox\n ON copy_inbox.id = candidate.source_link_id\n AND copy_inbox.macro_id = $1\n WHERE calendar_meeting_uid(candidate.ical_uid)\n = calendar_meeting_uid(mentioned.ical_uid)\n AND candidate.status <> 'cancelled'\n AND (\n candidate.owner_id = $1\n OR EXISTS (\n SELECT 1\n FROM macro_user_links link\n WHERE link.link_id = candidate.source_link_id\n AND link.primary_macro_id = $1\n )\n )\n UNION ALL\n SELECT\n mentioned.id,\n true,\n false,\n true,\n false,\n false,\n false,\n mentioned.title,\n mentioned.description,\n mentioned.location,\n mentioned.organizer_email,\n mentioned.organizer_name,\n mentioned.recurrence_lines,\n mentioned.starts_at,\n mentioned.ends_at,\n mentioned.start_date,\n mentioned.end_date,\n mentioned.time_zone,\n mentioned.updated_at\n WHERE mentioned.visibility IN ('default', 'public')\n AND EXISTS (\n SELECT 1\n FROM entity_access grant_row\n JOIN comms_channel_participants participant\n ON participant.channel_id::text = grant_row.source_id\n AND participant.user_id = $1\n AND participant.left_at IS NULL\n WHERE grant_row.entity_id = mentioned.id\n AND grant_row.entity_type = 'calendar_event'\n AND grant_row.source_type = 'channel'\n )\n ) resolved\n ORDER BY\n resolved.is_channel_shared,\n resolved.is_owned DESC,\n resolved.is_mentioned DESC,\n resolved.updated_at DESC,\n resolved.id\n LIMIT 1\n ) viewer_event ON true\n LEFT JOIN LATERAL (\n SELECT\n instance.occurrence_key,\n instance.recurrence_id,\n instance.starts_at,\n instance.ends_at,\n instance.start_date,\n instance.end_date\n FROM calendar_event_occurrences instance\n CROSS JOIN LATERAL (\n SELECT COALESCE(\n instance.starts_at,\n instance.start_date::timestamp AT TIME ZONE 'UTC'\n ) AS at\n ) instance_start\n WHERE instance.event_id = viewer_event.id\n AND NOT instance.is_cancelled\n ORDER BY\n (instance.occurrence_key\n IS NOT DISTINCT FROM requested.occurrence_key) DESC,\n (instance_start.at >= $4) DESC,\n CASE WHEN instance_start.at >= $4 THEN instance_start.at END ASC,\n instance_start.at DESC,\n instance.occurrence_key\n LIMIT 1\n ) occurrence ON true\n -- An exception's content replaces the series content for the\n -- previewed occurrence alone, as it does in the event view.\n LEFT JOIN calendar_event_overrides occurrence_override\n ON occurrence_override.event_id = viewer_event.id\n AND occurrence_override.recurrence_id = occurrence.recurrence_id\n LEFT JOIN LATERAL (\n SELECT count(*) AS attendee_count\n FROM calendar_event_attendees attendee\n WHERE attendee.event_id = viewer_event.id\n ) attendees ON true\n ORDER BY requested.ord\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "mention_exists!",+ "type_info": "Bool"+ },+ {+ "ordinal": 1,+ "name": "resolved_event_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "is_channel_shared?",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "is_snapshot?",+ "type_info": "Bool"+ },+ {+ "ordinal": 4,+ "name": "inbox_organizes?",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "inbox_attends?",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "title?",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "description?",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "location?",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "organizer_email?",+ "type_info": "Text"+ },+ {+ "ordinal": 10,+ "name": "organizer_name?",+ "type_info": "Text"+ },+ {+ "ordinal": 11,+ "name": "recurrence_lines?",+ "type_info": "TextArray"+ },+ {+ "ordinal": 12,+ "name": "event_starts_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 13,+ "name": "event_ends_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 14,+ "name": "event_start_date?",+ "type_info": "Date"+ },+ {+ "ordinal": 15,+ "name": "event_end_date?",+ "type_info": "Date"+ },+ {+ "ordinal": 16,+ "name": "time_zone?",+ "type_info": "Text"+ },+ {+ "ordinal": 17,+ "name": "updated_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 18,+ "name": "occurrence_key?",+ "type_info": "Text"+ },+ {+ "ordinal": 19,+ "name": "occurrence_starts_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 20,+ "name": "occurrence_ends_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 21,+ "name": "occurrence_start_date?",+ "type_info": "Date"+ },+ {+ "ordinal": 22,+ "name": "occurrence_end_date?",+ "type_info": "Date"+ },+ {+ "ordinal": 23,+ "name": "attendee_count?",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "TextArray",+ "Timestamptz",+ "Int4"+ ]+ },+ "nullable": [+ null,+ true,+ true,+ true,+ true,+ true,+ null,+ true,+ null,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ true,+ null+ ]+ },+ "hash": "4516dcc374f177843056362d6ee78825fcd40ce8c536c97013ca815287a5c5c9"+}diff --git a/.sqlx/query-662d6d7de2b8ad270d128647bc46d1ea423d1991e14273f9fb7b92f41285ddc1.json b/.sqlx/query-662d6d7de2b8ad270d128647bc46d1ea423d1991e14273f9fb7b92f41285ddc1.jsonnew file mode 100644index 0000000000..fe9bfedde1--- /dev/null+++ b/.sqlx/query-662d6d7de2b8ad270d128647bc46d1ea423d1991e14273f9fb7b92f41285ddc1.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n link.id AS link_id,\n link.email_address::text AS \"email_address!\",\n link.provider::text AS \"provider!\",\n ARRAY(\n SELECT calendar.provider_calendar_id\n FROM calendar_accounts account\n JOIN calendars calendar ON calendar.account_id = account.id\n WHERE account.email_link_id = link.id\n AND account.sync_status <> 'disabled'\n AND NOT calendar.is_deleted\n AND calendar.access_role IN ('owner', 'writer')\n ) AS \"writable_calendar_ids!\"\n FROM email_links link\n WHERE link.macro_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_address!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "provider!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "writable_calendar_ids!",+ "type_info": "TextArray"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ null+ ]+ },+ "hash": "662d6d7de2b8ad270d128647bc46d1ea423d1991e14273f9fb7b92f41285ddc1"+}diff --git a/.sqlx/query-6a3169c9f261fe5c96f383935a87309bf4ee6dffc35917ec7110dd286a33c174.json b/.sqlx/query-6a3169c9f261fe5c96f383935a87309bf4ee6dffc35917ec7110dd286a33c174.jsondeleted file mode 100644index eb11fa0a40..0000000000--- a/.sqlx/query-6a3169c9f261fe5c96f383935a87309bf4ee6dffc35917ec7110dd286a33c174.json+++ /dev/null@@ -1,41 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n candidate.id AS \"event_id!\",\n copy_inbox.email_address AS \"inbox!\",\n COALESCE(\n lower(copy_inbox.email_address) = lower(candidate.organizer_email)\n OR EXISTS (\n SELECT 1\n FROM calendar_event_attendees organizer\n WHERE organizer.event_id = candidate.id\n AND organizer.is_organizer\n AND lower(organizer.email) = lower(copy_inbox.email_address)\n ),\n false\n ) AS \"organizes!\",\n EXISTS (\n SELECT 1\n FROM calendar_event_attendees guest\n WHERE guest.event_id = candidate.id\n AND lower(guest.email) = lower(copy_inbox.email_address)\n ) AS \"attends!\"\n FROM calendar_events addressed\n JOIN calendar_events candidate\n ON calendar_meeting_uid(candidate.ical_uid)\n = calendar_meeting_uid(addressed.ical_uid)\n JOIN email_links copy_inbox\n ON copy_inbox.id = candidate.source_link_id\n AND copy_inbox.macro_id = $1\n WHERE addressed.id = $2\n AND candidate.owner_id = $1\n AND candidate.status <> 'cancelled'\n ORDER BY lower(copy_inbox.email_address), candidate.id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "event_id!",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "inbox!",- "type_info": "Varchar"- },- {- "ordinal": 2,- "name": "organizes!",- "type_info": "Bool"- },- {- "ordinal": 3,- "name": "attends!",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Text",- "Uuid"- ]- },- "nullable": [- false,- false,- null,- null- ]- },- "hash": "6a3169c9f261fe5c96f383935a87309bf4ee6dffc35917ec7110dd286a33c174"-}diff --git a/.sqlx/query-dbcdf16f753763951eb5fa555659dc7531c2cd4ee05941e1ce47f75f03d50e92.json b/.sqlx/query-dbcdf16f753763951eb5fa555659dc7531c2cd4ee05941e1ce47f75f03d50e92.jsonnew file mode 100644index 0000000000..f1f3ad49e9--- /dev/null+++ b/.sqlx/query-dbcdf16f753763951eb5fa555659dc7531c2cd4ee05941e1ce47f75f03d50e92.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n candidate.id AS \"event_id!\",\n copy_inbox.email_address AS \"inbox!\",\n COALESCE(\n lower(copy_inbox.email_address) = lower(candidate.organizer_email)\n OR EXISTS (\n SELECT 1\n FROM calendar_event_attendees organizer\n WHERE organizer.event_id = candidate.id\n AND organizer.is_organizer\n AND lower(organizer.email) = lower(copy_inbox.email_address)\n )\n OR EXISTS (\n SELECT 1\n FROM calendar_accounts organizer_account\n JOIN calendars organizer_calendar\n ON organizer_calendar.account_id = organizer_account.id\n WHERE organizer_account.email_link_id = copy_inbox.id\n AND organizer_account.sync_status <> 'disabled'\n AND NOT organizer_calendar.is_deleted\n AND organizer_calendar.access_role IN ('owner', 'writer')\n AND lower(organizer_calendar.provider_calendar_id)\n = lower(candidate.organizer_email)\n ),\n false\n ) AS \"organizes!\",\n EXISTS (\n SELECT 1\n FROM calendar_event_attendees guest\n WHERE guest.event_id = candidate.id\n AND lower(guest.email) = lower(copy_inbox.email_address)\n ) AS \"attends!\"\n FROM calendar_events addressed\n JOIN calendar_events candidate\n ON calendar_meeting_uid(candidate.ical_uid)\n = calendar_meeting_uid(addressed.ical_uid)\n JOIN email_links copy_inbox\n ON copy_inbox.id = candidate.source_link_id\n AND copy_inbox.macro_id = $1\n WHERE addressed.id = $2\n AND candidate.owner_id = $1\n AND candidate.status <> 'cancelled'\n ORDER BY lower(copy_inbox.email_address), candidate.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "inbox!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "organizes!",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "attends!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ null+ ]+ },+ "hash": "dbcdf16f753763951eb5fa555659dc7531c2cd4ee05941e1ce47f75f03d50e92"+}diff --git a/apps/web/src/features/calendar/components/composer/event-form-model.ts b/apps/web/src/features/calendar/components/composer/event-form-model.tsindex da930439c8..46274ede73 100644--- a/apps/web/src/features/calendar/components/composer/event-form-model.ts+++ b/apps/web/src/features/calendar/components/composer/event-form-model.ts@@ -239,11 +239,16 @@ function initialConferenceChoice(* Guest emails an existing event seeds into the editor: every attendee except* the viewer when they are a mere guest. The organizer is kept even when it is* the viewer, so a replacement attendee list submitted by the organizer never- * drops them.+ * drops them. So is the viewer's own row on an event they organize through a+ * calendar Google names as the organizer, such as their secondary calendar,+ * which lists them only as a guest.*/export function eventGuestEmails(event: CalendarEvent): string[] {return event.attendees- .filter((attendee) => attendee.isOrganizer || !attendee.isSelf)+ .filter(+ (attendee) =>+ attendee.isOrganizer || !attendee.isSelf || event.viewerCan.organize+ ).map((attendee) => attendee.email);}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 47a9d4a425..f580a8c263 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@@ -1355,6 +1355,42 @@ describe('guests of an event the viewer was invited to', () => {dispose();}});++ it('keeps the viewer on a meeting their secondary calendar organizes', async () => {+ // Google names the secondary calendar as the organizer and lists the+ // viewer's own address as a plain guest.+ const organized = invitedEvent(+ { ...mayModify, setGuestPolicy: true, organize: true },+ {+ organizerEmail: '[email protected]',+ attendees: [+ {+ email: '[email protected]',+ isOrganizer: false,+ isOptional: false,+ isSelf: true,+ responseStatus: 'accepted',+ },+ ],+ }+ );+ const { editor, dispose } = editorFor(organized, true);+ try {+ expect(editor.initialValues()?.guests).toBe('[email protected]');++ await editor.save({+ ...unchanged,+ guestEmails: ['[email protected]', '[email protected]'],+ });++ expect(mocks.updateEvent.mock.lastCall?.[0].patch.attendees).toEqual([+ { email: '[email protected]' },+ { email: '[email protected]' },+ ]);+ } finally {+ dispose();+ }+ });});describe('guest permissions', () => {diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex e62a1241b2..16e5f5ea55 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -146,6 +146,25 @@ reminder dispatch, team availability, and provider/Postgres persistence.a channel-shared event never grants. The agent reads a mentioned event with`ReadCalendarEvent` (`src/inbound/toolset/read_calendar_event.rs`), which goesthrough `mention_previews`: the hover card's visibility and fields.+- Google names the calendar an event was made on as its organizer, so an+ event on a secondary calendar has that calendar's id+ (`…@group.calendar.google.com`) as `organizer_email`; Google's+ `organizer.self` is not stored. An inbox organizes an event when the+ organizer is its address or a calendar it can write+ (`OwnedInbox::organizes`, fed by `owned_inboxes`' `writable_calendar_ids`),+ as Google allows, and the mention preview's `inbox_organizes` and+ `meeting_copies` apply the same rule in SQL. When such an event also lists+ the inbox's address, Google invites its primary calendar too, and both+ copies share one entity whose canonical copy is that invitation. Changes+ only the organizer may make (details, guests, guest policy, deleting) go+ through the copy on the organizer's calendar+ (`CalendarEventMutationTarget::organizer_copy_calendar_id`,+ `src/domain/mutations/organizer_copy.rs`), then the addressed copy is read+ back (`CalendarMutationProvider::refresh_event`) so the entity shows the+ change before sync; reminders, availability and answers stay on the+ addressed copy. A new event lists the inbox as an accepted guest on its+ primary calendar and on Outlook, but on another Google calendar only when it+ has other guests, as Google's own client does, so a solo event is one block.- `viewer_can` is viewer-relative, like an attendee's `is_self`: resolve it with`ActorInboxes::mark_event` and the copy's source link wherever a read pathmarks the viewer, and never store it. Each connected inbox gets its own copydiff --git a/crates/calendar_events/src/domain/acting.rs b/crates/calendar_events/src/domain/acting.rsindex c5524a63d1..9141137ad5 100644--- a/crates/calendar_events/src/domain/acting.rs+++ b/crates/calendar_events/src/domain/acting.rs@@ -14,6 +14,11 @@ pub struct OwnedInbox {pub email: String,/// The provider the inbox's calendar syncs from.pub provider: CalendarProvider,+ /// Provider ids of the calendars the inbox can write. Google names the+ /// calendar an event was created on as its organizer, so an event made+ /// on a secondary calendar is organized by that calendar's id, not the+ /// inbox's address.+ pub writable_calendar_ids: Vec<String>,}impl OwnedInbox {@@ -21,6 +26,18 @@ impl OwnedInbox {pub fn matches(&self, email: &str) -> bool {self.email.eq_ignore_ascii_case(email)}++ /// Whether this inbox organizes an event with this organizer: its own+ /// address, or a calendar it can write. Google lets whoever can write the+ /// organizer's calendar change the event as its organizer, from any of+ /// their copies.+ pub fn organizes(&self, organizer_email: &str) -> bool {+ self.matches(organizer_email)+ || self+ .writable_calendar_ids+ .iter()+ .any(|id| id.eq_ignore_ascii_case(organizer_email))+ }}/// The clicker's own connected inboxes.@@ -71,6 +88,7 @@ impl ActorInboxes {link_id: Uuid::nil(),email: email.into().to_ascii_lowercase(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),}],}}diff --git a/crates/calendar_events/src/domain/acting/test.rs b/crates/calendar_events/src/domain/acting/test.rsindex c375e3789c..c8f6710ca1 100644--- a/crates/calendar_events/src/domain/acting/test.rs+++ b/crates/calendar_events/src/domain/acting/test.rs@@ -18,6 +18,7 @@ fn inbox(link_id: u128, email: &str) -> OwnedInbox {link_id: Uuid::from_u128(link_id),email: email.to_string(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),}}diff --git a/crates/calendar_events/src/domain/capabilities.rs b/crates/calendar_events/src/domain/capabilities.rsindex 9c923c5117..ff172a0a5d 100644--- a/crates/calendar_events/src/domain/capabilities.rs+++ b/crates/calendar_events/src/domain/capabilities.rs@@ -114,7 +114,10 @@ impl ViewerCapabilities {////// Only the copy's own inbox counts: another of the actor's inboxes/// organizing or attending the event makes them nothing on this copy,- /// which is written through this inbox's grant. `None` is an actor who+ /// which is written through this inbox's grant. The inbox organizes the+ /// event when the organizer is its address or a calendar it can write+ /// ([`OwnedInbox::organizes`]), as for an event made on a secondary+ /// calendar, even on the copy the organizer's calendar invited it to. `None` is an actor who/// does not own the copy's inbox, such as a delegate, or a teammate or/// channel member looking at someone else's projection; they may do/// nothing beyond the event-without-attendees rule. Answering always@@ -151,7 +154,7 @@ impl ViewerCapabilities {let is_organizer = inbox.is_some_and(|inbox| {access.organizer_email- .is_some_and(|email| inbox.matches(email))+ .is_some_and(|email| inbox.organizes(email))|| access.attendees.iter()diff --git a/crates/calendar_events/src/domain/capabilities/test.rs b/crates/calendar_events/src/domain/capabilities/test.rsindex 417afe92b6..2ea17cd730 100644--- a/crates/calendar_events/src/domain/capabilities/test.rs+++ b/crates/calendar_events/src/domain/capabilities/test.rs@@ -15,6 +15,7 @@ fn google(email: &str) -> OwnedInbox {link_id: Uuid::from_u128(1),email: email.to_string(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),}}@@ -295,16 +296,19 @@ fn three_inboxes() -> ActorInboxes {link_id: ORGANIZER_LINK,email: ORGANIZER.to_string(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),},OwnedInbox {link_id: GUEST_LINK,email: GUEST.to_string(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),},OwnedInbox {link_id: OUTLOOK_LINK,email: OUTLOOK.to_string(),provider: CalendarProvider::Outlook,+ writable_calendar_ids: Vec::new(),},]).expect("the actor owns inboxes")@@ -405,3 +409,69 @@ const NO_INVITES: GuestPolicy = GuestPolicy {can_invite_others: false,can_see_other_guests: true,};++/// The id Google gives a secondary calendar, which it names as the organizer+/// of the events made on it.+const SECONDARY_CALENDAR: &str = "[email protected]";++fn with_writable_calendars(mut inbox: OwnedInbox, ids: &[&str]) -> OwnedInbox {+ inbox.writable_calendar_ids = ids.iter().map(|id| id.to_string()).collect();+ inbox+}++/// An event made through Macro on the inbox's secondary calendar before the+/// creator stopped being listed: the calendar organizes it and the inbox's+/// own address is its only guest.+fn made_on_secondary_calendar() -> CalendarEvent {+ let mut event = event(vec![attendee(GUEST, false)], GuestPolicy::default());+ event.organizer_email = Some(SECONDARY_CALENDAR.to_string());+ event+}++#[test]+fn an_inbox_that_can_write_the_organizing_calendar_may_do_everything() {+ let inbox = with_writable_calendars(+ google(GUEST),+ &[GUEST, "[email protected]"],+ );++ let capabilities = ViewerCapabilities::for_event(&made_on_secondary_calendar(), Some(&inbox));++ assert_eq!(capabilities, EVERYTHING);+}++#[test]+fn an_inbox_that_only_reads_the_organizing_calendar_stays_a_guest() {+ // Only writable calendars are loaded into the inbox, so a calendar it+ // merely reads lends it nothing.+ let inbox = with_writable_calendars(google(GUEST), &[GUEST]);++ let capabilities = ViewerCapabilities::for_event(&made_on_secondary_calendar(), Some(&inbox));++ assert_eq!(+ capabilities,+ ViewerCapabilities {+ invite_guests: true,+ rsvp: true,+ ..ViewerCapabilities::NONE+ }+ );+}++#[test]+fn another_of_the_actors_inboxes_writing_the_organizing_calendar_lends_nothing() {+ let event = made_on_secondary_calendar();+ let other = with_writable_calendars(+ OwnedInbox {+ link_id: Uuid::from_u128(2),+ ..google("[email protected]")+ },+ &[SECONDARY_CALENDAR],+ );+ let actor = ActorInboxes::from_owned(vec![google(GUEST), other]).unwrap();++ let capabilities = ViewerCapabilities::for_event(&event, actor.inbox(Uuid::from_u128(1)));++ assert!(!capabilities.organize);+ assert!(!capabilities.edit_details);+}diff --git a/crates/calendar_events/src/domain/changes/test.rs b/crates/calendar_events/src/domain/changes/test.rsindex 8e134d4afe..192f2d1a54 100644--- a/crates/calendar_events/src/domain/changes/test.rs+++ b/crates/calendar_events/src/domain/changes/test.rs@@ -465,6 +465,7 @@ async fn attendee_self_flags_follow_the_viewers_inboxes() {link_id: LINK_A,email: "[email protected]".to_owned(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),}],..Default::default()});@@ -502,6 +503,7 @@ async fn one_event_is_read_with_the_viewers_attendee_flags() {link_id: LINK_A,email: "[email protected]".to_owned(),provider: CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),}],..Default::default()});diff --git a/crates/calendar_events/src/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex a401cec23e..e6d7a99986 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -1488,6 +1488,11 @@ pub struct CalendarEventMutationTarget {pub guest_policy: GuestPolicy,/// Whether the entity is a snapshot of a shared meeting.pub is_snapshot: bool,+ /// Another writable calendar of the copy's inbox that holds the+ /// organizer's own copy, as when the inbox is invited to an event made+ /// on its secondary calendar. Changes only the organizer may make go+ /// through that copy, as in Google's own client.+ pub organizer_copy_calendar_id: Option<Uuid>,}impl CalendarEventMutationTarget {diff --git a/crates/calendar_events/src/domain/mutations.rs b/crates/calendar_events/src/domain/mutations.rsindex d0d0f00c13..d3c862f6c0 100644--- a/crates/calendar_events/src/domain/mutations.rs+++ b/crates/calendar_events/src/domain/mutations.rs@@ -8,10 +8,12 @@use std::collections::HashMap;mod copy;+mod copy_writes;mod details;mod guest_policy;pub(crate) mod invite;mod join;+mod organizer_copy;mod replacement;use chrono::Utc;@@ -314,7 +316,7 @@ where// on the owner's behalf, so it must not gain an organizer guest.if draft.out_of_office.is_some() {validate_out_of_office_create(&draft, &target)?;- } else {+ } else if invites_creator(&target, &draft) {ensure_organizer_attendee(&mut draft.attendees, &target.token_identity.email_address);}let access_token = self.fetch_token(&target.token_identity).await?;@@ -336,7 +338,7 @@ whererequester_id: &str,event_id: Uuid,calendar_id: Option<Uuid>,- mut patch: CalendarEventPatch,+ patch: CalendarEventPatch,scope: CalendarUpdateScope,) -> Result<CalendarEvent, CalendarMutationError> {if patch.is_empty() {@@ -363,119 +365,18 @@ wherelet target = self.resolve_mutation_target(requester_id, event_id, calendar_id).await?;- if target.is_read_only {- return Err(CalendarMutationError::ReadOnly);- }- self.require_provider_writes(target.token_identity.provider)?;- validate_conference(target.token_identity.provider, patch.conference)?;- // The stored list is the baseline — an occurrence's own list when- // an occurrence-scoped patch addresses one — so a retained guest's- // per-instance RSVP wins over their series status.- let stored = self.stored_attendees(event_id, &scope).await?;- let capabilities = invite::copy_capabilities(&target, &stored);- // Checked before any guest is invited, so a refused change leaves- // the event untouched.- self.require_detail_rights(- event_id,- &scope,- capabilities,- target.is_snapshot,- &mut patch,- )- .await?;- guest_policy::require_guest_policy_rights(&target, &scope, capabilities, &mut patch)?;- if patch.is_empty() {- return Err(CalendarMutationError::InvalidInput(EMPTY_PATCH.to_string()));- }- if let Some(mut attendees) = patch.attendees.take() {- if capabilities.remove_guests {- preserve_retained_attendee_state(&mut attendees, &stored);- patch.attendees = Some(attendees);- } else {- // A guest who may not remove guests only adds, through the- // invite path, which keeps every guest the provider holds.- let additions =- invite::guest_list_additions(attendees, &stored, target.copy_inbox())?;- if !additions.is_empty() {- let invited = self- .invite_guests(- requester_id,- event_id,- calendar_id,- additions,- scope.clone(),- )- .await?;- if patch.is_empty() {- return Ok(invited);- }- } else if patch.is_empty() {- return Err(CalendarMutationError::InvalidInput(EMPTY_PATCH.to_string()));- }- }- }- let access_token = self.fetch_token(&target.token_identity).await?;- let google_target =- target.provider_target(OccurrenceRange::maintenance_horizon(Utc::now()));- match scope {- CalendarUpdateScope::All => {- let updated = self- .provider- .update_event(- &access_token,- &google_target,- target.master_provider_event_id(),- &patch,- )- .await- .map_err(provider_error)?;- let Some(upsert) = updated else {- // The provider no longer has the event; retire the stale- // local source the same way a feed tombstone would.- self.retire_gone_source(&target).await;- return Err(CalendarMutationError::NotFound);- };- self.persist_echo(target.actor.as_ref(), upsert).await- }- CalendarUpdateScope::ThisEvent { recurrence_id } => {- let outcome = self- .provider- .update_event_instance(- &access_token,- &google_target,- target.master_provider_event_id(),- &recurrence_id,- &patch,- )- .await- .map_err(provider_error)?;- match outcome {- ProviderInstanceUpdateOutcome::Applied(upsert) => {- self.persist_occurrence_echo(target.actor.as_ref(), *upsert, &recurrence_id)- .await- }- ProviderInstanceUpdateOutcome::OccurrenceGone(upsert) => {- // Nothing was written, but the provider's view of the- // series is fresher than whatever listed this- // occurrence — persist it so the phantom disappears.- self.persist_echo(target.actor.as_ref(), *upsert)- .await- .inspect_err(|error| {- tracing::warn!(- error=?error,- event_id=%target.event_id,- "failed to persist the series refresh for a vanished occurrence"- );- })- .ok();- Err(CalendarMutationError::OccurrenceNotFound)- }- ProviderInstanceUpdateOutcome::SeriesGone => {- self.retire_gone_source(&target).await;- Err(CalendarMutationError::NotFound)- }- }+ match target.organizer_copy_calendar_id {+ Some(organizer_calendar_id) if patch.reaches_meeting() => {+ self.update_through_organizer_copy(+ requester_id,+ target,+ organizer_calendar_id,+ patch,+ scope,+ )+ .await}+ _ => self.update_copy(requester_id, target, patch, scope).await,}}@@ -490,70 +391,17 @@ wherelet target = self.resolve_mutation_target(requester_id, event_id, calendar_id).await?;- if target.is_read_only {- return Err(CalendarMutationError::ReadOnly);- }- self.require_provider_writes(target.token_identity.provider)?;- let access_token = self.fetch_token(&target.token_identity).await?;- let google_target =- target.provider_target(OccurrenceRange::maintenance_horizon(Utc::now()));- let outcome = match &scope {- CalendarDeletionScope::All => {- self.provider- .delete_event(- &access_token,- &google_target,- target.master_provider_event_id(),- )- .await- .map_err(provider_error)?;- ProviderSeriesMutationOutcome::SeriesDeleted- }- CalendarDeletionScope::ThisEvent { recurrence_id } => self- .provider- .delete_event_instance(- &access_token,- &google_target,- target.master_provider_event_id(),- recurrence_id,+ match target.organizer_copy_calendar_id {+ Some(organizer_calendar_id) => {+ self.delete_through_organizer_copy(+ requester_id,+ target,+ organizer_calendar_id,+ scope,).await- .map_err(provider_error)?,- CalendarDeletionScope::ThisAndFollowing { recurrence_id } => self- .provider- .truncate_recurring_event(- &access_token,- &google_target,- target.master_provider_event_id(),- recurrence_id,- )- .await- .map_err(provider_error)?,- };- match outcome {- ProviderSeriesMutationOutcome::Applied(upsert) => self- .persist_echo(target.actor.as_ref(), *upsert)- .await- .map(|_| ()),- // Either the deletion removed the series or it was already- // gone; retiring the local source converges both.- ProviderSeriesMutationOutcome::SeriesDeleted | ProviderSeriesMutationOutcome::Gone => {- // Retiring a recurring master's source also retires its- // expanded instances, so this reports several events; each- // announces its own fate.- let retired = self- .repository- .remove_provider_source(- target.account_id,- target.calendar_id,- target.master_provider_event_id(),- )- .await- .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;- self.announce_retirements(&target.owner_id, target.email_link_id, retired)- .await;- Ok(())}+ None => self.delete_copy(&target, &scope).await,}}@@ -903,6 +751,23 @@ fn validate_reminders(reminders: &EventReminders) -> Result<(), CalendarMutationOk(())}+/// Whether a new event lists the inbox it is written through as an accepted+/// guest. On its primary calendar the inbox is the organizer, which every+/// guest should see. Google names any other calendar as the organizer of the+/// events made on it, and lists the inbox only as a guest, which invites the+/// inbox's primary calendar too: as in Google's own client, it joins only a+/// meeting with other guests, and an event of its own stays on the calendar+/// it was made on.+fn invites_creator(target: &CalendarCreationTarget, draft: &CalendarEventDraft) -> bool {+ target.is_primary+ || target.token_identity.provider != super::models::CalendarProvider::Google+ || draft.attendees.iter().any(|attendee| {+ !attendee+ .eq_ignore_ascii_case(&target.token_identity.email_address)+ })+}+fn ensure_organizer_attendee(attendees: &mut Vec<CalendarAttendeeInput>, organizer_email: &str) {let mut kept = false;attendees.retain_mut(|attendee| {diff --git a/crates/calendar_events/src/domain/mutations/copy_writes.rs b/crates/calendar_events/src/domain/mutations/copy_writes.rsnew file mode 100644index 0000000000..4bf1ce6ec2--- /dev/null+++ b/crates/calendar_events/src/domain/mutations/copy_writes.rs@@ -0,0 +1,210 @@+//! Writing one copy of an event: the update and delete every route ends in,+//! addressed to the copy the caller named or, for the organizer's changes,+//! the organizer's copy.+use super::*;++impl<R, G, T, B, N> CalendarMutationServiceImpl<R, G, T, B, N>+where+ R: CalendarRepository,+ G: CalendarMutationProvider,+ T: CalendarAccessTokenProvider,+ B: MacroEventBroker,+ N: CalendarRefreshNotifier,+{+ /// Apply a validated patch to the copy `target` addresses.+ pub(super) async fn update_copy(+ &self,+ requester_id: &str,+ target: CalendarEventMutationTarget,+ mut patch: CalendarEventPatch,+ scope: CalendarUpdateScope,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ if target.is_read_only {+ return Err(CalendarMutationError::ReadOnly);+ }+ self.require_provider_writes(target.token_identity.provider)?;+ validate_conference(target.token_identity.provider, patch.conference)?;+ // The stored list is the baseline — an occurrence's own list when+ // an occurrence-scoped patch addresses one — so a retained guest's+ // per-instance RSVP wins over their series status.+ let stored = self.stored_attendees(target.event_id, &scope).await?;+ let capabilities = invite::copy_capabilities(&target, &stored);+ // Checked before any guest is invited, so a refused change leaves+ // the event untouched.+ self.require_detail_rights(+ target.event_id,+ &scope,+ capabilities,+ target.is_snapshot,+ &mut patch,+ )+ .await?;+ guest_policy::require_guest_policy_rights(&target, &scope, capabilities, &mut patch)?;+ if patch.is_empty() {+ return Err(CalendarMutationError::InvalidInput(EMPTY_PATCH.to_string()));+ }+ if let Some(mut attendees) = patch.attendees.take() {+ if capabilities.remove_guests {+ preserve_retained_attendee_state(&mut attendees, &stored);+ patch.attendees = Some(attendees);+ } else {+ // A guest who may not remove guests only adds, through the+ // invite path, which keeps every guest the provider holds.+ let additions =+ invite::guest_list_additions(attendees, &stored, target.copy_inbox())?;+ if !additions.is_empty() {+ let invited = self+ .invite_guests(+ requester_id,+ target.event_id,+ Some(target.calendar_id),+ additions,+ scope.clone(),+ )+ .await?;+ if patch.is_empty() {+ return Ok(invited);+ }+ } else if patch.is_empty() {+ return Err(CalendarMutationError::InvalidInput(EMPTY_PATCH.to_string()));+ }+ }+ }+ let access_token = self.fetch_token(&target.token_identity).await?;+ let google_target =+ target.provider_target(OccurrenceRange::maintenance_horizon(Utc::now()));+ match scope {+ CalendarUpdateScope::All => {+ let updated = self+ .provider+ .update_event(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ &patch,+ )+ .await+ .map_err(provider_error)?;+ let Some(upsert) = updated else {+ // The provider no longer has the event; retire the stale+ // local source the same way a feed tombstone would.+ self.retire_gone_source(&target).await;+ return Err(CalendarMutationError::NotFound);+ };+ self.persist_echo(target.actor.as_ref(), upsert).await+ }+ CalendarUpdateScope::ThisEvent { recurrence_id } => {+ let outcome = self+ .provider+ .update_event_instance(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ &recurrence_id,+ &patch,+ )+ .await+ .map_err(provider_error)?;+ match outcome {+ ProviderInstanceUpdateOutcome::Applied(upsert) => {+ self.persist_occurrence_echo(target.actor.as_ref(), *upsert, &recurrence_id)+ .await+ }+ ProviderInstanceUpdateOutcome::OccurrenceGone(upsert) => {+ // Nothing was written, but the provider's view of the+ // series is fresher than whatever listed this+ // occurrence — persist it so the phantom disappears.+ self.persist_echo(target.actor.as_ref(), *upsert)+ .await+ .inspect_err(|error| {+ tracing::warn!(+ error=?error,+ event_id=%target.event_id,+ "failed to persist the series refresh for a vanished occurrence"+ );+ })+ .ok();+ Err(CalendarMutationError::OccurrenceNotFound)+ }+ ProviderInstanceUpdateOutcome::SeriesGone => {+ self.retire_gone_source(&target).await;+ Err(CalendarMutationError::NotFound)+ }+ }+ }+ }+ }++ /// Delete the copy `target` addresses, or the occurrences `scope` names.+ pub(super) async fn delete_copy(+ &self,+ target: &CalendarEventMutationTarget,+ scope: &CalendarDeletionScope,+ ) -> Result<(), CalendarMutationError> {+ if target.is_read_only {+ return Err(CalendarMutationError::ReadOnly);+ }+ self.require_provider_writes(target.token_identity.provider)?;+ let access_token = self.fetch_token(&target.token_identity).await?;+ let google_target =+ target.provider_target(OccurrenceRange::maintenance_horizon(Utc::now()));+ let outcome = match scope {+ CalendarDeletionScope::All => {+ self.provider+ .delete_event(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ )+ .await+ .map_err(provider_error)?;+ ProviderSeriesMutationOutcome::SeriesDeleted+ }+ CalendarDeletionScope::ThisEvent { recurrence_id } => self+ .provider+ .delete_event_instance(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ recurrence_id,+ )+ .await+ .map_err(provider_error)?,+ CalendarDeletionScope::ThisAndFollowing { recurrence_id } => self+ .provider+ .truncate_recurring_event(+ &access_token,+ &google_target,+ target.master_provider_event_id(),+ recurrence_id,+ )+ .await+ .map_err(provider_error)?,+ };+ match outcome {+ ProviderSeriesMutationOutcome::Applied(upsert) => self+ .persist_echo(target.actor.as_ref(), *upsert)+ .await+ .map(|_| ()),+ // Either the deletion removed the series or it was already+ // gone; retiring the local source converges both.+ ProviderSeriesMutationOutcome::SeriesDeleted | ProviderSeriesMutationOutcome::Gone => {+ // Retiring a recurring master's source also retires its+ // expanded instances, so this reports several events; each+ // announces its own fate.+ let retired = self+ .repository+ .remove_provider_source(+ target.account_id,+ target.calendar_id,+ target.master_provider_event_id(),+ )+ .await+ .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;+ self.announce_retirements(&target.owner_id, target.email_link_id, retired)+ .await;+ Ok(())+ }+ }+ }+}diff --git a/crates/calendar_events/src/domain/mutations/invite.rs b/crates/calendar_events/src/domain/mutations/invite.rsindex 8812067718..aead1b6b46 100644--- a/crates/calendar_events/src/domain/mutations/invite.rs+++ b/crates/calendar_events/src/domain/mutations/invite.rs@@ -60,6 +60,28 @@ where"provider",tracing::field::debug(target.token_identity.provider),);+ match target.organizer_copy_calendar_id {+ Some(organizer_calendar_id) => {+ self.invite_through_organizer_copy(+ requester_id,+ target,+ organizer_calendar_id,+ guests,+ scope,+ )+ .await+ }+ None => self.add_guests_to(&target, guests, scope).await,+ }+ }++ /// Add guests to the copy `target` addresses.+ pub(super) async fn add_guests_to(+ &self,+ target: &CalendarEventMutationTarget,+ guests: Vec<CalendarAttendeeInput>,+ scope: CalendarUpdateScope,+ ) -> Result<CalendarEvent, CalendarMutationError> {if target.is_read_only {return Err(CalendarMutationError::ReadOnly);}@@ -76,8 +98,8 @@ whereelse {return Err(CalendarMutationError::NotAttendee);};- let stored = self.stored_attendees(event_id, &scope).await?;- let capabilities = copy_capabilities(&target, &stored);+ let stored = self.stored_attendees(target.event_id, &scope).await?;+ let capabilities = copy_capabilities(target, &stored);if !capabilities.invite_guests {return Err(invite_refusal(capabilities,@@ -124,15 +146,15 @@ where}ProviderInviteOutcome::NotAttendee => Err(CalendarMutationError::NotAttendee),ProviderInviteOutcome::Forbidden(policy) => {- self.record_guest_policy(&target, policy).await;+ self.record_guest_policy(target, policy).await;Err(CalendarMutationError::GuestsCannotInvite)}ProviderInviteOutcome::GuestListHidden(policy) => {- self.record_guest_policy(&target, policy).await;+ self.record_guest_policy(target, policy).await;Err(CalendarMutationError::GuestListHidden)}ProviderInviteOutcome::Gone => {- self.retire_gone_source(&target).await;+ self.retire_gone_source(target).await;Err(CalendarMutationError::NotFound)}}diff --git a/crates/calendar_events/src/domain/mutations/organizer_copy.rs b/crates/calendar_events/src/domain/mutations/organizer_copy.rsnew file mode 100644index 0000000000..37631c3215--- /dev/null+++ b/crates/calendar_events/src/domain/mutations/organizer_copy.rs@@ -0,0 +1,188 @@+//! Writing through the organizer's copy. Google names the calendar an event+//! was made on as its organizer, so an event made on a secondary calendar+//! that lists the inbox's own address reaches the inbox twice: the+//! organizer's copy on the secondary calendar and an invitation on its+//! primary calendar, one entity whose canonical copy is the invitation. Only+//! the organizer's copy takes the organizer's changes, as in Google's own+//! client, so those changes go through it, and the addressed copy is then+//! read back so the entity shows them without waiting for sync.+use super::*;++impl<R, G, T, B, N> CalendarMutationServiceImpl<R, G, T, B, N>+where+ R: CalendarRepository,+ G: CalendarMutationProvider,+ T: CalendarAccessTokenProvider,+ B: MacroEventBroker,+ N: CalendarRefreshNotifier,+{+ /// Apply the meeting's changes through the organizer's copy, then what+ /// the provider keeps on each copy (reminders, availability) to the+ /// addressed copy, whose echo also brings the meeting's changes back.+ #[tracing::instrument(+ name = "calendar.update_through_organizer_copy",+ skip(self, requester_id, target, patch, scope),+ fields(+ event_id = %target.event_id,+ calendar_id = %target.calendar_id,+ organizer_calendar_id = %organizer_calendar_id,+ read_back = tracing::field::Empty,+ ),+ err+ )]+ pub(super) async fn update_through_organizer_copy(+ &self,+ requester_id: &str,+ target: CalendarEventMutationTarget,+ organizer_calendar_id: Uuid,+ mut patch: CalendarEventPatch,+ scope: CalendarUpdateScope,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ let own = CalendarEventPatch {+ reminders: patch.reminders.take(),+ transparency: patch.transparency.take(),+ ..CalendarEventPatch::default()+ };+ let organizer_copy = self+ .resolve_mutation_target(requester_id, target.event_id, Some(organizer_calendar_id))+ .await?;+ let organized = self+ .update_copy(requester_id, organizer_copy, patch, scope.clone())+ .await?;+ if own.is_empty() {+ return Ok(self.read_back(&target, &scope, organized).await);+ }+ tracing::Span::current().record("read_back", "own_fields");+ self.update_copy(requester_id, target, own, scope).await+ }++ /// Add guests through the organizer's copy, then read the addressed+ /// copy back.+ #[tracing::instrument(+ name = "calendar.invite_through_organizer_copy",+ skip(self, requester_id, target, guests, scope),+ fields(+ event_id = %target.event_id,+ calendar_id = %target.calendar_id,+ organizer_calendar_id = %organizer_calendar_id,+ read_back = tracing::field::Empty,+ ),+ err+ )]+ pub(super) async fn invite_through_organizer_copy(+ &self,+ requester_id: &str,+ target: CalendarEventMutationTarget,+ organizer_calendar_id: Uuid,+ guests: Vec<CalendarAttendeeInput>,+ scope: CalendarUpdateScope,+ ) -> Result<CalendarEvent, CalendarMutationError> {+ let organizer_copy = self+ .resolve_mutation_target(requester_id, target.event_id, Some(organizer_calendar_id))+ .await?;+ let invited = self+ .add_guests_to(&organizer_copy, guests, scope.clone())+ .await?;+ Ok(self.read_back(&target, &scope, invited).await)+ }++ /// Delete through the organizer's copy, which cancels the event for+ /// every guest, then read the addressed copy back so the cancelled+ /// invitation leaves the entity too.+ #[tracing::instrument(+ name = "calendar.delete_through_organizer_copy",+ skip(self, requester_id, target, scope),+ fields(+ event_id = %target.event_id,+ calendar_id = %target.calendar_id,+ organizer_calendar_id = %organizer_calendar_id,+ read_back = tracing::field::Empty,+ ),+ err+ )]+ pub(super) async fn delete_through_organizer_copy(+ &self,+ requester_id: &str,+ target: CalendarEventMutationTarget,+ organizer_calendar_id: Uuid,+ scope: CalendarDeletionScope,+ ) -> Result<(), CalendarMutationError> {+ let organizer_copy = self+ .resolve_mutation_target(requester_id, target.event_id, Some(organizer_calendar_id))+ .await?;+ self.delete_copy(&organizer_copy, &scope).await?;+ let read_back = match self.refreshed_copy(&target).await {+ Ok(Some(upsert)) => match self.persist_echo(target.actor.as_ref(), upsert).await {+ Ok(_) => "refreshed",+ Err(error) => {+ tracing::warn!(error = ?error, "failed to persist the read-back copy");+ "failed"+ }+ },+ Ok(None) => {+ self.retire_gone_source(&target).await;+ "gone"+ }+ Err(error) => {+ tracing::warn!(error = ?error, "failed to read the copy back after a delete");+ "failed"+ }+ };+ tracing::Span::current().record("read_back", read_back);+ Ok(())+ }++ /// The addressed copy as the provider now has it, after a write through+ /// the organizer's copy. The write already succeeded, so a failed read+ /// falls back to the organizer copy's echo and leaves the rest to sync.+ async fn read_back(+ &self,+ target: &CalendarEventMutationTarget,+ scope: &CalendarUpdateScope,+ written: CalendarEvent,+ ) -> CalendarEvent {+ let refreshed = match self.refreshed_copy(target).await {+ Ok(Some(upsert)) => match scope {+ CalendarUpdateScope::All => self.persist_echo(target.actor.as_ref(), upsert).await,+ CalendarUpdateScope::ThisEvent { recurrence_id } => {+ self.persist_occurrence_echo(target.actor.as_ref(), upsert, recurrence_id)+ .await+ }+ },+ // The change took the inbox off the event, so the organizer's+ // copy is all that is left of it.+ Ok(None) => {+ self.retire_gone_source(target).await;+ tracing::Span::current().record("read_back", "gone");+ return written;+ }+ Err(error) => Err(error),+ };+ match refreshed {+ Ok(event) => {+ tracing::Span::current().record("read_back", "refreshed");+ event+ }+ Err(error) => {+ tracing::warn!(error = ?error, "failed to read the copy back after a write");+ tracing::Span::current().record("read_back", "failed");+ written+ }+ }+ }++ async fn refreshed_copy(+ &self,+ target: &CalendarEventMutationTarget,+ ) -> Result<Option<CalendarEventUpsert>, CalendarMutationError> {+ let access_token = self.fetch_token(&target.token_identity).await?;+ self.provider+ .refresh_event(+ &access_token,+ &target.provider_target(OccurrenceRange::maintenance_horizon(Utc::now())),+ target.master_provider_event_id(),+ )+ .await+ .map_err(provider_error)+ }+}diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex 4ec747efd7..f4191e827c 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -22,6 +22,7 @@ fn owned(link_id: Uuid, email: &str) -> OwnedInbox {link_id,email: email.to_string(),provider: super::super::models::CalendarProvider::Google,+ writable_calendar_ids: Vec::new(),}}@@ -51,6 +52,7 @@ fn mutation_target(is_read_only: bool) -> CalendarEventMutationTarget {organizer_email: Some("[email protected]".to_string()),guest_policy: GuestPolicy::default(),is_snapshot: false,+ organizer_copy_calendar_id: None,}}@@ -200,6 +202,8 @@ struct FakeRepo {join_requests: Arc<Mutex<Vec<crate::domain::join_requests::CalendarJoinRequest>>>,/// The requester's copies of the addressed meeting.meeting_copies: Vec<crate::domain::models::MeetingCopy>,+ /// Copies on other calendars, addressed by their calendar id.+ copy_targets: Vec<CalendarEventMutationTarget>,}impl Default for FakeRepo {@@ -227,6 +231,7 @@ impl Default for FakeRepo {scheduled_syncs: Default::default(),join_requests: Default::default(),meeting_copies: Vec::new(),+ copy_targets: Vec::new(),}}}@@ -495,11 +500,18 @@ impl CalendarRepository for FakeRepo {&self,_requester_id: &str,_event_id: Uuid,- _calendar_id: Option<Uuid>,+ calendar_id: Option<Uuid>,) -> Result<Option<CalendarEventMutationTarget>, rootcause::Report> {if self.fail_owned_inboxes {return Err(rootcause::report!("owned inboxes unavailable"));}+ if let Some(copy) = self+ .copy_targets+ .iter()+ .find(|copy| Some(copy.calendar_id) == calendar_id)+ {+ return Ok(Some(copy.clone()));+ }Ok(self.mutation_target.clone())}@@ -620,6 +632,8 @@ struct FakeProvider {invited_guests: Arc<Mutex<Vec<Vec<CalendarAttendeeInput>>>>,imported: Arc<Mutex<Vec<(String, crate::domain::ics::EventSnapshot)>>>,invited_as: Arc<Mutex<Vec<Vec<String>>>>,+ /// Whether reading a copy back finds it gone.+ refresh_gone: bool,}impl FakeProvider {@@ -636,12 +650,14 @@ impl FakeProvider {invited_guests: Arc::new(Mutex::new(Vec::new())),imported: Arc::new(Mutex::new(Vec::new())),invited_as: Arc::new(Mutex::new(Vec::new())),+ refresh_gone: false,}}fn echo(&self, target: &ProviderCalendarTarget) -> CalendarEventUpsert {let mut upsert = echo_upsert(&target.owner_id);upsert.source.details_mut().email_link_id = target.email_link_id;+ upsert.source.details_mut().calendar_id = target.calendar_id;upsert.event.attendees = self.echo_attendees.clone();upsert.overrides = self.echo_overrides.clone();if let Some(time) = &self.echo_time {@@ -723,6 +739,22 @@ impl CalendarMutationProvider for FakeProvider {})}+ async fn refresh_event(+ &self,+ _access_token: &str,+ target: &ProviderCalendarTarget,+ master_provider_event_id: &str,+ ) -> Result<Option<CalendarEventUpsert>, CalendarProviderError> {+ self.calls.lock().unwrap().push(format!(+ "refresh:{}:{master_provider_event_id}",+ target.provider_calendar_id+ ));+ if self.refresh_gone {+ return Ok(None);+ }+ Ok(Some(self.echo(target)))+ }+async fn delete_event(&self,_access_token: &str,@@ -3042,4 +3074,5 @@ mod details;mod guest_policy;mod invite;mod join;+mod organizer_copy;mod replacement;diff --git a/crates/calendar_events/src/domain/mutations/test/guest_policy.rs b/crates/calendar_events/src/domain/mutations/test/guest_policy.rsindex 1e9cff3fa6..4e4fa0c730 100644--- a/crates/calendar_events/src/domain/mutations/test/guest_policy.rs+++ b/crates/calendar_events/src/domain/mutations/test/guest_policy.rs@@ -48,6 +48,7 @@ fn outlook_organizer_repo() -> FakeRepo {link_id: SELF_LINK,email: "[email protected]".to_string(),provider: CalendarProvider::Outlook,+ writable_calendar_ids: Vec::new(),}]);repo}diff --git a/crates/calendar_events/src/domain/mutations/test/invite.rs b/crates/calendar_events/src/domain/mutations/test/invite.rsindex 151bc4a60b..c64cfbed57 100644--- a/crates/calendar_events/src/domain/mutations/test/invite.rs+++ b/crates/calendar_events/src/domain/mutations/test/invite.rs@@ -441,6 +441,7 @@ fn outlook_repo(organizer: &str) -> FakeRepo {link_id: SELF_LINK,email: "[email protected]".to_string(),provider: CalendarProvider::Outlook,+ writable_calendar_ids: Vec::new(),}]);repo}diff --git a/crates/calendar_events/src/domain/mutations/test/join.rs b/crates/calendar_events/src/domain/mutations/test/join.rsindex 5dd12a191c..3434f2f701 100644--- a/crates/calendar_events/src/domain/mutations/test/join.rs+++ b/crates/calendar_events/src/domain/mutations/test/join.rs@@ -222,6 +222,7 @@ fn on_outlook(mut repo: FakeRepo) -> FakeRepo {link_id: SELF_LINK,email: "[email protected]".to_string(),provider: CalendarProvider::Outlook,+ writable_calendar_ids: Vec::new(),}]);repo}diff --git a/crates/calendar_events/src/domain/mutations/test/organizer_copy.rs b/crates/calendar_events/src/domain/mutations/test/organizer_copy.rsnew file mode 100644index 0000000000..48c92d5010--- /dev/null+++ b/crates/calendar_events/src/domain/mutations/test/organizer_copy.rs@@ -0,0 +1,353 @@+//! Events organized by a calendar the inbox can write, such as its own+//! secondary calendar: what a new one lists, and which copy takes each+//! change once the inbox's primary calendar holds an invitation to it.+use super::*;+use crate::domain::models::CalendarProvider;++/// The id Google gives a secondary calendar, which it names as the organizer+/// of the events made on it.+const SECONDARY: &str = "[email protected]";+const INVITATION_CALENDAR: Uuid = Uuid::from_u128(0xa);+const ORGANIZER_CALENDAR: Uuid = Uuid::from_u128(0xb);++fn actor() -> Option<ActorInboxes> {+ ActorInboxes::from_owned(vec![OwnedInbox {+ writable_calendar_ids: vec!["[email protected]".to_string(), SECONDARY.to_string()],+ ..owned(SELF_LINK, "[email protected]")+ }])+}++/// The invitation the secondary calendar sent the inbox's primary calendar:+/// the entity's canonical copy, which the web addresses.+fn invitation() -> CalendarEventMutationTarget {+ CalendarEventMutationTarget {+ calendar_id: INVITATION_CALENDAR,+ provider_calendar_id: "[email protected]".to_string(),+ organizer_email: Some(SECONDARY.to_string()),+ actor: actor(),+ organizer_copy_calendar_id: Some(ORGANIZER_CALENDAR),+ ..mutation_target(false)+ }+}++/// The organizer's own copy, on the secondary calendar.+fn organizer_copy(account_id: Uuid) -> CalendarEventMutationTarget {+ CalendarEventMutationTarget {+ calendar_id: ORGANIZER_CALENDAR,+ provider_calendar_id: SECONDARY.to_string(),+ organizer_copy_calendar_id: None,+ account_id,+ ..invitation()+ }+}++fn repo() -> FakeRepo {+ let invitation = invitation();+ FakeRepo {+ copy_targets: vec![organizer_copy(invitation.account_id)],+ mutation_target: Some(invitation),+ stored_attendees: vec![echo_attendee("[email protected]", false)],+ persisted_event_id: Some(Uuid::now_v7()),+ ..FakeRepo::default()+ }+}++fn written_calendars(upserts: &Mutex<Vec<CalendarEventUpsert>>) -> Vec<Uuid> {+ upserts+ .lock()+ .unwrap()+ .iter()+ .map(|upsert| upsert.source.details().calendar_id)+ .collect()+}++fn reminders() -> EventReminders {+ EventReminders {+ use_default: false,+ overrides: Vec::new(),+ }+}++#[tokio::test]+async fn a_title_change_goes_through_the_organizer_copy_and_reads_the_invitation_back() {+ let repo = repo();+ let upserts = repo.upserts.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();+ let patches = provider.updated_patches.clone();++ service(repo, provider, FakeTokens::ok())+ .update_event(+ "macro|user",+ Uuid::now_v7(),+ Some(INVITATION_CALENDAR),+ CalendarEventPatch {+ title: Some("Renamed".to_string()),+ ..CalendarEventPatch::default()+ },+ CalendarUpdateScope::All,+ )+ .await+ .unwrap();++ assert_eq!(+ calls.lock().unwrap().as_slice(),+ ["update:master-id", "refresh:[email protected]:master-id"]+ );+ assert_eq!(patches.lock().unwrap()[0].title.as_deref(), Some("Renamed"));+ assert_eq!(+ written_calendars(&upserts),+ [ORGANIZER_CALENDAR, INVITATION_CALENDAR]+ );+}++#[tokio::test]+async fn reminders_saved_with_a_title_stay_on_the_invitation() {+ let repo = repo();+ let upserts = repo.upserts.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();+ let patches = provider.updated_patches.clone();++ service(repo, provider, FakeTokens::ok())+ .update_event(+ "macro|user",+ Uuid::now_v7(),+ Some(INVITATION_CALENDAR),+ CalendarEventPatch {+ title: Some("Renamed".to_string()),+ reminders: Some(reminders()),+ ..CalendarEventPatch::default()+ },+ CalendarUpdateScope::All,+ )+ .await+ .unwrap();++ assert_eq!(+ calls.lock().unwrap().as_slice(),+ ["update:master-id", "update:master-id"]+ );+ assert_eq!(+ patches.lock().unwrap().as_slice(),+ [+ CalendarEventPatch {+ title: Some("Renamed".to_string()),+ ..CalendarEventPatch::default()+ },+ CalendarEventPatch {+ reminders: Some(reminders()),+ ..CalendarEventPatch::default()+ },+ ]+ );+ assert_eq!(+ written_calendars(&upserts),+ [ORGANIZER_CALENDAR, INVITATION_CALENDAR]+ );+}++#[tokio::test]+async fn reminders_alone_stay_on_the_invitation() {+ let repo = repo();+ let upserts = repo.upserts.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();++ service(repo, provider, FakeTokens::ok())+ .update_event(+ "macro|user",+ Uuid::now_v7(),+ Some(INVITATION_CALENDAR),+ CalendarEventPatch {+ reminders: Some(reminders()),+ ..CalendarEventPatch::default()+ },+ CalendarUpdateScope::All,+ )+ .await+ .unwrap();++ assert_eq!(calls.lock().unwrap().as_slice(), ["update:master-id"]);+ assert_eq!(written_calendars(&upserts), [INVITATION_CALENDAR]);+}++#[tokio::test]+async fn guests_are_added_through_the_organizer_copy() {+ let repo = repo();+ let upserts = repo.upserts.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();++ service(repo, provider, FakeTokens::ok())+ .invite_guests(+ "macro|user",+ Uuid::now_v7(),+ Some(INVITATION_CALENDAR),+ vec![CalendarAttendeeInput {+ email: "[email protected]".to_string(),+ is_optional: false,+ response_status: None,+ }],+ CalendarUpdateScope::All,+ )+ .await+ .unwrap();++ assert_eq!(+ calls.lock().unwrap().as_slice(),+ ["invite:master-id:all", "refresh:[email protected]:master-id"]+ );+ assert_eq!(+ written_calendars(&upserts),+ [ORGANIZER_CALENDAR, INVITATION_CALENDAR]+ );+}++#[tokio::test]+async fn deleting_cancels_through_the_organizer_copy_and_retires_the_invitation() {+ let repo = repo();+ let account_id = repo.mutation_target.as_ref().unwrap().account_id;+ let removed = repo.removed_sources.clone();+ let mut provider = FakeProvider::new(FakeProviderBehavior::Echo);+ provider.refresh_gone = true;+ let calls = provider.calls.clone();++ service(repo, provider, FakeTokens::ok())+ .delete_event(+ "macro|user",+ Uuid::now_v7(),+ Some(INVITATION_CALENDAR),+ CalendarDeletionScope::All,+ )+ .await+ .unwrap();++ assert_eq!(+ calls.lock().unwrap().as_slice(),+ ["delete:master-id", "refresh:[email protected]:master-id"]+ );+ assert_eq!(+ removed.lock().unwrap().as_slice(),+ [+ (account_id, ORGANIZER_CALENDAR, "master-id".to_string()),+ (account_id, INVITATION_CALENDAR, "master-id".to_string()),+ ]+ );+}++#[tokio::test]+async fn an_answer_stays_on_the_invitation() {+ let repo = repo();+ let upserts = repo.upserts.clone();+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let calls = provider.calls.clone();++ service(repo, provider, FakeTokens::ok())+ .respond_to_event(+ "macro|user",+ Uuid::now_v7(),+ Some(INVITATION_CALENDAR),+ AttendeeResponseStatus::Accepted,+ CalendarRsvpScope::All,+ None,+ )+ .await+ .unwrap();++ assert_eq!(calls.lock().unwrap().as_slice(), ["rsvp:master-id:all"]);+ assert_eq!(written_calendars(&upserts), [INVITATION_CALENDAR]);+}++fn secondary_calendar(provider: CalendarProvider) -> CalendarCreationTarget {+ CalendarCreationTarget {+ provider_calendar_id: SECONDARY.to_string(),+ is_primary: false,+ token_identity: CalendarLinkTokenIdentity {+ provider,+ ..token_identity()+ },+ ..creation_target(false)+ }+}++async fn created_attendees(+ target: CalendarCreationTarget,+ attendees: Vec<CalendarAttendeeInput>,+) -> Vec<CalendarAttendeeInput> {+ let provider = FakeProvider::new(FakeProviderBehavior::Echo);+ let drafts = provider.created_drafts.clone();+ service(+ FakeRepo {+ creation_target: Some(target),+ persisted_event_id: Some(Uuid::now_v7()),+ ..FakeRepo::default()+ },+ provider,+ FakeTokens::ok(),+ )+ .create_event(+ "macro|user",+ None,+ None,+ CalendarEventDraft {+ attendees,+ ..draft()+ },+ )+ .await+ .unwrap();+ drafts.lock().unwrap()[0].attendees.clone()+}++fn invitee(email: &str) -> CalendarAttendeeInput {+ CalendarAttendeeInput {+ email: email.to_string(),+ is_optional: false,+ response_status: None,+ }+}++#[tokio::test]+async fn an_event_of_ones_own_on_a_secondary_calendar_invites_no_one() {+ let attendees =+ created_attendees(secondary_calendar(CalendarProvider::Google), Vec::new()).await;++ assert_eq!(attendees, []);+}++#[tokio::test]+async fn a_meeting_on_a_secondary_calendar_invites_its_creator_too() {+ let attendees = created_attendees(+ secondary_calendar(CalendarProvider::Google),+ vec![invitee("[email protected]")],+ )+ .await;++ assert_eq!(+ attendees,+ [+ CalendarAttendeeInput {+ response_status: Some(AttendeeResponseStatus::Accepted),+ ..invitee("[email protected]")+ },+ invitee("[email protected]"),+ ]+ );+}++#[tokio::test]+async fn an_outlook_mailbox_organizes_an_event_on_any_of_its_calendars() {+ // Graph names the mailbox as the organizer of every calendar's events,+ // and never invites the organizer to its own meeting.+ let attendees =+ created_attendees(secondary_calendar(CalendarProvider::Outlook), Vec::new()).await;++ assert_eq!(+ attendees,+ [CalendarAttendeeInput {+ response_status: Some(AttendeeResponseStatus::Accepted),+ ..invitee("[email protected]")+ }]+ );+}diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex cd0db64d70..34ed2e1692 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -184,6 +184,16 @@ pub trait CalendarMutationProvider: Send + Sync + 'static {patch: &CalendarEventPatch,) -> impl Future<Output = Result<ProviderInstanceUpdateOutcome, CalendarProviderError>> + Send;+ /// Read an event's series back from the target calendar, as after a+ /// write through another of its copies. Returns `None` when the copy no+ /// longer exists or was cancelled at the provider.+ fn refresh_event(+ &self,+ access_token: &str,+ target: &ProviderCalendarTarget,+ master_provider_event_id: &str,+ ) -> impl Future<Output = Result<Option<CalendarEventUpsert>, CalendarProviderError>> + Send;+/// Delete an event. An event already gone at the provider is success.fn delete_event(&self,diff --git a/crates/calendar_events/src/domain/providers.rs b/crates/calendar_events/src/domain/providers.rsindex 451b0efd61..d892bd6838 100644--- a/crates/calendar_events/src/domain/providers.rs+++ b/crates/calendar_events/src/domain/providers.rs@@ -58,6 +58,25 @@ impl<G: CalendarMutationProvider, O: CalendarMutationProvider> CalendarMutationP}}}+ async fn refresh_event(+ &self,+ access_token: &str,+ target: &ProviderCalendarTarget,+ master_provider_event_id: &str,+ ) -> Result<Option<CalendarEventUpsert>, CalendarProviderError> {+ match target.provider {+ CalendarProvider::Google => {+ self.google+ .refresh_event(access_token, target, master_provider_event_id)+ .await+ }+ CalendarProvider::Outlook => {+ self.outlook+ .refresh_event(access_token, target, master_provider_event_id)+ .await+ }+ }+ }async fn update_event_instance(&self,access_token: &str,diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rsindex dfd50c68f6..f70eff84dd 100644--- a/crates/calendar_events/src/outbound/google.rs+++ b/crates/calendar_events/src/outbound/google.rs@@ -1235,6 +1235,30 @@ impl<G: GoogleRequestGate> CalendarMutationProvider for GoogleCalendarClient<G>}}+ #[tracing::instrument(+ skip(self, access_token, target),+ fields(provider_calendar_id = %target.provider_calendar_id),+ err+ )]+ async fn refresh_event(+ &self,+ access_token: &str,+ target: &ProviderCalendarTarget,+ master_provider_event_id: &str,+ ) -> Result<Option<CalendarEventUpsert>, CalendarProviderError> {+ match self+ .refresh_series(access_token, target, master_provider_event_id, None)+ .await?+ {+ SeriesOutcome::Refreshed(upsert) => Ok(Some(*upsert)),+ SeriesOutcome::Gone => Ok(None),+ SeriesOutcome::Malformed => Err(CalendarProviderError::new(+ CalendarProviderErrorKind::Permanent,+ "Google Calendar returned a malformed series",+ )),+ }+ }+#[tracing::instrument(skip(self, access_token, target),fields(provider_calendar_id = %target.provider_calendar_id),diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex ee9ae43a29..8184eaccff 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -1350,6 +1350,20 @@ impl CalendarRepository for PgCalendarRepository {WHERE organizer.event_id = candidate.idAND organizer.is_organizerAND lower(organizer.email) = lower(copy_inbox.email_address)+ )+ -- A calendar the inbox can write organizes it,+ -- as Google names a secondary calendar.+ OR EXISTS (+ SELECT 1+ FROM calendar_accounts organizer_account+ JOIN calendars organizer_calendar+ ON organizer_calendar.account_id = organizer_account.id+ WHERE organizer_account.email_link_id = copy_inbox.id+ AND organizer_account.sync_status <> 'disabled'+ AND NOT organizer_calendar.is_deleted+ AND organizer_calendar.access_role IN ('owner', 'writer')+ AND lower(organizer_calendar.provider_calendar_id)+ = lower(candidate.organizer_email)),false) AS inbox_organizes,@@ -1501,6 +1515,18 @@ impl CalendarRepository for PgCalendarRepository {WHERE organizer.event_id = candidate.idAND organizer.is_organizerAND lower(organizer.email) = lower(copy_inbox.email_address)+ )+ OR EXISTS (+ SELECT 1+ FROM calendar_accounts organizer_account+ JOIN calendars organizer_calendar+ ON organizer_calendar.account_id = organizer_account.id+ WHERE organizer_account.email_link_id = copy_inbox.id+ AND organizer_account.sync_status <> 'disabled'+ AND NOT organizer_calendar.is_deleted+ AND organizer_calendar.access_role IN ('owner', 'writer')+ AND lower(organizer_calendar.provider_calendar_id)+ = lower(candidate.organizer_email)),false) AS "organizes!",@@ -2238,6 +2264,23 @@ impl CalendarRepository for PgCalendarRepository {source.calendar_id AS "calendar_id!",calendar.provider_calendar_id,calendar.access_role,+ -- Google names the calendar an event was made on as its+ -- organizer; the copy on it takes the organizer's changes.+ (+ SELECT organizer_source.calendar_id+ FROM calendar_event_sources organizer_source+ JOIN calendars organizer_calendar+ ON organizer_calendar.id = organizer_source.calendar_id+ AND organizer_calendar.account_id = organizer_source.account_id+ WHERE organizer_source.event_id = event.id+ AND organizer_source.source_kind IN ('google','outlook')+ AND organizer_source.calendar_id <> source.calendar_id+ AND NOT organizer_calendar.is_deleted+ AND organizer_calendar.access_role IN ('owner', 'writer')+ AND lower(organizer_calendar.provider_calendar_id)+ = lower(event.organizer_email)+ LIMIT 1+ ) AS organizer_copy_calendar_id,account.email_link_id,link.fusionauth_user_id,link.email_address,@@ -2315,6 +2358,7 @@ impl CalendarRepository for PgCalendarRepository {can_see_other_guests: row.guests_can_see_other_guests,},is_snapshot: row.is_snapshot,+ organizer_copy_calendar_id: row.organizer_copy_calendar_id,}))}@@ -2561,11 +2605,20 @@ impl CalendarRepository for PgCalendarRepository {sqlx::query!(r#"SELECT- id AS link_id,- email_address::text AS "email_address!",- provider::text AS "provider!"- FROM email_links- WHERE macro_id = $1+ link.id AS link_id,+ link.email_address::text AS "email_address!",+ link.provider::text AS "provider!",+ ARRAY(+ SELECT calendar.provider_calendar_id+ FROM calendar_accounts account+ JOIN calendars calendar ON calendar.account_id = account.id+ WHERE account.email_link_id = link.id+ AND account.sync_status <> 'disabled'+ AND NOT calendar.is_deleted+ AND calendar.access_role IN ('owner', 'writer')+ ) AS "writable_calendar_ids!"+ FROM email_links link+ WHERE link.macro_id = $1"#,requester_id,)@@ -2579,6 +2632,7 @@ impl CalendarRepository for PgCalendarRepository {email: row.email_address,provider: CalendarProvider::from_link(&row.provider).ok_or_else(|| rootcause::report!("unsupported calendar provider"))?,+ writable_calendar_ids: row.writable_calendar_ids,})}).collect()diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex af71296e4a..b56d7550b3 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -7265,6 +7265,7 @@ mod meeting_copies;mod meeting_uid;#[cfg(feature = "notes")]mod notes;+mod organizer_calendar;mod source_access;mod replacement;diff --git a/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rs b/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rsnew file mode 100644index 0000000000..7a0f685e5e--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rs@@ -0,0 +1,210 @@+//! Events Google says a calendar organizes: the inbox that can write that+//! calendar organizes them, whichever of its copies it holds.+use super::*;++/// The id Google gives a secondary calendar, which it names as the organizer+/// of the events made on it.+const SECONDARY: &str = "[email protected]";++fn secondary_calendar(provider_calendar_id: &str, access_role: &str) -> ProviderCalendar {+ ProviderCalendar {+ provider_calendar_id: provider_calendar_id.to_string(),+ name: "Personal".to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some(access_role.to_string()),+ is_primary: false,+ is_selected: true,+ default_reminders: Vec::new(),+ }+}++/// One copy of an event organized by `organizer` that lists the inbox's own+/// address as its guest, as Macro wrote events on secondary calendars+/// before October 2026.+fn copy_of(+ owner_id: &str,+ link_id: Uuid,+ provider: (Uuid, Uuid),+ organizer: &str,+ inbox_email: &str,+) -> CalendarEventUpsert {+ let mut copy = timed_upsert(+ owner_id,+ link_id,+ provider,+ "[email protected]",+ "Focus time",+ 1,+ );+ copy.event.organizer_email = Some(organizer.to_string());+ copy.event.is_read_only = false;+ copy.event.attendees[0].email = inbox_email.to_string();+ copy+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn owned_inboxes_carry_the_calendars_each_can_write(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, _) = grant_and_provider_ids(&repo, link_id).await;+ repo.upsert_calendar_fixture(account_id, secondary_calendar(SECONDARY, "owner"))+ .await+ .unwrap();+ repo.upsert_calendar_fixture(+ account_id,+ secondary_calendar("en.usa#[email protected]", "reader"),+ )+ .await+ .unwrap();+ let removed = repo+ .upsert_calendar_fixture(+ account_id,+ secondary_calendar("[email protected]", "owner"),+ )+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE calendars SET is_deleted = true WHERE id = $1",+ removed+ )+ .execute(&pool)+ .await+ .unwrap();++ let inboxes = repo.owned_inboxes(owner_id).await.unwrap();++ assert_eq!(inboxes.len(), 1);+ let mut writable = inboxes[0].writable_calendar_ids.clone();+ writable.sort();+ assert_eq!(writable, [SECONDARY, "primary"]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_invitation_from_a_secondary_calendar_names_the_organizers_copy(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let inbox_email = link_email(&pool, link_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = grant_and_provider_ids(&repo, link_id).await;+ let secondary_id = repo+ .upsert_calendar_fixture(account_id, secondary_calendar(SECONDARY, "owner"))+ .await+ .unwrap();+ let event_id = repo+ .upsert_event(CalendarEventWrite::UserMutation(copy_of(+ owner_id,+ link_id,+ (account_id, secondary_id),+ SECONDARY,+ &inbox_email,+ )))+ .await+ .unwrap()+ .event_id;+ // Google invites the inbox's primary calendar, whose copy shares the+ // entity and becomes canonical.+ repo.upsert_event(CalendarEventWrite::UserMutation(copy_of(+ owner_id,+ link_id,+ (account_id, primary_id),+ SECONDARY,+ &inbox_email,+ )))+ .await+ .unwrap();++ let invitation = repo+ .get_event_mutation_target(owner_id, event_id, None)+ .await+ .unwrap()+ .expect("the owner may address their invitation");+ let organizer_copy = repo+ .get_event_mutation_target(owner_id, event_id, Some(secondary_id))+ .await+ .unwrap()+ .expect("the owner may address the organizer's copy");++ assert_eq!(invitation.calendar_id, primary_id);+ assert_eq!(invitation.organizer_copy_calendar_id, Some(secondary_id));+ assert_eq!(organizer_copy.organizer_copy_calendar_id, None);+ assert_eq!(+ repo.meeting_copies(owner_id, event_id)+ .await+ .unwrap()+ .iter()+ .map(|copy| copy.organizes)+ .collect::<Vec<_>>(),+ [true]+ );+ let previews = repo+ .mention_previews(+ owner_id,+ vec![CalendarMentionRequestItem {+ event_id,+ occurrence_key: None,+ }],+ Utc.with_ymd_and_hms(2026, 7, 23, 0, 0, 0).unwrap(),+ )+ .await+ .unwrap();+ let CalendarMentionPreview::Accessible(preview) = &previews[0] else {+ panic!(+ "the owner's preview should be accessible: {:?}",+ previews[0]+ );+ };+ assert_eq!(preview.viewer_copy, Some(CalendarMentionViewerCopy::Event));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_calendar_the_inbox_only_reads_lends_its_copy_nothing(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let inbox_email = link_email(&pool, link_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = grant_and_provider_ids(&repo, link_id).await;+ let shared_id = repo+ .upsert_calendar_fixture(account_id, secondary_calendar(SECONDARY, "reader"))+ .await+ .unwrap();+ let event_id = repo+ .upsert_event(CalendarEventWrite::UserMutation(copy_of(+ owner_id,+ link_id,+ (account_id, primary_id),+ SECONDARY,+ &inbox_email,+ )))+ .await+ .unwrap()+ .event_id;+ repo.upsert_event(CalendarEventWrite::UserMutation(copy_of(+ owner_id,+ link_id,+ (account_id, shared_id),+ SECONDARY,+ &inbox_email,+ )))+ .await+ .unwrap();++ let invitation = repo+ .get_event_mutation_target(owner_id, event_id, None)+ .await+ .unwrap()+ .expect("the owner may address their invitation");++ assert_eq!(invitation.organizer_copy_calendar_id, None);+ assert_eq!(+ repo.meeting_copies(owner_id, event_id)+ .await+ .unwrap()+ .iter()+ .map(|copy| copy.organizes)+ .collect::<Vec<_>>(),+ [false]+ );+}diff --git a/crates/email_api_client/src/outbound/outlook/calendar.rs b/crates/email_api_client/src/outbound/outlook/calendar.rsindex 68cdb4c219..544b9510e0 100644--- a/crates/email_api_client/src/outbound/outlook/calendar.rs+++ b/crates/email_api_client/src/outbound/outlook/calendar.rs@@ -740,6 +740,16 @@ impl CalendarMutationProvider for OutlookApiClientRepository {None => Ok(ProviderInstanceUpdateOutcome::SeriesGone),}}+ async fn refresh_event(+ &self,+ token: &str,+ target: &ProviderCalendarTarget,+ id: &str,+ ) -> Result<Option<CalendarEventUpsert>, CalendarProviderError> {+ self.calendar_scope(target)?+ .calendar_refresh(&AccessToken::new(token.to_owned()), target, id)+ .await+ }async fn delete_event(&self,token: &str,diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 35ccb32273..4afc125b7d 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -624,6 +624,18 @@ refuses a policy change from anyone but the organizer with 403 `not_organizer`,Outlook event with`provider_rejected`. `viewerCan.organize` marks the organizer of the displayed copy, includingon Outlook, where `setGuestPolicy` is false.+Google names the calendar an event was made on as its organizer, so an event on a secondary+calendar shows `Organizer` with that calendar's name, and its organizer email is the calendar's+id (`…@group.calendar.google.com`). Whoever can write that calendar organizes the event, as in+Google: details, guests, guest permissions and Delete work as on their primary calendar, on+every copy. A new event on a calendar other than the primary lists its creator as a guest only+when it has other guests, as Google's own client does, so an event of one's own shows as one+block in Google. With guests, Google also invites the creator's primary calendar; Macro shows+both copies as one event, sends the organizer's changes and Delete through the copy on the+secondary calendar, and keeps reminders and answers on the invitation. To verify, create an+event on a secondary calendar with no guests and another with a guest, open each (no `Only the+organizer can change this event.`), change the title, add a guest, then delete it, and check+Google: the first shows once, and both disappear from every calendar after the delete.The details header's `Download .ics` icon button, beside `Copy event`, saves the event as aniCalendar file named after its title, so it can be passed on or added to another calendar. Thefile holds the series (its repeat rule, in the event's original time zone), title, description