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): sync once when Calendar opens on an event it doesn't have yet (#8712)

gbirman512aa7bc25b4
diff --git a/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx b/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
index 47fd5be5a0..78d42c114d 100644
--- a/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
+++ b/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
@@ -2,7 +2,7 @@ import { CalendarViewContextProvider } from '@app/features/calendar/components/C
import { useCalendarUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';
import { CalendarFocusContextProvider } from '@app/features/calendar-view/calendar-focus-target';
-import { resolveCalendarTarget } from '@app/features/calendar-view/calendar-target';
+import { createCalendarFocusTarget } from '@app/features/calendar-view/calendar-target';
import { createCalendarTargetAim } from '@app/features/calendar-view/calendar-target-request';
import { Workspace } from '@app/features/calendar-view/components/Workspace';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
@@ -15,7 +15,7 @@ import { createMethodRegistration } from '@core/orchestrator';
import { blockHandleSignal } from '@core/signal/load';
import { useCalendarOccurrencesQuery } from '@queries/calendar/occurrences';
import { useSearchParams } from '@solidjs/router';
-import { createMemo, onMount, Show } from 'solid-js';
+import { onMount, Show } from 'solid-js';
import type { CalendarBlockProps } from './types';
function CalendarBlockDisabledRedirect() {
@@ -78,18 +78,10 @@ function CalendarBlockAdapter(props: CalendarBlockProps) {
};
}
);
- // A cold `.data` read suspends the nearest <Suspense>, which is the one
- // wrapping each calendar page: the first aim of a session enables this
- // query, so reading it unguarded blanks the whole grid for the length of
- // the fetch and remounts it. There is no target to resolve until the
- // occurrences land anyway.
- const focusTarget = createMemo(() => {
- const request = targetRequest();
- if (!request || !occurrencesQuery.isSuccess) {
- return undefined;
- }
- return resolveCalendarTarget(occurrencesQuery.data?.items ?? [], request);
- });
+ const focusTarget = createCalendarFocusTarget(
+ targetRequest,
+ occurrencesQuery
+ );
onMount(() => {
analytics.pageView('calendar');
diff --git a/apps/web/src/features/calendar-view/calendar-target.test.ts b/apps/web/src/features/calendar-view/calendar-target.test.ts
new file mode 100644
index 0000000000..651ee20ea5
--- /dev/null
+++ b/apps/web/src/features/calendar-view/calendar-target.test.ts
@@ -0,0 +1,102 @@
+import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
+import { createRoot, createSignal } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { describe, expect, it, vi } from 'vitest';
+import { createCalendarFocusTarget } from './calendar-target';
+import type { CalendarFocusRequest } from './types';
+
+vi.mock('@queries/calendar/occurrences', () => ({
+ syncCalendarOccurrences: vi.fn(),
+}));
+
+const OCCURRENCE_KEY = '2026-10-29T21:00:00+00:00';
+
+function request(requestId: number): CalendarFocusRequest {
+ return {
+ eventId: 'just-added-copy',
+ occurrenceKey: OCCURRENCE_KEY,
+ range: { startDate: '2026-10-29', endDate: '2026-10-30' },
+ requestId,
+ requestedAt: Date.now(),
+ } as CalendarFocusRequest;
+}
+
+function occurrence(eventId: string): CalendarOccurrenceItem {
+ return {
+ event: { id: eventId },
+ occurrence: {
+ occurrenceKey: OCCURRENCE_KEY,
+ time: {
+ kind: 'timed',
+ startsAt: '2026-10-29T21:00:00Z',
+ endsAt: '2026-10-29T21:30:00Z',
+ },
+ },
+ } as unknown as CalendarOccurrenceItem;
+}
+
+function setup(items: CalendarOccurrenceItem[], isSuccess = true) {
+ const refreshCalendar = vi.fn(async () => {});
+ const [aim, setAim] = createSignal<CalendarFocusRequest | undefined>(
+ request(1)
+ );
+ const [locator, setLocator] = createStore({ isSuccess, data: { items } });
+ return createRoot((dispose) => ({
+ target: createCalendarFocusTarget(aim, locator, refreshCalendar),
+ refreshCalendar,
+ setAim,
+ setLocator,
+ dispose,
+ }));
+}
+
+describe('createCalendarFocusTarget', () => {
+ it('syncs once when the loaded week lacks the event, then lands on it', async () => {
+ // A cached week from before the copy was added.
+ const view = setup([occurrence('older-event')]);
+ await Promise.resolve();
+
+ expect(view.target()).toBeUndefined();
+ expect(view.refreshCalendar).toHaveBeenCalledOnce();
+
+ view.setLocator('data', 'items', [
+ occurrence('older-event'),
+ occurrence('just-added-copy'),
+ ]);
+ expect(view.target()?.eventId).toBe('just-added-copy');
+ expect(view.target()?.requestId).toBe(1);
+ expect(view.refreshCalendar).toHaveBeenCalledOnce();
+ view.dispose();
+ });
+
+ it('does not sync for an event the week already has', async () => {
+ const view = setup([occurrence('just-added-copy')]);
+ await Promise.resolve();
+
+ expect(view.target()?.eventId).toBe('just-added-copy');
+ expect(view.refreshCalendar).not.toHaveBeenCalled();
+ view.dispose();
+ });
+
+ it('syncs again for a later open that still finds nothing', async () => {
+ const view = setup([]);
+ await Promise.resolve();
+ view.setAim(request(2));
+ await Promise.resolve();
+
+ expect(view.refreshCalendar).toHaveBeenCalledTimes(2);
+ view.dispose();
+ });
+
+ it('waits for the locator before deciding the event is missing', async () => {
+ const view = setup([], false);
+ await Promise.resolve();
+ expect(view.refreshCalendar).not.toHaveBeenCalled();
+
+ view.setLocator('isSuccess', true);
+ await Promise.resolve();
+
+ expect(view.refreshCalendar).toHaveBeenCalledOnce();
+ view.dispose();
+ });
+});
diff --git a/apps/web/src/features/calendar-view/calendar-target.ts b/apps/web/src/features/calendar-view/calendar-target.ts
index 71736d13af..be42523d77 100644
--- a/apps/web/src/features/calendar-view/calendar-target.ts
+++ b/apps/web/src/features/calendar-view/calendar-target.ts
@@ -1,5 +1,9 @@
import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import { syncCalendarOccurrences } from '@queries/calendar/occurrences';
import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
+import { type Accessor, createEffect, createMemo } from 'solid-js';
import type { CalendarFocusTarget } from './calendar-focus-target';
import type { CalendarFocusRequest } from './types';
@@ -40,3 +44,54 @@ export function resolveCalendarTarget(
requestedAt: request.requestedAt,
};
}
+
+/** The locator occurrence query, as far as target resolution reads it. */
+interface CalendarLocatorQuery {
+ readonly isSuccess: boolean;
+ readonly data?: { items: CalendarOccurrenceItem[] };
+}
+
+/**
+ * The occurrence the calendar is aimed at, resolved from the locator query
+ * over the request's range.
+ *
+ * The tab's calendar data can predate the target: a copy just added from a
+ * shared-event card while no calendar was open reaches a cached week only on
+ * a later sync, long after the request has expired. When the locator answers
+ * without the event, the calendar data is brought forward once per request
+ * (a delta sync, waiting for a cache that is still starting, then a refetch),
+ * so the target can still land.
+ */
+export function createCalendarFocusTarget(
+ request: Accessor<CalendarFocusRequest | undefined>,
+ locator: CalendarLocatorQuery,
+ refreshCalendar: () => Promise<unknown> = syncCalendarOccurrences
+): Accessor<CalendarFocusTarget | undefined> {
+ // A cold `.data` read suspends the nearest <Suspense>, which is the one
+ // wrapping each calendar page: the first aim of a session enables this
+ // query, so reading it unguarded blanks the whole grid for the length of
+ // the fetch and remounts it. There is no target to resolve until the
+ // occurrences land anyway.
+ const target = createMemo(() => {
+ const current = request();
+ if (!current || !locator.isSuccess) return undefined;
+ return resolveCalendarTarget(locator.data?.items ?? [], current);
+ });
+
+ let refreshedRequestId: number | undefined;
+ createEffect(() => {
+ const current = request();
+ if (!current || !locator.isSuccess || target()) return;
+ if (refreshedRequestId === current.requestId) return;
+ refreshedRequestId = current.requestId;
+ fireAndForget(
+ Telemetry.span('calendar.focus_target_refresh', async (span) => {
+ span.setAttr('calendar.event_id', current.eventId);
+ await refreshCalendar();
+ }),
+ 'calendar-target'
+ );
+ });
+
+ return target;
+}
diff --git a/apps/web/src/features/calendar-view/calendar-view.tsx b/apps/web/src/features/calendar-view/calendar-view.tsx
index b11eb76f94..4c0cfc41c7 100644
--- a/apps/web/src/features/calendar-view/calendar-view.tsx
+++ b/apps/web/src/features/calendar-view/calendar-view.tsx
@@ -27,7 +27,7 @@ import {
Show,
} from 'solid-js';
import { CalendarFocusContextProvider } from './calendar-focus-target';
-import { resolveCalendarTarget } from './calendar-target';
+import { createCalendarFocusTarget } from './calendar-target';
import { createCalendarTargetAim } from './calendar-target-request';
import { calendarSearch, calendarSearchTarget } from './calendar-url';
import { CalendarViewSkeleton } from './calendar-view-skeleton';
@@ -180,13 +180,10 @@ export function CalendarView(props: CalendarViewProps) {
};
}
);
- const focusTarget = createMemo(() => {
- const request = targetRequest();
- if (!request || !occurrencesQuery.isSuccess) {
- return undefined;
- }
- return resolveCalendarTarget(occurrencesQuery.data?.items ?? [], request);
- });
+ const focusTarget = createCalendarFocusTarget(
+ targetRequest,
+ occurrencesQuery
+ );
const setFocusedEventId = (eventId: string | undefined) => {
const next = eventId ?? '';
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.ts
index 8525f3c946..67dbc1e227 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
@@ -1,6 +1,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { calendarKeys } from '../../keys';
-import { invalidateCalendarOccurrences } from '../../occurrences';
+import {
+ invalidateCalendarOccurrences,
+ syncCalendarOccurrences,
+} from '../../occurrences';
import {
type CalendarSyncController,
setActiveCalendarSyncController,
@@ -71,6 +74,43 @@ describe('invalidateCalendarOccurrences', () => {
warn.mockRestore();
});
+ it('syncs a starting cache before an expected read refetches', async () => {
+ const order: string[] = [];
+ let ready!: () => void;
+ const runDelta = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ ready = () => {
+ order.push('delta');
+ resolve();
+ };
+ })
+ );
+ invalidateQueriesMock.mockImplementation(async () => {
+ order.push('invalidate');
+ });
+ setActiveCalendarSyncController({
+ answering: () => false,
+ runDelta,
+ } as unknown as CalendarSyncController);
+
+ const sync = syncCalendarOccurrences();
+ await Promise.resolve();
+ expect(invalidateQueriesMock).not.toHaveBeenCalled();
+ ready();
+ await sync;
+
+ expect(order).toEqual(['delta', 'invalidate']);
+ });
+
+ it('refetches the REST viewports when there is no cache to sync', async () => {
+ await syncCalendarOccurrences();
+
+ expect(invalidateQueriesMock).toHaveBeenCalledWith({
+ queryKey: calendarKeys.occurrences._def,
+ });
+ });
+
it('nests cache-backed keys under the REST prefix', () => {
const range = {
start: '2026-10-05T00:00:00.000Z',
diff --git a/apps/web/src/lib/queries/calendar/occurrences.ts b/apps/web/src/lib/queries/calendar/occurrences.ts
index 7e1427c551..c328dee4c5 100644
--- a/apps/web/src/lib/queries/calendar/occurrences.ts
+++ b/apps/web/src/lib/queries/calendar/occurrences.ts
@@ -1,5 +1,6 @@
import { throwOnErr } from '@core/util/result';
import type { CacheHost } from '@graphql-cache/index';
+import { Telemetry } from '@macro-inc/observability';
import { queryClient } from '@queries/client';
import { subscribeToVisibleCacheChanges } from '@queries/subscribe-to-visible-cache-changes';
import { storageServiceClient } from '@service-storage/client';
@@ -259,3 +260,30 @@ export async function invalidateCalendarOccurrences() {
queryKey: calendarKeys.occurrences._def,
});
}
+
+/**
+ * Brings the calendar forward for a read that came back without something it
+ * expected. Unlike `invalidateCalendarOccurrences`, the delta always runs,
+ * waiting for a cache that is still starting: nothing awaits this refresh, and
+ * a refetch that skipped the delta could reread a stale covered week.
+ */
+export async function syncCalendarOccurrences() {
+ const controller = activeCalendarSyncController();
+ await Telemetry.span('calendar.occurrences_delta_sync', async (span) => {
+ span.setAttr('calendar.transport', controller ? 'graphql' : 'rest');
+ if (!controller) return;
+ try {
+ await controller.runDelta();
+ span.setAttr('calendar.delta.outcome', 'synced');
+ } catch (error) {
+ span.setAttr('calendar.delta.outcome', 'failed');
+ span.error('Calendar delta sync failed');
+ console.warn('Calendar delta sync failed', error);
+ }
+ });
+ return Telemetry.span('calendar.occurrences_refetch', () =>
+ queryClient.invalidateQueries({
+ queryKey: calendarKeys.occurrences._def,
+ })
+ );
+}
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index 3b5979b245..cc67808967 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -729,7 +729,9 @@ in a delegated inbox), with an `Open` button that opens the viewer's copy. A men
viewer's own copy shows neither. A shared-event sheet open on a phone stays up when the viewer
adds the event or is invited, and switches to that line and `Open` in place. Opening from the
sheet (`Open`, the title, or Open in New Split) closes it, since the native apps keep the
-pane behind the opened one mounted.
+pane behind the opened one mounted. When Calendar opens on an event its loaded week doesn't
+have yet, such as a copy added a moment ago while Calendar was closed, it syncs once and then
+shows the event's details.
## Scheduling — `/app/scheduling`