Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calendar): finish edits and deletes once the provider accepts them (#8786)
teo8a347e1b28af
diff --git a/apps/web/src/lib/queries/calendar/mutations.ts b/apps/web/src/lib/queries/calendar/mutations.tsindex 0642fab793..04ca13bfa8 100644--- a/apps/web/src/lib/queries/calendar/mutations.ts+++ b/apps/web/src/lib/queries/calendar/mutations.ts@@ -49,6 +49,14 @@ export type {type CalendarMutationContext = { rollback: () => void };+/**+ * Moves when a write starts patching the occurrence viewports. A refresh+ * from an earlier write drops its refetch once this has moved: the server+ * may not have the newer write yet, so the refetch could undo its optimistic+ * patch, and the newer write refreshes the viewports itself once it settles.+ */+let occurrenceWriteRevision = 0;+/*** Optimistically rewrite every cached occurrence viewport (each visible* range is its own cache entry) and return a rollback that restores the@@ -57,6 +65,7 @@ type CalendarMutationContext = { rollback: () => void };async function patchOccurrenceCaches(update: (items: CalendarOccurrenceItem[]) => CalendarOccurrenceItem[]): Promise<CalendarMutationContext> {+ occurrenceWriteRevision += 1;await queryClient.cancelQueries({queryKey: calendarKeys.occurrences._def,});@@ -73,6 +82,21 @@ async function patchOccurrenceCaches(};}+/**+ * Refreshes what a settled write can change without holding the mutation+ * open: the write is done once the provider answers, while a delta sync can+ * queue behind other cache work for many seconds.+ */+function refreshAfterWrite(eventId: string) {+ fireAndForget(invalidateCalendarInvitations(), 'calendar-mutations');+ invalidateCalendarEventPreviews(eventId);+ const revision = occurrenceWriteRevision;+ fireAndForget(+ invalidateCalendarOccurrences(() => revision === occurrenceWriteRevision),+ 'calendar-mutations'+ );+}+function patchEventItems(eventId: string,patch: (item: CalendarOccurrenceItem) => CalendarOccurrenceItem@@ -283,6 +307,7 @@ export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {>({onMutate: async (args) => {+ occurrenceWriteRevision += 1;const revision = ++rsvpRevisionCounter;await queryClient.cancelQueries({queryKey: calendarKeys.occurrences._def,@@ -512,11 +537,7 @@ export function useInviteCalendarEventGuestsMutation()),onError: (_error, _args, context) => context?.rollback(),- onSettled: (_data, _error, args) => {- fireAndForget(invalidateCalendarInvitations(), 'calendar-mutations');- invalidateCalendarEventPreviews(args.eventId);- return invalidateCalendarOccurrences();- },+ onSettled: (_data, _error, args) => refreshAfterWrite(args.eventId),},callbacks),@@ -618,11 +639,13 @@ type DeleteCallbacks = MutationCallbacks<CalendarMutationContext>;-/** Deletes an event (a recurring event's entire series) at the provider. */-export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {- return useMutation(() => ({- mutationFn: async (args: DeleteCalendarEventArgs) => {- const host = answeringGraphqlCalendarHost();+async function deleteCalendarEvent(args: DeleteCalendarEventArgs) {+ return Telemetry.span('calendar.delete_event', async (span) => {+ const host = answeringGraphqlCalendarHost();+ span.setAttr('calendar.event_id', args.eventId);+ span.setAttr('calendar.delete.scope', args.scope ?? 'all');+ span.setAttr('calendar.transport', host ? 'graphql' : 'rest');+ try {if (host) {await executeGraphqlDelete(host, args);return;@@ -634,7 +657,18 @@ export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {recurrenceId: args.recurrenceId,}));- },+ } catch (error) {+ // Provider messages can quote addresses; record only the category.+ span.error('Calendar event delete failed');+ throw error;+ }+ });+}++/** Deletes an event (a recurring event's entire series) at the provider. */+export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {+ return useMutation(() => ({+ mutationFn: deleteCalendarEvent,...withCallbacks<unknown,Error,@@ -645,11 +679,7 @@ export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {onMutate: (args) =>patchOccurrenceCaches((items) => applyDeletion(items, args)),onError: (_error, _args, context) => context?.rollback(),- onSettled: (_data, _error, args) => {- fireAndForget(invalidateCalendarInvitations(), 'calendar-mutations');- invalidateCalendarEventPreviews(args.eventId);- return invalidateCalendarOccurrences();- },+ onSettled: (_data, _error, args) => refreshAfterWrite(args.eventId),},callbacks),@@ -745,16 +775,15 @@ function applyEventPatch(return { ...item, event, occurrence };}-/**- * Patches event fields. A recurring event patches the whole series by- * default; a `this_event` scope writes the patch as a single-occurrence- * exception addressed by `recurrenceId`, so the optimistic update lands on- * that occurrence alone.- */-export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {- return useMutation(() => ({- mutationFn: async (args: UpdateCalendarEventArgs) => {- const host = answeringGraphqlCalendarHost();+async function updateCalendarEvent(+ args: UpdateCalendarEventArgs+): Promise<CalendarEventEntity | undefined> {+ return Telemetry.span('calendar.update_event', async (span) => {+ const host = answeringGraphqlCalendarHost();+ span.setAttr('calendar.event_id', args.eventId);+ span.setAttr('calendar.update.scope', args.scope ?? 'all');+ span.setAttr('calendar.transport', host ? 'graphql' : 'rest');+ try {if (host) return committedEvent(await executeGraphqlUpdate(host, args));return await throwOnErr(() =>emailClient.updateCalendarEvent(args.eventId, {@@ -764,7 +793,23 @@ export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {recurrenceId: args.recurrenceId,}));- },+ } catch (error) {+ // Provider messages can quote addresses; record only the category.+ span.error('Calendar event update failed');+ throw error;+ }+ });+}++/**+ * Patches event fields. A recurring event patches the whole series by+ * default; a `this_event` scope writes the patch as a single-occurrence+ * exception addressed by `recurrenceId`, so the optimistic update lands on+ * that occurrence alone.+ */+export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {+ return useMutation(() => ({+ mutationFn: updateCalendarEvent,...withCallbacks<CalendarEventEntity | undefined,Error,@@ -785,11 +830,7 @@ export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {);},onError: (_error, _args, context) => context?.rollback(),- onSettled: (_data, _error, args) => {- fireAndForget(invalidateCalendarInvitations(), 'calendar-mutations');- invalidateCalendarEventPreviews(args.eventId);- return invalidateCalendarOccurrences();- },+ onSettled: (_data, _error, args) => refreshAfterWrite(args.eventId),},callbacks),diff --git a/apps/web/src/lib/queries/calendar/occurrences.ts b/apps/web/src/lib/queries/calendar/occurrences.tsindex c328dee4c5..fd23d3f77b 100644--- a/apps/web/src/lib/queries/calendar/occurrences.ts+++ b/apps/web/src/lib/queries/calendar/occurrences.ts@@ -247,15 +247,19 @@ export function useCalendarOccurrencesQuery(* Refetches every mounted occurrence viewport. With calendar reads on the* cache, the delta runs first so the viewports see the change that prompted* the refresh rather than the cache from before it. A cache still starting- * would hold the delta, so the viewports refetch without it.+ * would hold the delta, so the viewports refetch without it. The refetch is+ * skipped when `stillCurrent` turns false while the delta runs.*/-export async function invalidateCalendarOccurrences() {+export async function invalidateCalendarOccurrences(+ stillCurrent: () => boolean = () => true+) {const controller = activeCalendarSyncController();if (controller?.answering()) {await controller.runDelta().catch((error) => {console.warn('Calendar delta sync failed', error);});}+ if (!stillCurrent()) return;return queryClient.invalidateQueries({queryKey: calendarKeys.occurrences._def,});diff --git a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsxindex cb4cef573e..899ebc8e50 100644--- a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx+++ b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx@@ -1,10 +1,18 @@import { previewKeys } from '@queries/preview/keys';import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';-import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import {+ QueryClient,+ QueryClientProvider,+ QueryObserver,+} from '@tanstack/solid-query';import { err, ok } from 'neverthrow';import type { JSX } from 'solid-js';import { render } from 'solid-js/web';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ type CalendarSyncController,+ setActiveCalendarSyncController,+} from '../graphql/sync-controller';import { invalidateInvitationScheduling } from '../invitations';import { calendarKeys } from '../keys';import {@@ -196,6 +204,30 @@ function deferredResult() {return { promise, resolve };}+/**+ * Keeps viewport A on screen, so a settled write refetches it, and holds that+ * refetch open until the test answers it.+ */+function watchViewportA() {+ let answer!: (data: CalendarOccurrencesData) => void;+ const refetch = vi.fn(+ () =>+ new Promise<CalendarOccurrencesData>((resolve) => {+ answer = resolve;+ })+ );+ const unsubscribe = new QueryObserver(testQueryClient, {+ queryKey: calendarKeys.occurrences('user', viewportA).queryKey,+ queryFn: refetch,+ staleTime: Number.POSITIVE_INFINITY,+ }).subscribe(() => {});+ return {+ refetch,+ answer: (data: CalendarOccurrencesData) => answer(data),+ unsubscribe,+ };+}+beforeEach(() => {vi.clearAllMocks();testQueryClient = new QueryClient({@@ -207,6 +239,7 @@ beforeEach(() => {afterEach(() => {dispose?.();dispose = undefined;+ setActiveCalendarSyncController(undefined);testQueryClient.clear();});@@ -557,6 +590,27 @@ describe('useDeleteCalendarEventMutation', () => {expect(items.map((item) => item.event.id)).toEqual(['event-1']);});+ it('finishes once the provider deletes the event, before the viewport refetch returns', async () => {+ deleteCalendarEventMock.mockResolvedValue(ok({}));+ const viewport = watchViewportA();+ const remove = renderHook(() => useDeleteCalendarEventMutation());++ const deleted = remove.mutateAsync({ eventId: 'event-1' });+ await vi.waitFor(() => expect(viewport.refetch).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(remove.isSuccess).toBe(true));+ await deleted;+ expect(viewportData(viewportA)?.items.map((item) => item.event.id)).toEqual(+ ['event-2']+ );++ viewport.answer({ items: [recurringItem()], syncStatus: 'ready' });+ await vi.waitFor(() => expect(testQueryClient.isFetching()).toBe(0));+ expect(viewportData(viewportA)?.items.map((item) => item.event.id)).toEqual(+ ['event-2']+ );+ viewport.unsubscribe();+ });+it('restores removed items when the request fails', async () => {deleteCalendarEventMock.mockResolvedValue(failure());const remove = renderHook(() => useDeleteCalendarEventMutation());@@ -646,6 +700,84 @@ describe('useUpdateCalendarEventMutation', () => {});});+ it('finishes a save once the provider accepts it, then shows the refetched event', async () => {+ updateCalendarEventMock.mockResolvedValue(ok({ id: 'event-1' }));+ const viewport = watchViewportA();+ const update = renderHook(() => useUpdateCalendarEventMutation());+ const titleOfEvent1 = () =>+ viewportData(viewportA)?.items.find((item) => item.event.id === 'event-1')+ ?.event.title;++ const saved = update.mutateAsync({+ eventId: 'event-1',+ patch: { title: 'Renamed' },+ });+ await vi.waitFor(() => expect(viewport.refetch).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(update.isSuccess).toBe(true));+ await saved;+ expect(titleOfEvent1()).toBe('Renamed');++ const refetched = standaloneItem();+ refetched.event.title = 'Renamed by the provider';+ viewport.answer({ items: [refetched], syncStatus: 'ready' });+ await vi.waitFor(() =>+ expect(titleOfEvent1()).toBe('Renamed by the provider')+ );+ viewport.unsubscribe();+ });++ it("keeps a newer edit on screen when an earlier save's refresh lands during it", async () => {+ const deltas: Array<() => void> = [];+ setActiveCalendarSyncController({+ answering: () => true,+ runDelta: () =>+ new Promise<void>((resolve) => {+ deltas.push(resolve);+ }),+ } as unknown as CalendarSyncController);+ let serverTitle = 'First';+ const read = vi.fn(async (): Promise<CalendarOccurrencesData> => {+ const item = standaloneItem();+ item.event.title = serverTitle;+ return { items: [item, recurringItem()], syncStatus: 'ready' };+ });+ const unsubscribe = new QueryObserver(testQueryClient, {+ queryKey: calendarKeys.occurrences('user', viewportA).queryKey,+ queryFn: read,+ staleTime: Number.POSITIVE_INFINITY,+ }).subscribe(() => {});+ const second = deferredResult();+ updateCalendarEventMock+ .mockResolvedValueOnce(ok({ id: 'event-1' }))+ .mockReturnValueOnce(second.promise);+ const update = renderHook(() => useUpdateCalendarEventMutation());+ const titleOfEvent1 = () =>+ viewportData(viewportA)?.items.find((item) => item.event.id === 'event-1')+ ?.event.title;++ await update.mutateAsync({ eventId: 'event-1', patch: { title: 'First' } });+ const saving = update.mutateAsync({+ eventId: 'event-1',+ patch: { title: 'Second' },+ });+ await vi.waitFor(() => expect(titleOfEvent1()).toBe('Second'));++ deltas[0]();+ await new Promise((resolve) => setTimeout(resolve, 0));+ await vi.waitFor(() => expect(testQueryClient.isFetching()).toBe(0));+ expect(titleOfEvent1()).toBe('Second');++ serverTitle = 'Second';+ second.resolve(ok({ id: 'event-1' }));+ await saving;+ await vi.waitFor(() => expect(deltas).toHaveLength(2));+ deltas[1]();+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(testQueryClient.isFetching()).toBe(0));+ expect(titleOfEvent1()).toBe('Second');+ unsubscribe();+ });+it('scopes an optimistic edit to the targeted occurrence, or widens to the series', async () => {const keys = ['2026-08-04T09:00:00Z',diff --git a/crates/email_api_client/AGENTS.md b/crates/email_api_client/AGENTS.mdindex 0cb6059f99..ac9afed46a 100644--- a/crates/email_api_client/AGENTS.md+++ b/crates/email_api_client/AGENTS.md@@ -19,7 +19,9 @@ Outlook (Microsoft Graph) outbound adapters.- `src/outbound/gmail.rs`: the Gmail adapter (feature `outbound-gmail`).- `src/outbound/outlook.rs`: the Microsoft Graph adapter (feature`outbound-outlook`); every Graph call goes through `outlook/transport.rs`,- which owns request headers, provider error mapping, and write-failure logs.+ which owns request headers, provider error mapping, write-failure logs,+ and one `outlook.graph_request` span per attempt (with an+ `outlook.graph_admission` child for the per-mailbox gate wait).## Scopediff --git a/crates/email_api_client/src/outbound/outlook/transport.rs b/crates/email_api_client/src/outbound/outlook/transport.rsindex d65dff9b2f..d2165e79d3 100644--- a/crates/email_api_client/src/outbound/outlook/transport.rs+++ b/crates/email_api_client/src/outbound/outlook/transport.rs@@ -3,6 +3,7 @@ use std::time::{Duration, SystemTime};use reqwest::{Method, RequestBuilder, Response, StatusCode};use serde::de::DeserializeOwned;use serde_json::Value;+use tracing::Instrument;use url::Url;use super::{IMMUTABLE_ID_PREFERENCE, OutlookApiClientRepository};@@ -16,6 +17,12 @@ pub(super) struct GraphFailure {pub(super) request_id: Option<String>,}+impl std::fmt::Display for GraphFailure {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.error.fmt(f)+ }+}+impl From<EmailApiError> for GraphFailure {fn from(error: EmailApiError) -> Self {Self {@@ -87,6 +94,7 @@ impl OutlookApiClientRepository {body: Option<&Value>,expected_version: Option<&str>,) -> Result<Response, GraphFailure> {+ let path = url.path().to_owned();let refreshed = self.refreshed_token.lock()@@ -114,7 +122,7 @@ impl OutlookApiClientRepository {.rejected_token_refresh.as_ref().and_then(|_| request.try_clone());- match self.gated_graph_request(request).await {+ match self.graph_attempt(request, &method, &path, false).await {Err(GraphFailure {error: EmailApiError::AuthRequired,..@@ -137,7 +145,8 @@ impl OutlookApiClientRepository {.map_err(|_| invalid_response())?;authorization.set_sensitive(true);headers.insert(reqwest::header::AUTHORIZATION, authorization);- self.gated_graph_request(retry.headers(headers)).await+ self.graph_attempt(retry.headers(headers), &method, &path, true)+ .await} else {Err(EmailApiError::AuthRequired.into())}@@ -146,6 +155,31 @@ impl OutlookApiClientRepository {}}+ /// One Graph round trip, including its wait for the mailbox gate. A replay+ /// with a refreshed token is its own attempt, so each keeps its status.+ #[tracing::instrument(+ name = "outlook.graph_request",+ skip_all,+ fields(+ otel.kind = "client",+ http.request.method = %method,+ url.path = path,+ link_id = self.mailbox.map(|mailbox| tracing::field::display(mailbox.link_id)),+ http.response.status_code = tracing::field::Empty,+ reauthorized = reauthorized,+ ),+ err(level = "warn")+ )]+ async fn graph_attempt(+ &self,+ request: RequestBuilder,+ method: &Method,+ path: &str,+ reauthorized: bool,+ ) -> Result<Response, GraphFailure> {+ self.gated_graph_request(request).await+ }+/// Includes anonymous, preauthorized attachment uploads in mailbox accounting.pub(super) async fn gated_request(&self,@@ -159,7 +193,14 @@ impl OutlookApiClientRepository {async fn gated_graph_request(&self, request: RequestBuilder) -> Result<Response, GraphFailure> {let permit = if let Some(gate) = &self.gate {let mailbox = self.mailbox.ok_or_else(invalid_response)?;- Some((mailbox, gate.acquire(mailbox).await?))+ let permit = gate+ .acquire(mailbox)+ .instrument(tracing::info_span!(+ "outlook.graph_admission",+ link_id = %mailbox.link_id+ ))+ .await?;+ Some((mailbox, permit))} else {None};@@ -185,10 +226,11 @@ impl OutlookApiClientRepository {let request = request.map_err(transport_failed)?;let method = request.method().clone();let response = client.execute(request).await.map_err(transport_failed)?;- if response.status().is_success() {+ let status = response.status();+ tracing::Span::current().record("http.response.status_code", status.as_u16());+ if status.is_success() {return Ok(response);}- let status = response.status();let path = response.url().path().to_owned();let request_id = response.headers()