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): stop calendar reads waiting on local cache startup (#7734)
gbirman9af01f115548
diff --git a/apps/web/src/lib/queries/calendar/calendars.ts b/apps/web/src/lib/queries/calendar/calendars.tsindex 508a1bebda..d302d15d90 100644--- a/apps/web/src/lib/queries/calendar/calendars.ts+++ b/apps/web/src/lib/queries/calendar/calendars.ts@@ -1,4 +1,5 @@import { throwOnErr } from '@core/util/result';+import type { CacheHost } from '@graphql-cache/index';import { subscribeToVisibleCacheChanges } from '@queries/subscribe-to-visible-cache-changes';import type { VisibleCalendar } from '@service-calendar/generated/schemas/visibleCalendar';import { emailClient } from '@service-email/client';@@ -8,6 +9,10 @@ import { useQuery, useQueryClient } from '@tanstack/solid-query';import { type Accessor, createEffect, onCleanup } from 'solid-js';import { useGraphqlCalendarHost } from './graphql/flag';import { mapVisibleCalendar } from './graphql/map';+import {+ calendarCacheAnswered,+ withinCacheHeadStart,+} from './graphql/readiness';import { calendarKeys } from './keys';export type { VisibleCalendar };@@ -48,7 +53,7 @@ export function useVisibleCalendarsQuery(if (host) {return {queryKey: calendarKeys.visibleCalendars._ctx.graphql.queryKey,- queryFn: readCachedCalendars,+ queryFn: () => readCalendarList(host),staleTime: Infinity,networkMode: 'offlineFirst' as const,enabled: options?.().enabled !== false,@@ -56,14 +61,35 @@ export function useVisibleCalendarsQuery(}return {queryKey: calendarKeys.visibleCalendars.queryKey,- queryFn: async () =>- (await throwOnErr(() => emailClient.listCalendars())).calendars,+ queryFn: listCalendars,staleTime: CALENDAR_LIST_STALE_TIME,enabled: options?.().enabled !== false,};});}+async function listCalendars() {+ return (await throwOnErr(() => emailClient.listCalendars())).calendars;+}++/**+ * Reads the list from the cache. A cache that has not answered a calendar read+ * gets a head start; past it, or if its read fails, the list comes from REST.+ */+async function readCalendarList(host: CacheHost) {+ if (calendarCacheAnswered(host)) return readCachedCalendars();+ const cached = await withinCacheHeadStart(+ (async () => {+ try {+ return await readCachedCalendars();+ } catch {+ return 'not-ready' as const;+ }+ })()+ );+ return cached === 'not-ready' ? listCalendars() : cached;+}+/** Reads the calendar list from the cache, fetching it once when absent. */async function readCachedCalendars() {const result = await getGraphqlSoupClient()diff --git a/apps/web/src/lib/queries/calendar/graphql/flag.ts b/apps/web/src/lib/queries/calendar/graphql/flag.tsindex 86215ffeb1..59ddb3bb5b 100644--- a/apps/web/src/lib/queries/calendar/graphql/flag.ts+++ b/apps/web/src/lib/queries/calendar/graphql/flag.ts@@ -10,6 +10,7 @@ import {graphqlCacheEnabled,} from '@service-storage/graphql-soup';import { type Accessor, createSignal } from 'solid-js';+import { calendarCacheAnswered } from './readiness';// Hosts whose native engine predates calendar ranges stay on REST.const [unsupportedHosts, setUnsupportedHosts] = createSignal(@@ -47,3 +48,13 @@ export function graphqlCalendarHost(): CacheHost | undefined {isFeatureEnabled(enableGraphqlCalendar));}++/**+ * The cache host for calendar writes: only one that has answered a calendar+ * read, so a mutation never waits behind cache startup and goes to REST+ * meanwhile.+ */+export function answeringGraphqlCalendarHost(): CacheHost | undefined {+ const host = graphqlCalendarHost();+ return host && calendarCacheAnswered(host) ? host : undefined;+}diff --git a/apps/web/src/lib/queries/calendar/graphql/range.ts b/apps/web/src/lib/queries/calendar/graphql/range.tsindex 9f607051b4..331be22ff2 100644--- a/apps/web/src/lib/queries/calendar/graphql/range.ts+++ b/apps/web/src/lib/queries/calendar/graphql/range.ts@@ -2,6 +2,7 @@ import {type CacheHost,type CalendarLinkWatermarkWire,type CalendarRangeCacheArgs,+ type CalendarRangeCacheResult,type CalendarSpanWire,MAX_RECORD_SELECTION_PAGE_SIZE,readRecordsByKeys,@@ -18,6 +19,12 @@ import type { CalendarOccurrenceQueryRange } from '../keys';import type { CalendarOccurrencesData } from '../occurrences';import { mapCalendarOccurrence, mapCalendarSyncStatus } from './map';import { fetchCached } from './network';+import {+ CALENDAR_CACHE_HEAD_START_MS,+ calendarCacheAnswered,+ markCalendarCacheAnswered,+ withinCacheHeadStart,+} from './readiness';const MS_PER_DAY = 86_400_000;const OCCURRENCE_PAGE_SIZE = 2000;@@ -265,10 +272,44 @@ async function readOccurrenceItems(return items;}+// The outstanding first read of each host that has not answered yet.+const firstReads = new WeakMap<object, Promise<unknown>>();++export type CalendarRangeRead =+ | { kind: 'range'; data: CalendarOccurrencesData }+ | { kind: 'unsupported' }+ | { kind: 'not-ready' };+/**- * Answers a viewport from the cache, fetching only spans never fetched.- * Resolves `undefined` when the host cannot serve calendar ranges.+ * Asks the host for a viewport. A host that has never answered gets a head+ * start; past it, or while an earlier first read is still outstanding, the+ * caller reads from REST instead of waiting on cache startup.*/+async function askCalendarRange(+ host: Pick<CacheHost, 'calendarRange'>,+ args: CalendarRangeCacheArgs,+ headStartMs: number+): Promise<CalendarRangeCacheResult | 'not-ready'> {+ if (calendarCacheAnswered(host)) return host.calendarRange(args);+ if (firstReads.has(host)) return 'not-ready';+ const answer = (async (): Promise<CalendarRangeCacheResult | 'not-ready'> => {+ try {+ const result = await host.calendarRange(args);+ if (result.kind === 'range') markCalendarCacheAnswered(host);+ return result;+ } catch {+ // A failed first read leaves the host unanswered: this viewport reads+ // REST and the next read asks again.+ return 'not-ready';+ } finally {+ firstReads.delete(host);+ }+ })();+ firstReads.set(host, answer);+ return withinCacheHeadStart(answer, headStartMs);+}++/** Answers a viewport from the cache, fetching only spans never fetched. */export async function readCalendarRange(host: Pick<CacheHost,@@ -278,11 +319,18 @@ export async function readCalendarRange(options: {fetchPage?: FetchCalendarOccurrencePage;signal?: AbortSignal;+ headStartMs?: number;} = {}-): Promise<CalendarOccurrencesData | undefined> {+): Promise<CalendarRangeRead> {const args = toCalendarRangeArgs(range);- let result = await host.calendarRange(args);- if (result.kind === 'unsupported') return undefined;+ const first = await askCalendarRange(+ host,+ args,+ options.headStartMs ?? CALENDAR_CACHE_HEAD_START_MS+ );+ if (first === 'not-ready') return { kind: 'not-ready' };+ let result = first;+ if (result.kind === 'unsupported') return { kind: 'unsupported' };if (result.gaps.length > 0) {for (const window of calendarGapWindows(result.gaps)) {await fetchCalendarWindow(@@ -293,10 +341,13 @@ export async function readCalendarRange();}result = await host.calendarRange(args);- if (result.kind === 'unsupported') return undefined;+ if (result.kind === 'unsupported') return { kind: 'unsupported' };}return {- items: await readOccurrenceItems(host, result.occurrenceKeys),- syncStatus: latestSyncStatus,+ kind: 'range',+ data: {+ items: await readOccurrenceItems(host, result.occurrenceKeys),+ syncStatus: latestSyncStatus,+ },};}diff --git a/apps/web/src/lib/queries/calendar/graphql/readiness.ts b/apps/web/src/lib/queries/calendar/graphql/readiness.tsnew file mode 100644index 0000000000..59c2bd8e30--- /dev/null+++ b/apps/web/src/lib/queries/calendar/graphql/readiness.ts@@ -0,0 +1,35 @@+// A host answers nothing until its engine has started, and a start that fails+// can take minutes to give up, so callers wait on a host only once it has+// answered a calendar read.+const answeredHosts = new WeakSet<object>();++/**+ * How long a host that has not answered a calendar read yet gets before a+ * calendar view reads from REST. A healthy browser cache starts in about 0.4s+ * at the median; one that fails to start can take minutes to give up.+ */+export const CALENDAR_CACHE_HEAD_START_MS = 1_000;++export function markCalendarCacheAnswered(host: object): void {+ answeredHosts.add(host);+}++export function calendarCacheAnswered(host: object): boolean {+ return answeredHosts.has(host);+}++/** The read's result if it settles within the head start, else `not-ready`. */+export async function withinCacheHeadStart<T>(+ read: Promise<T>,+ headStartMs = CALENDAR_CACHE_HEAD_START_MS+): Promise<T | 'not-ready'> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const headStart = new Promise<'not-ready'>((resolve) => {+ timer = setTimeout(() => resolve('not-ready'), headStartMs);+ });+ try {+ return await Promise.race([read, headStart]);+ } finally {+ clearTimeout(timer);+ }+}diff --git a/apps/web/src/lib/queries/calendar/graphql/sync-controller.ts b/apps/web/src/lib/queries/calendar/graphql/sync-controller.tsindex e9024d0579..e8b2d6ba16 100644--- a/apps/web/src/lib/queries/calendar/graphql/sync-controller.ts+++ b/apps/web/src/lib/queries/calendar/graphql/sync-controller.ts@@ -8,6 +8,7 @@ import {CalendarsDocument,} from '@service-storage/graphql/generated/graphql';import { fetchCached } from './network';+import { calendarCacheAnswered } from './readiness';export type CalendarChangesPage =CalendarChangesQuery['user']['calendarChanges'];@@ -76,6 +77,11 @@ export class CalendarSyncController {this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;}+ /** Whether the cache has answered a calendar read, so a run cannot stall on cache startup. */+ answering(): boolean {+ return calendarCacheAnswered(this.host);+ }+/** Schedules one debounced delta run. */markStale(_reason: CalendarStaleReason): void {if (this.disposed) return;diff --git a/apps/web/src/lib/queries/calendar/graphql/tests/invalidation.test.ts b/apps/web/src/lib/queries/calendar/graphql/tests/invalidation.test.tsindex a1dedda7cf..8525f3c946 100644--- a/apps/web/src/lib/queries/calendar/graphql/tests/invalidation.test.ts+++ b/apps/web/src/lib/queries/calendar/graphql/tests/invalidation.test.ts@@ -33,6 +33,7 @@ describe('invalidateCalendarOccurrences', () => {order.push('invalidate');});setActiveCalendarSyncController({+ answering: () => true,runDelta,} as unknown as CalendarSyncController);@@ -44,9 +45,23 @@ describe('invalidateCalendarOccurrences', () => {});});+ it('refetches without waiting on a cache that is still starting', async () => {+ const runDelta = vi.fn(() => new Promise<void>(() => {}));+ setActiveCalendarSyncController({+ answering: () => false,+ runDelta,+ } as unknown as CalendarSyncController);++ await invalidateCalendarOccurrences();++ expect(runDelta).not.toHaveBeenCalled();+ expect(invalidateQueriesMock).toHaveBeenCalledTimes(1);+ });+it('still refetches when the delta fails', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});setActiveCalendarSyncController({+ answering: () => true,runDelta: vi.fn().mockRejectedValue(new Error('offline')),} as unknown as CalendarSyncController);diff --git a/apps/web/src/lib/queries/calendar/graphql/tests/range.test.ts b/apps/web/src/lib/queries/calendar/graphql/tests/range.test.tsindex ed0539001f..2c031d7736 100644--- a/apps/web/src/lib/queries/calendar/graphql/tests/range.test.ts+++ b/apps/web/src/lib/queries/calendar/graphql/tests/range.test.ts@@ -14,6 +14,7 @@ import {recordCalendarSyncStatus,toCalendarRangeArgs,} from '../range';+import { calendarCacheAnswered } from '../readiness';import { graphqlOccurrence } from './fixtures';vi.mock('@service-storage/graphql-soup', () => ({@@ -74,6 +75,12 @@ function fakeHost(results: CalendarRangeCacheResult[]) {};}+async function readData(...args: Parameters<typeof readCalendarRange>) {+ const read = await readCalendarRange(...args);+ if (read.kind !== 'range') throw new Error(`expected a range: ${read.kind}`);+ return read.data;+}+describe('readCalendarRange', () => {beforeEach(() =>recordCalendarSyncStatus(@@ -89,7 +96,7 @@ describe('readCalendarRange', () => {}),]);const fetchPage = vi.fn();- const data = await readCalendarRange(host, week, { fetchPage });+ const data = await readData(host, week, { fetchPage });expect(fetchPage).not.toHaveBeenCalled();expect(host.calendarCommit).not.toHaveBeenCalled();expect(host.calendarRange).toHaveBeenCalledWith(toCalendarRangeArgs(week));@@ -132,7 +139,7 @@ describe('readCalendarRange', () => {}));- const data = await readCalendarRange(host, week, { fetchPage });+ const data = await readData(host, week, { fetchPage });expect(fetchPage).toHaveBeenCalledTimes(2);expect(fetchPage.mock.calls[0]?.[0]).toEqual({@@ -182,7 +189,72 @@ describe('readCalendarRange', () => {it('reports an unsupported host so the caller reads from REST', async () => {const host = fakeHost([{ kind: 'unsupported' }]);- await expect(readCalendarRange(host, week)).resolves.toBeUndefined();+ await expect(readCalendarRange(host, week)).resolves.toEqual({+ kind: 'unsupported',+ });+ });++ it('sends viewports to REST while a starting cache has not answered', async () => {+ let answer: (result: CalendarRangeCacheResult) => void = () => {};+ const host = fakeHost([+ range({ occurrenceKeys: ['GraphqlCalendarOccurrence:event-1:a'] }),+ ]);+ host.calendarRange.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ answer = resolve;+ })+ );++ await expect(+ readCalendarRange(host, week, { headStartMs: 5 })+ ).resolves.toEqual({ kind: 'not-ready' });+ await expect(+ readCalendarRange(host, week, { headStartMs: 5 })+ ).resolves.toEqual({ kind: 'not-ready' });+ expect(host.calendarRange).toHaveBeenCalledTimes(1);+ expect(calendarCacheAnswered(host)).toBe(false);++ answer(range({}));+ await vi.waitFor(() => expect(calendarCacheAnswered(host)).toBe(true));+ const data = await readData(host, week, { headStartMs: 5 });+ expect(data.items).toHaveLength(1);+ });++ it('reads REST and asks again after a starting cache fails its first read', async () => {+ const host = fakeHost([+ range({ occurrenceKeys: ['GraphqlCalendarOccurrence:event-1:a'] }),+ ]);+ host.calendarRange.mockRejectedValueOnce(new Error('cache worker timeout'));++ await expect(readCalendarRange(host, week)).resolves.toEqual({+ kind: 'not-ready',+ });+ const data = await readData(host, week);+ expect(data.items).toHaveLength(1);+ expect(calendarCacheAnswered(host)).toBe(true);+ });++ it('does not count a late unsupported answer as answering', async () => {+ let answer: (result: CalendarRangeCacheResult) => void = () => {};+ const host = fakeHost([{ kind: 'unsupported' }]);+ host.calendarRange.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ answer = resolve;+ })+ );++ await expect(+ readCalendarRange(host, week, { headStartMs: 5 })+ ).resolves.toEqual({ kind: 'not-ready' });+ answer({ kind: 'unsupported' });+ await vi.waitFor(async () =>+ expect(await readCalendarRange(host, week)).toEqual({+ kind: 'unsupported',+ })+ );+ expect(calendarCacheAnswered(host)).toBe(false);});});diff --git a/apps/web/src/lib/queries/calendar/graphql/tests/readiness.test.ts b/apps/web/src/lib/queries/calendar/graphql/tests/readiness.test.tsnew file mode 100644index 0000000000..b262bd1265--- /dev/null+++ b/apps/web/src/lib/queries/calendar/graphql/tests/readiness.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';+import { withinCacheHeadStart } from '../readiness';++describe('withinCacheHeadStart', () => {+ it('returns a read that settles within the head start', async () => {+ await expect(+ withinCacheHeadStart(Promise.resolve('cached'), 50)+ ).resolves.toBe('cached');+ });++ it('gives up on a read that outlasts the head start', async () => {+ await expect(+ withinCacheHeadStart(new Promise<string>(() => {}), 5)+ ).resolves.toBe('not-ready');+ });+});diff --git a/apps/web/src/lib/queries/calendar/mutations.ts b/apps/web/src/lib/queries/calendar/mutations.tsindex b5118e4005..6eacc73ed6 100644--- a/apps/web/src/lib/queries/calendar/mutations.ts+++ b/apps/web/src/lib/queries/calendar/mutations.ts@@ -15,7 +15,7 @@ import type { CalendarEventSourceContent } from '@service-storage/generated/scheimport type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';import type { EventTime } from '@service-storage/generated/schemas/eventTime';import { useMutation } from '@tanstack/solid-query';-import { graphqlCalendarHost } from './graphql/flag';+import { answeringGraphqlCalendarHost } from './graphql/flag';import {committedEvent,executeGraphqlCreate,@@ -256,7 +256,7 @@ export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {return useMutation(() => ({mutationKey: RSVP_MUTATION_KEY,mutationFn: async (args: RsvpCalendarEventArgs) => {- const host = graphqlCalendarHost();+ const host = answeringGraphqlCalendarHost();if (host) return committedEvent(await executeGraphqlRsvp(host, args));return await throwOnErr(() =>emailClient.rsvpCalendarEvent(args.eventId, {@@ -437,7 +437,7 @@ type DeleteCallbacks = MutationCallbacks<export function useDeleteCalendarEventMutation(callbacks?: DeleteCallbacks) {return useMutation(() => ({mutationFn: async (args: DeleteCalendarEventArgs) => {- const host = graphqlCalendarHost();+ const host = answeringGraphqlCalendarHost();if (host) {await executeGraphqlDelete(host, args);return;@@ -566,7 +566,7 @@ function applyEventPatch(export function useUpdateCalendarEventMutation(callbacks?: UpdateCallbacks) {return useMutation(() => ({mutationFn: async (args: UpdateCalendarEventArgs) => {- const host = graphqlCalendarHost();+ const host = answeringGraphqlCalendarHost();if (host) return committedEvent(await executeGraphqlUpdate(host, args));return await throwOnErr(() =>emailClient.updateCalendarEvent(args.eventId, {@@ -625,7 +625,7 @@ type CreateCallbacks = MutationCallbacks<export function useCreateCalendarEventMutation(callbacks?: CreateCallbacks) {return useMutation(() => ({mutationFn: async (args: CreateCalendarEventRequest) => {- if (graphqlCalendarHost())+ if (answeringGraphqlCalendarHost())return (await executeGraphqlCreate(args)).event;return await throwOnErr(() => emailClient.createCalendarEvent(args));},diff --git a/apps/web/src/lib/queries/calendar/occurrences.ts b/apps/web/src/lib/queries/calendar/occurrences.tsindex d55e6c2238..d4c9c01c77 100644--- a/apps/web/src/lib/queries/calendar/occurrences.ts+++ b/apps/web/src/lib/queries/calendar/occurrences.ts@@ -12,6 +12,7 @@ import {useGraphqlCalendarHost,} from './graphql/flag';import { readCalendarRange } from './graphql/range';+import { calendarCacheAnswered } from './graphql/readiness';import { activeCalendarSyncController } from './graphql/sync-controller';import { type CalendarOccurrenceQueryRange, calendarKeys } from './keys';@@ -150,9 +151,9 @@ export function useCalendarOccurrencesQuery(if (!range) {throw new Error('Calendar occurrence range is unavailable');}- const cached = await readCalendarRange(host, range, { signal });- if (cached) return cached;- markCalendarCacheUnsupported(host);+ const read = await readCalendarRange(host, range, { signal });+ if (read.kind === 'range') return read.data;+ if (read.kind === 'unsupported') markCalendarCacheUnsupported(host);return fetchCalendarOccurrences(range, signal);},enabled,@@ -161,6 +162,16 @@ export function useCalendarOccurrencesQuery(networkMode: 'offlineFirst' as const,placeholderData: (p: CalendarOccurrencesData | undefined) => p,refetchOnWindowFocus: false,+ // Read from REST while the cache was starting: poll like the REST+ // path until the provider sync finishes.+ refetchInterval: (query: {+ state: { data: CalendarOccurrencesData | undefined };+ }) =>+ options?.().pollWhileSyncing !== false &&+ !calendarCacheAnswered(host) &&+ query.state.data?.syncStatus === CalendarSyncStatus.syncing+ ? CALENDAR_SYNC_POLL_INTERVAL+ : false,};}@@ -190,11 +201,12 @@ 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.+ * the refresh rather than the cache from before it. A cache still starting+ * would hold the delta, so the viewports refetch without it.*/export async function invalidateCalendarOccurrences() {const controller = activeCalendarSyncController();- if (controller) {+ if (controller?.answering()) {await controller.runDelta().catch((error) => {console.warn('Calendar delta sync failed', error);});diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 03999cfd0d..2d6212b5c7 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1226,7 +1226,12 @@ coming online, or returning to the tab runs one `CalendarChanges` delta thatapplies edits made elsewhere. RSVPs, edits, deletions, and creates show at oncethrough the durable mutation queue: a rejected write rolls back with the usualerror, and a write made offline stays visible and replays on reconnect. Native-apps whose engine lacks the calendar cache commands keep the REST path.+apps whose engine lacks the calendar cache commands keep the REST path. Until the+cache answers its first calendar read, viewports wait at most a second and then+read from REST, and writes use REST, so a cache that is slow to start or fails+("Local cache unavailable") never leaves the calendar on skeletons. Writes in+that window behave as on the REST path: offline, they roll back with an error+instead of replaying.A single period arrow retains its slide. Rapid arrow clicks and period hotkeysaccumulate against the requested date and interrupt unfinished slides, without