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.

fix(calendar): keep rsvp buttons live during the provider round trip (#5534)

gbirman6e0c80606fb4
diff --git a/apps/web/src/features/calendar/events/EventRsvpSection.tsx b/apps/web/src/features/calendar/events/EventRsvpSection.tsx
index 2eddd813b9..8e09bf843b 100644
--- a/apps/web/src/features/calendar/events/EventRsvpSection.tsx
+++ b/apps/web/src/features/calendar/events/EventRsvpSection.tsx
@@ -104,7 +104,6 @@ export function EventRsvpSection(props: { event: CalendarEvent }) {
}
size="sm"
class="rounded-lg px-2.5"
- disabled={rsvp.isPending}
label={option.label}
onClick={() => respond(option.response)}
>
@@ -116,18 +115,11 @@ export function EventRsvpSection(props: { event: CalendarEvent }) {
</div>
<Dialog
open={pendingResponse() !== undefined}
- onOpenChange={(open) =>
- !open && !rsvp.isPending && setPendingResponse(undefined)
- }
+ onOpenChange={(open) => !open && setPendingResponse(undefined)}
>
<Panel depth={2} class="max-w-[calc(100vw-2rem)] rounded-xl text-ink">
<Panel.Header class="gap-1 px-2">
- <Dialog.CloseButton
- as={Button}
- variant="ghost"
- size="icon-sm"
- disabled={rsvp.isPending}
- >
+ <Dialog.CloseButton as={Button} variant="ghost" size="icon-sm">
<CloseIcon />
</Dialog.CloseButton>
<Dialog.Title as="span" class="m-0 p-0 text-sm font-medium">
@@ -154,7 +146,6 @@ export function EventRsvpSection(props: { event: CalendarEvent }) {
<Button
variant="ghost"
class="rounded-lg"
- disabled={rsvp.isPending}
label="Cancel"
onClick={() => setPendingResponse(undefined)}
>
@@ -163,7 +154,6 @@ export function EventRsvpSection(props: { event: CalendarEvent }) {
<Button
variant="active"
class="rounded-lg"
- disabled={rsvp.isPending}
label="OK"
onClick={confirm}
>
diff --git a/apps/web/src/lib/queries/calendar/mutations.ts b/apps/web/src/lib/queries/calendar/mutations.ts
index 26959eedb1..9d4f41f440 100644
--- a/apps/web/src/lib/queries/calendar/mutations.ts
+++ b/apps/web/src/lib/queries/calendar/mutations.ts
@@ -97,16 +97,93 @@ type RsvpCallbacks = MutationCallbacks<
CalendarEventEntity,
Error,
RsvpCalendarEventArgs,
- CalendarMutationContext
+ RsvpMutationContext
>;
+const RSVP_MUTATION_KEY = ['calendar', 'rsvp'] as const;
+
+type RsvpMutationContext = CalendarMutationContext & {
+ /** Drops this mutation's writer stamps once it has settled. */
+ release: () => void;
+};
+
+let rsvpRevisionCounter = 0;
+/**
+ * Latest optimistic writer per (event, occurrence). Value equality cannot
+ * tell overlapping same-response mutations apart, so rollback ownership is
+ * tracked explicitly: an older mutation's failure must not revert an
+ * occurrence a newer mutation has since answered.
+ */
+const rsvpLastWriter = new Map<string, number>();
+
+const rsvpWriterKey = (eventId: string, occurrenceKey: string) =>
+ JSON.stringify([eventId, occurrenceKey]);
+
+function selfResponseOf(
+ item: CalendarOccurrenceItem
+): AttendeeResponseStatus | undefined {
+ return item.event.attendees.find((attendee) => attendee.isSelf)
+ ?.responseStatus;
+}
+
+function withSelfResponse(
+ item: CalendarOccurrenceItem,
+ response: AttendeeResponseStatus
+): CalendarOccurrenceItem {
+ return {
+ ...item,
+ event: {
+ ...item.event,
+ attendees: item.event.attendees.map((attendee) =>
+ attendee.isSelf ? { ...attendee, responseStatus: response } : attendee
+ ),
+ },
+ };
+}
+
+function patchOccurrenceQueries(
+ update: (items: CalendarOccurrenceItem[]) => CalendarOccurrenceItem[]
+) {
+ queryClient.setQueriesData<CalendarOccurrencesData>(
+ { queryKey: calendarKeys.occurrences._def },
+ (old) => old && { ...old, items: update(old.items) }
+ );
+}
+
+/** Previous self responses of the occurrences a scoped answer covers. */
+function readAnsweredResponses(
+ args: RsvpCalendarEventArgs
+): Map<string, AttendeeResponseStatus> {
+ const previous = new Map<string, AttendeeResponseStatus>();
+ for (const [, data] of queryClient.getQueriesData<CalendarOccurrencesData>({
+ queryKey: calendarKeys.occurrences._def,
+ })) {
+ for (const item of data?.items ?? []) {
+ if (!answeredByRsvp(item, args)) continue;
+ const key = item.occurrence.occurrenceKey;
+ if (previous.has(key)) continue;
+ const response = selfResponseOf(item);
+ if (response !== undefined) previous.set(key, response);
+ }
+ }
+ return previous;
+}
+
/**
* Sets the viewer's RSVP for one occurrence or the whole series. Google
* records an occurrence-scoped response as an exception instance, so the
* answer can differ per occurrence.
+ *
+ * The buttons stay enabled while the request is in flight (the round trip
+ * writes through to the provider, which takes seconds), so overlapping
+ * mutations are expected: the rollback restores only the occurrences this
+ * mutation still owns per the writer stamps, and only the last mutation to
+ * settle refetches — otherwise an earlier settle would clobber a later
+ * mutation's optimistic state with stale server data.
*/
export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {
return useMutation(() => ({
+ mutationKey: RSVP_MUTATION_KEY,
mutationFn: async (args: RsvpCalendarEventArgs) =>
await throwOnErr(() =>
emailClient.rsvpCalendarEvent(args.eventId, {
@@ -119,29 +196,66 @@ export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {
CalendarEventEntity,
Error,
RsvpCalendarEventArgs,
- CalendarMutationContext
+ RsvpMutationContext
>(
{
- onMutate: (args) =>
- patchOccurrenceCaches((items) =>
+ onMutate: async (args) => {
+ const revision = ++rsvpRevisionCounter;
+ await queryClient.cancelQueries({
+ queryKey: calendarKeys.occurrences._def,
+ });
+ const previous = readAnsweredResponses(args);
+ for (const occurrenceKey of previous.keys()) {
+ rsvpLastWriter.set(
+ rsvpWriterKey(args.eventId, occurrenceKey),
+ revision
+ );
+ }
+ patchOccurrenceQueries((items) =>
items.map((item) =>
answeredByRsvp(item, args)
- ? {
- ...item,
- event: {
- ...item.event,
- attendees: item.event.attendees.map((attendee) =>
- attendee.isSelf
- ? { ...attendee, responseStatus: args.response }
- : attendee
- ),
- },
- }
+ ? withSelfResponse(item, args.response)
: item
)
- ),
+ );
+ return {
+ rollback: () => {
+ patchOccurrenceQueries((items) =>
+ items.map((item) => {
+ if (!answeredByRsvp(item, args)) return item;
+ const occurrenceKey = item.occurrence.occurrenceKey;
+ if (
+ rsvpLastWriter.get(
+ rsvpWriterKey(args.eventId, occurrenceKey)
+ ) !== revision
+ ) {
+ return item;
+ }
+ const restored = previous.get(occurrenceKey);
+ if (restored === undefined) return item;
+ if (selfResponseOf(item) !== args.response) return item;
+ return withSelfResponse(item, restored);
+ })
+ );
+ },
+ release: () => {
+ for (const occurrenceKey of previous.keys()) {
+ const key = rsvpWriterKey(args.eventId, occurrenceKey);
+ if (rsvpLastWriter.get(key) === revision) {
+ rsvpLastWriter.delete(key);
+ }
+ }
+ },
+ };
+ },
onError: (_error, _args, context) => context?.rollback(),
- onSettled: () => invalidateCalendarOccurrences(),
+ onSettled: (_data, _error, _args, context) => {
+ context?.release();
+ if (queryClient.isMutating({ mutationKey: RSVP_MUTATION_KEY }) > 1) {
+ return;
+ }
+ return invalidateCalendarOccurrences();
+ },
},
callbacks
),
diff --git a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx
index 9b8ba0bb3e..1ff3adc67b 100644
--- a/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx
+++ b/apps/web/src/lib/queries/calendar/tests/mutations.test.tsx
@@ -146,6 +146,14 @@ function renderHook<T>(factory: () => T): T {
const failure = () =>
err([{ code: 'HTTP_ERROR' as const, message: 'provider says no' }]);
+function deferredResult() {
+ let resolve!: (value: unknown) => void;
+ const promise = new Promise<unknown>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
beforeEach(() => {
vi.clearAllMocks();
testQueryClient = new QueryClient({
@@ -182,45 +190,48 @@ describe('useRsvpCalendarEventMutation', () => {
});
});
- it('scopes the optimistic answer to the occurrences it covers', async () => {
- // Three occurrences of one series, so a scoped answer has something to
- // leave alone.
- const seriesOccurrence = (key: string): CalendarOccurrenceItem =>
- ({
- event: {
- id: 'event-3',
- title: 'Standup',
- recurrenceLines: ['RRULE:FREQ=DAILY'],
- time: { kind: 'timed', startsAt: key, endsAt: key },
- attendees: [
- {
- email: '[email protected]',
- isSelf: true,
- responseStatus: 'accepted',
- },
- ],
- },
- occurrence: {
- eventId: 'event-3',
- occurrenceKey: key,
- recurrenceId: key,
- time: { kind: 'timed', startsAt: key, endsAt: key },
- },
- }) as unknown as CalendarOccurrenceItem;
- const keys = [
- '2026-08-04T09:00:00Z',
- '2026-08-05T09:00:00Z',
- '2026-08-06T09:00:00Z',
- ];
+ // Three occurrences of one series, so a scoped answer has something to
+ // leave alone.
+ const seriesOccurrence = (key: string): CalendarOccurrenceItem =>
+ ({
+ event: {
+ id: 'event-3',
+ title: 'Standup',
+ recurrenceLines: ['RRULE:FREQ=DAILY'],
+ time: { kind: 'timed', startsAt: key, endsAt: key },
+ attendees: [
+ {
+ email: '[email protected]',
+ isSelf: true,
+ responseStatus: 'accepted',
+ },
+ ],
+ },
+ occurrence: {
+ eventId: 'event-3',
+ occurrenceKey: key,
+ recurrenceId: key,
+ time: { kind: 'timed', startsAt: key, endsAt: key },
+ },
+ }) as unknown as CalendarOccurrenceItem;
+ const seriesKeys = [
+ '2026-08-04T09:00:00Z',
+ '2026-08-05T09:00:00Z',
+ '2026-08-06T09:00:00Z',
+ ];
+ const seedSeries = () =>
testQueryClient.setQueryData(
calendarKeys.occurrences('user', viewportA).queryKey,
- { items: keys.map(seriesOccurrence), syncStatus: 'ready' }
+ { items: seriesKeys.map(seriesOccurrence), syncStatus: 'ready' }
);
- const responseAt = (key: string) =>
- viewportData(viewportA)
- ?.items.find((item) => item.occurrence.occurrenceKey === key)
- ?.event.attendees.find((attendee) => attendee.isSelf)?.responseStatus;
+ const responseAt = (key: string) =>
+ viewportData(viewportA)
+ ?.items.find((item) => item.occurrence.occurrenceKey === key)
+ ?.event.attendees.find((attendee) => attendee.isSelf)?.responseStatus;
+ it('scopes the optimistic answer to the occurrences it covers', async () => {
+ const keys = seriesKeys;
+ seedSeries();
rsvpCalendarEventMock.mockResolvedValue(ok({ id: 'event-3' }));
const rsvp = renderHook(() => useRsvpCalendarEventMutation());
@@ -281,6 +292,135 @@ describe('useRsvpCalendarEventMutation', () => {
).toBe('needs_action');
}
});
+
+ const selfStatus = () =>
+ viewportData(viewportA)
+ ?.items.find((item) => item.event.id === 'event-1')
+ ?.event.attendees.find((attendee) => attendee.isSelf)?.responseStatus;
+
+ it('keeps the newer optimistic response when an older overlapping request fails', async () => {
+ const first = deferredResult();
+ const second = deferredResult();
+ rsvpCalendarEventMock
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const rsvp = renderHook(() => useRsvpCalendarEventMutation());
+
+ const firstMutation = rsvp
+ .mutateAsync({ eventId: 'event-1', response: 'accepted' })
+ .catch(() => {});
+ await vi.waitFor(() => expect(selfStatus()).toBe('accepted'));
+
+ const secondMutation = rsvp.mutateAsync({
+ eventId: 'event-1',
+ response: 'tentative',
+ });
+ await vi.waitFor(() => expect(selfStatus()).toBe('tentative'));
+
+ first.resolve(failure());
+ await firstMutation;
+ expect(selfStatus()).toBe('tentative');
+
+ second.resolve(ok({ id: 'event-1' }));
+ await secondMutation;
+ expect(selfStatus()).toBe('tentative');
+ });
+
+ it('keeps a newer identical response when the older request fails', async () => {
+ const first = deferredResult();
+ const second = deferredResult();
+ rsvpCalendarEventMock
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const rsvp = renderHook(() => useRsvpCalendarEventMutation());
+
+ const firstMutation = rsvp
+ .mutateAsync({ eventId: 'event-1', response: 'accepted' })
+ .catch(() => {});
+ await vi.waitFor(() => expect(selfStatus()).toBe('accepted'));
+
+ // The second answer picks the same response, so equal cache values
+ // cannot reveal which mutation wrote last — wait for its request to
+ // confirm its optimistic write went through.
+ const secondMutation = rsvp.mutateAsync({
+ eventId: 'event-1',
+ response: 'accepted',
+ });
+ await vi.waitFor(() =>
+ expect(rsvpCalendarEventMock).toHaveBeenCalledTimes(2)
+ );
+
+ second.resolve(ok({ id: 'event-1' }));
+ await secondMutation;
+ expect(selfStatus()).toBe('accepted');
+
+ first.resolve(failure());
+ await firstMutation;
+ expect(selfStatus()).toBe('accepted');
+ });
+
+ it('rolls a failed series answer back around a newer occurrence answer', async () => {
+ seedSeries();
+ const first = deferredResult();
+ const second = deferredResult();
+ rsvpCalendarEventMock
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const rsvp = renderHook(() => useRsvpCalendarEventMutation());
+
+ const firstMutation = rsvp
+ .mutateAsync({ eventId: 'event-3', response: 'tentative', scope: 'all' })
+ .catch(() => {});
+ await vi.waitFor(() => expect(responseAt(seriesKeys[0])).toBe('tentative'));
+
+ const secondMutation = rsvp.mutateAsync({
+ eventId: 'event-3',
+ response: 'declined',
+ scope: 'this_event',
+ recurrenceId: seriesKeys[1],
+ occurrenceKey: seriesKeys[1],
+ });
+ await vi.waitFor(() => expect(responseAt(seriesKeys[1])).toBe('declined'));
+
+ first.resolve(failure());
+ await firstMutation;
+ expect(responseAt(seriesKeys[0])).toBe('accepted');
+ expect(responseAt(seriesKeys[1])).toBe('declined');
+ expect(responseAt(seriesKeys[2])).toBe('accepted');
+
+ second.resolve(ok({ id: 'event-3' }));
+ await secondMutation;
+ expect(responseAt(seriesKeys[1])).toBe('declined');
+ });
+
+ it('only refetches once the last overlapping request settles', async () => {
+ const first = deferredResult();
+ const second = deferredResult();
+ rsvpCalendarEventMock
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const invalidateSpy = vi.spyOn(testQueryClient, 'invalidateQueries');
+ const rsvp = renderHook(() => useRsvpCalendarEventMutation());
+
+ const firstMutation = rsvp.mutateAsync({
+ eventId: 'event-1',
+ response: 'accepted',
+ });
+ await vi.waitFor(() => expect(selfStatus()).toBe('accepted'));
+ const secondMutation = rsvp.mutateAsync({
+ eventId: 'event-1',
+ response: 'declined',
+ });
+ await vi.waitFor(() => expect(selfStatus()).toBe('declined'));
+
+ first.resolve(ok({ id: 'event-1' }));
+ await firstMutation;
+ expect(invalidateSpy).not.toHaveBeenCalled();
+
+ second.resolve(ok({ id: 'event-1' }));
+ await secondMutation;
+ expect(invalidateSpy).toHaveBeenCalledTimes(1);
+ });
});
describe('useDeleteCalendarEventMutation', () => {