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): lock an open composer once the guest loses modify rights (#8649)
gbirman4b855f298f6a
diff --git a/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsxindex 98e027bf62..df7a614308 100644--- a/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsx+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.test.tsx@@ -22,6 +22,9 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({vi.mock('@core/hotkey/hotkeys', () => ({useHotkeyDOMScope: () => [() => {}],}));+vi.mock('@app/features/calendar/hooks/use-synced-calendar-event', () => ({+ useSyncedCalendarEvent: () => () => undefined,+}));vi.mock('@app/features/calendar/hooks/use-event-editor', () => ({useEventEditor: () => ({initialValues: () => undefined,diff --git a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsxindex bd5e734c77..7b26bae9fc 100644--- a/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx+++ b/apps/web/src/features/block-calendar/components/EventComposerSplit.tsx@@ -6,6 +6,7 @@ import {} from '@app/features/calendar/components/composer/event-form-model';import { useCalendarGuestInvitesFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';import { useEventEditor } from '@app/features/calendar/hooks/use-event-editor';+import { useSyncedCalendarEvent } from '@app/features/calendar/hooks/use-synced-calendar-event';import type { CalendarEvent } from '@app/features/calendar/types';import { viewerReplacesGuests } from '@app/features/calendar/utils/event-guest-editing';import { EventReplacementAction } from '@app/features/calendar/views/event-replacement';@@ -59,7 +60,8 @@ function EventComposerContent(event: () => props.event,macroCallsEnabled,guestInvitesEnabled: useCalendarGuestInvitesFlag(),- onDetailEditsRefused: () => controller.resetDetails(),+ syncedEvent: useSyncedCalendarEvent(() => props.event),+ onDetailsLocked: () => controller.resetDetails(),onSaved: () => {props.onSaveSuccess?.();close();diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts b/apps/web/src/features/calendar/hooks/use-event-editor.test.tsindex 43ba2de63e..47a9d4a425 100644--- a/apps/web/src/features/calendar/hooks/use-event-editor.test.ts+++ b/apps/web/src/features/calendar/hooks/use-event-editor.test.ts@@ -1,4 +1,4 @@-import { createRoot } from 'solid-js';+import { createRoot, createSignal } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createCalendarEventFormController } from '../components/composer/create-calendar-event-form-controller';import {@@ -1065,15 +1065,17 @@ describe('guests of an event the viewer was invited to', () => {function editorFor(event: CalendarEvent,invitesEnabled: boolean,- onDetailEditsRefused?: () => void+ onDetailsLocked?: () => void,+ syncedEvent?: () => CalendarEvent | undefined) {return createRoot((dispose) => ({editor: useEventEditor({event: () => event,+ syncedEvent,onSaved: vi.fn(),macroCallsEnabled: () => false,guestInvitesEnabled: () => invitesEnabled,- onDetailEditsRefused,+ onDetailsLocked,}),dispose,}));@@ -1287,18 +1289,19 @@ describe('guests of an event the viewer was invited to', () => {it('locks the details when the server refuses a guest’s change', async () => {mocks.updateEvent.mockRejectedValueOnce({ code: 'guests_cannot_modify' });- const detailEditsRefused = vi.fn();+ const detailsLocked = vi.fn();const { editor, dispose } = editorFor(invitedEvent(mayModify),true,- detailEditsRefused+ detailsLocked);try {await editor.save({ ...unchanged, title: 'Planning review' });expect(mocks.failure).toHaveBeenCalledWith('Only the organizer can change this event.');- expect(detailEditsRefused).toHaveBeenCalledOnce();+ expect(mocks.alert).not.toHaveBeenCalled();+ expect(detailsLocked).toHaveBeenCalledOnce();expect(editor.disabledFields()?.title).toBe(true);expect(editor.detailsReadOnlyReason()).toBe('Only the organizer can change this event.'@@ -1316,6 +1319,42 @@ describe('guests of an event the viewer was invited to', () => {dispose();}});++ it('locks the open editor once the synced event stops letting the guest modify it', async () => {+ const opened = invitedEvent(mayModify);+ const [synced, setSynced] = createSignal<CalendarEvent | undefined>();+ const detailsLocked = vi.fn();+ const { editor, dispose } = editorFor(opened, true, detailsLocked, synced);+ try {+ // The day loads with the copy the editor opened with.+ setSynced(opened);+ expect(editor.disabledFields()?.title).toBeUndefined();+ expect(detailsLocked).not.toHaveBeenCalled();++ // The organizer turns Modify event off and the guest's copy syncs.+ setSynced(invitedEvent(mayInvite));+ expect(editor.disabledFields()?.title).toBe(true);+ expect(editor.detailsReadOnlyReason()).toBe(+ 'Only the organizer can change this event.'+ );+ expect(detailsLocked).toHaveBeenCalledOnce();+ expect(mocks.alert).toHaveBeenCalledWith(+ 'Only the organizer can change this event.'+ );++ await editor.save({+ ...unchanged,+ title: 'Planning review',+ reminders: thirtyMinutes,+ });+ expect(mocks.updateEvent).toHaveBeenCalledOnce();+ expect(mocks.updateEvent.mock.lastCall?.[0].patch).toEqual({+ reminders: thirtyMinutes,+ });+ } finally {+ dispose();+ }+ });});describe('guest permissions', () => {diff --git a/apps/web/src/features/calendar/hooks/use-event-editor.ts b/apps/web/src/features/calendar/hooks/use-event-editor.tsindex d6b5150773..bfe57a0675 100644--- a/apps/web/src/features/calendar/hooks/use-event-editor.ts+++ b/apps/web/src/features/calendar/hooks/use-event-editor.ts@@ -14,7 +14,13 @@ import {useUpdateMeetingMutation,} from '@queries/call/meetings';import type { CalendarUpdateScope } from '@service-email/client';-import { type Accessor, createMemo, createSignal } from 'solid-js';+import {+ type Accessor,+ createEffect,+ createMemo,+ createSignal,+ on,+} from 'solid-js';import { match } from 'ts-pattern';import {buildEventTime,@@ -111,11 +117,19 @@ interface UseEventEditorProps {*/guestInvitesEnabled?: Accessor<boolean>;/**- * Called when the server refuses a detail change and the details lock, so- * the form can return them to the event's own instead of holding changes- * it can no longer save.+ * The edited event as the calendar now holds it. The lock on its details+ * follows this copy, so a guest whose organizer stops letting guests+ * modify the event loses the details while the editor is open. The edit+ * itself still compares against `event`, the version it opened with.+ */+ syncedEvent?: Accessor<CalendarEvent | undefined>;+ /**+ * Called when the details lock while the editor is open, because the+ * server refused a detail change or the synced event no longer lets the+ * viewer change them, so the form can return them to the event's own+ * instead of holding changes it can no longer save.*/- onDetailEditsRefused?: () => void;+ onDetailsLocked?: () => void;}/** Shared create/edit query and mutation orchestration for any editor shell. */@@ -197,11 +211,23 @@ export function useEventEditor(props: UseEventEditorProps) {const [detailEditsRefused, setDetailEditsRefused] = createSignal(false);const detailsLocked = () => {const event = props.event();+ if (!event) return false;return (- event !== undefined &&- (detailEditsRefused() || guestEditsRestricted(event))+ detailEditsRefused() ||+ guestEditsRestricted(props.syncedEvent?.() ?? event));};+ // The lock can arrive from outside the form, with the synced event, so the+ // form is told rather than asked. The first run has no earlier state and+ // only records the lock the editor opened with.+ createEffect(+ on(detailsLocked, (locked, wasLocked) => {+ if (!locked || wasLocked !== false) return;+ props.onDetailsLocked?.();+ // A refused save already says why.+ if (!detailEditsRefused()) toast.alert(GUEST_EDITS_RESTRICTED);+ })+ );const updateMeeting = useUpdateMeetingMutation();const create = useCreateCalendarEventMutation();@@ -450,7 +476,6 @@ export function useEventEditor(props: UseEventEditorProps) {}} else if (event && isGuestEditRefused(error)) {setDetailEditsRefused(true);- props.onDetailEditsRefused?.();toast.failure(GUEST_EDITS_RESTRICTED);} else {toast.failure(diff --git a/apps/web/src/features/calendar/hooks/use-synced-calendar-event.test.tsx b/apps/web/src/features/calendar/hooks/use-synced-calendar-event.test.tsxnew file mode 100644index 0000000000..98df508e4e--- /dev/null+++ b/apps/web/src/features/calendar/hooks/use-synced-calendar-event.test.tsx@@ -0,0 +1,141 @@+// @vitest-environment jsdom+import type {+ CalendarOccurrencesData,+ CalendarOccurrencesQueryInput,+} from '@queries/calendar/occurrences';+import { cleanup, render, waitFor } from '@solidjs/testing-library';+import {+ QueryClient,+ QueryClientProvider,+ useQuery,+} from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import {+ type CalendarEvent,+ DEFAULT_GUEST_POLICY,+ mapCalendarOccurrence,+} from '../types';+import { useSyncedCalendarEvent } from './use-synced-calendar-event';++const requests = vi.hoisted(() => ({+ occurrences: vi.fn<() => Promise<CalendarOccurrencesData>>(),+}));++vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'user',+}));+vi.mock('@queries/calendar/occurrences', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@queries/calendar/occurrences')>()),+ useCalendarOccurrencesQuery: (+ input: Accessor<CalendarOccurrencesQueryInput>+ ) =>+ useQuery(() => ({+ queryKey: ['occurrences', input().userId, input().range],+ queryFn: requests.occurrences,+ enabled: input().range !== undefined,+ })),+}));++const time = {+ kind: 'timed' as const,+ startsAt: '2026-10-25T15:00:00Z',+ endsAt: '2026-10-25T15:30:00Z',+};++function guestCopy(editDetails: boolean): CalendarOccurrencesData {+ return {+ syncStatus: 'ready',+ items: [+ {+ event: {+ id: 'event',+ ownerId: 'user',+ icalUid: 'uid',+ calendarId: 'calendar',+ title: 'Planning',+ time,+ attendees: [+ {+ email: '[email protected]',+ isOptional: false,+ isOrganizer: true,+ isSelf: false,+ responseStatus: 'accepted',+ },+ {+ email: '[email protected]',+ isOptional: false,+ isOrganizer: false,+ isSelf: true,+ responseStatus: 'accepted',+ },+ ],+ recurrenceLines: [],+ sequence: 0,+ isReadOnly: false,+ guestPolicy: { ...DEFAULT_GUEST_POLICY, canModify: editDetails },+ isSnapshot: false,+ viewerCan: {+ editDetails,+ inviteGuests: true,+ removeGuests: editDetails,+ setGuestPolicy: false,+ rsvp: true,+ organize: false,+ },+ status: 'confirmed',+ transparency: 'opaque',+ visibility: 'default',+ createdAt: time.startsAt,+ updatedAt: time.startsAt,+ },+ occurrence: {+ eventId: 'event',+ occurrenceKey: time.startsAt,+ time,+ isCancelled: false,+ },+ },+ ],+ };+}++let queryClient: QueryClient;++beforeEach(() => {+ vi.clearAllMocks();+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+});++afterEach(() => {+ cleanup();+ queryClient.clear();+});++it('keeps the last synced copy, and the lock it brought, through a failed refetch', async () => {+ const [item] = guestCopy(true).items;+ if (!item) throw new Error('fixture has an occurrence');+ const opened = mapCalendarOccurrence(item);+ // The organizer turned modifying off before the day loaded.+ requests.occurrences.mockResolvedValueOnce(guestCopy(false));+ let synced!: Accessor<CalendarEvent | undefined>;+ render(() => (+ <QueryClientProvider client={queryClient}>+ {(() => {+ synced = useSyncedCalendarEvent(() => opened);+ return null;+ })()}+ </QueryClientProvider>+ ));++ await waitFor(() => expect(synced()?.viewerCan.editDetails).toBe(false));++ requests.occurrences.mockRejectedValueOnce(new Error('offline'));+ await queryClient.refetchQueries();++ expect(queryClient.getQueryCache().getAll()[0]?.state.status).toBe('error');+ expect(synced()?.viewerCan.editDetails).toBe(false);+});diff --git a/apps/web/src/features/calendar/hooks/use-synced-calendar-event.ts b/apps/web/src/features/calendar/hooks/use-synced-calendar-event.tsnew file mode 100644index 0000000000..1e5c402ec2--- /dev/null+++ b/apps/web/src/features/calendar/hooks/use-synced-calendar-event.ts@@ -0,0 +1,47 @@+import { useUserId } from '@core/context/user';+import {+ createCalendarOccurrenceQueryRange,+ useCalendarOccurrencesQuery,+} from '@queries/calendar/occurrences';+import { queryReadyGate } from '@queries/gate';+import { addDays, startOfDay } from 'date-fns';+import { type Accessor, createMemo } from 'solid-js';+import { type CalendarEvent, mapCalendarOccurrence } from '../types';++/**+ * An open event as the calendar's occurrence cache now holds it, read over+ * the occurrence's own day, so what syncs while an editor is open reaches+ * the editor: the organizer taking away the viewer's rights, for one.+ * Undefined until that day loads, and once the occurrence is gone; a+ * failed refetch keeps the last copy, so a lock it brought holds.+ */+export function useSyncedCalendarEvent(+ event: Accessor<CalendarEvent | undefined>+): Accessor<CalendarEvent | undefined> {+ const userId = useUserId();+ const range = createMemo(() => {+ const current = event();+ if (!current) return undefined;+ const day = startOfDay(+ current.allDay+ ? new Date(`${current.start}T00:00:00`)+ : new Date(current.start)+ );+ return createCalendarOccurrenceQueryRange(day, addDays(day, 1));+ });+ const query = useCalendarOccurrencesQuery(() => ({+ userId: userId(),+ range: range(),+ }));++ return createMemo(() => {+ const current = event();+ if (!current || !queryReadyGate(query)) return undefined;+ const item = query.data.items.find(+ (candidate) =>+ candidate.occurrence.eventId === current.eventId &&+ candidate.occurrence.occurrenceKey === current.occurrenceKey+ );+ return item ? mapCalendarOccurrence(item) : undefined;+ });+}diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex d315749d60..31d6df0d5b 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -484,7 +484,10 @@ A guest the organizer does not let modify the event (`viewerCan.editDetails` falrepeat, conferencing and location controls are disabled, each with the tooltip `Only theorganizer can change this event.`; the same line shows under the pills, which is all atouch device shows. Notifications stay editable and Save sends only `reminders` (plus any-invitation). That guest cannot drag or resize the event on the grid either. Someone+invitation). An editor already open when the organizer turns modifying off follows the+guest's copy once it syncs: the same fields lock, return to the event's own (keeping+notification and guest changes) and a toast shows the line. That guest cannot drag or resize+the event on the grid either. Someoneneither organizing nor invited, such as a delegate on a shared calendar, keeps what theircalendar access allows. The update refuses a detail change from such a guest with 403`guests_cannot_modify` (fields resent at their stored value are ignored, so the agent can