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): answer an Outlook inbox's invitation card as that inbox (#8760)
gbirmanb0f23066738b
diff --git a/.sqlx/query-88137bfcf2e9ca7079b14f097c72b8c6e9ebbe4d336a1056b8db995c6a7fecbf.json b/.sqlx/query-a51fb62f12b072f3adff0fe773a29fd227451234b6ab747abb08d021a8a2fcd4.jsonsimilarity index 57%rename from .sqlx/query-88137bfcf2e9ca7079b14f097c72b8c6e9ebbe4d336a1056b8db995c6a7fecbf.jsonrename to .sqlx/query-a51fb62f12b072f3adff0fe773a29fd227451234b6ab747abb08d021a8a2fcd4.jsonindex 44f2c116aa..a706d21703 100644--- a/.sqlx/query-88137bfcf2e9ca7079b14f097c72b8c6e9ebbe4d336a1056b8db995c6a7fecbf.json+++ b/.sqlx/query-a51fb62f12b072f3adff0fe773a29fd227451234b6ab747abb08d021a8a2fcd4.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT requested.ord AS \"ord!\", candidate.id, candidate.source_link_id, candidate.email_address, candidate.sequence, candidate.status, candidate.updated_at,\n (SELECT o.occurrence_key FROM calendar_event_occurrences o\n CROSS JOIN LATERAL (SELECT COALESCE(o.starts_at, o.start_date::timestamp AT TIME ZONE 'UTC') AS starts,\n COALESCE(o.ends_at, o.end_date::timestamp AT TIME ZONE 'UTC') AS ends) span\n WHERE o.event_id = candidate.id AND (requested.occurrence_key IS NULL OR o.occurrence_key = requested.occurrence_key OR o.recurrence_id = requested.occurrence_key)\n -- A series resolves to its current or next live occurrence, else its latest.\n ORDER BY o.is_cancelled, (span.ends > now()) DESC,\n CASE WHEN span.ends > now() THEN span.starts END, span.starts DESC, o.occurrence_key\n LIMIT 1) AS occurrence_key\n FROM unnest($2::text[], $3::text[]) WITH ORDINALITY requested(uid, occurrence_key, ord)\n CROSS JOIN LATERAL (\n SELECT e.id, e.source_link_id, l.email_address, e.sequence, e.status, e.updated_at\n FROM calendar_events e JOIN email_links l ON l.id = e.source_link_id\n WHERE e.ical_uid = requested.uid\n AND ((e.owner_id = $1 AND l.macro_id = $1)\n OR EXISTS (SELECT 1 FROM macro_user_links delegation\n WHERE delegation.primary_macro_id = $1 AND delegation.link_id = e.source_link_id))\n AND EXISTS (SELECT 1 FROM calendar_event_sources s JOIN calendar_accounts a ON a.id = s.account_id JOIN calendars c ON c.id = s.calendar_id WHERE s.event_id = e.id AND s.source_kind IN ('google', 'outlook') AND NOT c.is_deleted AND a.sync_status NOT IN ('disabled', 'reauth_required'))\n ORDER BY e.id LIMIT 16\n ) candidate\n ",+ "query": "\n SELECT requested.ord AS \"ord!\", candidate.id, candidate.source_link_id, candidate.email_address, candidate.sequence, candidate.status, candidate.updated_at,\n (SELECT o.occurrence_key FROM calendar_event_occurrences o\n CROSS JOIN LATERAL (SELECT COALESCE(o.starts_at, o.start_date::timestamp AT TIME ZONE 'UTC') AS starts,\n COALESCE(o.ends_at, o.end_date::timestamp AT TIME ZONE 'UTC') AS ends) span\n WHERE o.event_id = candidate.id AND (requested.occurrence_key IS NULL OR o.occurrence_key = requested.occurrence_key OR o.recurrence_id = requested.occurrence_key)\n -- A series resolves to its current or next live occurrence, else its latest.\n ORDER BY o.is_cancelled, (span.ends > now()) DESC,\n CASE WHEN span.ends > now() THEN span.starts END, span.starts DESC, o.occurrence_key\n LIMIT 1) AS occurrence_key\n FROM unnest($2::text[], $3::text[], $4::uuid[]) WITH ORDINALITY requested(uid, occurrence_key, preferred_link_id, ord)\n CROSS JOIN LATERAL (\n SELECT e.id, e.source_link_id, l.email_address, e.sequence, e.status, e.updated_at\n FROM calendar_events e JOIN email_links l ON l.id = e.source_link_id\n WHERE calendar_meeting_uid(e.ical_uid) = calendar_meeting_uid(requested.uid)\n AND ((e.owner_id = $1 AND l.macro_id = $1)\n OR EXISTS (SELECT 1 FROM macro_user_links delegation\n WHERE delegation.primary_macro_id = $1 AND delegation.link_id = e.source_link_id))\n AND EXISTS (SELECT 1 FROM calendar_event_sources s JOIN calendar_accounts a ON a.id = s.account_id JOIN calendars c ON c.id = s.calendar_id WHERE s.event_id = e.id AND s.source_kind IN ('google', 'outlook') AND NOT c.is_deleted AND a.sync_status NOT IN ('disabled', 'reauth_required'))\n AND EXISTS (SELECT 1 FROM calendar_event_occurrences o WHERE o.event_id = e.id AND (requested.occurrence_key IS NULL OR o.occurrence_key = requested.occurrence_key OR o.recurrence_id = requested.occurrence_key))\n -- The receiving inbox's copy stays inside the limit however many copies there are.\n ORDER BY e.source_link_id = requested.preferred_link_id DESC, e.id LIMIT 16\n ) candidate\n ","describe": {"columns": [{@@ -48,7 +48,8 @@"Left": ["Text","TextArray",- "TextArray"+ "TextArray",+ "UuidArray"]},"nullable": [@@ -62,5 +63,5 @@null]},- "hash": "88137bfcf2e9ca7079b14f097c72b8c6e9ebbe4d336a1056b8db995c6a7fecbf"+ "hash": "a51fb62f12b072f3adff0fe773a29fd227451234b6ab747abb08d021a8a2fcd4"}diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 239afe27d9..f565bbd64a 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -180,8 +180,9 @@ reminder dispatch, team availability, and provider/Postgres persistence.UID: Exchange gives a meeting it imports from an invitation its own UID thatwraps the original after `vCal-Uid`, and the SQL function unwraps it, so anOutlook copy of a Google meeting pairs with its Google copies in- `meeting_copies`, the mention preview and `event_export`. Email invitation- matching (`pg/invitations.rs`) still compares the raw UID.+ `meeting_copies`, the mention preview, `event_export` and email invitation+ matching (`pg/invitations.rs`), where an Outlook inbox's invitation card+ resolves to that inbox's own copy and answers as it.- Preserve the conservative OOO refresh hint on write outcomes and sync reports;its contract is in [team sharing](../../docs/design/calendar-team-sharing.md).- The team out-of-office overlay (`src/outbound/pg_team/ooo.rs`) starts fromdiff --git a/crates/calendar_events/src/outbound/pg/invitations.rs b/crates/calendar_events/src/outbound/pg/invitations.rsindex 277e2ce79f..0bb8cd6d03 100644--- a/crates/calendar_events/src/outbound/pg/invitations.rs+++ b/crates/calendar_events/src/outbound/pg/invitations.rs@@ -31,6 +31,10 @@ impl CalendarInvitationRepository for PgCalendarRepository {.iter().map(|item| item.occurrence_key.clone()).collect::<Vec<_>>();+ let preferred_links = items+ .iter()+ .map(|item| item.preferred_link_id)+ .collect::<Vec<_>>();let matches = sqlx::query!(r#"SELECT requested.ord AS "ord!", candidate.id, candidate.source_link_id, candidate.email_address, candidate.sequence, candidate.status, candidate.updated_at,(SELECT o.occurrence_key FROM calendar_event_occurrences o@@ -41,18 +45,20 @@ impl CalendarInvitationRepository for PgCalendarRepository {ORDER BY o.is_cancelled, (span.ends > now()) DESC,CASE WHEN span.ends > now() THEN span.starts END, span.starts DESC, o.occurrence_keyLIMIT 1) AS occurrence_key- FROM unnest($2::text[], $3::text[]) WITH ORDINALITY requested(uid, occurrence_key, ord)+ FROM unnest($2::text[], $3::text[], $4::uuid[]) WITH ORDINALITY requested(uid, occurrence_key, preferred_link_id, ord)CROSS JOIN LATERAL (SELECT e.id, e.source_link_id, l.email_address, e.sequence, e.status, e.updated_atFROM calendar_events e JOIN email_links l ON l.id = e.source_link_id- WHERE e.ical_uid = requested.uid+ WHERE calendar_meeting_uid(e.ical_uid) = calendar_meeting_uid(requested.uid)AND ((e.owner_id = $1 AND l.macro_id = $1)OR EXISTS (SELECT 1 FROM macro_user_links delegationWHERE delegation.primary_macro_id = $1 AND delegation.link_id = e.source_link_id))AND EXISTS (SELECT 1 FROM calendar_event_sources s JOIN calendar_accounts a ON a.id = s.account_id JOIN calendars c ON c.id = s.calendar_id WHERE s.event_id = e.id AND s.source_kind IN ('google', 'outlook') AND NOT c.is_deleted AND a.sync_status NOT IN ('disabled', 'reauth_required'))- ORDER BY e.id LIMIT 16+ AND EXISTS (SELECT 1 FROM calendar_event_occurrences o WHERE o.event_id = e.id AND (requested.occurrence_key IS NULL OR o.occurrence_key = requested.occurrence_key OR o.recurrence_id = requested.occurrence_key))+ -- The receiving inbox's copy stays inside the limit however many copies there are.+ ORDER BY e.source_link_id = requested.preferred_link_id DESC, e.id LIMIT 16) candidate- "#, viewer, &uids, &requested_keys as &[Option<String>]).fetch_all(&self.pool).await.map_err(report)?;+ "#, viewer, &uids, &requested_keys as &[Option<String>], &preferred_links).fetch_all(&self.pool).await.map_err(report)?;let ids = matches.iter().map(|r| r.id).collect::<Vec<_>>();let keys = matches.iter()diff --git a/crates/calendar_events/src/outbound/pg/test/invitations.rs b/crates/calendar_events/src/outbound/pg/test/invitations.rsindex 5285c42553..7f35f8fb2a 100644--- a/crates/calendar_events/src/outbound/pg/test/invitations.rs+++ b/crates/calendar_events/src/outbound/pg/test/invitations.rs@@ -1,3 +1,4 @@+use super::meeting_uid::exchange_uid;use super::*;use crate::domain::invitations::{CalendarInvitationRepository, CalendarInvitationResolver, CalendarInvitationService,@@ -23,9 +24,18 @@ fn identity(link: Uuid) -> InvitationIdentity {}}async fn event(pool: &PgPool, repo: &PgCalendarRepository, viewer: &str, link: Uuid) -> Uuid {+ event_with_uid(pool, repo, viewer, link, "invite-uid").await+}+async fn event_with_uid(+ pool: &PgPool,+ repo: &PgCalendarRepository,+ viewer: &str,+ link: Uuid,+ uid: &str,+) -> Uuid {persist_complete_grant(pool, link, 1).await;let provider = provider_ids(repo, link).await;- let mut upsert = timed_upsert(viewer, link, provider, "invite-uid", "Review", 1);+ let mut upsert = timed_upsert(viewer, link, provider, uid, "Review", 1);upsert.event.is_read_only = false;upsert.event.recurrence_lines.clear();upsert.occurrences.truncate(1);@@ -96,6 +106,110 @@ async fn invitation_accounts_are_authorized_and_ambiguity_never_guesses(pool: Pg));}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_outlook_inbox_answers_through_its_own_copy_of_a_google_meeting(pool: PgPool) {+ let viewer = "macro|[email protected]";+ insert_user(&pool, viewer).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let google = insert_link(&pool, viewer).await;+ let outlook = insert_link(&pool, viewer).await;+ // Exchange stores the copy it imports from the invitation under its own+ // UID, which wraps the invitation's.+ let outlook_event =+ event_with_uid(&pool, &repo, viewer, outlook, &exchange_uid("invite-uid")).await;+ let outlook_email = sqlx::query_scalar!(+ "SELECT email_address FROM email_links WHERE id = $1",+ outlook+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ let resolver = CalendarInvitationResolver::new(repo.clone());+ let only_outlook = resolver+ .resolve(viewer, &[identity(outlook)])+ .await+ .unwrap();+ assert!(+ matches!(&only_outlook[0], InvitationResolution::Resolved {+ event, responding_email, can_respond: true, ..+ } if event.id == outlook_event && responding_email == &outlook_email),+ "{only_outlook:?}"+ );++ // With a Google copy on another inbox, the Outlook inbox's card still+ // answers as itself, and a card from neither inbox does not guess.+ event(&pool, &repo, viewer, google).await;+ let result = resolver+ .resolve(viewer, &[identity(outlook), identity(Uuid::nil())])+ .await+ .unwrap();+ assert!(+ matches!(&result[0], InvitationResolution::Resolved {+ event, responding_email, ..+ } if event.id == outlook_event && responding_email == &outlook_email),+ "{result:?}"+ );+ assert!(+ matches!(result[1], InvitationResolution::Ambiguous),+ "{result:?}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_receiving_inbox_keeps_its_copy_past_the_candidate_limit(pool: PgPool) {+ let viewer = "macro|[email protected]";+ insert_user(&pool, viewer).await;+ let repo = PgCalendarRepository::new(pool.clone());+ for _ in 0..16 {+ let link = insert_link(&pool, viewer).await;+ event(&pool, &repo, viewer, link).await;+ }+ // Created last, its copy sorts after the 16 others.+ let receiving = insert_link(&pool, viewer).await;+ let received = event(&pool, &repo, viewer, receiving).await;+ let result = CalendarInvitationResolver::new(repo)+ .resolve(viewer, &[identity(receiving)])+ .await+ .unwrap();+ assert!(+ matches!(&result[0], InvitationResolution::Resolved { event, .. } if event.id == received),+ "{result:?}"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn copies_without_the_requested_occurrence_leave_room_for_one_with_it(pool: PgPool) {+ let viewer = "macro|[email protected]";+ insert_user(&pool, viewer).await;+ let repo = PgCalendarRepository::new(pool.clone());+ for _ in 0..16 {+ let link = insert_link(&pool, viewer).await;+ event(&pool, &repo, viewer, link).await;+ }+ // Created last, and the only copy holding the second occurrence.+ let link = insert_link(&pool, viewer).await;+ persist_complete_grant(&pool, link, 1).await;+ let provider = provider_ids(&repo, link).await;+ let mut upsert = timed_upsert(viewer, link, provider, "invite-uid", "Review", 1);+ upsert.event.is_read_only = false;+ upsert.event.recurrence_lines.clear();+ upsert.occurrences.remove(0);+ upsert.occurrences.truncate(1);+ let requested = upsert.occurrences[0].occurrence_key.clone();+ let holding = repo.upsert_event_fixture(upsert).await.unwrap();+ let mut identity = identity(Uuid::nil());+ identity.occurrence_key = Some(requested.clone());+ let result = CalendarInvitationResolver::new(repo)+ .resolve(viewer, &[identity])+ .await+ .unwrap();+ assert!(+ matches!(&result[0], InvitationResolution::Resolved { event, occurrence, .. }+ if event.id == holding && occurrence.occurrence_key == requested),+ "{result:?}"+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn invitation_delegation_is_scoped_to_the_granted_inbox(pool: PgPool) {let viewer = "macro|[email protected]";diff --git a/crates/calendar_events/src/outbound/pg/test/meeting_uid.rs b/crates/calendar_events/src/outbound/pg/test/meeting_uid.rsindex 03c0c035c7..59a2e74d11 100644--- a/crates/calendar_events/src/outbound/pg/test/meeting_uid.rs+++ b/crates/calendar_events/src/outbound/pg/test/meeting_uid.rs@@ -3,7 +3,7 @@ use crate::domain::ics::CalendarEventExportAccess;/// The UID Exchange gives a meeting it imports from an invitation carrying/// `uid`: a GlobalObjectId whose data wraps `uid` after "vCal-Uid".-fn exchange_uid(uid: &str) -> String {+pub(super) fn exchange_uid(uid: &str) -> String {let mut data = b"vCal-Uid".to_vec();data.extend_from_slice(&[1, 0, 0, 0]);data.extend_from_slice(uid.as_bytes());