Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(calendar): ai chat calendar compose ui (#5796)

dev-rbb234353c1040
diff --git a/apps/docs/AI/mcp/tools/create-calendar-event.mdx b/apps/docs/AI/mcp/tools/create-calendar-event.mdx
index 71d71216ea..6c777a116e 100644
--- a/apps/docs/AI/mcp/tools/create-calendar-event.mdx
+++ b/apps/docs/AI/mcp/tools/create-calendar-event.mdx
@@ -1,11 +1,11 @@
---
title: CreateCalendarEvent
-description: "Create an event on the user's calendar, inviting any listed attendees through Google Calendar. The event is written to Google immediately, so attendees receive invitations the moment it is created — confirm details with the user before creating events with attendees. The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. [\"RRULE:FREQ=WEEKLY;BYDAY=MO\"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected."
+description: "Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call. The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. [\"RRULE:FREQ=WEEKLY;BYDAY=MO\"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected."
---
# CreateCalendarEvent
-Create an event on the user's calendar, inviting any listed attendees through Google Calendar. The event is written to Google immediately, so attendees receive invitations the moment it is created — confirm details with the user before creating events with attendees.
+Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call.
The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected.
@@ -20,4 +20,5 @@ The event lands on the user's primary calendar unless `calendarId` (from ListCal
| `attendees` | AttendeeInput[] | No | Attendees to invite by email. They are notified by Google Calendar as soon as the event is created. Omit for a solo event. |
| `recurrenceLines` | string[] | No | Raw RFC 5545 recurrence lines (RRULE, RDATE, EXDATE), e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO,WE"]. Omit for a one-off event. |
| `calendarId` | string | No | Calendar to create the event on, from ListCalendars. Omit to use the user's primary calendar. |
+| `reminders` | EventRemindersInput | No | Reminder configuration for the event. Omit to use the selected calendar's defaults. |
| `addGoogleMeet` | boolean | No | Attach a freshly generated Google Meet video conference to the event. |
diff --git a/apps/web/src/features/calendar/components/composer/EventForm.tsx b/apps/web/src/features/calendar/components/composer/EventForm.tsx
index cd55144856..3be34ce373 100644
--- a/apps/web/src/features/calendar/components/composer/EventForm.tsx
+++ b/apps/web/src/features/calendar/components/composer/EventForm.tsx
@@ -22,6 +22,8 @@ export interface EventFormProps {
isEdit?: boolean;
disabledFields?: EventEditorDisabledFields;
showRecurringEditNotice?: boolean;
+ /** Disable interaction without presenting the form as an in-flight save. */
+ disabled?: boolean;
pending: boolean;
class?: string;
onCalendarChange?: (calendarId: string, color: string) => void;
@@ -39,11 +41,12 @@ export function EventForm(props: EventFormProps) {
const controller = props.controller;
const state = controller.state;
const isEdit = () => props.isEdit ?? false;
+ const formIsDisabled = () => props.pending || props.disabled === true;
const fieldIsReadOnly = (field: keyof EventEditorDisabledFields) =>
props.disabledFields?.[field] === true;
const fieldIsDisabled = (field: keyof EventEditorDisabledFields) =>
- props.pending || fieldIsReadOnly(field);
+ formIsDisabled() || fieldIsReadOnly(field);
createEffect(() => {
const option = controller.selectedCalendarOption();
@@ -53,7 +56,7 @@ export function EventForm(props: EventFormProps) {
const submit = () => {
const values = controller.submitValues();
- if (!values || props.pending) return;
+ if (!values || formIsDisabled()) return;
props.onSubmit(values);
};
@@ -142,21 +145,21 @@ export function EventForm(props: EventFormProps) {
onChange={(calendarId) =>
controller.setField('calendarId', calendarId)
}
- disabled={props.pending}
+ disabled={formIsDisabled()}
readOnly={fieldIsReadOnly('calendar')}
/>
<EventComposerRecurrencePill
options={controller.recurrenceOptions()}
value={controller.selectedRecurrenceOption()}
onChange={controller.changeRecurrenceChoice}
- disabled={props.pending}
+ disabled={formIsDisabled()}
readOnly={fieldIsReadOnly('recurrence')}
/>
<EventComposerGuestsPill
options={controller.guestOptions}
selected={controller.selectedGuests()}
onChange={controller.setSelectedGuests}
- disabled={props.pending}
+ disabled={formIsDisabled()}
readOnly={fieldIsReadOnly('guests')}
/>
<EventComposerConferencePill
@@ -212,7 +215,7 @@ export function EventForm(props: EventFormProps) {
type="button"
variant="ghost"
class="rounded-lg"
- disabled={props.pending}
+ disabled={formIsDisabled()}
onClick={props.onCancel}
>
Cancel
@@ -222,7 +225,7 @@ export function EventForm(props: EventFormProps) {
variant={controller.canSave() ? 'active' : 'ghost'}
depth={3}
class="rounded-lg border-0"
- disabled={!controller.canSave() || props.pending}
+ disabled={!controller.canSave() || formIsDisabled()}
aria-label={isEdit() ? 'Save' : 'Create event'}
>
<Show
diff --git a/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx b/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx
index 720df11862..ac30be3f5f 100644
--- a/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx
+++ b/apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx
@@ -65,10 +65,11 @@ type RenderItem =
/**
* Tools rendered outside the standard grouped activity chrome own their full
* presentation. The dashboard renders as a full-bleed view, not a tool row.
- * SendEmail suspends the chat on a user-interactive compose UI (send/cancel),
- * so it must stay visible rather than being collapsed inside a tool group.
+ * Deferred user tools suspend the chat on an interactive compose UI, so they
+ * must stay visible rather than being collapsed inside a tool group.
*/
const STANDALONE_TOOLS: ReadonlySet<string> = new Set([
+ 'CreateCalendarEvent',
'DisplayResults',
'SendEmail',
]);
diff --git a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
index 475e8b1437..7b03087328 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/CalendarTools.tsx
@@ -4,8 +4,9 @@ import CalendarPlus from '@phosphor-icons/core/regular/calendar-plus.svg';
import CalendarX from '@phosphor-icons/core/regular/calendar-x.svg';
import type { NamedTool } from '@service-cognition/generated/tools/tool';
import { format, isSameDay, subDays } from 'date-fns';
-import { createSignal, For, Show } from 'solid-js';
+import { createSignal, For, Match, Show, Switch } from 'solid-js';
import { BaseTool } from './BaseTool';
+import { CalendarChatCompose } from './calendar/ChatCompose';
import { Tool } from './Tool';
import { createToolRenderer } from './ToolRenderer';
@@ -14,7 +15,11 @@ type CalendarEventListItem = NamedTool<
'response'
>['data']['events'][number];
-type ToolCalendarEvent = NamedTool<'CreateCalendarEvent', 'response'>['data'];
+type ToolCalendarEvent = NamedTool<'UpdateCalendarEvent', 'response'>['data'];
+type CreateCalendarEventResponse = NamedTool<
+ 'CreateCalendarEvent',
+ 'response'
+>['data'];
type ToolCalendar = NamedTool<
'ListCalendars',
@@ -83,73 +88,130 @@ const EventDetails = (props: { event: ToolCalendarEvent }) => (
</Tool.List>
);
-const mutationRenderer = (
- name: 'CreateCalendarEvent' | 'UpdateCalendarEvent',
- icon: typeof CalendarPlus,
- label: string
-) =>
- createToolRenderer({
- name,
- render: (ctx) => {
- const [isExpanded, setIsExpanded] = createSignal(false);
- const event = () => ctx.response?.data as ToolCalendarEvent | undefined;
- const callLabel = () => {
- const scope = (ctx.tool.data as { scope?: string }).scope;
- return scope === 'this_event' ? `${label} occurrence` : label;
- };
- const title = () => {
- const responseTitle = event()?.title;
- if (responseTitle) return responseTitle;
- const callTitle = (ctx.tool.data as { title?: string | null }).title;
- return callTitle ?? undefined;
- };
+function createdEvent(
+ response: CreateCalendarEventResponse | undefined
+): ToolCalendarEvent | undefined {
+ return typeof response === 'object' &&
+ response !== null &&
+ 'UserAction' in response
+ ? response.UserAction
+ : undefined;
+}
- return (
- <BaseTool
- icon={icon}
- renderContext={ctx.renderContext}
- type="call"
- response={
- event() && isExpanded() ? (
- <EventDetails event={event() as ToolCalendarEvent} />
- ) : undefined
- }
- >
- <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
- <span class="min-w-0 truncate">
- {callLabel()}
- <Show when={title()}>
- {(eventTitle) => (
- <>
- {' '}
- <span class="text-ink">{eventTitle()}</span>
- </>
- )}
- </Show>
- </span>
- <Tool.ResultToggle
- expanded={isExpanded()}
- onToggle={() => setIsExpanded((expanded) => !expanded)}
- showToggle={Boolean(event())}
- status={event() ? 'Done' : undefined}
- />
- </div>
- </BaseTool>
- );
- },
- });
+function CalendarMutationCard(props: {
+ event?: ToolCalendarEvent;
+ icon: typeof CalendarPlus;
+ label: string;
+ renderContext: Parameters<typeof BaseTool>[0]['renderContext'];
+ status?: string;
+ title?: string;
+}) {
+ const [isExpanded, setIsExpanded] = createSignal(false);
+ const title = () => props.event?.title ?? props.title;
-export const createCalendarEventHandler = mutationRenderer(
- 'CreateCalendarEvent',
- CalendarPlus,
- 'Create calendar event'
-);
+ return (
+ <BaseTool
+ icon={props.icon}
+ renderContext={props.renderContext}
+ type="call"
+ response={
+ props.event && isExpanded() ? (
+ <EventDetails event={props.event} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">
+ <span class="min-w-0 truncate">
+ {props.label}
+ <Show when={title()}>
+ {(eventTitle) => (
+ <>
+ {' '}
+ <span class="text-ink">{eventTitle()}</span>
+ </>
+ )}
+ </Show>
+ </span>
+ <Tool.ResultToggle
+ expanded={isExpanded()}
+ onToggle={() => setIsExpanded((expanded) => !expanded)}
+ showToggle={props.event !== undefined}
+ status={props.event ? 'Done' : props.status}
+ />
+ </div>
+ </BaseTool>
+ );
+}
-export const updateCalendarEventHandler = mutationRenderer(
- 'UpdateCalendarEvent',
- CalendarDots,
- 'Update calendar event'
-);
+export const createCalendarEventHandler = createToolRenderer({
+ name: 'CreateCalendarEvent',
+ render: (ctx) => {
+ const response = () => ctx.response?.data;
+ const event = () => createdEvent(response());
+
+ return (
+ <Switch
+ fallback={
+ <CalendarMutationCard
+ icon={CalendarPlus}
+ label="Create calendar event"
+ renderContext={ctx.renderContext}
+ title={ctx.tool.data.title}
+ />
+ }
+ >
+ <Match when={response() === 'PendingUserExecution'}>
+ <CalendarChatCompose
+ chatId={ctx.chat_id}
+ initialData={ctx.tool.data}
+ messageId={ctx.message_id}
+ streamLocked={ctx.renderContext.isStreaming}
+ toolCallId={ctx.tool.id}
+ />
+ </Match>
+ <Match when={response() === 'Rejected'}>
+ <CalendarMutationCard
+ icon={CalendarPlus}
+ label="Create calendar event"
+ renderContext={ctx.renderContext}
+ status="Canceled"
+ title={ctx.tool.data.title}
+ />
+ </Match>
+ <Match when={event()}>
+ {(created) => (
+ <CalendarMutationCard
+ event={created()}
+ icon={CalendarPlus}
+ label="Create calendar event"
+ renderContext={ctx.renderContext}
+ />
+ )}
+ </Match>
+ </Switch>
+ );
+ },
+});
+
+export const updateCalendarEventHandler = createToolRenderer({
+ name: 'UpdateCalendarEvent',
+ render: (ctx) => {
+ const scope = () => ctx.tool.data.scope;
+ return (
+ <CalendarMutationCard
+ event={ctx.response?.data}
+ icon={CalendarDots}
+ label={
+ scope() === 'this_event'
+ ? 'Update calendar event occurrence'
+ : 'Update calendar event'
+ }
+ renderContext={ctx.renderContext}
+ title={ctx.tool.data.title ?? undefined}
+ />
+ );
+ },
+});
export const deleteCalendarEventHandler = createToolRenderer({
name: 'DeleteCalendarEvent',
diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx
new file mode 100644
index 0000000000..99001a7fe0
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx
@@ -0,0 +1,346 @@
+import { createCalendarEventFormController } from '@app/features/calendar/components/composer/create-calendar-event-form-controller';
+import { EventForm } from '@app/features/calendar/components/composer/EventForm';
+import type { EventEditorSubmitValues } from '@app/features/calendar/components/composer/event-form-model';
+import { DEFAULT_CALENDAR_SOURCE } from '@app/features/calendar/types';
+import {
+ calendarDisplayLabel,
+ spansMultipleInboxes,
+} from '@app/features/calendar/utils/calendar-label';
+import { useChatContext } from '@core/component/AI/context';
+import type { AssistantMessagePart } from '@core/component/AI/types';
+import { toast } from '@core/component/Toast/Toast';
+import { recipientEntityMapper, useContacts } from '@core/user';
+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
+import { invalidateCalendarOccurrences } from '@queries/calendar/occurrences';
+import { useChatQuery } from '@queries/chat';
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';
+import { debounce } from '@solid-primitives/scheduled';
+import { Layer } from '@ui';
+import { createMemo, createSignal, onCleanup, Show, Suspense } from 'solid-js';
+import {
+ createCalendarEventToEditorInitialValues,
+ editorSubmitValuesToCreateCalendarEvent,
+} from './event-form-adapter';
+
+type CreateCalendarEventResponse = NamedTool<
+ 'CreateCalendarEvent',
+ 'response'
+>['data'];
+type ToolCalendarEvent = Extract<
+ CreateCalendarEventResponse,
+ { UserAction: unknown }
+>['UserAction'];
+
+type CalendarChatComposeProps = {
+ chatId: string;
+ messageId: string;
+ toolCallId: string;
+ initialData: CreateCalendarEvent;
+ streamLocked?: boolean;
+};
+
+function createdEvent(response: unknown): ToolCalendarEvent | undefined {
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('UserAction' in response) ||
+ typeof response.UserAction !== 'object' ||
+ response.UserAction === null ||
+ !('eventId' in response.UserAction) ||
+ typeof response.UserAction.eventId !== 'string'
+ ) {
+ return undefined;
+ }
+ return response.UserAction as ToolCalendarEvent;
+}
+
+function toolError(response: unknown) {
+ if (
+ typeof response === 'object' &&
+ response !== null &&
+ 'error' in response &&
+ typeof response.error === 'string'
+ ) {
+ return response.error;
+ }
+ return undefined;
+}
+
+function updateToolParts(
+ parts: AssistantMessagePart[],
+ toolCallId: string,
+ response: CreateCalendarEventResponse,
+ args?: CreateCalendarEvent
+) {
+ let changed = false;
+ const nextParts = parts.map((part) => {
+ if (args && part.type === 'toolCall' && part.id === toolCallId) {
+ changed = true;
+ return { ...part, json: args };
+ }
+ if (part.type === 'toolCallResponseJson' && part.id === toolCallId) {
+ changed = true;
+ return { ...part, json: response };
+ }
+ return part;
+ });
+ return changed ? nextParts : parts;
+}
+
+function CalendarChatComposeFallback() {
+ return (
+ <Layer depth={2}>
+ <div
+ role="status"
+ aria-label="Loading calendar editor"
+ aria-busy="true"
+ class="flex min-h-64 animate-pulse flex-col gap-6 rounded-xl border border-edge-muted bg-surface p-4 shadow-sm"
+ >
+ <span class="sr-only">Loading calendar editor</span>
+
+ <div class="flex flex-col gap-4">
+ <div class="flex items-center gap-2">
+ <div class="h-7 w-28 rounded-lg bg-skeleton" />
+ <div class="h-7 w-28 rounded-lg bg-skeleton" />
+ <div class="h-7 w-16 rounded-lg bg-skeleton" />
+ </div>
+ <div class="h-6 w-2/5 rounded-md bg-skeleton" />
+ <div class="h-3 w-3/4 rounded-full bg-skeleton" />
+ </div>
+
+ <div class="flex flex-wrap gap-2">
+ <div class="h-7 w-24 rounded-full bg-skeleton" />
+ <div class="h-7 w-28 rounded-full bg-skeleton" />
+ <div class="h-7 w-20 rounded-full bg-skeleton" />
+ <div class="h-7 w-24 rounded-full bg-skeleton" />
+ </div>
+
+ <div class="mt-auto flex justify-end gap-3">
+ <div class="h-8 w-16 rounded-lg bg-skeleton" />
+ <div class="h-8 w-28 rounded-lg bg-skeleton" />
+ </div>
+ </div>
+ </Layer>
+ );
+}
+
+/** Inline editor for a deferred CreateCalendarEvent tool call. */
+function CalendarChatComposeContent(props: CalendarChatComposeProps) {
+ const chat = useChatContext();
+ const chatQuery = useChatQuery(() => props.chatId);
+ const calendarsQuery = useVisibleCalendarsQuery();
+ const contacts = useContacts();
+ const [operation, setOperation] = createSignal<'create' | 'reject'>();
+
+ const isOwner = () => chatQuery.data?.userAccessLevel === 'owner';
+ const ownerGateDisabled = () => !chatQuery.isSuccess || !isOwner();
+ const showOwnerDisabledMessage = () => chatQuery.isSuccess && !isOwner();
+ const interactionLocked = () =>
+ toolFinalized ||
+ ownerGateDisabled() ||
+ props.streamLocked === true ||
+ operation() !== undefined;
+
+ const guestOptions = createMemo(() =>
+ contacts().map(recipientEntityMapper('user'))
+ );
+ const writableCalendars = createMemo(
+ () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []
+ );
+ const calendarsSpanInboxes = () => spansMultipleInboxes(writableCalendars());
+ const calendarOptions = createMemo(() =>
+ writableCalendars().map((calendar) => ({
+ id: calendar.id,
+ label: calendarDisplayLabel(calendar, calendarsSpanInboxes()),
+ color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,
+ defaultReminders: calendar.defaultReminders,
+ }))
+ );
+
+ let toolFinalized = false;
+ let lastPersistedSnapshot = JSON.stringify(props.initialData);
+ let lastEnqueuedSnapshot = lastPersistedSnapshot;
+ let persistenceQueue = Promise.resolve();
+
+ const controller = createCalendarEventFormController({
+ initialValue: createCalendarEventToEditorInitialValues(props.initialData),
+ calendarOptions,
+ guestOptions,
+ onChange: scheduleUpdate,
+ });
+
+ function currentArgs(values = controller.submitValues()) {
+ return values
+ ? editorSubmitValuesToCreateCalendarEvent(values, props.initialData)
+ : undefined;
+ }
+
+ const debouncedUpdate = debounce(() => void enqueueUpdate(), 150);
+
+ function scheduleUpdate() {
+ if (toolFinalized || interactionLocked()) return;
+ debouncedUpdate();
+ }
+
+ function enqueueUpdate() {
+ if (toolFinalized || operation() !== undefined) return persistenceQueue;
+ const args = currentArgs();
+ if (!args) return persistenceQueue;
+
+ const snapshot = JSON.stringify(args);
+ if (snapshot === lastEnqueuedSnapshot) return persistenceQueue;
+ lastEnqueuedSnapshot = snapshot;
+
+ persistenceQueue = persistenceQueue.then(async () => {
+ if (toolFinalized) return;
+ try {
+ const result =
+ await cognitionApiServiceClient.updateToolCall<'CreateCalendarEvent'>(
+ {
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ args,
+ }
+ );
+ if (result.isOk()) {
+ lastPersistedSnapshot = snapshot;
+ return;
+ }
+ } catch {
+ // Keep the queue usable so a later edit or confirmation can retry.
+ }
+ if (lastEnqueuedSnapshot === snapshot) {
+ lastEnqueuedSnapshot = lastPersistedSnapshot;
+ }
+ toast.failure('Failed to save calendar event changes');
+ });
+
+ return persistenceQueue;
+ }
+
+ function updateLocalResponse(
+ response: CreateCalendarEventResponse,
+ args?: CreateCalendarEvent
+ ) {
+ chat.setMessages((messages) =>
+ messages.map((message) => {
+ if (message.id !== props.messageId || !Array.isArray(message.content)) {
+ return message;
+ }
+ const content = updateToolParts(
+ message.content,
+ props.toolCallId,
+ response,
+ args
+ );
+ return content === message.content ? message : { ...message, content };
+ })
+ );
+ }
+
+ async function handleCreate(values: EventEditorSubmitValues) {
+ if (interactionLocked()) return;
+ setOperation('create');
+ debouncedUpdate.clear();
+ await persistenceQueue;
+
+ const args = currentArgs(values);
+ if (!args) {
+ setOperation(undefined);
+ return;
+ }
+ const result =
+ await cognitionApiServiceClient.callTool<'CreateCalendarEvent'>({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ args,
+ });
+
+ if (result.isErr()) {
+ setOperation(undefined);
+ toast.failure('Failed to create calendar event');
+ return;
+ }
+
+ const event = createdEvent(result.value);
+ if (!event) {
+ setOperation(undefined);
+ toast.failure('Failed to create calendar event', {
+ subtext: toolError(result.value),
+ });
+ return;
+ }
+
+ toolFinalized = true;
+ setOperation(undefined);
+ updateLocalResponse(result.value as CreateCalendarEventResponse, args);
+ void invalidateCalendarOccurrences();
+ toast.success('Calendar event created');
+ }
+
+ async function handleCancel() {
+ if (interactionLocked()) return;
+ setOperation('reject');
+ debouncedUpdate.clear();
+ await persistenceQueue;
+
+ const result = await cognitionApiServiceClient.rejectToolCall({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ });
+ if (result.isErr()) {
+ setOperation(undefined);
+ toast.failure('Failed to cancel calendar event');
+ return;
+ }
+
+ toolFinalized = true;
+ setOperation(undefined);
+ updateLocalResponse('Rejected');
+ }
+
+ onCleanup(() => debouncedUpdate.clear());
+
+ return (
+ <Layer depth={2}>
+ <div class="flex max-h-[32rem] min-h-0 flex-col gap-3 rounded-xl border border-edge-muted bg-surface p-4 text-ink shadow-sm">
+ <Show when={showOwnerDisabledMessage()}>
+ <p class="text-xs text-ink-extra-muted/60">
+ Only the chat owner can create or edit this calendar event.
+ </p>
+ </Show>
+ <Show when={props.streamLocked && !showOwnerDisabledMessage()}>
+ <p class="text-xs text-ink-extra-muted/60">
+ Waiting for the response to finish before this event can be edited.
+ </p>
+ </Show>
+ <EventForm
+ controller={controller}
+ disabled={
+ toolFinalized ||
+ ownerGateDisabled() ||
+ props.streamLocked === true ||
+ operation() === 'reject'
+ }
+ pending={operation() === 'create'}
+ onCancel={() => void handleCancel()}
+ onSubmit={(values) => void handleCreate(values)}
+ />
+ </div>
+ </Layer>
+ );
+}
+
+/** Query-scoped boundary for the deferred calendar editor. */
+export function CalendarChatCompose(props: CalendarChatComposeProps) {
+ return (
+ <Suspense fallback={<CalendarChatComposeFallback />}>
+ <CalendarChatComposeContent {...props} />
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.ts b/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.ts
new file mode 100644
index 0000000000..02a3c61138
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/event-form-adapter.ts
@@ -0,0 +1,132 @@
+import type {
+ EventEditorInitialValues,
+ EventEditorSubmitValues,
+} from '@app/features/calendar/components/composer/event-form-model';
+import type {
+ CreateCalendarEvent,
+ EventTimeInput,
+} from '@service-cognition/generated/tools/types';
+import { format, isValid, parseISO, subDays } from 'date-fns';
+
+const DATE_VALUE = 'yyyy-MM-dd';
+const DATETIME_VALUE = "yyyy-MM-dd'T'HH:mm";
+
+function formatLocalInstant(value: string) {
+ const instant = new Date(value);
+ return isValid(instant) ? format(instant, DATETIME_VALUE) : '';
+}
+
+function inclusiveAllDayEnd(exclusiveEnd: string) {
+ const end = parseISO(exclusiveEnd);
+ return isValid(end) ? format(subDays(end, 1), DATE_VALUE) : exclusiveEnd;
+}
+
+function cloneReminders(
+ reminders: CreateCalendarEvent['reminders']
+): EventEditorInitialValues['reminders'] {
+ if (!reminders) return undefined;
+ return {
+ useDefault: reminders.useDefault,
+ overrides: reminders.overrides?.map((reminder) => ({ ...reminder })),
+ };
+}
+
+/** Convert deferred calendar-tool arguments into values understood by EventForm. */
+export function createCalendarEventToEditorInitialValues(
+ event: CreateCalendarEvent
+): EventEditorInitialValues {
+ const common = {
+ title: event.title,
+ recurrenceLines: [...(event.recurrenceLines ?? [])],
+ calendarId: event.calendarId ?? undefined,
+ guests: (event.attendees ?? [])
+ .map((attendee) => attendee.email)
+ .join(', '),
+ location: event.location ?? '',
+ description: event.description ?? '',
+ conference: event.addGoogleMeet
+ ? ('google_meet' as const)
+ : ('none' as const),
+ reminders: cloneReminders(event.reminders),
+ };
+
+ if (event.time.kind === 'allDay') {
+ return {
+ ...common,
+ allDay: true,
+ start: event.time.startDate,
+ end: inclusiveAllDayEnd(event.time.endDate),
+ };
+ }
+
+ return {
+ ...common,
+ allDay: false,
+ start: formatLocalInstant(event.time.startsAt),
+ end: formatLocalInstant(event.time.endsAt),
+ };
+}
+
+function toolTime(
+ time: EventEditorSubmitValues['time'],
+ original: EventTimeInput
+): EventTimeInput {
+ if (time.kind === 'allDay') {
+ return {
+ kind: 'allDay',
+ startDate: time.startDate,
+ endDate: time.endDate,
+ };
+ }
+
+ return {
+ kind: 'timed',
+ startsAt: time.startsAt,
+ endsAt: time.endsAt,
+ timeZone:
+ original.kind === 'timed'
+ ? (original.timeZone ?? time.timeZone)
+ : time.timeZone,
+ };
+}
+
+function attendees(
+ emails: string[],
+ original: CreateCalendarEvent['attendees']
+): NonNullable<CreateCalendarEvent['attendees']> {
+ const existing = new Map(
+ (original ?? []).map((attendee) => [
+ attendee.email.trim().toLowerCase(),
+ attendee,
+ ])
+ );
+
+ return emails.map((email) => {
+ const previous = existing.get(email.trim().toLowerCase());
+ return previous?.isOptional === undefined
+ ? { email }
+ : { email, isOptional: previous.isOptional };
+ });
+}
+
+/** Merge editable EventForm values back into the deferred tool arguments. */
+export function editorSubmitValuesToCreateCalendarEvent(
+ values: EventEditorSubmitValues,
+ original: CreateCalendarEvent
+): CreateCalendarEvent {
+ return {
+ ...original,
+ title: values.title,
+ time: toolTime(values.time, original.time),
+ description: values.description || undefined,
+ location: values.location || undefined,
+ attendees: attendees(values.guestEmails, original.attendees),
+ recurrenceLines: values.recurrenceLines ?? original.recurrenceLines ?? [],
+ calendarId: values.calendarId,
+ addGoogleMeet:
+ values.conference === undefined
+ ? original.addGoogleMeet
+ : values.conference === 'google_meet',
+ reminders: cloneReminders(values.reminders ?? original.reminders),
+ };
+}
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.ts
index 75fd2519b0..3f41126bfc 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
@@ -685,35 +685,75 @@ export const CreateCalendarEvent = z.object({
.optional(),
recurrenceLines: z.array(z.string()).optional(),
calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+ reminders: z
+ .union([
+ z.object({
+ useDefault: z.boolean(),
+ overrides: z
+ .array(
+ z.object({ method: z.string(), minutes: z.number().int().gte(0) })
+ )
+ .optional(),
+ }),
+ z.null(),
+ ])
+ .optional(),
addGoogleMeet: z.boolean().optional(),
});
-export const ToolCalendarEvent = z.object({
- eventId: z.string().uuid(),
- title: z.string(),
- start: z.string(),
- end: z.string(),
- isAllDay: z.boolean(),
- timeZone: z.union([z.string(), z.null()]).optional(),
- location: z.union([z.string(), z.null()]).optional(),
- description: z.union([z.string(), z.null()]).optional(),
- status: z.string(),
- isRecurring: z.boolean(),
- recurrenceLines: z.array(z.string()),
- attendees: z.array(
- z.object({
- email: z.string(),
- responseStatus: z.string(),
- isOrganizer: z.boolean(),
- isOptional: z.boolean(),
- })
- ),
- attendeeCount: z.number().int().gte(0),
- organizerEmail: z.union([z.string(), z.null()]).optional(),
- conferenceUrl: z.union([z.string(), z.null()]).optional(),
- isReadOnly: z.boolean(),
- calendarId: z.union([z.string().uuid(), z.null()]).optional(),
-});
+export const UserToolResponseForToolCalendarEvent = z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('PendingUserExecution'),
+ z.literal('Rejected'),
+ z
+ .object({
+ UserAction: z.object({
+ eventId: z.string().uuid(),
+ title: z.string(),
+ start: z.string(),
+ end: z.string(),
+ isAllDay: z.boolean(),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ location: z.union([z.string(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ status: z.string(),
+ isRecurring: z.boolean(),
+ recurrenceLines: z.array(z.string()),
+ attendees: z.array(
+ z.object({
+ email: z.string(),
+ responseStatus: z.string(),
+ isOrganizer: z.boolean(),
+ isOptional: z.boolean(),
+ })
+ ),
+ attendeeCount: z.number().int().gte(0),
+ organizerEmail: z.union([z.string(), z.null()]).optional(),
+ conferenceUrl: z.union([z.string(), z.null()]).optional(),
+ isReadOnly: z.boolean(),
+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+ }),
+ })
+ .strict(),
+ ];
+ 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',
+ });
+ }
+ });
export const CreateDocument = z.object({
documentName: z.string(),
@@ -3494,64 +3534,67 @@ export const SendEmail = z.object({
includeSignature: z.union([z.boolean(), z.null()]).optional(),
});
-export const UserToolResponse = z.any().superRefine((x, ctx) => {
- const schemas = [
- z.literal('PendingUserExecution'),
- z.literal('Rejected'),
- z
- .object({
- UserAction: z.any().superRefine((x, ctx) => {
- const schemas = [
- z.literal('userEdited'),
- z
- .object({
- sent: z.object({
- message_id: z.string().uuid(),
- thread_id: z.string().uuid(),
- }),
- })
- .strict(),
- z
- .object({
- convertedToDraft: z.object({ draft_id: z.string().uuid() }),
- })
- .strict(),
- ];
- 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',
- });
- }
- }),
- })
- .strict(),
- ];
- 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',
- });
- }
-});
+export const UserToolResponseForSendEmailResponse = z
+ .any()
+ .superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('PendingUserExecution'),
+ z.literal('Rejected'),
+ z
+ .object({
+ UserAction: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('userEdited'),
+ z
+ .object({
+ sent: z.object({
+ message_id: z.string().uuid(),
+ thread_id: z.string().uuid(),
+ }),
+ })
+ .strict(),
+ z
+ .object({
+ convertedToDraft: z.object({ draft_id: z.string().uuid() }),
+ })
+ .strict(),
+ ];
+ 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',
+ });
+ }
+ }),
+ })
+ .strict(),
+ ];
+ 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',
+ });
+ }
+ });
export const SetEntityProperty = z.object({
entity_id: z.string(),
@@ -3833,6 +3876,33 @@ export const UpdateCalendarEvent = z.object({
.optional(),
});
+export const ToolCalendarEvent = z.object({
+ eventId: z.string().uuid(),
+ title: z.string(),
+ start: z.string(),
+ end: z.string(),
+ isAllDay: z.boolean(),
+ timeZone: z.union([z.string(), z.null()]).optional(),
+ location: z.union([z.string(), z.null()]).optional(),
+ description: z.union([z.string(), z.null()]).optional(),
+ status: z.string(),
+ isRecurring: z.boolean(),
+ recurrenceLines: z.array(z.string()),
+ attendees: z.array(
+ z.object({
+ email: z.string(),
+ responseStatus: z.string(),
+ isOrganizer: z.boolean(),
+ isOptional: z.boolean(),
+ })
+ ),
+ attendeeCount: z.number().int().gte(0),
+ organizerEmail: z.union([z.string(), z.null()]).optional(),
+ conferenceUrl: z.union([z.string(), z.null()]).optional(),
+ isReadOnly: z.boolean(),
+ calendarId: z.union([z.string().uuid(), z.null()]).optional(),
+});
+
export const UpdateReminder = z.object({
reminderId: z.string().uuid(),
description: z.union([z.string(), z.null()]).optional(),
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 47df625683..c2cb315b5e 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -22,7 +22,7 @@ type ToolParserMap = {
};
CreateCalendarEvent: {
call: types.CreateCalendarEvent;
- response: types.ToolCalendarEvent;
+ response: types.UserToolResponseForToolCalendarEvent;
};
CreateDocument: {
call: types.CreateDocument;
@@ -161,7 +161,10 @@ type ToolParserMap = {
call: types.SendChannelMessage;
response: types.SendChannelMessageResponse;
};
- SendEmail: { call: types.SendEmail; response: types.UserToolResponse };
+ SendEmail: {
+ call: types.SendEmail;
+ response: types.UserToolResponseForSendEmailResponse;
+ };
SetEntityProperty: {
call: types.SetEntityProperty;
response: types.SetEntityPropertyResponse;
@@ -199,7 +202,7 @@ const toolParserMap = {
},
CreateCalendarEvent: {
call: schemas.CreateCalendarEvent,
- response: schemas.ToolCalendarEvent,
+ response: schemas.UserToolResponseForToolCalendarEvent,
},
CreateDocument: {
call: schemas.CreateDocument,
@@ -365,7 +368,10 @@ const toolParserMap = {
call: schemas.SendChannelMessage,
response: schemas.SendChannelMessageResponse,
},
- SendEmail: { call: schemas.SendEmail, response: schemas.UserToolResponse },
+ SendEmail: {
+ call: schemas.SendEmail,
+ response: schemas.UserToolResponseForSendEmailResponse,
+ },
SetEntityProperty: {
call: schemas.SetEntityProperty,
response: schemas.SetEntityPropertyResponse,
@@ -414,7 +420,7 @@ type ToolDataMap = {
};
CreateCalendarEvent: {
call: types.CreateCalendarEvent;
- response: types.ToolCalendarEvent;
+ response: types.UserToolResponseForToolCalendarEvent;
};
CreateDocument: {
call: types.CreateDocument;
@@ -553,7 +559,10 @@ type ToolDataMap = {
call: types.SendChannelMessage;
response: types.SendChannelMessageResponse;
};
- SendEmail: { call: types.SendEmail; response: types.UserToolResponse };
+ SendEmail: {
+ call: types.SendEmail;
+ response: types.UserToolResponseForSendEmailResponse;
+ };
SetEntityProperty: {
call: types.SetEntityProperty;
response: types.SetEntityPropertyResponse;
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.ts
index f683b1d783..4248bf8caa 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
@@ -138,6 +138,15 @@ export type EventTimeInput =
endDate: string;
kind: 'allDay';
};
+/**
+ * User tools are pending until a user executes them
+ */
+export type UserToolResponseForToolCalendarEvent =
+ | 'PendingUserExecution'
+ | 'Rejected'
+ | {
+ UserAction: ToolCalendarEvent;
+ };
/**
* External systems items can be imported from.
*/
@@ -540,7 +549,7 @@ export type SearchSkillsMatchType = 'partial' | 'exact';
/**
* User tools are pending until a user executes them
*/
-export type UserToolResponse =
+export type UserToolResponseForSendEmailResponse =
| 'PendingUserExecution'
| 'Rejected'
| {
@@ -1344,7 +1353,7 @@ export interface CrmCompanySearchDomain {
createdAt: string;
}
/**
- * Create an event on the user's calendar, inviting any listed attendees through Google Calendar. The event is written to Google immediately, so attendees receive invitations the moment it is created — confirm details with the user before creating events with attendees.
+ * Prepare an event on the user's calendar, inviting any listed attendees through Google Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and confirm the event; use the tool to present the proposal instead of asking for a redundant confirmation in prose. When the pending call is executed, the event is written to Google immediately and attendees receive invitations. Other clients should confirm attendee events before executing the call.
*
* The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. ["RRULE:FREQ=WEEKLY;BYDAY=MO"]. Returns the created event with its `eventId` for later updates or deletion. Fails if the user has no writable calendar connected.
*/
@@ -1374,6 +1383,10 @@ export interface CreateCalendarEvent {
* Calendar to create the event on, from ListCalendars. Omit to use the user's primary calendar.
*/
calendarId?: string | null;
+ /**
+ * Reminder configuration for the event. Omit to use the selected calendar's defaults.
+ */
+ reminders?: EventRemindersInput | null;
/**
* Attach a freshly generated Google Meet video conference to the event.
*/
@@ -1392,6 +1405,32 @@ export interface AttendeeInput {
*/
isOptional?: boolean;
}
+/**
+ * Reminder configuration supplied when creating a calendar event.
+ */
+export interface EventRemindersInput {
+ /**
+ * Whether the selected calendar's default reminders should apply.
+ */
+ useDefault: boolean;
+ /**
+ * Overrides used when calendar defaults are disabled.
+ */
+ overrides?: EventReminderOverrideInput[];
+}
+/**
+ * One reminder override supplied to a calendar tool.
+ */
+export interface EventReminderOverrideInput {
+ /**
+ * Provider reminder method. `popup` creates a Macro notification.
+ */
+ method: string;
+ /**
+ * Minutes before the event start.
+ */
+ minutes: number;
+}
/**
* A calendar event as returned by the create and update tools.
*/
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 97558927bb..234057c475 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -18,7 +18,7 @@ mod tool_context;
pub use anthropic::toolset::AnthropicToolContext;
use anthropic::toolset::anthropic_toolset;
-use calendar_events::inbound::toolset::calendar_toolset;
+use calendar_events::inbound::toolset::{calendar_toolset, mcp_toolset as calendar_mcp_toolset};
use call::inbound::toolset::call_toolset;
use channels::inbound::toolset::channel_toolset;
use chat::inbound::toolset::chat_toolset;
@@ -132,13 +132,13 @@ pub fn all_tool_frontend_schemas() -> FrontendSchemas {
.build()
}
-/// Toolset for the MCP server — excludes SendEmail.
+/// Toolset for the MCP server — excludes chat-deferred user tools.
pub fn mcp_tools() -> ToolSetWithPrompt {
let toolset = subagent_toolset()
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolRemindersToolContext>(reminders_toolset())
.add_subtoolset::<ToolEmailToolContext>(email_mcp_toolset())
- .add_subtoolset::<ToolCalendarToolContext>(calendar_toolset())
+ .add_subtoolset::<ToolCalendarToolContext>(calendar_mcp_toolset())
.add_subtoolset::<ToolImportToolContext>(import_toolset())
.add_tool::<Subagent, ToolServiceContext>();
let toolset = Arc::new(toolset);
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index f0849d217d..874b258c31 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -43,3 +43,28 @@ fn search_toolset_passes_schema_validation() {
fn frontend_schemas_build() {
let _ = all_tool_frontend_schemas();
}
+
+#[test]
+fn frontend_schemas_distinguish_user_tool_response_types() {
+ let json = all_tool_frontend_schemas()
+ .to_json_pretty()
+ .expect("frontend schemas serialize");
+ let schemas: serde_json::Value = serde_json::from_str(&json).expect("valid schema json");
+ let tools = schemas["tools"].as_array().expect("tools array");
+ let output_for = |name: &str| {
+ tools
+ .iter()
+ .find(|tool| tool["name"] == name)
+ .and_then(|tool| tool["output"].as_str())
+ .expect("tool output schema")
+ };
+
+ assert_eq!(
+ output_for("CreateCalendarEvent"),
+ "UserToolResponseForToolCalendarEvent"
+ );
+ assert_eq!(
+ output_for("SendEmail"),
+ "UserToolResponseForSendEmailResponse"
+ );
+}
diff --git a/crates/ai_toolset/src/toolset/tool_object/user_tool.rs b/crates/ai_toolset/src/toolset/tool_object/user_tool.rs
index 003c37139c..bc1b7196eb 100644
--- a/crates/ai_toolset/src/toolset/tool_object/user_tool.rs
+++ b/crates/ai_toolset/src/toolset/tool_object/user_tool.rs
@@ -33,6 +33,7 @@ impl<T: ToolAnnotated> ToolAnnotated for UserTool<T> {
/// User tools are pending until a user executes them
#[derive(Serialize, Deserialize, JsonSchema, ToSchema, Debug, Clone, PartialEq)]
+#[schemars(rename = "UserToolResponseFor{T}")]
pub enum UserToolResponse<T> {
/// Tool has not yet been executed
PendingUserExecution,
diff --git a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
index bb7aded03c..a8e494e03f 100644
--- a/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
+++ b/crates/calendar_events/src/inbound/toolset/create_calendar_event.rs
@@ -8,7 +8,8 @@ use schemars::JsonSchema;
use serde::Deserialize;
use super::{
- AttendeeInput, CalendarToolContext, EventTimeInput, ToolCalendarEvent, mutation_tool_error,
+ AttendeeInput, CalendarToolContext, EventRemindersInput, EventTimeInput, ToolCalendarEvent,
+ mutation_tool_error,
};
use crate::domain::{
models::{CalendarEventDraft, ConferenceChange},
@@ -21,9 +22,12 @@ use crate::domain::{
#[schemars(
title = "CreateCalendarEvent",
description = "\
-Create an event on the user's calendar, inviting any listed attendees through Google \
-Calendar. The event is written to Google immediately, so attendees receive invitations the \
-moment it is created — confirm details with the user before creating events with attendees.\n\
+Prepare an event on the user's calendar, inviting any listed attendees through Google \
+Calendar. In Macro chat this tool opens an inline composer so the user can review, edit, and \
+confirm the event; use the tool to present the proposal instead of asking for a redundant \
+confirmation in prose. When the pending call is executed, the event is written to Google \
+immediately and attendees receive invitations. Other clients should confirm attendee events \
+before executing the call.\n\
\n\
The event lands on the user's primary calendar unless `calendarId` (from ListCalendars) \
targets another one. For recurring events pass RFC 5545 lines in `recurrenceLines`, e.g. \
@@ -77,6 +81,13 @@ pub struct CreateCalendarEvent {
#[serde(default)]
pub calendar_id: Option<uuid::Uuid>,
+ /// Reminder configuration.
+ #[schemars(
+ description = "Reminder configuration for the event. Omit to use the selected calendar's defaults."
+ )]
+ #[serde(default)]
+ pub reminders: Option<EventRemindersInput>,
+
/// Whether to attach a Google Meet conference.
#[schemars(
description = "Attach a freshly generated Google Meet video conference to the event."
@@ -86,7 +97,8 @@ pub struct CreateCalendarEvent {
}
impl ToolAnnotated for CreateCalendarEvent {
- const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create calendar event");
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::additive("Create calendar event").with_open_world();
}
#[async_trait]
@@ -120,7 +132,7 @@ where
recurrence_lines: self.recurrence_lines.clone(),
visibility: None,
transparency: None,
- reminders: None,
+ reminders: self.reminders.clone().map(Into::into),
conference: self.add_google_meet.then_some(ConferenceChange::GoogleMeet),
};
diff --git a/crates/calendar_events/src/inbound/toolset/mod.rs b/crates/calendar_events/src/inbound/toolset/mod.rs
index 7f6afcbc0e..9795b075a7 100644
--- a/crates/calendar_events/src/inbound/toolset/mod.rs
+++ b/crates/calendar_events/src/inbound/toolset/mod.rs
@@ -23,7 +23,9 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::domain::{
- models::{CalendarAttendeeInput, CalendarEvent, EventTime},
+ models::{
+ CalendarAttendeeInput, CalendarEvent, EventReminderOverride, EventReminders, EventTime,
+ },
ports::{CalendarMutationError, CalendarMutationService, CalendarOccurrenceService},
};
@@ -76,8 +78,7 @@ where
}
}
-/// Create the calendar toolset.
-pub fn calendar_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>
+fn shared_calendar_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>
where
M: CalendarMutationService,
O: CalendarOccurrenceService,
@@ -85,11 +86,34 @@ where
AsyncToolCollection::new()
.add_tool::<ListCalendarEvents, CalendarToolContext<M, O>>()
.add_tool::<ListCalendars, CalendarToolContext<M, O>>()
- .add_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()
.add_tool::<UpdateCalendarEvent, CalendarToolContext<M, O>>()
.add_tool::<DeleteCalendarEvent, CalendarToolContext<M, O>>()
}
+/// Create the AI chat calendar toolset.
+///
+/// Event creation is deferred until the user reviews and executes the pending
+/// call. Reads, updates, and deletions continue to execute in the agent loop.
+pub fn calendar_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ shared_calendar_toolset().add_user_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()
+}
+
+/// Create the MCP calendar toolset.
+///
+/// MCP clients receive the real create tool and apply their own confirmation
+/// policy from its annotations rather than the chat-specific deferred flow.
+pub fn mcp_toolset<M, O>() -> AsyncToolCollection<CalendarToolContext<M, O>>
+where
+ M: CalendarMutationService,
+ O: CalendarOccurrenceService,
+{
+ shared_calendar_toolset().add_tool::<CreateCalendarEvent, CalendarToolContext<M, O>>()
+}
+
/// The mutually exclusive time shape supplied to calendar tools.
#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", tag = "kind")]
@@ -163,6 +187,45 @@ impl From<AttendeeInput> for CalendarAttendeeInput {
}
}
+/// One reminder override supplied to a calendar tool.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EventReminderOverrideInput {
+ /// Provider reminder method. `popup` creates a Macro notification.
+ pub method: String,
+ /// Minutes before the event start.
+ pub minutes: u32,
+}
+
+impl From<EventReminderOverrideInput> for EventReminderOverride {
+ fn from(input: EventReminderOverrideInput) -> Self {
+ Self {
+ method: input.method,
+ minutes: input.minutes,
+ }
+ }
+}
+
+/// Reminder configuration supplied when creating a calendar event.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EventRemindersInput {
+ /// Whether the selected calendar's default reminders should apply.
+ pub use_default: bool,
+ /// Overrides used when calendar defaults are disabled.
+ #[serde(default)]
+ pub overrides: Vec<EventReminderOverrideInput>,
+}
+
+impl From<EventRemindersInput> for EventReminders {
+ fn from(input: EventRemindersInput) -> Self {
+ Self {
+ use_default: input.use_default,
+ overrides: input.overrides.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
/// An attendee of a calendar event, as returned by calendar tools.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/calendar_events/src/inbound/toolset/test.rs b/crates/calendar_events/src/inbound/toolset/test.rs
index c9336fdf98..8d7acaec29 100644
--- a/crates/calendar_events/src/inbound/toolset/test.rs
+++ b/crates/calendar_events/src/inbound/toolset/test.rs
@@ -1,7 +1,7 @@
use std::sync::Mutex;
use ai_toolset::schema::generate_validated_input_schema;
-use ai_toolset::{AsyncTool, RequestContext, ServiceContext};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolSet};
use chrono::{NaiveDate, TimeZone, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
@@ -9,8 +9,9 @@ use uuid::Uuid;
use super::*;
use crate::domain::models::{
AttendeeResponseStatus, CalendarAttendee, CalendarEventDraft, CalendarEventPatch,
- CalendarOccurrence, CalendarSyncStatus, ConferenceChange, EventReminders, EventStatus,
- EventTransparency, EventVisibility, OccurrenceRange, VisibleCalendar,
+ CalendarOccurrence, CalendarSyncStatus, ConferenceChange, EventReminderOverride,
+ EventReminders, EventStatus, EventTransparency, EventVisibility, OccurrenceRange,
+ VisibleCalendar,
};
use crate::domain::ports::{
CalendarDeletionScope, CalendarMutationError, CalendarMutationService,
@@ -274,6 +275,49 @@ fn empty_occurrences() -> MockOccurrences {
}
}
+fn create_tool_args() -> serde_json::Value {
+ serde_json::json!({
+ "title": "Design review",
+ "time": {
+ "kind": "timed",
+ "startsAt": "2026-08-20T17:00:00Z",
+ "endsAt": "2026-08-20T18:00:00Z",
+ "timeZone": "America/New_York"
+ },
+ "attendees": [],
+ "recurrenceLines": [],
+ "addGoogleMeet": false
+ })
+}
+
+#[tokio::test]
+async fn ai_toolset_defers_create_without_mutating_calendar() {
+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());
+ let args = create_tool_args();
+ let pending = calendar_toolset()
+ .try_tool_call(context.0, request_context(), "CreateCalendarEvent", &args)
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(pending, serde_json::json!("PendingUserExecution"));
+ assert!(mutations.created.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn mcp_toolset_executes_create_directly() {
+ let (mutations, context) = context(MockMutations::default(), empty_occurrences());
+ let args = create_tool_args();
+ let event = mcp_toolset()
+ .try_tool_call(context.0, request_context(), "CreateCalendarEvent", &args)
+ .await
+ .unwrap()
+ .unwrap();
+
+ assert_eq!(event["eventId"], Uuid::from_u128(7).to_string());
+ assert_eq!(mutations.created.lock().unwrap().len(), 1);
+}
+
#[tokio::test]
async fn create_converts_input_into_a_domain_draft() {
let (mutations, context) = context(MockMutations::default(), empty_occurrences());
@@ -293,6 +337,13 @@ async fn create_converts_input_into_a_domain_draft() {
}],
recurrence_lines: vec!["RRULE:FREQ=WEEKLY".to_string()],
calendar_id: Some(calendar_id),
+ reminders: Some(EventRemindersInput {
+ use_default: false,
+ overrides: vec![EventReminderOverrideInput {
+ method: "popup".to_string(),
+ minutes: 15,
+ }],
+ }),
add_google_meet: true,
};
let response = tool.call(context, request_context()).await.unwrap();
@@ -310,6 +361,16 @@ async fn create_converts_input_into_a_domain_draft() {
vec!["RRULE:FREQ=WEEKLY".to_string()]
);
assert_eq!(draft.conference, Some(ConferenceChange::GoogleMeet));
+ assert_eq!(
+ draft.reminders,
+ Some(EventReminders {
+ use_default: false,
+ overrides: vec![EventReminderOverride {
+ method: "popup".to_string(),
+ minutes: 15,
+ }],
+ })
+ );
assert!(matches!(draft.time, EventTime::AllDay { .. }));
}
@@ -333,6 +394,7 @@ async fn create_surfaces_missing_calendar_as_an_actionable_error() {
attendees: Vec::new(),
recurrence_lines: Vec::new(),
calendar_id: None,
+ reminders: None,
add_google_meet: false,
};
let error = tool.call(context, request_context()).await.unwrap_err();