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): name the inbox and role of each event copy in agent tool results (#8683)
gbirman32690463b1f0
diff --git a/apps/docs/AI/mcp/tools/list-calendar-events.mdx b/apps/docs/AI/mcp/tools/list-calendar-events.mdxindex b3653db9b8..0aa7359518 100644--- a/apps/docs/AI/mcp/tools/list-calendar-events.mdx+++ b/apps/docs/AI/mcp/tools/list-calendar-events.mdx@@ -11,6 +11,8 @@ List the user's calendar events between two instants, across every calendar theyUse this to answer questions about the user's schedule ("what's on my calendar tomorrow?"), to find an event the user wants changed or removed, and to check for conflicts before creating an event. Keep the window as narrow as the request allows — a day or a week — since wide windows truncate at 200 occurrences. The window must be at most 370 days and within one year past to two years future. If `syncStatus` is `syncing`, tell the user results may still be incomplete.+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.+## Parameters| Parameter | Type | Required | Description |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 1db394adb6..c3aedd507c 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@@ -2274,6 +2274,32 @@ export const UserToolResponseForToolCalendarEvent = zmacroCallUrl: z.union([z.string(), z.null()]).optional(),isReadOnly: z.boolean(),calendarId: z.union([z.string().uuid(), z.null()]).optional(),+ calendarName: z.union([z.string(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),+ myRole: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('organizer'), z.literal('guest')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),}),}).strict(),@@ -2501,6 +2527,31 @@ export const ToolCalendarEvent = z.object({macroCallUrl: z.union([z.string(), z.null()]).optional(),isReadOnly: z.boolean(),calendarId: z.union([z.string().uuid(), z.null()]).optional(),+ calendarName: z.union([z.string(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),+ myRole: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('organizer'), z.literal('guest')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),});export const CreateContact = z.object({@@ -9514,10 +9565,38 @@ export const ListCalendarEventsResponse = z.object({organize: z.boolean(),}),calendarId: z.union([z.string().uuid(), z.null()]).optional(),+ calendarName: z.union([z.string(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),+ myRole: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('organizer'), z.literal('guest')];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),copies: z.array(z.object({calendarId: z.string().uuid(),+ calendarName: z.union([z.string(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),title: z.string(),isReadOnly: z.boolean(),})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 1443ca63f9..fa557be68a 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@@ -426,6 +426,10 @@ export type UserToolResponseForToolCalendarEvent =| {UserAction: ToolCalendarEvent;};+/**+ * What the user is on one copy of an event, through the inbox holding it.+ */+export type ToolEventRole = 'organizer' | 'guest';/*** Channel types an agent may create.*/@@ -7017,6 +7021,19 @@ export interface ToolCalendarEvent {* Calendar the event belongs to, when known.*/calendarId?: string | null;+ /**+ * Display name of that calendar, when known.+ */+ calendarName?: string | null;+ /**+ * Connected inbox address the calendar belongs to, when known.+ */+ inbox?: string | null;+ /**+ * Whether the user organizes this event or is a guest on it, through+ * that inbox; absent when they are neither.+ */+ myRole?: ToolEventRole | null;}/*** An attendee of a calendar event, as returned by calendar tools.@@ -10784,6 +10801,8 @@ export interface ListBotsResponse {* List the user's calendar events between two instants, across every calendar they have connected. Returns one entry per occurrence (a recurring event appears once per instance in the window), soonest first, with the `eventId` needed by UpdateCalendarEvent and DeleteCalendarEvent.** Use this to answer questions about the user's schedule ("what's on my calendar tomorrow?"), to find an event the user wants changed or removed, and to check for conflicts before creating an event. Keep the window as narrow as the request allows — a day or a week — since wide windows truncate at 200 occurrences. The window must be at most 370 days and within one year past to two years future. If `syncStatus` is `syncing`, tell the user results may still be incomplete.+ *+ * 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.*/export interface ListCalendarEvents {/**@@ -10905,6 +10924,21 @@ export interface CalendarEventListItem {* Calendar the event belongs to, when known.*/calendarId?: string | null;+ /**+ * Display name of that calendar, when known.+ */+ calendarName?: string | null;+ /**+ * Connected inbox address holding this copy of the event. A meeting on+ * several of the user's inboxes is listed once per inbox, each with its+ * own `eventId`.+ */+ inbox?: string | null;+ /**+ * Whether the user organizes this event or is a guest on it, through+ * `inbox`; absent when they are neither.+ */+ myRole?: ToolEventRole | null;/*** Every calendar carrying a copy of this event when there is more than* one, primary first. Pass a copy's `calendarId` to UpdateCalendarEvent@@ -10950,6 +10984,14 @@ export interface CalendarEventCopyItem {* Calendar holding this copy.*/calendarId: string;+ /**+ * Display name of that calendar, when known.+ */+ calendarName?: string | null;+ /**+ * Connected inbox address the calendar belongs to, when known.+ */+ inbox?: string | null;/*** The copy's own title.*/diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 6ab1c74816..8e5082b250 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -136,6 +136,9 @@ reminder dispatch, team availability, and provider/Postgres persistence.canonical copy's values) and in each source's projection, omitted there whileit holds Google's default. Event responses always carry both;`StoredSourceProjection` strips them so unchanged events keep comparing equal.+ Since one meeting on two inboxes is two entities, the agent tools label every+ event they return with its calendar's name, its `inbox` and the user's+ `myRole` there (`ToolEventRole::of`), so the agent can ask or pick by inbox.- Preserve the conservative OOO refresh hint on write outcomes and sync reports;its contract is in [team sharing](../../docs/design/calendar-team-sharing.md).diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rsindex df79de4c88..c39ecb265c 100644--- a/crates/calendar_events/src/inbound/toolset.rs+++ b/crates/calendar_events/src/inbound/toolset.rs@@ -15,6 +15,7 @@ mod update_calendar_event;#[cfg(test)]mod test;+use std::collections::HashMap;use std::sync::Arc;use ai_toolset::{AsyncToolCollection, ToolCallError};@@ -22,12 +23,13 @@ use chrono::NaiveDate;use chrono::{DateTime, Utc};use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use uuid::Uuid;use crate::domain::{meeting_links::{CreateEventWithMacroCallError, EventWithMacroCall, MeetingLinkError},models::{CalendarAttendeeInput, CalendarEvent, EventReminderOverride, EventReminders, EventTime,- OutOfOfficeAutoDeclineMode, OutOfOfficeProperties,+ OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, VisibleCalendar,},ports::{CalendarMutationError, CalendarMutationService, CalendarOccurrenceService,@@ -369,6 +371,89 @@ pub struct ToolCalendarEvent {pub is_read_only: bool,/// Calendar the event belongs to, when known.pub calendar_id: Option<uuid::Uuid>,+ /// Display name of that calendar, when known.+ pub calendar_name: Option<String>,+ /// Connected inbox address the calendar belongs to, when known.+ pub inbox: Option<String>,+ /// Whether the user organizes this event or is a guest on it, through+ /// that inbox; absent when they are neither.+ pub my_role: Option<ToolEventRole>,+}++/// What the user is on one copy of an event, through the inbox holding it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ToolEventRole {+ /// The inbox organizes the event, or the event has no guests and is the+ /// user's own.+ Organizer,+ /// The inbox is invited to the event.+ Guest,+}++impl ToolEventRole {+ /// The role of the copy's inbox, read the way clients read it: `organize`+ /// marks the organizer, and only the copy's own inbox row is `is_self`.+ fn of(event: &CalendarEvent) -> Option<Self> {+ let own_row = event.attendees.iter().find(|attendee| attendee.is_self);+ if event.viewer_can.organize || own_row.is_some_and(|attendee| attendee.is_organizer) {+ Some(Self::Organizer)+ } else {+ own_row.map(|_| Self::Guest)+ }+ }+}++/// The calendars the user can see, to name the calendar and inbox each+/// event copy belongs to.+#[derive(Default)]+struct CalendarLabels {+ by_calendar: HashMap<Uuid, VisibleCalendar>,+ inbox_by_link: HashMap<Uuid, String>,+}++impl CalendarLabels {+ /// Load the requester's visible calendars. Labels only describe a result,+ /// so a failure leaves them out rather than failing a call whose change+ /// may already have reached the provider.+ async fn load<M: CalendarMutationService>(mutations: &M, requester_id: &str) -> Self {+ let Ok(calendars) = mutations+ .list_visible_calendars(requester_id)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "failed to load calendar names for a tool result");+ })+ else {+ return Self::default();+ };+ let inbox_by_link = calendars+ .iter()+ .map(|calendar| (calendar.email_link_id, calendar.email_address.clone()))+ .collect();+ let by_calendar = calendars+ .into_iter()+ .map(|calendar| (calendar.id, calendar))+ .collect();+ Self {+ by_calendar,+ inbox_by_link,+ }+ }++ fn calendar_name(&self, calendar_id: Option<Uuid>) -> Option<String> {+ calendar_id+ .and_then(|id| self.by_calendar.get(&id))+ .map(|calendar| calendar.name.clone())+ }++ /// The inbox holding a copy: its calendar's inbox, else the inbox whose+ /// grant backs it.+ fn inbox(&self, calendar_id: Option<Uuid>, link_id: Option<Uuid>) -> Option<String> {+ calendar_id+ .and_then(|id| self.by_calendar.get(&id))+ .map(|calendar| calendar.email_address.clone())+ .or_else(|| link_id.and_then(|id| self.inbox_by_link.get(&id)).cloned())+ }}const DESCRIPTION_PREVIEW_CHARS: usize = 280;@@ -410,7 +495,7 @@ fn time_fields(time: &EventTime) -> (String, String, bool, Option<String>) {}impl ToolCalendarEvent {- fn from_event(event: &CalendarEvent) -> Self {+ fn from_event(event: &CalendarEvent, labels: &CalendarLabels) -> Self {let (start, end, is_all_day, time_zone) = time_fields(&event.time);Self {event_id: event.id,@@ -441,13 +526,16 @@ impl ToolCalendarEvent {macro_call_url: None,is_read_only: event.is_read_only,calendar_id: event.calendar_id,+ calendar_name: labels.calendar_name(event.calendar_id),+ inbox: labels.inbox(event.calendar_id, None),+ my_role: ToolEventRole::of(event),}}- fn from_event_with_macro_call(created: &EventWithMacroCall) -> Self {+ fn from_event_with_macro_call(created: &EventWithMacroCall, labels: &CalendarLabels) -> Self {Self {macro_call_url: Some(created.meeting_link.url.clone()),- ..Self::from_event(&created.event)+ ..Self::from_event(&created.event, labels)}}}diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rsindex 5db1877430..8f6e8f6224 100644--- a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs@@ -10,9 +10,9 @@ use schemars::JsonSchema;use serde::Deserialize;use super::{- AttendeeInput, CalendarEventTypeInput, CalendarToolContext, EventRemindersInput,- EventTimeInput, OutOfOfficeInput, ToolCalendarEvent, macro_call_create_tool_error,- mutation_tool_error,+ AttendeeInput, CalendarEventTypeInput, CalendarLabels, CalendarToolContext,+ EventRemindersInput, EventTimeInput, OutOfOfficeInput, ToolCalendarEvent,+ macro_call_create_tool_error, mutation_tool_error,};use crate::domain::{meeting_links::create_event_with_macro_call,@@ -243,7 +243,10 @@ where).await.map_err(macro_call_create_tool_error)?;- return Ok(ToolCalendarEvent::from_event_with_macro_call(&created));+ let labels = CalendarLabels::load(&*service_context.mutations, &requester_id).await;+ return Ok(ToolCalendarEvent::from_event_with_macro_call(+ &created, &labels,+ ));}let event = service_context@@ -252,6 +255,7 @@ where.await.map_err(|error| mutation_tool_error("create the calendar event", error))?;- Ok(ToolCalendarEvent::from_event(&event))+ let labels = CalendarLabels::load(&*service_context.mutations, &requester_id).await;+ Ok(ToolCalendarEvent::from_event(&event, &labels))}}diff --git a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rsindex 8a24549646..61035864ff 100644--- a/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs+++ b/crates/calendar_events/src/inbound/toolset/list_calendar_events.rs@@ -4,17 +4,23 @@ use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,ToolResult,};+use std::collections::{HashMap, HashSet};+use async_trait::async_trait;use chrono::{DateTime, Utc};use rootcause::compat::boxed_error::IntoBoxedError;use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use uuid::Uuid;-use super::{CalendarToolContext, ToolEventAttendee, description_preview, time_fields};+use super::{+ CalendarLabels, CalendarToolContext, ToolEventAttendee, ToolEventRole, description_preview,+ time_fields,+};use crate::domain::{models::{- CalendarOccurrenceCursor, CalendarSyncStatus, OccurrenceListing, OccurrenceRange,- ViewerCapabilities,+ CalendarEvent, CalendarOccurrence, CalendarOccurrenceCursor, CalendarSyncStatus,+ OccurrenceRange, ViewerCapabilities,},ports::{CalendarMutationService, CalendarOccurrenceService, MeetingLinkProvider},service::CalendarValidationError,@@ -80,6 +86,15 @@ pub struct CalendarEventListItem {pub viewer_can: ViewerCapabilities,/// Calendar the event belongs to, when known.pub calendar_id: Option<uuid::Uuid>,+ /// Display name of that calendar, when known.+ pub calendar_name: Option<String>,+ /// Connected inbox address holding this copy of the event. A meeting on+ /// several of the user's inboxes is listed once per inbox, each with its+ /// own `eventId`.+ pub inbox: Option<String>,+ /// Whether the user organizes this event or is a guest on it, through+ /// `inbox`; absent when they are neither.+ pub my_role: Option<ToolEventRole>,/// Every calendar carrying a copy of this event when there is more than/// one, primary first. Pass a copy's `calendarId` to UpdateCalendarEvent/// or DeleteCalendarEvent to address that copy instead of the primary.@@ -93,6 +108,10 @@ pub struct CalendarEventListItem {pub struct CalendarEventCopyItem {/// Calendar holding this copy.pub calendar_id: uuid::Uuid,+ /// Display name of that calendar, when known.+ pub calendar_name: Option<String>,+ /// Connected inbox address the calendar belongs to, when known.+ pub inbox: Option<String>,/// The copy's own title.pub title: String,/// Whether that calendar prohibits modifying the copy.@@ -131,7 +150,14 @@ tomorrow?\"), to find an event the user wants changed or removed, and to check fbefore creating an event. Keep the window as narrow as the request allows — a day or a week \— since wide windows truncate at 200 occurrences. The window must be at most 370 days and \within one year past to two years future. If `syncStatus` is `syncing`, tell the user \-results may still be incomplete."+results may still be incomplete.\n\+\n\+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.")]pub struct ListCalendarEvents {/// Inclusive window start.@@ -196,7 +222,11 @@ whereoccurrences.extend(rows.into_iter().filter(|listing| !listing.occurrence.is_cancelled)- .map(OccurrenceListing::into_occurrence_event),+ .map(|listing| {+ let link_id = listing.link_id;+ let (event, occurrence) = listing.into_occurrence_event();+ (event, occurrence, link_id)+ }),);if !full_page {exhausted = true;@@ -218,9 +248,11 @@ whereinternal_error: anyhow::Error::from_boxed(error.into_boxed_error()),})?;+ let multi_inbox_meetings = multi_inbox_meetings(&occurrences);+ let labels = CalendarLabels::load(&*service_context.mutations, &requester_id).await;let events: Vec<CalendarEventListItem> = occurrences.into_iter()- .map(|(event, occurrence)| {+ .map(|(event, occurrence, link_id)| {let (start, end, is_all_day, time_zone) = time_fields(&occurrence.time);let is_recurring = !event.recurrence_lines.is_empty();CalendarEventListItem {@@ -259,12 +291,17 @@ whereis_read_only: event.is_read_only,viewer_can: event.viewer_can,calendar_id: event.calendar_id,+ calendar_name: labels.calendar_name(event.calendar_id),+ inbox: labels.inbox(event.calendar_id, Some(link_id)),+ my_role: ToolEventRole::of(&event),copies: if event.sources.len() > 1 {event.sources.iter().map(|copy| CalendarEventCopyItem {calendar_id: copy.calendar_id,+ calendar_name: labels.calendar_name(Some(copy.calendar_id)),+ inbox: labels.inbox(Some(copy.calendar_id), None),title: copy.title.clone(),is_read_only: copy.is_read_only,})@@ -281,7 +318,7 @@ whereCalendarSyncStatus::Ready => "ready",}.to_string();- let summary = build_summary(events.len(), truncated, &sync_status);+ let summary = build_summary(events.len(), truncated, &sync_status, multi_inbox_meetings);Ok(ListCalendarEventsResponse {events,@@ -323,12 +360,42 @@ fn end_date_bound(end: DateTime<Utc>) -> chrono::NaiveDate {}}-fn build_summary(count: usize, truncated: bool, sync_status: &str) -> String {+/// How many occurrences in the result are one meeting held by more than one+/// of the user's inboxes: the same iCalendar UID at the same time under+/// different event ids.+fn multi_inbox_meetings(occurrences: &[(CalendarEvent, CalendarOccurrence, Uuid)]) -> usize {+ let mut copies: HashMap<(&str, &str), HashSet<Uuid>> = HashMap::new();+ for (event, occurrence, _) in occurrences {+ copies+ .entry((event.ical_uid.as_str(), occurrence.occurrence_key.as_str()))+ .or_default()+ .insert(event.id);+ }+ copies.values().filter(|events| events.len() > 1).count()+}++fn build_summary(+ count: usize,+ truncated: bool,+ sync_status: &str,+ multi_inbox_meetings: usize,+) -> String {let mut summary = match count {0 => "No calendar events in this window.".to_string(),1 => "Found 1 calendar event.".to_string(),count => format!("Found {count} calendar events."),};+ match multi_inbox_meetings {+ 0 => {}+ 1 => summary.push_str(+ " 1 meeting is on more than one of the user's inboxes; tell its entries apart by \+ `inbox` and `myRole`.",+ ),+ meetings => summary.push_str(&format!(+ " {meetings} meetings are on more than one of the user's inboxes; tell their entries \+ apart by `inbox` and `myRole`."+ )),+ }if truncated {summary.push_str(" More exist — narrow the window to see the rest.");}diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rsindex 64c107e20b..24b267dd98 100644--- a/crates/calendar_events/src/inbound/toolset/test.rs+++ b/crates/calendar_events/src/inbound/toolset/test.rs@@ -1444,3 +1444,200 @@ async fn list_calendars_maps_visible_calendars() {assert!(!outlook.capabilities.reset_rsvp);assert_eq!(response.summary, "Found 2 calendars.");}++fn visible_calendar(id: u128, email_link_id: u128, inbox: &str, name: &str) -> VisibleCalendar {+ VisibleCalendar {+ provider: crate::domain::models::CalendarProvider::Google,+ capabilities: crate::domain::models::CalendarCapabilities::google(),+ id: Uuid::from_u128(id),+ email_link_id: Uuid::from_u128(email_link_id),+ email_address: inbox.to_string(),+ name: name.to_string(),+ color: None,+ is_primary: true,+ is_writable: true,+ is_subscription: false,+ sync_error: None,+ default_reminders: Vec::new(),+ }+}++/// One meeting synced through two of the user's inboxes is two entities;+/// each entry has to say which inbox holds it and what the user is there,+/// so the agent can ask by inbox instead of by id.+#[tokio::test]+async fn list_events_names_the_inbox_and_role_of_each_copy() {+ let mut organized = sample_event(Vec::new());+ organized.viewer_can = ViewerCapabilities {+ organize: true,+ ..ViewerCapabilities::NONE+ };+ let mut invited = sample_event(Vec::new());+ invited.id = Uuid::from_u128(8);+ invited.calendar_id = Some(Uuid::from_u128(10));+ invited.attendees[0].is_self = false;+ invited.attendees.push(CalendarAttendee {+ email: "[email protected]".to_string(),+ display_name: None,+ response_status: AttendeeResponseStatus::NeedsAction,+ is_organizer: false,+ is_optional: false,+ is_self: true,+ comment: None,+ });+ invited.viewer_can = ViewerCapabilities {+ rsvp: true,+ invite_guests: true,+ ..ViewerCapabilities::NONE+ };+ let mutations = MockMutations {+ calendars: Mutex::new(vec![+ visible_calendar(9, 1, "[email protected]", "Owner"),+ visible_calendar(10, 2, "[email protected]", "Second"),+ ]),+ ..Default::default()+ };+ let occurrences = MockOccurrences {+ rows: Mutex::new(vec![+ (organized.clone(), occurrence_of(&organized, "k-1", false)),+ (invited.clone(), occurrence_of(&invited, "k-1", false)),+ ]),+ status: CalendarSyncStatus::Ready,+ };+ let (_, context) = context(mutations, occurrences);++ let tool = ListCalendarEvents {+ start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 8, 21, 0, 0, 0).unwrap(),+ };+ let response = tool.call(context, request_context()).await.unwrap();++ assert_eq!(response.events.len(), 2);+ let first = &response.events[0];+ assert_eq!(first.inbox.as_deref(), Some("[email protected]"));+ assert_eq!(first.calendar_name.as_deref(), Some("Owner"));+ assert_eq!(first.my_role, Some(ToolEventRole::Organizer));+ let second = &response.events[1];+ assert_eq!(second.event_id, Uuid::from_u128(8));+ assert_eq!(second.inbox.as_deref(), Some("[email protected]"));+ assert_eq!(second.calendar_name.as_deref(), Some("Second"));+ assert_eq!(second.my_role, Some(ToolEventRole::Guest));+ assert!(+ response+ .summary+ .contains("1 meeting is on more than one of the user's inboxes"),+ "summary: {}",+ response.summary+ );+}++#[tokio::test]+async fn list_events_labels_each_calendar_copy_of_one_entity() {+ let mut event = sample_event(Vec::new());+ let copy = |calendar_id: u128, title: &str| crate::domain::models::CalendarEventSourceContent {+ calendar_id: Uuid::from_u128(calendar_id),+ title: title.to_string(),+ description: None,+ location: None,+ event_type: EventType::Default,+ visibility: EventVisibility::Default,+ transparency: EventTransparency::Opaque,+ is_read_only: false,+ reminders: EventReminders::default(),+ creator_email: None,+ creator_name: None,+ };+ event.sources = vec![copy(9, "Standup"), copy(12, "Team standup")];+ let mutations = MockMutations {+ calendars: Mutex::new(vec![+ visible_calendar(9, 1, "[email protected]", "Owner"),+ visible_calendar(12, 1, "[email protected]", "Team"),+ ]),+ ..Default::default()+ };+ let occurrences = MockOccurrences {+ rows: Mutex::new(vec![(event.clone(), occurrence_of(&event, "k-1", false))]),+ status: CalendarSyncStatus::Ready,+ };+ let (_, context) = context(mutations, occurrences);++ let tool = ListCalendarEvents {+ start: Utc.with_ymd_and_hms(2026, 8, 20, 0, 0, 0).unwrap(),+ end: Utc.with_ymd_and_hms(2026, 8, 21, 0, 0, 0).unwrap(),+ };+ let response = tool.call(context, request_context()).await.unwrap();++ let copies = &response.events[0].copies;+ assert_eq!(copies.len(), 2);+ assert_eq!(copies[1].calendar_name.as_deref(), Some("Team"));+ assert_eq!(copies[1].inbox.as_deref(), Some("[email protected]"));+ assert!(+ !response+ .summary+ .contains("more than one of the user's inboxes"),+ "one entity on two calendars of one inbox is not a multi-inbox meeting"+ );+}++#[test]+fn role_follows_the_copy_inbox() {+ let mut event = sample_event(Vec::new());+ assert_eq!(+ ToolEventRole::of(&event),+ Some(ToolEventRole::Organizer),+ "the inbox's own row organizes"+ );++ event.attendees[0].is_self = false;+ assert_eq!(+ ToolEventRole::of(&event),+ None,+ "neither organizer nor guest"+ );++ event.attendees[1].is_self = true;+ assert_eq!(ToolEventRole::of(&event), Some(ToolEventRole::Guest));++ event.attendees.clear();+ event.viewer_can = ViewerCapabilities {+ organize: true,+ ..ViewerCapabilities::NONE+ };+ assert_eq!(+ ToolEventRole::of(&event),+ Some(ToolEventRole::Organizer),+ "an own event without guests"+ );+}++#[tokio::test]+async fn update_result_names_the_copy_it_changed() {+ let mutations = MockMutations {+ calendars: Mutex::new(vec![visible_calendar(9, 1, "[email protected]", "Owner")]),+ ..Default::default()+ };+ let (_, context) = context(mutations, empty_occurrences());++ let tool = UpdateCalendarEvent {+ event_id: Uuid::from_u128(7),+ calendar_id: None,+ scope: UpdateScopeInput::All,+ recurrence_id: None,+ title: Some("Renamed".to_string()),+ description: None,+ location: None,+ time: None,+ attendees: None,+ recurrence_lines: None,+ conference: None,+ reminders: None,+ rsvp: None,+ out_of_office: None,+ guest_policy: None,+ };+ let result = tool.call(context, request_context()).await.unwrap();++ assert_eq!(result.inbox.as_deref(), Some("[email protected]"));+ assert_eq!(result.calendar_name.as_deref(), Some("Owner"));+ assert_eq!(result.my_role, Some(ToolEventRole::Organizer));+}diff --git a/crates/calendar_events/src/inbound/toolset/update_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/update_calendar_event.rsindex 5c00236249..c19b6b9c10 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, CalendarToolContext, EventRemindersInput, EventTimeInput, OutOfOfficeInput,- ToolCalendarEvent, mutation_tool_error,+ AttendeeInput, CalendarLabels, CalendarToolContext, EventRemindersInput, EventTimeInput,+ OutOfOfficeInput, ToolCalendarEvent, mutation_tool_error,};use crate::domain::{models::{AttendeeResponseStatus, CalendarEventPatch, ConferenceChange, GuestPolicy},@@ -384,6 +384,7 @@ where})?,};- Ok(ToolCalendarEvent::from_event(&event))+ let labels = CalendarLabels::load(&*service_context.mutations, &requester_id).await;+ Ok(ToolCalendarEvent::from_event(&event, &labels))}}