Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calendar): make the agent confirm which inbox's copy it changes (#8743)
gbirmane3c8b9a6d289
diff --git a/.sqlx/query-e873aa50b615d723e90e515711af09709d153881c0f81b54854c1aac88755c8b.json b/.sqlx/query-e873aa50b615d723e90e515711af09709d153881c0f81b54854c1aac88755c8b.jsonnew file mode 100644index 0000000000..e8eb360ad0--- /dev/null+++ b/.sqlx/query-e873aa50b615d723e90e515711af09709d153881c0f81b54854c1aac88755c8b.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 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 candidate.ical_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": "e873aa50b615d723e90e515711af09709d153881c0f81b54854c1aac88755c8b"+}diff --git a/apps/docs/AI/mcp/tools/delete-calendar-event.mdx b/apps/docs/AI/mcp/tools/delete-calendar-event.mdxindex 52850e6eaa..5f3d5d4aa3 100644--- a/apps/docs/AI/mcp/tools/delete-calendar-event.mdx+++ b/apps/docs/AI/mcp/tools/delete-calendar-event.mdx@@ -10,7 +10,7 @@ Delete an event from the user's calendar. The deletion is written to the calendaFor recurring events, `scope` controls how much is removed: "all" (default) removes the whole series, "this_event" removes one occurrence, and "this_and_following" ends the series from an occurrence onward. The scoped variants require `recurrenceId` from the targeted occurrence's ListCalendarEvents entry.-When the meeting is on several of the user's inboxes (one ListCalendarEvents entry per inbox), ask which inbox's copy to delete unless the user named one or only one copy is writable (`isReadOnly` false), in which case delete that one and say why. Deleting the copy the user organizes cancels the meeting for every guest, while deleting a copy where they are a guest only takes it off that inbox's calendar.+When the meeting is on several of the user's inboxes (one ListCalendarEvents entry per inbox), the tool refuses until `inbox` names the inbox of the copy to delete, and lists each copy. Ask which inbox's copy to delete unless the user named one or only one copy is writable (`isReadOnly` false), in which case delete that one, pass its `inbox` and say why. Deleting the copy the user organizes cancels the meeting for every guest. Deleting a copy where they are a guest takes the meeting off that inbox's calendar: on Google it also declines the invitation and tells the organizer, while on Outlook the organizer is not told and still sees the invitation unanswered.## Parameters@@ -18,5 +18,6 @@ When the meeting is on several of the user's inboxes (one ListCalendarEvents ent| --- | --- | --- | --- || `eventId` | string | Yes | The event's id, from ListCalendarEvents or CreateCalendarEvent. || `calendarId` | string | No | The `calendarId` of the copy to delete, from the `copies` of its ListCalendarEvents entry, for an event synced from more than one calendar. Omit to delete the event's primary copy. |+| `inbox` | string | No | The `inbox` of the copy to delete, from its ListCalendarEvents entry. Required when the meeting is on more than one of the user's inboxes: the tool refuses without it and lists each copy. It must be the inbox holding the copy `eventId` names. || `scope` | `"all"` \| `"this_event"` \| `"this_and_following"` | No | How much of a recurring series a deletion removes. || `recurrenceId` | string | No | The `recurrenceId` of the targeted occurrence, from its ListCalendarEvents entry. Required for "this_event" and "this_and_following". |diff --git a/apps/docs/AI/mcp/tools/list-calendar-events.mdx b/apps/docs/AI/mcp/tools/list-calendar-events.mdxindex 8b0d5a2950..0b57111377 100644--- a/apps/docs/AI/mcp/tools/list-calendar-events.mdx+++ b/apps/docs/AI/mcp/tools/list-calendar-events.mdx@@ -13,7 +13,7 @@ Use this to answer questions about the user's schedule ("what's on my calendar tEach entry names the calendar (`calendarName`) and connected inbox (`inbox`) holding that copy of the event, and `myRole` says whether the user organizes it or is a guest there. A meeting on several of the user's inboxes appears once per inbox, each with its own `eventId`, and what the user may do can differ between them. When asking which one the user means, describe each by its inbox and role, never by id; when the user names an inbox, act on the entry whose `inbox` matches.-When the user does not name an inbox, choose the copy by what the change does. Reminders belong to one copy only, so set them on one copy without asking and say which inbox you used. Answer an invitation on the copy where the user is a guest; when they are a guest through more than one inbox, ask which inbox answers, since each answers only for itself. Any other change reaches the meeting differently from each copy: the title, time, description, location, recurrence or conference, adding or removing guests, guest permissions, and deleting. Never pick a copy for such a change silently. If only one copy allows it (`viewerCan`, or for deleting, `isReadOnly` false), use that copy and say why (for example, only the copy the user organizes can move the meeting). If more than one can, ask which inbox, saying what the change would do from each, such as deleting the organizer's copy cancelling the meeting for everyone while deleting a guest's copy only takes it off that inbox's calendar.+When the user does not name an inbox, choose the copy by what the change does. Reminders belong to one copy only, so set them on one copy without asking and say which inbox you used. Answer an invitation on the copy where the user is a guest; when they are a guest through more than one inbox, ask which inbox answers, since each answers only for itself. Any other change reaches the meeting differently from each copy: the title, time, description, location, recurrence or conference, adding or removing guests, guest permissions, and deleting. UpdateCalendarEvent and DeleteCalendarEvent refuse such a change on a meeting held by several of the user's inboxes until `inbox` names the inbox of the copy being changed, and the refusal lists each copy. If only one copy allows the change (`viewerCan`, or for deleting, `isReadOnly` false), use that copy with its `inbox` and say why (for example, only the copy the user organizes can move the meeting). If more than one can, ask which inbox, saying what the change would do from each. Add guests from the copy the user organizes when there is one: it invites them directly, while a guest's copy invites only as far as the organizer allows. Deleting the organizer's copy cancels the meeting for everyone, while deleting a guest's copy takes the meeting off that inbox's calendar and, on Google, also declines the invitation and tells the organizer.## Parametersdiff --git a/apps/docs/AI/mcp/tools/update-calendar-event.mdx b/apps/docs/AI/mcp/tools/update-calendar-event.mdxindex 9f0feb5563..00d61a3e19 100644--- a/apps/docs/AI/mcp/tools/update-calendar-event.mdx+++ b/apps/docs/AI/mcp/tools/update-calendar-event.mdx@@ -16,7 +16,7 @@ A guest without modify rights (`viewerCan.editDetails` false while `viewerCan.rs`rsvp` sets the user's own response to an invitation and is independent of the field edits — it can be the only thing this call changes. It applies at the same `scope` as the rest of the call and answers as the connected inbox the event's copy belongs to, so it only works when that inbox is an attendee.-When the meeting is on several of the user's inboxes, ListCalendarEvents lists one entry per inbox; pick the copy by its rule. Reminders may go to one copy and an `rsvp` to the copy where the user is a guest, naming the inbox in your reply. Any other change goes to the only copy whose `viewerCan` allows it, with the reason, or to the copy the user chooses when more than one could make it. One call changes one copy, so an edit on one copy and an `rsvp` on another take two calls.+When the meeting is on several of the user's inboxes, ListCalendarEvents lists one entry per inbox; pick the copy by its rule. Reminders may go to one copy and an `rsvp` to the copy where the user is a guest, naming the inbox in your reply. Any other change needs `inbox`, the inbox of the copy it changes; without it the tool refuses and lists each copy. Use the only copy whose `viewerCan` allows the change, with the reason, or the copy the user chooses when more than one could make it, and add guests from the copy the user organizes when there is one. One call changes one copy, so an edit on one copy and an `rsvp` on another take two calls.## Parameters@@ -24,6 +24,7 @@ When the meeting is on several of the user's inboxes, ListCalendarEvents lists o| --- | --- | --- | --- || `eventId` | string | Yes | The event's id, from ListCalendarEvents or CreateCalendarEvent. || `calendarId` | string | No | The `calendarId` of the copy to update, from the `copies` of its ListCalendarEvents entry, for an event synced from more than one calendar. Omit to update the event's primary copy. |+| `inbox` | string | No | The `inbox` of the copy this call changes, from its ListCalendarEvents entry. Required when the meeting is on more than one of the user's inboxes and the call changes anything but `reminders` or `rsvp`: the tool refuses without it and lists each copy. It must be the inbox holding the copy `eventId` names. || `scope` | `"all"` \| `"this_event"` | Yes | How much of a recurring series an update applies to. || `recurrenceId` | string | No | The `recurrenceId` of the targeted occurrence, from its ListCalendarEvents entry. Required for "this_event"; omit for "all". || `title` | string | No | Replacement title. Omit to keep the current title. |diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex bff4666a06..f107c95be6 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -4441,6 +4441,7 @@ export const DeleteBotResponse = z.object({export const DeleteCalendarEvent = z.object({eventId: z.string().uuid(),calendarId: z.union([z.string().uuid(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),scope: z.any().superRefine((x, ctx) => {@@ -16116,6 +16117,7 @@ export const UpdateBookingSettings = zexport const UpdateCalendarEvent = z.object({eventId: z.string().uuid(),calendarId: z.union([z.string().uuid(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),scope: z.any().superRefine((x, ctx) => {const schemas = [z.literal('all'), z.literal('this_event')];const errors = schemas.reduce<z.ZodError[]>(diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex f7538b94ce..234948f1dd 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -8343,7 +8343,7 @@ export interface DeleteBotResponse {** For recurring events, `scope` controls how much is removed: "all" (default) removes the whole series, "this_event" removes one occurrence, and "this_and_following" ends the series from an occurrence onward. The scoped variants require `recurrenceId` from the targeted occurrence's ListCalendarEvents entry.*- * When the meeting is on several of the user's inboxes (one ListCalendarEvents entry per inbox), ask which inbox's copy to delete unless the user named one or only one copy is writable (`isReadOnly` false), in which case delete that one and say why. Deleting the copy the user organizes cancels the meeting for every guest, while deleting a copy where they are a guest only takes it off that inbox's calendar.+ * When the meeting is on several of the user's inboxes (one ListCalendarEvents entry per inbox), the tool refuses until `inbox` names the inbox of the copy to delete, and lists each copy. Ask which inbox's copy to delete unless the user named one or only one copy is writable (`isReadOnly` false), in which case delete that one, pass its `inbox` and say why. Deleting the copy the user organizes cancels the meeting for every guest. Deleting a copy where they are a guest takes the meeting off that inbox's calendar: on Google it also declines the invitation and tells the organizer, while on Outlook the organizer is not told and still sees the invitation unanswered.*/export interface DeleteCalendarEvent {/**@@ -8354,6 +8354,10 @@ export interface DeleteCalendarEvent {* The `calendarId` of the copy to delete, from the `copies` of its ListCalendarEvents entry, for an event synced from more than one calendar. Omit to delete the event's primary copy.*/calendarId?: string | null;+ /**+ * The `inbox` of the copy to delete, from its ListCalendarEvents entry. Required when the meeting is on more than one of the user's inboxes: the tool refuses without it and lists each copy. It must be the inbox holding the copy `eventId` names.+ */+ inbox?: string | null;scope?: DeletionScopeInput;/*** The `recurrenceId` of the targeted occurrence, from its ListCalendarEvents entry. Required for "this_event" and "this_and_following".@@ -11235,7 +11239,7 @@ export interface ListBotsResponse {** Each entry names the calendar (`calendarName`) and connected inbox (`inbox`) holding that copy of the event, and `myRole` says whether the user organizes it or is a guest there. A meeting on several of the user's inboxes appears once per inbox, each with its own `eventId`, and what the user may do can differ between them. When asking which one the user means, describe each by its inbox and role, never by id; when the user names an inbox, act on the entry whose `inbox` matches.*- * When the user does not name an inbox, choose the copy by what the change does. Reminders belong to one copy only, so set them on one copy without asking and say which inbox you used. Answer an invitation on the copy where the user is a guest; when they are a guest through more than one inbox, ask which inbox answers, since each answers only for itself. Any other change reaches the meeting differently from each copy: the title, time, description, location, recurrence or conference, adding or removing guests, guest permissions, and deleting. Never pick a copy for such a change silently. If only one copy allows it (`viewerCan`, or for deleting, `isReadOnly` false), use that copy and say why (for example, only the copy the user organizes can move the meeting). If more than one can, ask which inbox, saying what the change would do from each, such as deleting the organizer's copy cancelling the meeting for everyone while deleting a guest's copy only takes it off that inbox's calendar.+ * When the user does not name an inbox, choose the copy by what the change does. Reminders belong to one copy only, so set them on one copy without asking and say which inbox you used. Answer an invitation on the copy where the user is a guest; when they are a guest through more than one inbox, ask which inbox answers, since each answers only for itself. Any other change reaches the meeting differently from each copy: the title, time, description, location, recurrence or conference, adding or removing guests, guest permissions, and deleting. UpdateCalendarEvent and DeleteCalendarEvent refuse such a change on a meeting held by several of the user's inboxes until `inbox` names the inbox of the copy being changed, and the refusal lists each copy. If only one copy allows the change (`viewerCan`, or for deleting, `isReadOnly` false), use that copy with its `inbox` and say why (for example, only the copy the user organizes can move the meeting). If more than one can, ask which inbox, saying what the change would do from each. Add guests from the copy the user organizes when there is one: it invites them directly, while a guest's copy invites only as far as the organizer allows. Deleting the organizer's copy cancels the meeting for everyone, while deleting a guest's copy takes the meeting off that inbox's calendar and, on Google, also declines the invitation and tells the organizer.*/export interface ListCalendarEvents {/**@@ -15473,7 +15477,7 @@ export interface UpdateBookingSettings {** `rsvp` sets the user's own response to an invitation and is independent of the field edits — it can be the only thing this call changes. It applies at the same `scope` as the rest of the call and answers as the connected inbox the event's copy belongs to, so it only works when that inbox is an attendee.*- * When the meeting is on several of the user's inboxes, ListCalendarEvents lists one entry per inbox; pick the copy by its rule. Reminders may go to one copy and an `rsvp` to the copy where the user is a guest, naming the inbox in your reply. Any other change goes to the only copy whose `viewerCan` allows it, with the reason, or to the copy the user chooses when more than one could make it. One call changes one copy, so an edit on one copy and an `rsvp` on another take two calls.+ * When the meeting is on several of the user's inboxes, ListCalendarEvents lists one entry per inbox; pick the copy by its rule. Reminders may go to one copy and an `rsvp` to the copy where the user is a guest, naming the inbox in your reply. Any other change needs `inbox`, the inbox of the copy it changes; without it the tool refuses and lists each copy. Use the only copy whose `viewerCan` allows the change, with the reason, or the copy the user chooses when more than one could make it, and add guests from the copy the user organizes when there is one. One call changes one copy, so an edit on one copy and an `rsvp` on another take two calls.*/export interface UpdateCalendarEvent {/**@@ -15484,6 +15488,10 @@ export interface UpdateCalendarEvent {* The `calendarId` of the copy to update, from the `copies` of its ListCalendarEvents entry, for an event synced from more than one calendar. Omit to update the event's primary copy.*/calendarId?: string | null;+ /**+ * The `inbox` of the copy this call changes, from its ListCalendarEvents entry. Required when the meeting is on more than one of the user's inboxes and the call changes anything but `reminders` or `rsvp`: the tool refuses without it and lists each copy. It must be the inbox holding the copy `eventId` names.+ */+ inbox?: string | null;scope: UpdateScopeInput;/*** The `recurrenceId` of the targeted occurrence, from its ListCalendarEvents entry. Required for "this_event"; omit for "all".diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 822dd42695..575bf948c6 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -155,7 +155,12 @@ reminder dispatch, team availability, and provider/Postgres persistence.if the reply names its inbox (an answer asks first when the user is a guestthrough several inboxes); a change whose effect differs by copy (details,guests, permissions, deleting) goes to the only copy allowed to make it, with- the reason, or the agent asks.+ the reason, or the agent asks, and guests are added from the copy the user+ organizes. UpdateCalendarEvent and DeleteCalendarEvent enforce it+ (`confirm_copy`): such a change on a meeting the user holds through several+ of their own inboxes (`meeting_copies`, matched by iCalendar UID) is refused,+ listing each copy, until `inbox` names the addressed copy's inbox. An Outlook+ copy of a Google meeting carries Exchange's UID, so it is not matched.- 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/domain/models.rs b/crates/calendar_events/src/domain/models.rsindex 32580583bc..a401cec23e 100644--- a/crates/calendar_events/src/domain/models.rs+++ b/crates/calendar_events/src/domain/models.rs@@ -1378,6 +1378,35 @@ impl CalendarEventPatch {pub fn is_empty(&self) -> bool {self == &Self::default()}++ /// Whether the patch changes the meeting itself rather than only what+ /// the provider keeps on each copy: reminders and availability.+ pub fn reaches_meeting(&self) -> bool {+ let Self {+ title,+ description,+ location,+ time,+ attendees,+ recurrence_lines,+ visibility,+ transparency: _,+ reminders: _,+ conference,+ out_of_office,+ guest_policy,+ } = self;+ title.is_some()+ || description.is_some()+ || location.is_some()+ || time.is_some()+ || attendees.is_some()+ || recurrence_lines.is_some()+ || visibility.is_some()+ || conference.is_some()+ || out_of_office.is_some()+ || guest_policy.is_some()+ }}/// The stored details of an event or one of its occurrences: what every@@ -1495,6 +1524,20 @@ impl CalendarEventMutationTarget {}}+/// One of the requester's own copies of a meeting: the event held through+/// one of their inboxes under the meeting's iCalendar UID.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct MeetingCopy {+ /// The copy's event id.+ pub event_id: Uuid,+ /// Address of the inbox holding the copy.+ pub inbox: String,+ /// Whether that inbox organizes the meeting.+ pub organizes: bool,+ /// Whether that inbox is on the meeting's guest list.+ pub attends: bool,+}+/// A calendar visible to a requester, listed for pickers and filters.#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex 23ea5b58ba..a66b7c47ea 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -294,6 +294,14 @@ impl CalendarRepository for FakeRepo {unreachable!()}+ async fn meeting_copies(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Vec<crate::domain::models::MeetingCopy>, rootcause::Report> {+ unreachable!()+ }+async fn event_export(&self,_requester_id: &str,diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 3f95654519..90115e2505 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -21,9 +21,9 @@ use super::models::{CalendarReminderDispatchMessage, CalendarReminderFiring, CalendarReminderSweepSummary,CalendarSyncStatus, DisconnectedCalendar, DueCalendarReminder, EventDetails,GoogleCalendarSyncSnapshot, GoogleEventSyncBatch, GoogleScopeSet, GoogleSyncPlan,- GoogleWatchChannel, GoogleWatchConfig, GuestPolicy, OccurrenceListing, OccurrenceRange,- OwnedInbox, ProviderCalendar, ProviderCalendarTarget, StoredGoogleCalendar, TeamOutOfOffice,- VisibleCalendar,+ GoogleWatchChannel, GoogleWatchConfig, GuestPolicy, MeetingCopy, OccurrenceListing,+ OccurrenceRange, OwnedInbox, ProviderCalendar, ProviderCalendarTarget, StoredGoogleCalendar,+ TeamOutOfOffice, VisibleCalendar,};/// Classification supplied by provider adapters to backfill policy.@@ -455,6 +455,15 @@ pub trait CalendarOccurrenceService: Send + Sync + 'static {requester_id: &str,) -> impl Future<Output = Result<Option<String>, Report>> + Send;+ /// Every copy of `event_id`'s meeting the requester holds through one of+ /// their own inboxes, so a caller can tell when one meeting sits on+ /// several of them.+ fn meeting_copies(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Vec<MeetingCopy>, Report>> + Send;+/// Render an event the requester can see — their own, or one shared with/// a channel they belong to — as an iCalendar document, with its title./// `None` when the event does not exist or is not visible to them.@@ -569,6 +578,16 @@ pub trait CalendarRepository: Send + Sync + 'static {now: DateTime<Utc>,) -> impl Future<Output = Result<Vec<CalendarMentionPreview>, Report>> + Send;+ /// Every copy of `event_id`'s meeting (same iCalendar UID) the requester+ /// holds through an inbox they own or have linked, ordered by inbox.+ /// Cancelled copies are left out, and an event they hold no copy of+ /// yields none.+ fn meeting_copies(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Vec<MeetingCopy>, Report>> + Send;+/// Series content of an event the requester can see, for export or/// copying, with how they see it: the requester's own projection of the/// meeting (same iCalendar UID) on one of their own or linked calendars,diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex be03eb0edb..6440035c9b 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -207,6 +207,22 @@ whereself.repository.primary_time_zone(requester_id).await}+ /// Every copy of `event_id`'s meeting the requester holds through one of+ /// their own inboxes.+ #[tracing::instrument(skip(self, requester_id), fields(copies), err)]+ pub async fn meeting_copies(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> Result<Vec<super::models::MeetingCopy>, Report> {+ let copies = self+ .repository+ .meeting_copies(requester_id, event_id)+ .await?;+ tracing::Span::current().record("copies", copies.len());+ Ok(copies)+ }+/// Export an event the requester can see as an iCalendar document.#[tracing::instrument(skip(self, requester_id), err)]pub async fn event_ics(@@ -297,6 +313,14 @@ whereCalendarService::primary_time_zone(self, requester_id)}+ fn meeting_copies(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> impl Future<Output = Result<Vec<super::models::MeetingCopy>, Report>> + Send {+ CalendarService::meeting_copies(self, requester_id, event_id)+ }+fn event_ics(&self,requester_id: &str,diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex 724723bc6e..36f601bd20 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -105,6 +105,14 @@ impl CalendarRepository for FakeRepo {.collect())}+ async fn meeting_copies(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Vec<crate::domain::models::MeetingCopy>, Report> {+ Ok(Vec::new())+ }+async fn event_export(&self,_requester_id: &str,diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rsindex 81c69653ba..32627efd9f 100644--- a/crates/calendar_events/src/inbound/toolset.rs+++ b/crates/calendar_events/src/inbound/toolset.rs@@ -23,6 +23,7 @@ use std::sync::Arc;use ai_toolset::{AsyncToolCollection, ToolCallError};use chrono::NaiveDate;use chrono::{DateTime, Utc};+use rootcause::compat::boxed_error::IntoBoxedError;use schemars::JsonSchema;use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -31,7 +32,7 @@ use crate::domain::{meeting_links::{CreateEventWithMacroCallError, EventWithMacroCall, MeetingLinkError},models::{CalendarAttendeeInput, CalendarEvent, EventReminderOverride, EventReminders, EventTime,- OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, VisibleCalendar,+ MeetingCopy, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, VisibleCalendar,},ports::{CalendarMutationError, CalendarMutationService, CalendarOccurrenceService,@@ -481,6 +482,121 @@ impl CalendarLabels {}}+/// A change that reaches a meeting differently depending on which of the+/// user's copies makes it.+#[derive(Clone, Copy)]+enum CopyChange {+ /// Details, guests or guest permissions; `adds_guests` when the call+ /// carries a guest list.+ Update {+ adds_guests: bool,+ },+ Delete,+}++/// Make sure the agent chose which copy to change when the meeting is on+/// several of the user's inboxes. With `inbox` set, it must be the inbox+/// holding the addressed copy; without it, a call addressing one of several+/// inboxes' copies is refused with each copy's inbox and role, so the agent+/// asks the user instead of picking one.+async fn confirm_copy<O: CalendarOccurrenceService>(+ occurrences: &O,+ requester_id: &str,+ event_id: Uuid,+ inbox: Option<&str>,+ change: CopyChange,+) -> Result<(), ToolCallError> {+ let copies = occurrences+ .meeting_copies(requester_id, event_id)+ .await+ .map_err(|error| ToolCallError {+ description: "Failed to check which of the user's inboxes hold this meeting. Try \+ again shortly."+ .to_string(),+ internal_error: anyhow::Error::from_boxed(error.into_boxed_error()),+ })?;+ // A copy held through an inbox the user doesn't own, such as a delegated+ // one, has no siblings to tell apart.+ let Some(addressed) = copies.iter().find(|copy| copy.event_id == event_id) else {+ return Ok(());+ };+ if let Some(inbox) = inbox.map(str::trim) {+ if addressed.inbox.eq_ignore_ascii_case(inbox) {+ return Ok(());+ }+ let other = copies+ .iter()+ .find(|copy| copy.inbox.eq_ignore_ascii_case(inbox))+ .map(|copy| format!(" The copy on {inbox} is eventId {}.", copy.event_id))+ .unwrap_or_default();+ return Err(ToolCallError {+ description: format!(+ "`inbox` {inbox} does not hold this copy: eventId {event_id} is the copy on \+ {}.{other}",+ addressed.inbox+ ),+ internal_error: anyhow::anyhow!("inbox does not match the addressed copy"),+ });+ }+ let inboxes: std::collections::HashSet<String> = copies+ .iter()+ .map(|copy| copy.inbox.to_lowercase())+ .collect();+ if inboxes.len() < 2 {+ return Ok(());+ }+ Err(ToolCallError {+ description: copy_question(&copies, inboxes.len(), change),+ internal_error: anyhow::anyhow!("copy not confirmed on a meeting held by several inboxes"),+ })+}++/// What the agent needs to ask which copy to change: each copy's inbox,+/// role and id, and what the change would do from each.+fn copy_question(copies: &[MeetingCopy], inboxes: usize, change: CopyChange) -> String {+ let listed = copies+ .iter()+ .map(|copy| {+ let role = if copy.organizes {+ "organizes it"+ } else if copy.attends {+ "is a guest"+ } else {+ "holds a copy"+ };+ format!("{} {role} (eventId {})", copy.inbox, copy.event_id)+ })+ .collect::<Vec<_>>()+ .join("; ");+ let effect = match change {+ CopyChange::Delete => {+ "Deleting the copy an inbox organizes cancels the meeting for every guest, while \+ deleting a guest's copy takes it off that inbox's calendar and, on Google, also \+ declines the invitation and tells the organizer."+ .to_string()+ }+ CopyChange::Update { adds_guests } => {+ let organizer = copies.iter().find(|copy| copy.organizes);+ match organizer {+ Some(organizer) if adds_guests => format!(+ "To add guests, suggest {}: it organizes the meeting, so they are invited \+ directly, while a guest's copy can invite only where the organizer allows \+ it.",+ organizer.inbox+ ),+ _ => "The change reaches the meeting differently from each copy, and a guest's \+ copy can only make it where the organizer allows it."+ .to_string(),+ }+ }+ };+ format!(+ "This meeting is on {inboxes} of the user's inboxes: {listed}. {effect} Ask the user \+ which inbox's copy to change, then call again with that copy's `eventId` and its inbox \+ as `inbox`."+ )+}+const DESCRIPTION_PREVIEW_CHARS: usize = 280;const ATTENDEES_SHOWN_MAX: usize = 20;diff --git a/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rsindex 879beec55c..f06ed5791e 100644--- a/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/delete_calendar_event.rs@@ -8,7 +8,7 @@ use async_trait::async_trait;use schemars::JsonSchema;use serde::{Deserialize, Serialize};-use super::{CalendarToolContext, mutation_tool_error};+use super::{CalendarToolContext, CopyChange, confirm_copy, mutation_tool_error};use crate::domain::ports::{CalendarDeletionScope, CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider,};@@ -52,10 +52,13 @@ series from an occurrence onward. The scoped variants require `recurrenceId` frotargeted occurrence's ListCalendarEvents entry.\n\\n\When the meeting is on several of the user's inboxes (one ListCalendarEvents entry per \-inbox), ask which inbox's copy to delete unless the user named one or only one copy is \-writable (`isReadOnly` false), in which case delete that one and say why. Deleting the copy \-the user organizes cancels the meeting for every guest, while deleting a copy where they are \-a guest only takes it off that inbox's calendar."+inbox), the tool refuses until `inbox` names the inbox of the copy to delete, and lists each \+copy. Ask which inbox's copy to delete unless the user named one or only one copy is writable \+(`isReadOnly` false), in which case delete that one, pass its `inbox` and say why. Deleting \+the copy the user organizes cancels the meeting for every guest. Deleting a copy where they \+are a guest takes the meeting off that inbox's calendar: on Google it also declines the \+invitation and tells the organizer, while on Outlook the organizer is not told and still sees \+the invitation unanswered.")]pub struct DeleteCalendarEvent {/// Event to delete.@@ -71,6 +74,16 @@ pub struct DeleteCalendarEvent {#[serde(default)]pub calendar_id: Option<uuid::Uuid>,+ /// Inbox holding the copy to delete.+ #[schemars(+ description = "The `inbox` of the copy to delete, from its ListCalendarEvents entry. \+ Required when the meeting is on more than one of the user's inboxes: \+ the tool refuses without it and lists each copy. It must be the inbox \+ holding the copy `eventId` names."+ )]+ #[serde(default)]+ pub inbox: Option<String>,+/// Deletion scope.#[schemars(description = "How much of a recurring series to remove: \"all\" (default), \@@ -109,7 +122,13 @@ whereservice_context: ServiceContext<CalendarToolContext<M, O, L>>,request_context: RequestContext,) -> ToolResult<Self::Output> {- tracing::info!(params=?self, "Delete calendar event");+ tracing::info!(+ event_id=%self.event_id,+ calendar_id=?self.calendar_id,+ scope=?self.scope,+ inbox_confirmed=self.inbox.is_some(),+ "Delete calendar event"+ );let requester_id = request_context.user_id.to_string();let scoped_occurrence = |kind: &'static str| {@@ -137,6 +156,14 @@ where),};+ confirm_copy(+ &*service_context.occurrences,+ &requester_id,+ self.event_id,+ self.inbox.as_deref(),+ CopyChange::Delete,+ )+ .await?;service_context.mutations.delete_event(&requester_id, self.event_id, self.calendar_id, scope)diff --git a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rsindex 146b5b2078..b9b35e333a 100644--- a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs+++ b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs@@ -165,12 +165,16 @@ Answer an invitation on the copy where the user is a guest; when they are a guesmore than one inbox, ask which inbox answers, since each answers only for itself. Any other \change reaches the meeting differently from each copy: the title, time, description, \location, recurrence or conference, adding or removing guests, guest permissions, and \-deleting. Never pick a copy for such a change silently. If only one copy allows it \-(`viewerCan`, or for deleting, `isReadOnly` false), use that copy and say why (for example, \-only the copy the user organizes can move the meeting). If more than one can, \-ask which inbox, saying what the change would do from each, such as deleting the organizer's \-copy cancelling the meeting for everyone while deleting a guest's copy only takes it off that \-inbox's calendar."+deleting. UpdateCalendarEvent and DeleteCalendarEvent refuse such a change on a meeting held \+by several of the user's inboxes until `inbox` names the inbox of the copy being changed, and \+the refusal lists each copy. If only one copy allows the change (`viewerCan`, or for deleting, \+`isReadOnly` false), use that copy with its `inbox` and say why (for example, only the copy \+the user organizes can move the meeting). If more than one can, ask which inbox, saying what \+the change would do from each. Add guests from the copy the user organizes when there is one: \+it invites them directly, while a guest's copy invites only as far as the organizer allows. \+Deleting the organizer's copy cancels the meeting for everyone, while deleting a guest's copy \+takes the meeting off that inbox's calendar and, on Google, also declines the invitation and \+tells the organizer.")]pub struct ListCalendarEvents {/// Inclusive window start.diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rsindex b2dfa49ecd..21da0fed15 100644--- a/crates/calendar_events/src/inbound/toolset/test.rs+++ b/crates/calendar_events/src/inbound/toolset/test.rs@@ -1,4 +1,5 @@mod add_shared_calendar_event;+mod copies;mod read_calendar_event;use std::sync::Mutex;@@ -15,7 +16,7 @@ use crate::domain::models::{AttendeeResponseStatus, CalendarAttendee, CalendarEventDraft, CalendarEventPatch,CalendarOccurrence, CalendarSyncStatus, ConferenceChange, EventReminderOverride,EventReminders, EventStatus, EventTransparency, EventType, EventVisibility, GuestPolicy,- OccurrenceRange, ViewerCapabilities, VisibleCalendar,+ MeetingCopy, OccurrenceRange, ViewerCapabilities, VisibleCalendar,};use crate::domain::ports::{CalendarDeletionScope, CalendarMutationError, CalendarMutationService,@@ -280,6 +281,7 @@ impl CalendarMutationService for MockMutations {struct MockOccurrences {rows: Mutex<Vec<(crate::domain::models::CalendarEvent, CalendarOccurrence)>>,status: CalendarSyncStatus,+ copies: Mutex<Vec<MeetingCopy>>,}impl CalendarOccurrenceService for MockOccurrences {@@ -352,6 +354,14 @@ impl CalendarOccurrenceService for MockOccurrences {unreachable!("no calendar tool resolves the primary time zone")}+ async fn meeting_copies(+ &self,+ _requester_id: &str,+ _event_id: Uuid,+ ) -> Result<Vec<MeetingCopy>, rootcause::Report> {+ Ok(self.copies.lock().unwrap().clone())+ }+async fn event_ics(&self,_requester_id: &str,@@ -434,6 +444,7 @@ fn empty_occurrences() -> MockOccurrences {MockOccurrences {rows: Mutex::new(Vec::new()),status: CalendarSyncStatus::Ready,+ copies: Mutex::new(Vec::new()),}}@@ -930,6 +941,7 @@ async fn update_converts_input_into_a_domain_patch() {let tool = UpdateCalendarEvent {event_id,calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: Some("Renamed".to_string()),@@ -972,6 +984,7 @@ async fn update_maps_out_of_office_settings_into_the_patch() {let tool = UpdateCalendarEvent {event_id,calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: None,@@ -1011,6 +1024,7 @@ async fn update_passes_the_selected_occurrence_scope() {let tool = UpdateCalendarEvent {event_id,calendar_id: None,+ inbox: None,scope: UpdateScopeInput::ThisEvent,recurrence_id: Some("2026-08-18T20:00:00+00:00".to_string()),title: None,@@ -1048,6 +1062,7 @@ async fn scoped_update_requires_a_recurrence_id() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::ThisEvent,recurrence_id: None,title: Some("Renamed".to_string()),@@ -1077,6 +1092,7 @@ async fn series_update_rejects_a_stray_recurrence_id() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: Some("2026-08-18T20:00:00+00:00".to_string()),title: Some("Renamed".to_string()),@@ -1103,6 +1119,7 @@ async fn update_carries_reminders_into_the_patch() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: None,@@ -1149,6 +1166,7 @@ async fn rsvp_alone_answers_without_patching() {let tool = UpdateCalendarEvent {event_id,calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: None,@@ -1184,6 +1202,7 @@ async fn rsvp_follows_the_occurrence_scope_of_the_call() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::ThisEvent,recurrence_id: Some("2026-08-18T20:00:00+00:00".to_string()),title: None,@@ -1220,6 +1239,7 @@ async fn update_answers_after_applying_the_patch() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: None,@@ -1250,6 +1270,7 @@ async fn update_without_a_change_or_an_rsvp_is_rejected() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: None,@@ -1277,6 +1298,7 @@ async fn scoped_deletion_requires_a_recurrence_id() {let tool = DeleteCalendarEvent {event_id: Uuid::from_u128(11),calendar_id: None,+ inbox: None,scope: DeletionScopeInput::ThisEvent,recurrence_id: None,};@@ -1293,6 +1315,7 @@ async fn deletion_passes_the_selected_scope() {let tool = DeleteCalendarEvent {event_id,calendar_id: None,+ inbox: None,scope: DeletionScopeInput::ThisAndFollowing,recurrence_id: Some("2026-08-20T17:00:00+00:00".to_string()),};@@ -1320,6 +1343,7 @@ async fn list_events_maps_occurrences_and_skips_cancelled_ones() {(recurring.clone(), occurrence_of(&recurring, "k-2", true)),]),status: CalendarSyncStatus::Syncing,+ copies: Mutex::new(Vec::new()),};let (_, context) = context(MockMutations::default(), occurrences);@@ -1357,6 +1381,7 @@ async fn list_events_reports_truncation() {let occurrences = MockOccurrences {rows: Mutex::new(rows),status: CalendarSyncStatus::Ready,+ copies: Mutex::new(Vec::new()),};let (_, context) = context(MockMutations::default(), occurrences);@@ -1392,6 +1417,7 @@ async fn cancelled_occurrences_do_not_count_toward_truncation() {let occurrences = MockOccurrences {rows: Mutex::new(rows),status: CalendarSyncStatus::Ready,+ copies: Mutex::new(Vec::new()),};let (_, context) = context(MockMutations::default(), occurrences);@@ -1520,6 +1546,7 @@ async fn list_events_names_the_inbox_and_role_of_each_copy() {(invited.clone(), occurrence_of(&invited, "k-1", false)),]),status: CalendarSyncStatus::Ready,+ copies: Mutex::new(Vec::new()),};let (_, context) = context(mutations, occurrences);@@ -1575,6 +1602,7 @@ async fn list_events_labels_each_calendar_copy_of_one_entity() {let occurrences = MockOccurrences {rows: Mutex::new(vec![(event.clone(), occurrence_of(&event, "k-1", false))]),status: CalendarSyncStatus::Ready,+ copies: Mutex::new(Vec::new()),};let (_, context) = context(mutations, occurrences);@@ -1638,6 +1666,7 @@ async fn update_result_names_the_copy_it_changed() {let tool = UpdateCalendarEvent {event_id: Uuid::from_u128(7),calendar_id: None,+ inbox: None,scope: UpdateScopeInput::All,recurrence_id: None,title: Some("Renamed".to_string()),diff --git a/crates/calendar_events/src/inbound/toolset/test/copies.rs b/crates/calendar_events/src/inbound/toolset/test/copies.rsnew file mode 100644index 0000000000..a74e8c58ba--- /dev/null+++ b/crates/calendar_events/src/inbound/toolset/test/copies.rs@@ -0,0 +1,235 @@+use super::*;++const ORGANIZED: Uuid = Uuid::from_u128(7);+const INVITED: Uuid = Uuid::from_u128(8);++fn copy(event_id: Uuid, inbox: &str, organizes: bool) -> MeetingCopy {+ MeetingCopy {+ event_id,+ inbox: inbox.to_string(),+ organizes,+ attends: true,+ }+}++/// One meeting on two of the user's inboxes: one organizes it, the other is+/// a guest.+fn two_inboxes() -> Vec<MeetingCopy> {+ vec![+ copy(INVITED, "[email protected]", false),+ copy(ORGANIZED, "[email protected]", true),+ ]+}++fn occurrences_with(copies: Vec<MeetingCopy>) -> MockOccurrences {+ MockOccurrences {+ rows: Mutex::new(Vec::new()),+ status: CalendarSyncStatus::Ready,+ copies: Mutex::new(copies),+ }+}++fn delete(event_id: Uuid, inbox: Option<&str>) -> DeleteCalendarEvent {+ serde_json::from_value(serde_json::json!({+ "eventId": event_id,+ "inbox": inbox,+ }))+ .unwrap()+}++fn update(args: serde_json::Value) -> UpdateCalendarEvent {+ let mut base = serde_json::json!({ "scope": "all" });+ base.as_object_mut()+ .unwrap()+ .extend(args.as_object().unwrap().clone());+ serde_json::from_value(base).unwrap()+}++#[tokio::test]+async fn deleting_one_of_several_inboxes_copies_asks_which() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ let error = delete(ORGANIZED, None)+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(mutations.deleted.lock().unwrap().is_empty());+ let description = &error.description;+ assert!(+ description.contains("2 of the user's inboxes"),+ "{description}"+ );+ assert!(+ description.contains(&format!(+ "[email protected] organizes it (eventId {ORGANIZED})"+ )),+ "{description}"+ );+ assert!(+ description.contains(&format!("[email protected] is a guest (eventId {INVITED})")),+ "{description}"+ );+ assert!(description.contains("cancels the meeting"), "{description}");+}++#[tokio::test]+async fn a_confirmed_inbox_lets_the_deletion_through() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ delete(INVITED, Some(" [email protected] "))+ .call(context, request_context())+ .await+ .unwrap();++ assert_eq!(mutations.deleted.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn an_inbox_that_does_not_hold_the_copy_is_refused() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ let error = delete(ORGANIZED, Some("[email protected]"))+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(mutations.deleted.lock().unwrap().is_empty());+ assert!(+ error.description.contains(&format!(+ "The copy on [email protected] is eventId {INVITED}"+ )),+ "{}",+ error.description+ );+}++#[tokio::test]+async fn a_meeting_on_one_inbox_needs_no_confirmation() {+ let (mutations, context) = context(+ MockMutations::default(),+ occurrences_with(vec![copy(ORGANIZED, "[email protected]", true)]),+ );++ delete(ORGANIZED, None)+ .call(context, request_context())+ .await+ .unwrap();++ assert_eq!(mutations.deleted.lock().unwrap().len(), 1);+}++/// A copy held through an inbox the user doesn't own, such as a delegated+/// one, is not among their copies and has nothing to tell apart.+#[tokio::test]+async fn a_copy_outside_the_users_own_inboxes_is_not_checked() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ delete(Uuid::from_u128(99), Some("[email protected]"))+ .call(context, request_context())+ .await+ .unwrap();++ assert_eq!(mutations.deleted.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn adding_guests_suggests_the_copy_the_user_organizes() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ let error = update(serde_json::json!({+ "eventId": INVITED,+ "attendees": [{ "email": "[email protected]" }],+ }))+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(mutations.updated.lock().unwrap().is_empty());+ assert!(+ error+ .description+ .contains("To add guests, suggest [email protected]"),+ "{}",+ error.description+ );+}++#[tokio::test]+async fn a_detail_change_asks_which_copy() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ let error = update(serde_json::json!({ "eventId": ORGANIZED, "title": "Renamed" }))+ .call(context, request_context())+ .await+ .unwrap_err();++ assert!(mutations.updated.lock().unwrap().is_empty());+ assert!(+ error+ .description+ .contains("Ask the user which inbox's copy"),+ "{}",+ error.description+ );+}++#[tokio::test]+async fn a_confirmed_detail_change_goes_through() {+ let (mutations, context) = context(MockMutations::default(), occurrences_with(two_inboxes()));++ update(serde_json::json!({+ "eventId": ORGANIZED,+ "inbox": "[email protected]",+ "title": "Renamed",+ }))+ .call(context, request_context())+ .await+ .unwrap();++ assert_eq!(mutations.updated.lock().unwrap().len(), 1);+}++/// Reminders and the user's own answer belong to one copy, so the agent may+/// pick it without asking.+#[tokio::test]+async fn reminders_and_answers_need_no_confirmation() {+ let (mutations, tool_context) =+ context(MockMutations::default(), occurrences_with(two_inboxes()));+ update(serde_json::json!({+ "eventId": INVITED,+ "reminders": { "useDefault": false, "overrides": [{ "method": "popup", "minutes": 10 }] },+ }))+ .call(tool_context, request_context())+ .await+ .unwrap();+ assert_eq!(mutations.updated.lock().unwrap().len(), 1);++ let (answers, answer_context) =+ context(MockMutations::default(), occurrences_with(two_inboxes()));+ update(serde_json::json!({ "eventId": INVITED, "rsvp": "accepted" }))+ .call(answer_context, request_context())+ .await+ .unwrap();+ assert_eq!(answers.answered.lock().unwrap().len(), 1);+}++#[test]+fn only_reminders_and_availability_stay_on_one_copy() {+ let reminders = CalendarEventPatch {+ reminders: Some(EventReminders::default()),+ transparency: Some(EventTransparency::Transparent),+ ..Default::default()+ };+ assert!(!reminders.reaches_meeting());+ let title = CalendarEventPatch {+ title: Some("Renamed".to_string()),+ ..Default::default()+ };+ assert!(title.reaches_meeting());+ let guests = CalendarEventPatch {+ attendees: Some(Vec::new()),+ ..Default::default()+ };+ assert!(guests.reaches_meeting());+}diff --git a/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rsindex 5993d287b9..292577552e 100644--- a/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/test/read_calendar_event.rs@@ -62,6 +62,14 @@ impl CalendarOccurrenceService for PreviewOccurrences {unreachable!("reading an event resolves no time zone")}+ async fn meeting_copies(+ &self,+ _requester_id: &str,+ _event_id: uuid::Uuid,+ ) -> Result<Vec<crate::domain::models::MeetingCopy>, rootcause::Report> {+ unreachable!("reading an event lists no copies")+ }+async fn event_ics(&self,_requester_id: &str,diff --git a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rsindex 8ff663e8c2..e545df296a 100644--- a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs@@ -10,8 +10,8 @@ use schemars::JsonSchema;use serde::Deserialize;use super::{- AttendeeInput, CalendarLabels, CalendarToolContext, EventRemindersInput, EventTimeInput,- OutOfOfficeInput, ToolCalendarEvent, mutation_tool_error,+ AttendeeInput, CalendarLabels, CalendarToolContext, CopyChange, EventRemindersInput,+ EventTimeInput, OutOfOfficeInput, ToolCalendarEvent, confirm_copy, mutation_tool_error,};use crate::domain::{models::{AttendeeResponseStatus, CalendarEventPatch, ConferenceChange, GuestPolicy},@@ -120,10 +120,12 @@ it only works when that inbox is an attendee.\n\\n\When the meeting is on several of the user's inboxes, ListCalendarEvents lists one entry per \inbox; pick the copy by its rule. Reminders may go to one copy and an `rsvp` to the copy \-where the user is a guest, naming the inbox in your reply. Any other change goes to the only \-copy whose `viewerCan` allows it, with the reason, or to the copy the user chooses when more \-than one could make it. One call changes one copy, so an edit on one copy and an `rsvp` on \-another take two calls."+where the user is a guest, naming the inbox in your reply. Any other change needs `inbox`, \+the inbox of the copy it changes; without it the tool refuses and lists each copy. Use the \+only copy whose `viewerCan` allows the change, with the reason, or the copy the user chooses \+when more than one could make it, and add guests from the copy the user organizes when there \+is one. One call changes one copy, so an edit on one copy and an `rsvp` on another take two \+calls.")]pub struct UpdateCalendarEvent {/// Event to update.@@ -139,6 +141,17 @@ pub struct UpdateCalendarEvent {#[serde(default)]pub calendar_id: Option<uuid::Uuid>,+ /// Inbox holding the copy this call changes.+ #[schemars(+ description = "The `inbox` of the copy this call changes, from its ListCalendarEvents \+ entry. Required when the meeting is on more than one of the user's \+ inboxes and the call changes anything but `reminders` or `rsvp`: the \+ tool refuses without it and lists each copy. It must be the inbox \+ holding the copy `eventId` names."+ )]+ #[serde(default)]+ pub inbox: Option<String>,+/// Update scope.#[schemars(description = "How much of a recurring series to change: \"this_event\" edits one \@@ -280,6 +293,7 @@ wherescope=?self.scope,attendee_count=?self.attendees.as_ref().map(Vec::len),rsvp=?self.rsvp,+ inbox_confirmed=self.inbox.is_some(),"Update calendar event");@@ -332,6 +346,22 @@ whereguest_policy: self.guest_policy,};+ // Reminders and the user's own answer belong to one copy; anything+ // else reaches the meeting, so the agent must have chosen the copy+ // when the meeting is on several of the user's inboxes.+ if patch.reaches_meeting() || self.inbox.is_some() {+ confirm_copy(+ &*service_context.occurrences,+ &requester_id,+ self.event_id,+ self.inbox.as_deref(),+ CopyChange::Update {+ adds_guests: patch.attendees.is_some(),+ },+ )+ .await?;+ }+// An RSVP is its own provider call, so a call carrying only one runs// only that half. Answering after the patch keeps a replaced attendee// list from discarding the response that was just recorded.diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex d715d8356f..921b1f819b 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -37,7 +37,7 @@ use crate::domain::{CalendarWatchRelease, ConferenceProvider, DisconnectedCalendar, DueCalendarReminder,EventDetails, EventReminderOverride, EventReminders, EventStart, EventStatus, EventTime,EventTransparency, EventType, EventVisibility, GOOGLE_CALENDAR_SCOPES,- GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel, GuestPolicy,+ GoogleCalendarSyncSnapshot, GoogleScopeSet, GoogleWatchChannel, GuestPolicy, MeetingCopy,OccurrenceException, OccurrenceListing, OccurrenceRange, OwnedInbox, ProviderCalendar,StoredGoogleCalendar, TeamOutOfOffice, ViewerCapabilities, VisibleCalendar,is_system_calendar,@@ -1479,6 +1479,64 @@ impl CalendarRepository for PgCalendarRepository {rows.into_iter().map(mention_preview_from_row).collect()}+ #[tracing::instrument(skip(self, requester_id), err)]+ async fn meeting_copies(+ &self,+ requester_id: &str,+ event_id: Uuid,+ ) -> Result<Vec<MeetingCopy>, Report> {+ // The copy's own inbox decides how the requester holds it, as it+ // decides their capabilities and the mention preview's `isOwned`.+ let rows = sqlx::query!(+ r#"+ SELECT+ candidate.id AS "event_id!",+ copy_inbox.email_address AS "inbox!",+ COALESCE(+ lower(copy_inbox.email_address) = lower(candidate.organizer_email)+ OR EXISTS (+ SELECT 1+ FROM calendar_event_attendees organizer+ WHERE organizer.event_id = candidate.id+ AND organizer.is_organizer+ AND lower(organizer.email) = lower(copy_inbox.email_address)+ ),+ false+ ) AS "organizes!",+ EXISTS (+ SELECT 1+ FROM calendar_event_attendees guest+ WHERE guest.event_id = candidate.id+ AND lower(guest.email) = lower(copy_inbox.email_address)+ ) AS "attends!"+ FROM calendar_events addressed+ JOIN calendar_events candidate+ ON candidate.ical_uid = addressed.ical_uid+ JOIN email_links copy_inbox+ ON copy_inbox.id = candidate.source_link_id+ AND copy_inbox.macro_id = $1+ WHERE addressed.id = $2+ AND candidate.owner_id = $1+ AND candidate.status <> 'cancelled'+ ORDER BY lower(copy_inbox.email_address), candidate.id+ "#,+ requester_id,+ event_id,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(report)?;+ Ok(rows+ .into_iter()+ .map(|row| MeetingCopy {+ event_id: row.event_id,+ inbox: row.inbox,+ organizes: row.organizes,+ attends: row.attends,+ })+ .collect())+ }+#[tracing::instrument(skip(self, requester_id), err)]async fn event_export(&self,diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex 61429f4ed6..d047f73bcf 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -7261,6 +7261,7 @@ mod details;mod export;mod invitations;mod join_requests;+mod meeting_copies;#[cfg(feature = "notes")]mod notes;mod source_access;diff --git a/crates/calendar_events/src/outbound/pg/test/meeting_copies.rs b/crates/calendar_events/src/outbound/pg/test/meeting_copies.rsnew file mode 100644index 0000000000..b62e0bb173--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/meeting_copies.rs@@ -0,0 +1,133 @@+use super::*;++async fn link_email(pool: &PgPool, link_id: Uuid) -> String {+ sqlx::query_scalar!(+ "SELECT email_address FROM email_links WHERE id = $1",+ link_id+ )+ .fetch_one(pool)+ .await+ .unwrap()+}++/// One meeting copied into each inbox it reaches: `organizer` organizes it+/// and `guest` is invited.+fn meeting_copy(+ owner_id: &str,+ link_id: Uuid,+ provider: (Uuid, Uuid),+ organizer: &str,+ guest: &str,+) -> CalendarEventUpsert {+ let mut copy = timed_upsert(+ owner_id,+ link_id,+ provider,+ "[email protected]",+ "Weekly sync",+ 1,+ );+ copy.event.organizer_email = Some(organizer.to_string());+ copy.event.attendees[0].email = guest.to_string();+ copy+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn meeting_copies_list_each_of_the_requesters_inboxes(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let other_id = "macro|[email protected]";+ let organizing_link = insert_link(&pool, owner_id).await;+ let invited_link = insert_link(&pool, owner_id).await;+ let cancelled_link = insert_link(&pool, owner_id).await;+ let other_link = insert_link(&pool, other_id).await;+ let organizing_inbox = link_email(&pool, organizing_link).await;+ let invited_inbox = link_email(&pool, invited_link).await;+ let repo = PgCalendarRepository::new(pool.clone());++ let organized = meeting_copy(+ owner_id,+ organizing_link,+ provider_ids(&repo, organizing_link).await,+ &organizing_inbox,+ &invited_inbox,+ );+ let organized_id = organized.event.id;+ repo.upsert_event_fixture(organized).await.unwrap();+ let invited = meeting_copy(+ owner_id,+ invited_link,+ provider_ids(&repo, invited_link).await,+ &organizing_inbox,+ &invited_inbox,+ );+ let invited_id = invited.event.id;+ repo.upsert_event_fixture(invited).await.unwrap();+ let mut cancelled = meeting_copy(+ owner_id,+ cancelled_link,+ provider_ids(&repo, cancelled_link).await,+ &organizing_inbox,+ &invited_inbox,+ );+ cancelled.event.status = EventStatus::Cancelled;+ repo.upsert_event_fixture(cancelled).await.unwrap();+ let others = meeting_copy(+ other_id,+ other_link,+ provider_ids(&repo, other_link).await,+ &organizing_inbox,+ &invited_inbox,+ );+ let others_id = others.event.id;+ repo.upsert_event_fixture(others).await.unwrap();+ let unrelated = timed_upsert(+ owner_id,+ organizing_link,+ provider_ids(&repo, organizing_link).await,+ "[email protected]",+ "Something else",+ 1,+ );+ repo.upsert_event_fixture(unrelated).await.unwrap();++ let mut expected = vec![+ MeetingCopy {+ event_id: organized_id,+ inbox: organizing_inbox.clone(),+ organizes: true,+ attends: false,+ },+ MeetingCopy {+ event_id: invited_id,+ inbox: invited_inbox.clone(),+ organizes: false,+ attends: true,+ },+ ];+ expected.sort_by_key(|copy| copy.inbox.to_lowercase());+ // The cancelled copy, the other user's copy and the unrelated meeting+ // are left out, whichever copy the lookup starts from.+ assert_eq!(+ repo.meeting_copies(owner_id, invited_id).await.unwrap(),+ expected+ );+ assert_eq!(+ repo.meeting_copies(owner_id, others_id).await.unwrap(),+ expected+ );+ assert_eq!(+ repo.meeting_copies(other_id, organized_id)+ .await+ .unwrap()+ .into_iter()+ .map(|copy| copy.event_id)+ .collect::<Vec<_>>(),+ vec![others_id]+ );+ assert!(+ repo.meeting_copies(owner_id, Uuid::now_v7())+ .await+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/complete_graph/src/schema/test/calendar.rs b/crates/complete_graph/src/schema/test/calendar.rsindex 2e57d6b261..8c2b7c1e8f 100644--- a/crates/complete_graph/src/schema/test/calendar.rs+++ b/crates/complete_graph/src/schema/test/calendar.rs@@ -134,6 +134,14 @@ impl CalendarOccurrenceService for RecordingCalendarReads {unreachable!("not part of the calendar user fields")}+ async fn meeting_copies(+ &self,+ _requester_id: &str,+ _event_id: uuid::Uuid,+ ) -> Result<Vec<calendar_events::domain::models::MeetingCopy>, Report> {+ unreachable!("no GraphQL read lists a meeting's copies")+ }+async fn event_ics(&self,_requester_id: &str,diff --git a/crates/graphql_calendar/src/user_query/test.rs b/crates/graphql_calendar/src/user_query/test.rsindex ff8e18c135..2f8663a0b6 100644--- a/crates/graphql_calendar/src/user_query/test.rs+++ b/crates/graphql_calendar/src/user_query/test.rs@@ -115,6 +115,14 @@ impl CalendarOccurrenceService for FakeReads {unreachable!("calendar GraphQL reads never resolve the primary time zone")}+ async fn meeting_copies(+ &self,+ _requester_id: &str,+ _event_id: uuid::Uuid,+ ) -> Result<Vec<calendar_events::domain::models::MeetingCopy>, Report> {+ unreachable!("no GraphQL read lists a meeting's copies")+ }+async fn event_ics(&self,_requester_id: &str,