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
perf(calendar): cut duplicate out-of-office overlay refetches (#8696)
gbirmandcfc464af0f5
diff --git a/apps/web/src/features/calendar-view/components/CalendarSidebar.test.tsx b/apps/web/src/features/calendar-view/components/CalendarSidebar.test.tsxindex 4e7e884f66..2c8c187cd9 100644--- a/apps/web/src/features/calendar-view/components/CalendarSidebar.test.tsx+++ b/apps/web/src/features/calendar-view/components/CalendarSidebar.test.tsx@@ -8,9 +8,10 @@ import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';import {QueryClient,QueryClientProvider,- useQuery,+ useQueries,useQueryClient,} from '@tanstack/solid-query';+import { addDays, format } from 'date-fns';import { createSignal } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';import { TeamOooUpcomingList } from './CalendarSidebar';@@ -33,8 +34,13 @@ vi.mock('@app/features/scheduling/calendar-actions', () => ({CalendarSchedulingActions: () => null,}));vi.mock('@queries/calendar/team-ooo', () => ({- useTeamOutOfOfficeQuery: () =>- useQuery(() => ({ queryKey: ['team-ooo'], queryFn: requests.teamOoo })),+ useTeamOutOfOfficeQueries: (input: () => { ranges: { start: string }[] }) =>+ useQueries(() => ({+ queries: input().ranges.map((range) => ({+ queryKey: ['team-ooo', range.start],+ queryFn: requests.teamOoo,+ })),+ })),}));const [selectedEvent, setSelectedEvent] = createSignal<CalendarEvent>();@@ -53,12 +59,14 @@ vi.mock('@app/components/view-shell', () => ({}));function teamOooItems(): TeamOutOfOfficeItem[] {+ const day = format(addDays(new Date(), 28), 'yyyy-MM-dd');+ const nextDay = format(addDays(new Date(), 29), 'yyyy-MM-dd');return [{eventId: 'ooo-1',- occurrenceKey: '2026-11-20',+ occurrenceKey: day,ownerId: 'macro|[email protected]',- time: { kind: 'allDay', startDate: '2026-11-20', endDate: '2026-11-21' },+ time: { kind: 'allDay', startDate: day, endDate: nextDay },},];}@@ -90,10 +98,11 @@ describe('TeamOooUpcomingList', () => {fireEvent.click(await screen.findByRole('button', { name: /Jackson/ }));const anchor = selectEvent.mock.calls[0][1];expect(anchor.getAttribute('aria-current')).toBe('true');+ const initialRequests = requests.teamOoo.mock.calls.length;await refetch();- expect(requests.teamOoo).toHaveBeenCalledTimes(2);+ expect(requests.teamOoo).toHaveBeenCalledTimes(initialRequests * 2);expect(screen.getByRole('button', { name: /Jackson/ })).toBe(anchor);expect(anchor.isConnected).toBe(true);});diff --git a/apps/web/src/features/calendar/hooks/use-team-ooo.test.tsx b/apps/web/src/features/calendar/hooks/use-team-ooo.test.tsxindex 72b3592705..e07dfe868a 100644--- a/apps/web/src/features/calendar/hooks/use-team-ooo.test.tsx+++ b/apps/web/src/features/calendar/hooks/use-team-ooo.test.tsx@@ -3,7 +3,7 @@ import {createCalendarOccurrenceQueryRange,} from '@queries/calendar/occurrences';import type {- TeamOutOfOfficeQueryInput,+ TeamOutOfOfficeQueriesInput,TeamOutOfOfficeQueryOptions,} from '@queries/calendar/team-ooo';import type { TeamOutOfOfficeItem } from '@service-storage/generated/schemas/teamOutOfOfficeItem';@@ -11,15 +11,22 @@ import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';import {QueryClient,QueryClientProvider,- useQuery,+ useQueries,} from '@tanstack/solid-query';import { type Accessor, createSignal, For, Suspense } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';import { TEAM_OOO_SOURCE_ID } from '../types';-import { useTeamOooEvents } from './use-team-ooo';+import {+ teamOooWindows,+ useTeamOooEvents,+ useUpcomingTeamOoo,+} from './use-team-ooo';const requests = vi.hoisted(() => ({- teamOoo: vi.fn<() => Promise<TeamOutOfOfficeItem[]>>(),+ teamOoo:+ vi.fn<+ (range: CalendarOccurrenceQueryRange) => Promise<TeamOutOfOfficeItem[]>+ >(),}));vi.mock('@core/context/user', () => ({@@ -36,20 +43,23 @@ vi.mock('./use-calendar-ui-flag', () => ({useCalendarTeamOooFlag: () => () => true,}));vi.mock('@queries/calendar/team-ooo', () => ({- useTeamOutOfOfficeQuery: (- input: Accessor<TeamOutOfOfficeQueryInput>,+ useTeamOutOfOfficeQueries: (+ input: Accessor<TeamOutOfOfficeQueriesInput>,options?: Accessor<TeamOutOfOfficeQueryOptions>) =>- useQuery(() => ({- queryKey: ['team-ooo', input().userId, input().range],- queryFn: requests.teamOoo,- enabled: options?.().enabled !== false,+ useQueries(() => ({+ queries: input().ranges.map((range) => ({+ queryKey: ['team-ooo', input().userId, range],+ queryFn: () => requests.teamOoo(range),+ enabled: options?.().enabled !== false,+ })),})),}));afterEach(() => {cleanup();requests.teamOoo.mockReset();+ vi.useRealTimers();});function vacation(range: CalendarOccurrenceQueryRange): TeamOutOfOfficeItem {@@ -115,3 +125,116 @@ describe('useTeamOooEvents', () => {await waitFor(() => expect(screen.queryByText('Ada: Vacation')).toBeNull());});});++const localRange = (start: Date, days: number) => {+ const end = new Date(start);+ end.setDate(end.getDate() + days);+ return createCalendarOccurrenceQueryRange(start, end);+};++function allDay(eventId: string, startDate: string, endDate: string) {+ return {+ eventId,+ occurrenceKey: startDate,+ ownerId: 'teammate',+ title: eventId,+ time: { kind: 'allDay', startDate, endDate },+ } satisfies TeamOutOfOfficeItem;+}++describe('teamOooWindows', () => {+ const now = new Date(2026, 9, 23, 12);++ it('gives the pager weeks and the upcoming list shared windows', () => {+ const weeks = [11, 18, 25].map((day) =>+ teamOooWindows(localRange(new Date(2026, 9, day), 7), now)+ );+ const upcoming = teamOooWindows(localRange(new Date(2026, 9, 23), 90), now);++ for (const windows of weeks) {+ expect(+ windows.map((window) => [window.startDate, window.endDate])+ ).toEqual([['2026-09-28', '2026-12-28']]);+ }+ expect(+ upcoming.map((window) => [window.startDate, window.endDate])+ ).toEqual([+ ['2026-09-28', '2026-12-28'],+ ['2026-12-28', '2027-03-29'],+ ]);+ });++ it('covers a viewport that crosses a window boundary with both windows', () => {+ const windows = teamOooWindows(localRange(new Date(2026, 11, 20), 14), now);++ expect(windows.map((window) => [window.startDate, window.endDate])).toEqual(+ [+ ['2026-09-28', '2026-12-28'],+ ['2026-12-28', '2027-03-29'],+ ]+ );+ });++ it('keeps windows inside the supported range', () => {+ const [first] = teamOooWindows(localRange(new Date(2025, 9, 27), 7), now);++ expect(first?.startDate).toBe('2025-10-24');+ expect(first?.endDate).toBe('2025-12-29');+ });+});++describe('shared team out-of-office windows', () => {+ it('requests each window once and shows each consumer only its own range', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date(2026, 9, 23, 12));+ requests.teamOoo.mockImplementation(async (range) =>+ [+ allDay('This week', '2026-10-23', '2026-10-24'),+ allDay('Across windows', '2026-12-27', '2026-12-29'),+ allDay('January', '2027-01-11', '2027-01-12'),+ ].filter(+ (item) =>+ item.time.startDate < range.endDate &&+ item.time.endDate > range.startDate+ )+ );+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Upcoming() {+ const upcoming = useUpcomingTeamOoo();+ return (+ <ol aria-label="Upcoming">+ <For each={upcoming.windows()}>+ {(window) => <li>{window.title}</li>}+ </For>+ </ol>+ );+ }++ render(() => (+ <QueryClientProvider client={client}>+ <Suspense>+ <For each={[11, 18, 25]}>+ {(day) => (+ <TeamOooTitles+ range={localRange(new Date(2026, 9, day), 7)}+ hiddenSourceIds={() => new Set<string>()}+ />+ )}+ </For>+ <Upcoming />+ </Suspense>+ </QueryClientProvider>+ ));++ const upcoming = await screen.findByRole('list', { name: 'Upcoming' });+ await waitFor(() =>+ expect(upcoming.textContent).toBe('This weekAcross windowsJanuary')+ );+ // Three pager weeks and the upcoming list read two windows.+ expect(requests.teamOoo).toHaveBeenCalledTimes(2);+ expect(screen.getAllByText('Ada: This week')).toHaveLength(1);+ expect(screen.queryByText('Ada: January')).toBeNull();+ });+});diff --git a/apps/web/src/features/calendar/hooks/use-team-ooo.ts b/apps/web/src/features/calendar/hooks/use-team-ooo.tsindex 9e829a3255..c354698a6a 100644--- a/apps/web/src/features/calendar/hooks/use-team-ooo.ts+++ b/apps/web/src/features/calendar/hooks/use-team-ooo.ts@@ -4,11 +4,21 @@ import {type CalendarOccurrenceQueryRange,createCalendarOccurrenceQueryRange,} from '@queries/calendar/occurrences';-import { useTeamOutOfOfficeQuery } from '@queries/calendar/team-ooo';+import {+ type TeamOutOfOfficeQueryOptions,+ useTeamOutOfOfficeQueries,+} from '@queries/calendar/team-ooo';import { useCurrentTeamQuery } from '@queries/team/teams';import { EventType } from '@service-storage/generated/schemas/eventType';import type { TeamOutOfOfficeItem } from '@service-storage/generated/schemas/teamOutOfOfficeItem';-import { parseISO } from 'date-fns';+import {+ addDays,+ differenceInCalendarDays,+ max,+ min,+ parseISO,+ startOfDay,+} from 'date-fns';import { type Accessor, createMemo } from 'solid-js';import {type CalendarEvent,@@ -16,7 +26,10 @@ import {NO_VIEWER_CAPABILITIES,TEAM_OOO_SOURCE_ID,} from '../types';-import { isCalendarRangeSupported } from '../utils/calendar-supported-range';+import {+ getCalendarSupportedRange,+ isCalendarRangeSupported,+} from '../utils/calendar-supported-range';import { useCalendarTeamOooFlag } from './use-calendar-ui-flag';/** Prefix of every per-teammate visibility-source id. */@@ -80,6 +93,144 @@ function mapTeamOooItem(item: TeamOutOfOfficeItem): CalendarEvent {};}+/** Days in one shared out-of-office request window. */+const TEAM_OOO_WINDOW_DAYS = 91;+/** A fixed local Monday, so every consumer derives the same windows. */+const TEAM_OOO_WINDOW_EPOCH = new Date(2024, 0, 1);++const windowIndex = (date: Date) =>+ Math.floor(+ differenceInCalendarDays(date, TEAM_OOO_WINDOW_EPOCH) / TEAM_OOO_WINDOW_DAYS+ );++/**+ * The fixed windows covering a viewport, inside the supported range. Every+ * overlay consumer requests whole windows, so the calendar's pages and its+ * sidebar share requests instead of each polling its own range.+ */+export function teamOooWindows(+ range: CalendarOccurrenceQueryRange,+ now = new Date()+): CalendarOccurrenceQueryRange[] {+ const supported = getCalendarSupportedRange(now);+ const lastDay = max([+ addDays(parseISO(range.endDate), -1),+ startOfDay(new Date(Date.parse(range.end) - 1)),+ ]);+ const first = Math.min(+ windowIndex(parseISO(range.startDate)),+ windowIndex(new Date(range.start))+ );+ const windows: CalendarOccurrenceQueryRange[] = [];+ for (let index = first; index <= windowIndex(lastDay); index += 1) {+ const start = max([+ addDays(TEAM_OOO_WINDOW_EPOCH, index * TEAM_OOO_WINDOW_DAYS),+ supported.start,+ ]);+ const end = min([+ addDays(TEAM_OOO_WINDOW_EPOCH, (index + 1) * TEAM_OOO_WINDOW_DAYS),+ supported.end,+ ]);+ if (start < end)+ windows.push(createCalendarOccurrenceQueryRange(start, end));+ }+ return windows;+}++const sameWindows = (+ previous: readonly CalendarOccurrenceQueryRange[],+ next: readonly CalendarOccurrenceQueryRange[]+) =>+ previous.length === next.length &&+ previous.every(+ (window, index) =>+ window.start === next[index]?.start && window.end === next[index]?.end+ );++/** The server's overlap rule, applied to the consumer's own viewport. */+function overlapsRange(+ item: TeamOutOfOfficeItem,+ range: CalendarOccurrenceQueryRange+) {+ const time = item.time;+ return time.kind === 'timed'+ ? Date.parse(time.startsAt) < Date.parse(range.end) &&+ Date.parse(time.endsAt) > Date.parse(range.start)+ : time.startDate < range.endDate && time.endDate > range.startDate;+}++const itemStart = (item: TeamOutOfOfficeItem) =>+ item.time.kind === 'timed'+ ? Date.parse(item.time.startsAt)+ : Date.parse(`${item.time.startDate}T00:00:00Z`);++/** Soonest first, then by event and occurrence, as the server orders them. */+function compareItems(left: TeamOutOfOfficeItem, right: TeamOutOfOfficeItem) {+ return (+ itemStart(left) - itemStart(right) ||+ left.eventId.localeCompare(right.eventId) ||+ left.occurrenceKey.localeCompare(right.occurrenceKey)+ );+}++/**+ * Teammates' out-of-office items in one viewport, read from the shared+ * windows covering it. Items arrive only once every window has settled, as+ * they did from the viewport's own request.+ */+function useTeamOooItems(+ range: Accessor<CalendarOccurrenceQueryRange | undefined>,+ options?: Accessor<TeamOutOfOfficeQueryOptions>+) {+ const userId = useUserId();+ const windows = createMemo(+ () => {+ const current = range();+ return current ? teamOooWindows(current) : [];+ },+ [],+ { equals: sameWindows }+ );+ const queries = useTeamOutOfOfficeQueries(+ () => ({ userId: userId(), ranges: windows() }),+ options+ );+ const items = createMemo<TeamOutOfOfficeItem[]>(() => {+ const current = range();+ // Pending reads suspend, and placeholder data belongs to the previous+ // range. Neither can supply events for the current viewport.+ if (+ !current ||+ queries.length === 0 ||+ !queries.every(+ (query) =>+ query.isSuccess && !query.isPaused && !query.isPlaceholderData+ )+ ) {+ return [];+ }+ const byOccurrence = new Map<string, TeamOutOfOfficeItem>();+ for (const query of queries) {+ if (!query.isSuccess) continue;+ for (const item of query.data) {+ if (overlapsRange(item, current)) {+ byOccurrence.set(+ JSON.stringify([item.eventId, item.occurrenceKey]),+ item+ );+ }+ }+ }+ return [...byOccurrence.values()].sort(compareItems);+ });++ return {+ items,+ isPending: () => queries.some((query) => query.isPending),+ isError: () => queries.some((query) => query.isError || query.isPaused),+ };+}+export interface TeamOooEventData {events: Accessor<CalendarEvent[]>;eventsById: Accessor<Map<string, CalendarEvent>>;@@ -95,7 +246,6 @@ export interface TeamOooEventOptions {export function useTeamOooEvents(options: TeamOooEventOptions): TeamOooEventData {- const userId = useUserId();const teamOooEnabled = useCalendarTeamOooFlag();const isRangeSupported = createMemo(() => {const range = options.range();@@ -103,26 +253,13 @@ export function useTeamOooEvents(});const isOverlayVisible = () =>teamOooEnabled() && options.isSourceVisible?.(TEAM_OOO_SOURCE_ID) !== false;- const query = useTeamOutOfOfficeQuery(- () => ({ userId: userId(), range: options.range() }),- () => ({- enabled: isRangeSupported() && isOverlayVisible(),- refetchOnWindowFocus: options.refetchOnWindowFocus?.(),- })- );+ const teamOoo = useTeamOooItems(options.range, () => ({+ enabled: isRangeSupported() && isOverlayVisible(),+ refetchOnWindowFocus: options.refetchOnWindowFocus?.(),+ }));const events = createMemo(() => {- // Pending reads suspend, and placeholder data belongs to the previous- // range. Neither can supply events for the current viewport.- if (- !isOverlayVisible() ||- !isRangeSupported() ||- !query.isSuccess ||- query.isPaused ||- query.isPlaceholderData- ) {- return [];- }- return query.data.map(mapTeamOooItem);+ if (!isOverlayVisible() || !isRangeSupported()) return [];+ return teamOoo.items().map(mapTeamOooItem);});const eventsById = createMemo(() => new Map(events().map((event) => [event.id, event]))@@ -161,19 +298,17 @@ export interface UpcomingTeamOoo {/** Teammates' out-of-office windows from today forward, soonest first. */export function useUpcomingTeamOoo(): UpcomingTeamOoo {- const userId = useUserId();const rangeStart = new Date();rangeStart.setHours(0, 0, 0, 0);const rangeEnd = new Date(rangeStart);rangeEnd.setDate(rangeEnd.getDate() + UPCOMING_TEAM_OOO_DAYS);const range = createCalendarOccurrenceQueryRange(rangeStart, rangeEnd);- const query = useTeamOutOfOfficeQuery(() => ({ userId: userId(), range }));+ const teamOoo = useTeamOooItems(() => range);const windows = createMemo<TeamOooWindow[]>(() => {- // Read data only on success so a pending query never hits the suspending- // resource read and an errored refetch never surfaces stale rows.- if (!query.isSuccess || query.isPaused) return [];- return query.data.map((item) => {+ // Items arrive only once every window settled, so an errored refetch+ // never surfaces stale rows.+ return teamOoo.items().map((item) => {const time = item.time;const [start, end, allDay] =time.kind === 'timed'@@ -195,7 +330,7 @@ export function useUpcomingTeamOoo(): UpcomingTeamOoo {return {windows,- isPending: () => query.isPending,- isError: () => query.isError || query.isPaused,+ isPending: teamOoo.isPending,+ isError: teamOoo.isError,};}diff --git a/apps/web/src/lib/queries/calendar/team-ooo.ts b/apps/web/src/lib/queries/calendar/team-ooo.tsindex bcdd29518f..05a9961dd1 100644--- a/apps/web/src/lib/queries/calendar/team-ooo.ts+++ b/apps/web/src/lib/queries/calendar/team-ooo.ts@@ -1,16 +1,19 @@import { throwOnErr } from '@core/util/result';import { storageServiceClient } from '@service-storage/client';import type { TeamOutOfOfficeItem } from '@service-storage/generated/schemas/teamOutOfOfficeItem';-import { queryOptions, useQuery } from '@tanstack/solid-query';+import { focusManager, queryOptions, useQueries } from '@tanstack/solid-query';+import { addDays, differenceInCalendarDays, format, parseISO } from 'date-fns';import type { Accessor } from 'solid-js';+import { queryClient } from '../client';import { type CalendarOccurrenceQueryRange, calendarKeys } from './keys';import { useCalendarTeamIdentityQuery } from './team';const TEAM_OOO_PAGE_SIZE = 2000;+const TEAM_OOO_POLL_INTERVAL = 30_000;-export interface TeamOutOfOfficeQueryInput {+export interface TeamOutOfOfficeQueriesInput {userId: string | undefined;- range: CalendarOccurrenceQueryRange | undefined;+ ranges: readonly CalendarOccurrenceQueryRange[];}export interface TeamOutOfOfficeQueryOptions {@@ -18,7 +21,27 @@ export interface TeamOutOfOfficeQueryOptions {refetchOnWindowFocus?: boolean;}-/** Fetches teammates' out-of-office occurrences for one viewport. */+/** The viewport's two halves by local date, or none for a single day. */+function splitRange(+ range: CalendarOccurrenceQueryRange+): [CalendarOccurrenceQueryRange, CalendarOccurrenceQueryRange] | undefined {+ const start = parseISO(range.startDate);+ const days = differenceInCalendarDays(parseISO(range.endDate), start);+ if (days < 2) return undefined;+ const middle = addDays(start, Math.floor(days / 2));+ const at = middle.toISOString();+ const date = format(middle, 'yyyy-MM-dd');+ return [+ { ...range, end: at, endDate: date },+ { ...range, start: at, startDate: date },+ ];+}++/**+ * Fetches teammates' out-of-office occurrences for one viewport. A viewport+ * with more than one page of them splits in half until each part fits, so a+ * busy team's later occurrences are not cut off.+ */export async function fetchTeamOutOfOffice(range: CalendarOccurrenceQueryRange,signal?: AbortSignal@@ -30,13 +53,24 @@ export async function fetchTeamOutOfOffice(signal,}));- return response.items;+ const halves = response.hasMore ? splitRange(range) : undefined;+ if (!halves) return response.items;+ const parts = await Promise.all(+ halves.map((half) => fetchTeamOutOfOffice(half, signal))+ );+ // An occurrence that spans the split comes back from both halves.+ const byOccurrence = new Map(+ parts+ .flat()+ .map((item) => [JSON.stringify([item.eventId, item.occurrenceKey]), item])+ );+ return [...byOccurrence.values()];}// Cached callbacks close over the resolved range and flags only.function teamOutOfOfficeQueryOptions(userId: string | undefined,- range: CalendarOccurrenceQueryRange | undefined,+ range: CalendarOccurrenceQueryRange,teamId: string | undefined,enabled: boolean,refetchOnWindowFocus: boolean@@ -44,33 +78,47 @@ function teamOutOfOfficeQueryOptions(return queryOptions({queryKey: calendarKeys.teamOutOfOffice(userId ?? '', range, teamId).queryKey,- queryFn: ({ signal }) => {- if (!range) {- throw new Error('Team out-of-office range is unavailable');- }-- return fetchTeamOutOfOffice(range, signal);- },- enabled:- Boolean(userId) && Boolean(teamId) && range !== undefined && enabled,+ queryFn: ({ signal }) => fetchTeamOutOfOffice(range, signal),+ enabled: Boolean(userId) && Boolean(teamId) && enabled,staleTime: 0,gcTime: 0,- refetchInterval: 30_000,refetchOnReconnect: 'always',refetchOnWindowFocus,});}-export function useTeamOutOfOfficeQuery(- input: Accessor<TeamOutOfOfficeQueryInput>,+let pollInstalled = false;++/**+ * Polls every mounted out-of-office range once per interval. TanStack runs+ * `refetchInterval` per observer, and the calendar's pages and its sidebar+ * observe the same ranges, so per-query intervals would fetch each range once+ * per observer. Like `refetchInterval`, it waits while the window is hidden.+ */+function ensureTeamOutOfOfficePolling() {+ if (pollInstalled) return;+ pollInstalled = true;+ setInterval(() => {+ if (!focusManager.isFocused()) return;+ queryClient.invalidateQueries(+ { queryKey: calendarKeys.teamOutOfOffice._def },+ { cancelRefetch: false }+ );+ }, TEAM_OOO_POLL_INTERVAL);+}++/** One query per range; observers of the same range share its request. */+export function useTeamOutOfOfficeQueries(+ input: Accessor<TeamOutOfOfficeQueriesInput>,options?: Accessor<TeamOutOfOfficeQueryOptions>) {+ ensureTeamOutOfOfficePolling();const identity = useCalendarTeamIdentityQuery(() => input().userId,() => options?.().enabled !== false);- return useQuery(() => {- const { userId, range } = input();+ return useQueries(() => {+ const { userId, ranges } = input();const opts = options?.();const team =identity.isSuccess && !identity.isPaused ? identity.data : undefined;@@ -78,12 +126,16 @@ export function useTeamOutOfOfficeQuery(? team.team.id: undefined;- return teamOutOfOfficeQueryOptions(- userId,- range,- teamId,- opts?.enabled !== false,- opts?.refetchOnWindowFocus ?? true- );+ return {+ queries: ranges.map((range) =>+ teamOutOfOfficeQueryOptions(+ userId,+ range,+ teamId,+ opts?.enabled !== false,+ opts?.refetchOnWindowFocus ?? true+ )+ ),+ };});}diff --git a/apps/web/src/lib/queries/calendar/tests/team-ooo.test.tsx b/apps/web/src/lib/queries/calendar/tests/team-ooo.test.tsxnew file mode 100644index 0000000000..1d58a3f947--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/team-ooo.test.tsx@@ -0,0 +1,147 @@+import {+ focusManager,+ QueryClient,+ QueryClientProvider,+} from '@tanstack/solid-query';+import { 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 { fetchTeamOutOfOffice, useTeamOutOfOfficeQueries } from '../team-ooo';++const listTeamOutOfOffice = vi.hoisted(() => vi.fn());++vi.mock('@service-storage/client', () => ({+ storageServiceClient: { listTeamOutOfOffice },+}));+vi.mock('../team', () => ({+ useCalendarTeamIdentityQuery: () => ({+ isSuccess: true,+ isPaused: false,+ data: { team: { id: 'team-a' }, members: [{ user_id: 'alice' }] },+ }),+}));++let testQueryClient: QueryClient;++vi.mock('../../client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));++const window = {+ start: '2026-09-28T04:00:00.000Z',+ end: '2026-12-28T05:00:00.000Z',+ startDate: '2026-09-28',+ endDate: '2026-12-28',+};++const disposers: (() => void)[] = [];++function renderObserver() {+ disposers.push(+ render(+ () => (+ <QueryClientProvider client={testQueryClient}>+ {(() => {+ useTeamOutOfOfficeQueries(() => ({+ userId: 'alice',+ ranges: [window],+ }));+ return null as unknown as JSX.Element;+ })()}+ </QueryClientProvider>+ ),+ document.body+ )+ );+}++beforeEach(() => {+ vi.useFakeTimers();+ focusManager.setFocused(true);+ listTeamOutOfOffice.mockResolvedValue(ok({ items: [] }));+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+});++afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+ focusManager.setFocused(undefined);+ vi.useRealTimers();+});++describe('useTeamOutOfOfficeQueries', () => {+ it('polls a window once per interval however many views observe it', async () => {+ // Views mount at different times, as the calendar's pages and its+ // sidebar do; per-observer intervals would each poll on their own clock.+ renderObserver();+ await vi.advanceTimersByTimeAsync(10_000);+ renderObserver();+ await vi.advanceTimersByTimeAsync(10_000);+ renderObserver();+ await vi.advanceTimersByTimeAsync(0);+ const mounted = listTeamOutOfOffice.mock.calls.length;++ await vi.advanceTimersByTimeAsync(10_000);+ expect(listTeamOutOfOffice).toHaveBeenCalledTimes(mounted + 1);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(listTeamOutOfOffice).toHaveBeenCalledTimes(mounted + 2);++ focusManager.setFocused(false);+ await vi.advanceTimersByTimeAsync(30_000);+ expect(listTeamOutOfOffice).toHaveBeenCalledTimes(mounted + 2);+ });+});++describe('fetchTeamOutOfOffice', () => {+ it('splits a window with more than one page until each part fits', async () => {+ const item = (eventId: string, startDate: string, endDate: string) => ({+ eventId,+ occurrenceKey: startDate,+ ownerId: 'bob',+ time: { kind: 'allDay' as const, startDate, endDate },+ });+ listTeamOutOfOffice.mockImplementationOnce(async () =>+ ok({ hasMore: true, items: [] })+ );+ listTeamOutOfOffice.mockImplementationOnce(async () =>+ ok({+ hasMore: false,+ items: [+ item('early', '2026-10-01', '2026-10-02'),+ item('spanning', '2026-11-10', '2026-11-14'),+ ],+ })+ );+ listTeamOutOfOffice.mockImplementationOnce(async () =>+ ok({+ hasMore: false,+ items: [+ item('spanning', '2026-11-10', '2026-11-14'),+ item('late', '2026-12-20', '2026-12-21'),+ ],+ })+ );++ const items = await fetchTeamOutOfOffice(window);++ expect(+ listTeamOutOfOffice.mock.calls.map(([args]) => [+ args.startDate,+ args.endDate,+ ])+ ).toEqual([+ ['2026-09-28', '2026-12-28'],+ ['2026-09-28', '2026-11-12'],+ ['2026-11-12', '2026-12-28'],+ ]);+ expect(items.map((found) => found.eventId)).toEqual([+ 'early',+ 'spanning',+ 'late',+ ]);+ });+});diff --git a/crates/email/src/domain/send_attempt.rs b/crates/email/src/domain/send_attempt.rsindex e9ee483384..2b5074fba0 100644--- a/crates/email/src/domain/send_attempt.rs+++ b/crates/email/src/domain/send_attempt.rs@@ -5,6 +5,8 @@ use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};use uuid::Uuid;+// Only the confirmed-send agent tool reads approval snapshots.+#[cfg(all(feature = "inbound", feature = "ai_tools"))]mod approval;use super::models::{diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex 76d03fadf7..1dcfaf15f5 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -646,7 +646,10 @@ shows or hides the overlay (the list itself always shows); clicking a row navigato that date. Coverage depends on each teammate having connected their own calendar and usingGoogle's out-of-office event type.-Routine sync notifications that explicitly exclude OOO changes refresh this list+The grid's pages and the list read the overlay from shared fixed 91-day windows,+each fetched once and refreshed by one 30-second poll while the tab is focused, so+an open calendar typically makes two out-of-office requests per poll. Routine sync+notifications that explicitly exclude OOO changes refresh this listin the background without returning to its skeleton. OOO changes, sharing changes,and notifications without that guarantee still clear cached rows and close openOOO details immediately before refetching.diff --git a/services/calendar_service/AGENTS.md b/services/calendar_service/AGENTS.mdindex dc0cad1c8d..b62e914471 100644--- a/services/calendar_service/AGENTS.md+++ b/services/calendar_service/AGENTS.md@@ -50,7 +50,9 @@ gateway `/calendar` prefix.- Reauth-required notifications ride the shared `LinkManagerQueue`, consumed by`email_service`; don't add a second calendar-specific reconnect notification.- Forward `team_ooo_changed` to both inbox and teammate refresh notifications;- sharing changes and uncertain sync results require `true`.+ sharing changes and uncertain sync results require `true`. An inbox refresh+ already refreshes its viewers' team views, so its teammate fan-out skips+ them; a sharing change also refreshes the sharer (`notify_sharers`).## Relateddiff --git a/services/calendar_service/src/calendar_refresh.rs b/services/calendar_service/src/calendar_refresh.rsindex 46bdb73018..493694d830 100644--- a/services/calendar_service/src/calendar_refresh.rs+++ b/services/calendar_service/src/calendar_refresh.rs@@ -66,7 +66,8 @@ impl calendar_events::domain::team::CalendarTeamNotifier for ConnectionGatewayCalet user_id = user_id.to_owned();tokio::spawn(async move {- crate::pubsub_util::cg_refresh_team_calendar(&client, &db, &[user_id], true).await;+ crate::pubsub_util::cg_refresh_team_calendar(&client, &db, &[user_id], true, true)+ .await;}.in_current_span(),);diff --git a/services/calendar_service/src/pubsub_util.rs b/services/calendar_service/src/pubsub_util.rsindex 77882ac5fa..e6acaa6237 100644--- a/services/calendar_service/src/pubsub_util.rs+++ b/services/calendar_service/src/pubsub_util.rs@@ -3,6 +3,9 @@use connection_gateway_client::client::ConnectionGatewayClient;use futures::{StreamExt, stream};+#[cfg(test)]+mod test;+/// Signal every viewer of a connected inbox's calendars — the link owner/// plus its delegated users — that the calendar projection changed. Best/// effort: an inactive or unreachable viewer only misses a refresh nudge.@@ -41,7 +44,9 @@ pub async fn cg_refresh_calendar(recipients.sort();recipients.dedup();if team_sharing_enabled {- cg_refresh_team_calendar(client, db, &recipients, team_ooo_changed).await;+ // These recipients' own refresh below already refreshes their team+ // views, so only their teammates need the team refresh.+ cg_refresh_team_calendar(client, db, &recipients, team_ooo_changed, false).await;}for macro_id in recipients {let _ = client@@ -54,12 +59,15 @@ pub async fn cg_refresh_calendar(}/// Invalidate teammate projections without exposing the underlying inbox IDs.+/// `notify_sharers` also refreshes `shared_by` themselves, for changes no+/// inbox refresh reaches them with, such as their own sharing setting.#[tracing::instrument(skip(client, db, shared_by))]pub async fn cg_refresh_team_calendar(client: &ConnectionGatewayClient,db: &sqlx::PgPool,shared_by: &[String],team_ooo_changed: bool,+ notify_sharers: bool,) {if !cfg!(feature = "connection_gateway") || shared_by.is_empty() {return;@@ -90,19 +98,40 @@ pub async fn cg_refresh_team_calendar(},).unwrap_or_default();- stream::iter(recipients.into_iter().flatten())- .for_each_concurrent(16, |user_id| {- let payload = payload.clone();- async move {- match tokio::time::timeout(- std::time::Duration::from_secs(3),- client.refresh_calendar(&user_id, payload),- ).await {- Ok(Ok(_)) => {},- Ok(Err(error)) => tracing::warn!(error=?error, "failed to invalidate a team calendar projection"),- Err(_) => tracing::warn!("team calendar invalidation timed out"),+ stream::iter(team_refresh_recipients(+ recipients,+ shared_by,+ notify_sharers,+ ))+ .for_each_concurrent(16, |user_id| {+ let payload = payload.clone();+ async move {+ match tokio::time::timeout(+ std::time::Duration::from_secs(3),+ client.refresh_calendar(&user_id, payload),+ )+ .await+ {+ Ok(Ok(_)) => {}+ Ok(Err(error)) => {+ tracing::warn!(error=?error, "failed to invalidate a team calendar projection")}+ Err(_) => tracing::warn!("team calendar invalidation timed out"),}- })- .await;+ }+ })+ .await;+}++/// The users a team refresh reaches, leaving out the sharers unless asked.+fn team_refresh_recipients(+ found: Vec<Option<String>>,+ shared_by: &[String],+ notify_sharers: bool,+) -> Vec<String> {+ found+ .into_iter()+ .flatten()+ .filter(|user_id| notify_sharers || !shared_by.contains(user_id))+ .collect()}diff --git a/services/calendar_service/src/pubsub_util/test.rs b/services/calendar_service/src/pubsub_util/test.rsnew file mode 100644index 0000000000..9288028c9c--- /dev/null+++ b/services/calendar_service/src/pubsub_util/test.rs@@ -0,0 +1,41 @@+use super::team_refresh_recipients;++fn found(users: &[&str]) -> Vec<Option<String>> {+ users.iter().map(|user| Some((*user).to_string())).collect()+}++#[test]+fn an_inbox_refresh_leaves_its_viewers_to_their_own_refresh() {+ let shared_by = [+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ];++ let recipients = team_refresh_recipients(+ found(&[+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ ]),+ &shared_by,+ false,+ );++ assert_eq!(recipients, ["macro|[email protected]"]);+}++#[test]+fn a_sharing_change_also_refreshes_the_sharer() {+ let shared_by = ["macro|[email protected]".to_string()];++ let recipients = team_refresh_recipients(+ found(&["macro|[email protected]", "macro|[email protected]"]),+ &shared_by,+ true,+ );++ assert_eq!(+ recipients,+ ["macro|[email protected]", "macro|[email protected]"]+ );+}