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
feat(calendar): remove the team calendar overlay and simplify team sharing settings (#8085)
gbirman398b351e4b65
diff --git a/apps/web/src/features/calendar-team/calendar-team.tsx b/apps/web/src/features/calendar-team/calendar-team.tsxindex 8a1639823e..dab3f17579 100644--- a/apps/web/src/features/calendar-team/calendar-team.tsx+++ b/apps/web/src/features/calendar-team/calendar-team.tsx@@ -1,41 +1,18 @@-import { CollapsibleSection } from '@app/components/view-shell';import { toast } from '@core/component/Toast/Toast';import { useUserId } from '@core/context/user';-import { getDisplayName, tryMacroId } from '@core/user';-import type { CalendarOccurrenceQueryRange } from '@queries/calendar/occurrences';import {useAvailabilityCalendarsQuery,useCalendarTeamIdentityQuery,useSetAvailabilityCalendarMutation,useSetTeamCalendarSharingMutation,- useTeamCalendarMembersQuery,- useTeamCalendarQuery,useTeamCalendarSharingQuery,} from '@queries/calendar/team';import type { CalendarTeamIdentity } from '@queries/calendar/team-keys';-import {- type Accessor,- createMemo,- createSignal,- Show,- Suspense,-} from 'solid-js';-import { useCalendarView } from '../calendar/components/CalendarViewContext';+import { type Accessor, Show, Suspense } from 'solid-js';+import { useCalendarSources } from '../calendar/hooks/use-calendar-sources';import { useCalendarTeamSharingFlag } from '../calendar/hooks/use-calendar-ui-flag';-import { isCalendarRangeSupported } from '../calendar/utils/calendar-supported-range';-import { useCalendarPreferences } from '../calendar/utils/preferences';-import { TeamCalendarControls } from './components/team-calendar-controls';import { TeamSharingSettings } from './components/team-sharing-settings';-import {- type CalendarTeamMemberDisplay,- teamCalendarColor,- teamCalendarSourceId,-} from './core/model';-import { createTeamCalendarState } from './primitives/create-team-calendar-state';-import { mapTeamCalendarItem } from './queries/map';--const teammateName = (id: string) =>- getDisplayName(tryMacroId(id)) || 'Teammate';+import { availabilitySources } from './core/availability';function useCalendarTeamIdentity(enabled: Accessor<boolean>) {const userId = useUserId();@@ -51,196 +28,68 @@ function useCalendarTeamIdentity(enabled: Accessor<boolean>) {return { identity, query };}-/** Production wiring for the isolated, read-only team overlay. */-export function useTeamCalendarOverlay(options: {- range: Accessor<CalendarOccurrenceQueryRange | undefined>;- enabled: Accessor<boolean>;- isSourceVisible: (sourceId: string) => boolean;-}) {- const flag = useCalendarTeamSharingFlag();- const enabled = () =>- flag() &&- options.enabled() &&- options.range() !== undefined &&- isCalendarRangeSupported(options.range()!);- const { identity, query: identityQuery } = useCalendarTeamIdentity(enabled);- const query = useTeamCalendarQuery(identity, options.range, enabled);- const state = createTeamCalendarState(- {- data: () =>- identity() && query.isSuccess ? query.data.items : undefined,- isPending: () =>- identityQuery.isPending ||- (identity() !== undefined && query.isPending),- isError: () => identityQuery.isError || query.isError,- isPaused: () => identityQuery.isPaused || query.isPaused,- },- enabled- );- const events = createMemo(() =>- state- .items()- .map((item) => mapTeamCalendarItem(item, teammateName(item.ownerId)))- .filter((event) => options.isSourceVisible(event.calendar.id))- );- return {- events,- isLoading: state.isLoading,- isError: state.isError,- retry: () => {- void identityQuery.refetch();- void query.refetch();- },- };-}--function TeamCalendarControlsConnected(props: {- enabled: boolean;- onEnabledChange: (enabled: boolean) => void;- isVisible: (sourceId: string) => boolean;- onVisibilityChange: (sourceId: string, visible: boolean) => void;-}) {- const flag = useCalendarTeamSharingFlag();- const { identity, query: identityQuery } = useCalendarTeamIdentity(flag);- const query = useTeamCalendarMembersQuery(identity);- const members = createMemo<CalendarTeamMemberDisplay[]>(() =>- identity() && query.isSuccess && !query.isPaused- ? query.data.map((member) => ({- ...member,- name: teammateName(member.userId),- color: teamCalendarColor(member.userId),- sourceId: teamCalendarSourceId(member.userId),- }))- : []- );- return (- <Show- when={- identity() ||- identityQuery.isPending ||- identityQuery.isError ||- identityQuery.isPaused- }- >- <TeamCalendarControls- {...props}- members={members()}- loading={- identityQuery.isPending ||- (identity() !== undefined && query.isPending)- }- error={- query.isError ||- identityQuery.isError ||- query.isPaused ||- identityQuery.isPaused- }- onRetry={() => {- void identityQuery.refetch();- void query.refetch();- }}- />- </Show>- );-}--export function CalendarTeamSidebar() {- const enabled = useCalendarTeamSharingFlag();- const calendar = useCalendarView();- const [open, setOpen] = createSignal(true);- return (- <Show when={enabled()}>- <Suspense- fallback={- <p class="px-2 text-xs text-ink-muted">Loading team calendars…</p>- }- >- <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>- <CollapsibleSection.Trigger>- <span>Team calendars</span>- <CollapsibleSection.Indicator />- </CollapsibleSection.Trigger>- <CollapsibleSection.Content>- <TeamCalendarControlsConnected- enabled={calendar.displaySettings.showTeamCalendars}- onEnabledChange={calendar.setShowTeamCalendars}- isVisible={calendar.isSourceVisible}- onVisibilityChange={calendar.setSourceVisibility}- />- </CollapsibleSection.Content>- </CollapsibleSection.Root>- </Suspense>- </Show>- );-}-function CalendarTeamSettingsContent() {const flag = useCalendarTeamSharingFlag();const { identity, query: identityQuery } = useCalendarTeamIdentity(flag);const sharing = useTeamCalendarSharingQuery(identity);const calendars = useAvailabilityCalendarsQuery(identity);+ const { sources } = useCalendarSources();const setSharing = useSetTeamCalendarSharingMutation();- const setCalendar = useSetAvailabilityCalendarMutation();- const [preferences, setPreferences] = useCalendarPreferences();+ const setCounted = useSetAvailabilityCalendarMutation();+ const availability = () =>+ calendars.isSuccess && !calendars.isPaused ? calendars.data.calendars : [];+ const countedIds = () =>+ new Set(+ availability()+ .filter((calendar) => calendar.contributesToAvailability)+ .map((calendar) => calendar.calendarId)+ );return (- <>- <TeamSharingSettings- hasTeam={identity() !== undefined}- teamLoading={identityQuery.isPending}- sharing={- sharing.isSuccess && !sharing.isPaused- ? sharing.data.sharing- : undefined- }- saving={setSharing.isPending}- error={- sharing.isError ||- identityQuery.isError ||- sharing.isPaused ||- identityQuery.isPaused- }- onChange={(value) =>- setSharing.mutate(value, {+ <TeamSharingSettings+ hasTeam={identity() !== undefined}+ teamLoading={identityQuery.isPending}+ sharing={+ sharing.isSuccess && !sharing.isPaused+ ? sharing.data.sharing+ : undefined+ }+ error={+ sharing.isError ||+ identityQuery.isError ||+ sharing.isPaused ||+ identityQuery.isPaused+ }+ onChange={(value) => {+ const current = identity();+ if (!current) return;+ setSharing.mutate(+ { identity: current, sharing: value },+ {onError: () => toast.failure('Could not update calendar sharing'),- })- }- onRetry={() => {- void identityQuery.refetch();- void sharing.refetch();- }}- calendars={- calendars.isSuccess && !calendars.isPaused- ? calendars.data.calendars- : []- }- calendarsLoading={identity() !== undefined && calendars.isPending}- calendarsError={calendars.isError || calendars.isPaused}- calendarSaving={setCalendar.isPending}- onCalendarChange={(calendarId, contributesToAvailability) =>- setCalendar.mutate(- { calendarId, contributesToAvailability },- {- onError: () =>- toast.failure('Could not update availability calendar'),- }- )- }- />- <TeamCalendarControlsConnected- enabled={preferences.showTeamCalendars}- onEnabledChange={(visible) =>- setPreferences('showTeamCalendars', visible)- }- isVisible={(id) => !preferences.hiddenSourceIds.includes(id)}- onVisibilityChange={(id, visible) =>- setPreferences('hiddenSourceIds', (ids) =>- visible- ? ids.filter((source) => source !== id)- : [...new Set([...ids, id])]- )- }- />- </>+ }+ );+ }}+ onRetry={() => {+ void identityQuery.refetch();+ void sharing.refetch();+ void calendars.refetch();+ }}+ calendars={availabilitySources(sources(), availability())}+ calendarsLoading={identity() !== undefined && calendars.isPending}+ calendarsError={calendars.isError || calendars.isPaused}+ isCounted={(calendarId) => countedIds().has(calendarId)}+ onCountedChange={(calendarIds, contributesToAvailability) => {+ const current = identity();+ if (!current) return;+ setCounted.mutate(+ { identity: current, calendarIds, contributesToAvailability },+ {+ onError: () =>+ toast.failure('Could not update availability calendars'),+ }+ );+ }}+ />);}diff --git a/apps/web/src/features/calendar-team/components/team-calendar-controls.tsx b/apps/web/src/features/calendar-team/components/team-calendar-controls.tsxdeleted file mode 100644index 76b99d0f26..0000000000--- a/apps/web/src/features/calendar-team/components/team-calendar-controls.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { Checkbox, ToggleSwitch } from '@ui';-import { For, Show } from 'solid-js';-import {- type CalendarTeamMemberDisplay,- canShowTeamMember,- teamMemberStatus,-} from '../core/model';--export function TeamCalendarControls(props: {- enabled: boolean;- onEnabledChange: (enabled: boolean) => void;- members: CalendarTeamMemberDisplay[];- loading: boolean;- error: boolean;- onRetry: () => void;- isVisible: (sourceId: string) => boolean;- onVisibilityChange: (sourceId: string, visible: boolean) => void;-}) {- return (- <div class="flex flex-col gap-2">- <div class="flex items-center justify-between gap-3 px-2 text-xs text-ink">- Show team calendars- <ToggleSwitch- checked={props.enabled}- onChange={props.onEnabledChange}- label="Show team calendars"- labelClass="sr-only"- />- </div>- <p class="px-2 text-xs text-ink-muted">- Shared event details can include calendars a teammate follows. Those- events do not necessarily mean they are busy.- </p>- <Show when={props.loading}>- <p role="status" class="px-2 text-xs text-ink-muted">- Loading team calendars…- </p>- </Show>- <Show when={props.error}>- <div role="status" class="px-2 text-xs text-ink-muted">- Team calendars unavailable.{' '}- <button type="button" class="underline" onClick={props.onRetry}>- Retry- </button>- </div>- </Show>- <For each={props.members}>- {(member) => (- <Checkbox- checked={- canShowTeamMember(member) && props.isVisible(member.sourceId)- }- disabled={!props.enabled || !canShowTeamMember(member)}- onChange={(visible) =>- props.onVisibilityChange(member.sourceId, visible)- }- class="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-ink hover:bg-hover data-disabled:opacity-60"- >- <Checkbox.Control />- <Checkbox.Label class="flex min-w-0 flex-1 items-center gap-2">- <span- aria-hidden="true"- class="size-2.5 shrink-0 rounded-sm"- style={{ 'background-color': member.color }}- />- <span class="min-w-0 flex-1 truncate" title={member.name}>- {member.name}- </span>- <span class="shrink-0 text-ink-muted">- {teamMemberStatus(member)}- </span>- </Checkbox.Label>- </Checkbox>- )}- </For>- </div>- );-}diff --git a/apps/web/src/features/calendar-team/components/team-sharing-settings.tsx b/apps/web/src/features/calendar-team/components/team-sharing-settings.tsxindex f2e3ab8a91..ad599e5e4a 100644--- a/apps/web/src/features/calendar-team/components/team-sharing-settings.tsx+++ b/apps/web/src/features/calendar-team/components/team-sharing-settings.tsx@@ -1,7 +1,8 @@-import { ToggleSwitch } from '@ui';-import { For, Show } from 'solid-js';+import { Show } from 'solid-js';+import { SourceControls } from '../../calendar/components/SourceControls';+import type { CalendarSource } from '../../calendar/types';+import { SettingsSelect } from '../../settings/components/settings-select';import {- ChoiceRow,SettingsCard,SettingsRow,SettingsSection,@@ -9,59 +10,46 @@ import {import type { CalendarSharing } from '../core/model';const choices: {- value: CalendarSharing;- title: string;+ id: CalendarSharing;+ name: string;description: string;}[] = [{- value: 'busy_only',- title: 'Busy blocks',- description:- 'Share time blocks from all synced calendars without event details. Out-of-office time on your primary calendar shows as "Out of office". Calendars you follow are distinguished from your own availability. This is the default.',+ id: 'busy_only',+ name: 'Busy blocks',+ description: 'Teammates see when you are busy, not what.',},{- value: 'all',- title: 'Event details',- description:- 'Share details from every calendar synced to Macro, including subscribed or delegated calendars, birthdays and holidays. Calendars unchecked in Google Calendar are included if synced. Private and confidential events share only busy blocks when they block time. This does not change Google Calendar permissions.',+ id: 'all',+ name: 'Event details',+ description: 'Teammates see your events. Private events stay busy blocks.',},{- value: 'none',- title: 'Nothing',- description:- 'Hide your calendar and availability from teammates in Macro, including team out of office.',+ id: 'none',+ name: 'Nothing',+ description: 'Teammates cannot see your calendar or availability.',},];-export interface AvailabilityCalendarDisplay {- calendarId: string;- name: string;- contributesToAvailability: boolean;- isPrimary: boolean;-}-export function TeamSharingSettings(props: {hasTeam: boolean;teamLoading: boolean;sharing: CalendarSharing | undefined;- saving: boolean;error: boolean;onChange: (sharing: CalendarSharing) => void;onRetry: () => void;- calendars: AvailabilityCalendarDisplay[];+ calendars: CalendarSource[];calendarsLoading: boolean;calendarsError: boolean;- calendarSaving: boolean;- onCalendarChange: (- calendarId: string,- contributesToAvailability: boolean- ) => void;+ isCounted: (calendarId: string) => boolean;+ onCountedChange: (calendarIds: string[], counted: boolean) => void;}) {+ const choice = () => choices.find((option) => option.id === props.sharing);return (<><SettingsSectiontitle="Team sharing"- description="Choose what teammates can read in Macro. Hiding a calendar in your Macro view does not change sharing. Sharing does not invite them to events or give them Google Calendar access."+ description="What teammates can see in Macro. Google Calendar permissions stay the same."><SettingsCard><Show@@ -88,69 +76,72 @@ export function TeamSharingSettings(props: {</SettingsRow>}>- <div class="flex flex-col gap-2 px-6 py-4">- <For each={choices}>- {(choice) => (- <ChoiceRow- name="calendar-team-sharing"- value={choice.value}- title={choice.title}- description={choice.description}- checked={props.sharing === choice.value}- disabled={props.sharing === undefined || props.saving}- onChange={() => props.onChange(choice.value)}- />- )}- </For>- <Show when={props.error}>- <p role="status" class="text-xs text-failure">- Could not load your sharing setting.{' '}+ <SettingsRow+ label="Share with teammates"+ description={+ props.error+ ? 'Could not load your sharing setting.'+ : choice()?.description+ }+ stackOnNarrow+ >+ <Show+ when={!props.error}+ fallback={<buttontype="button"- class="underline"+ class="text-xs underline"onClick={props.onRetry}>Retry</button>- </p>+ }+ >+ <SettingsSelect+ label="Share with teammates"+ class="w-44 min-w-0"+ options={choices}+ value={props.sharing}+ placeholder="Loading…"+ disabled={props.sharing === undefined}+ onChange={(id) => {+ const next = choices.find((option) => option.id === id);+ if (next) props.onChange(next.id);+ }}+ /></Show>- </div>+ </SettingsRow></Show></SettingsCard></SettingsSection><Show when={props.hasTeam}><SettingsSectiontitle="Calendars that count as busy"- description="By default, your primary calendars and meetings you attend count toward your availability. Following someone else's calendar does not make their meetings block your time. Choose any additional calendars that represent your schedule."+ description="Checked calendars block your time when teammates or agents check your availability.">- <SettingsCard>- <Show when={props.calendarsLoading}>- <SettingsRow label="Loading calendars…" />- </Show>- <Show when={props.calendarsError}>- <SettingsRow label="Could not load availability calendars" />- </Show>- <For each={props.calendars}>- {(calendar) => (- <SettingsRow- label={calendar.name}- description={- calendar.isPrimary ? 'Primary calendar' : undefined- }- >- <ToggleSwitch- checked={calendar.contributesToAvailability}- disabled={props.calendarSaving}- onChange={(included) =>- props.onCalendarChange(calendar.calendarId, included)- }- label={`Count ${calendar.name} toward my availability`}- labelClass="sr-only"- />- </SettingsRow>- )}- </For>- </SettingsCard>+ <Show when={props.calendarsLoading}>+ <p role="status" class="text-sm text-ink-muted">+ Loading calendars…+ </p>+ </Show>+ <Show when={props.calendarsError}>+ <p role="status" class="text-sm text-ink-muted">+ Could not load your calendars.{' '}+ <button type="button" class="underline" onClick={props.onRetry}>+ Retry+ </button>+ </p>+ </Show>+ <div class="-mx-2">+ <SourceControls+ sources={props.calendars}+ isVisible={props.isCounted}+ onVisibilityChange={(calendarId, counted) =>+ props.onCountedChange([calendarId], counted)+ }+ onGroupVisibilityChange={props.onCountedChange}+ />+ </div></SettingsSection></Show></>diff --git a/apps/web/src/features/calendar-team/core/availability.test.ts b/apps/web/src/features/calendar-team/core/availability.test.tsnew file mode 100644index 0000000000..0c0abbd3f5--- /dev/null+++ b/apps/web/src/features/calendar-team/core/availability.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import { availabilitySources } from './availability';++const calendar = (calendarId: string, name = calendarId) => ({+ calendarId,+ name,+ isPrimary: false,+ contributesToAvailability: false,+});++describe('availabilitySources', () => {+ it('keeps source order, colors, and accounts for countable calendars', () => {+ const primary = {+ id: 'primary',+ name: '[email protected]',+ color: 'red',+ emailAddress: '[email protected]',+ emailLinkId: 'link',+ isPrimary: true,+ };+ const holidays = {+ id: 'holidays',+ name: 'Holidays',+ color: 'green',+ emailAddress: '[email protected]',+ emailLinkId: 'link',+ isSubscription: true,+ };+ const hidden = { id: 'not-countable', name: 'Other', color: 'blue' };+ expect(+ availabilitySources(+ [primary, hidden, holidays],+ [calendar('holidays'), calendar('primary')]+ )+ ).toEqual([primary, holidays]);+ });++ it('still lists a countable calendar the source list has not loaded', () => {+ expect(availabilitySources([], [calendar('new', 'New calendar')])).toEqual([+ {+ id: 'new',+ name: 'New calendar',+ color: 'var(--color-accent)',+ isPrimary: false,+ },+ ]);+ });+});diff --git a/apps/web/src/features/calendar-team/core/availability.ts b/apps/web/src/features/calendar-team/core/availability.tsnew file mode 100644index 0000000000..0d9f8886e1--- /dev/null+++ b/apps/web/src/features/calendar-team/core/availability.ts@@ -0,0 +1,30 @@+import type { AvailabilityCalendar } from '@service-calendar/generated/schemas/availabilityCalendar';+import {+ type CalendarSource,+ DEFAULT_CALENDAR_SOURCE,+} from '../../calendar/types';++/**+ * The calendars that can count toward availability, presented like the+ * sidebar's sources: the viewer's own sources in their order and colors, then+ * any the source list does not know yet.+ */+export function availabilitySources(+ sources: readonly CalendarSource[],+ calendars: readonly AvailabilityCalendar[]+): CalendarSource[] {+ const calendarIds = new Set(calendars.map((calendar) => calendar.calendarId));+ const known = sources.filter((source) => calendarIds.has(source.id));+ const knownIds = new Set(known.map((source) => source.id));+ return [+ ...known,+ ...calendars+ .filter((calendar) => !knownIds.has(calendar.calendarId))+ .map((calendar) => ({+ id: calendar.calendarId,+ name: calendar.name,+ color: DEFAULT_CALENDAR_SOURCE.color,+ isPrimary: calendar.isPrimary,+ })),+ ];+}diff --git a/apps/web/src/features/calendar-team/core/merge.test.ts b/apps/web/src/features/calendar-team/core/merge.test.tsindex f0399de4b8..b0665064a6 100644--- a/apps/web/src/features/calendar-team/core/merge.test.ts+++ b/apps/web/src/features/calendar-team/core/merge.test.ts@@ -5,24 +5,12 @@ describe('calendar overlay composition', () => {it('keeps a directly accessible occurrence authoritative', () => {const own = { id: 'meeting', calendar: { id: 'own' }, isReadOnly: false };const team = { id: 'meeting', calendar: { id: 'team' }, isReadOnly: true };- expect(mergeCalendarOverlays([own], [team], [team])).toEqual([own]);+ expect(mergeCalendarOverlays([own], [team])).toEqual([own]);});- it('replaces a shown teammate OOO source with their shared source only', () => {- const aliceOoo = { id: 'alice-ooo', calendar: { id: 'team-ooo:alice' } };+ it('adds teammate OOO the viewer cannot read directly', () => {+ const own = { id: 'meeting', calendar: { id: 'own' } };const bobOoo = { id: 'bob-ooo', calendar: { id: 'team-ooo:bob' } };- const alice = {- id: 'alice-team',- calendar: { id: 'team-calendar:alice' },- teamProjection: { ownerId: 'alice' },- };- expect(mergeCalendarOverlays([], [aliceOoo, bobOoo], [alice])).toEqual([- bobOoo,- alice,- ]);- expect(mergeCalendarOverlays([], [aliceOoo, bobOoo], [])).toEqual([- aliceOoo,- bobOoo,- ]);+ expect(mergeCalendarOverlays([own], [bobOoo])).toEqual([own, bobOoo]);});});diff --git a/apps/web/src/features/calendar-team/core/merge.ts b/apps/web/src/features/calendar-team/core/merge.tsindex e8051bc1eb..ecc3b5e2ba 100644--- a/apps/web/src/features/calendar-team/core/merge.ts+++ b/apps/web/src/features/calendar-team/core/merge.ts@@ -1,28 +1,12 @@interface DisplayEvent {id: string;- calendar: { id: string };- teamProjection?: { ownerId: string };}-/** Keep direct-copy interactions authoritative; the team source supersedes its OOO overlay. */+/** Keep direct-copy interactions authoritative over a teammate's OOO overlay. */export function mergeCalendarOverlays<T extends DisplayEvent>(own: T[],- outOfOffice: T[],- shared: T[]+ outOfOffice: T[]): T[] {const ownIds = new Set(own.map((event) => event.id));- const sharedOwners = new Set(- shared.flatMap((event) =>- event.teamProjection ? [event.teamProjection.ownerId] : []- )- );- return [- ...own,- ...outOfOffice.filter(- (event) =>- !ownIds.has(event.id) &&- !sharedOwners.has(event.calendar.id.replace(/^team-ooo:/, ''))- ),- ...shared.filter((event) => !ownIds.has(event.id)),- ];+ return [...own, ...outOfOffice.filter((event) => !ownIds.has(event.id))];}diff --git a/apps/web/src/features/calendar-team/core/model.ts b/apps/web/src/features/calendar-team/core/model.tsindex 7f7402fa33..3949bf00f4 100644--- a/apps/web/src/features/calendar-team/core/model.ts+++ b/apps/web/src/features/calendar-team/core/model.ts@@ -1,49 +1,2 @@/** Team sharing is a Macro read permission, separate from Google permissions. */export type CalendarSharing = 'busy_only' | 'all' | 'none';--export interface CalendarTeamMember {- userId: string;- sharing: CalendarSharing;- coverage: 'ready' | 'unavailable' | 'hidden';-}--export interface CalendarTeamMemberDisplay extends CalendarTeamMember {- name: string;- color: string;- sourceId: string;-}--export const TEAM_CALENDAR_SOURCE = 'team-calendar';--export function teamCalendarSourceId(ownerId: string) {- return `${TEAM_CALENDAR_SOURCE}:${ownerId}`;-}--/** The source and owner scope prevent collisions with a directly accessible copy. */-export function teamCalendarRenderId(ownerId: string, projectionId: string) {- return JSON.stringify([TEAM_CALENDAR_SOURCE, ownerId, projectionId]);-}--export function teamCalendarColor(ownerId: string) {- const colors = [- 'var(--color-accent)',- 'var(--color-ink-muted)',- 'var(--color-success)',- 'var(--color-alert)',- ];- let hash = 0;- for (const character of ownerId)- hash = (hash * 31 + character.charCodeAt(0)) >>> 0;- return colors[hash % colors.length];-}--export function teamMemberStatus(member: CalendarTeamMember): string {- if (member.coverage === 'hidden' || member.sharing === 'none')- return 'Not shared';- if (member.coverage === 'unavailable') return 'Calendar unavailable';- return member.sharing === 'all' ? 'Event details' : 'Busy blocks';-}--export function canShowTeamMember(member: CalendarTeamMember) {- return member.coverage === 'ready' && member.sharing !== 'none';-}diff --git a/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.test.ts b/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.test.tsdeleted file mode 100644index 6428be8216..0000000000--- a/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { createRoot, createSignal } from 'solid-js';-import { describe, expect, it } from 'vitest';-import { createTeamCalendarState } from './create-team-calendar-state';--describe('team calendar state', () => {- it('drops stale details on a denied refresh and on a disabled identity', () => {- createRoot((dispose) => {- const [error, setError] = createSignal(false);- const [enabled, setEnabled] = createSignal(true);- const state = createTeamCalendarState(- {- data: () => ['Previously authorized title'],- isPending: () => false,- isError: error,- },- enabled- );- expect(state.items()).toEqual(['Previously authorized title']);- setError(true);- expect(state.items()).toEqual([]);- expect(state.isError()).toBe(true);- setEnabled(false);- setError(false);- expect(state.items()).toEqual([]);- dispose();- });- });-});--it('hides retained details when an offline refresh is paused', () => {- createRoot((dispose) => {- const [paused, setPaused] = createSignal(false);- const state = createTeamCalendarState(- {- data: () => ['Previously authorized title'],- isPending: () => false,- isError: () => false,- isPaused: paused,- },- () => true- );- expect(state.items()).toHaveLength(1);- setPaused(true);- expect(state.items()).toEqual([]);- expect(state.isError()).toBe(true);- dispose();- });-});diff --git a/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.ts b/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.tsdeleted file mode 100644index 0a2bf7a15e..0000000000--- a/apps/web/src/features/calendar-team/primitives/create-team-calendar-state.ts+++ /dev/null@@ -1,26 +0,0 @@-import { type Accessor, createMemo } from 'solid-js';--export interface TeamCalendarSource<T> {- data: Accessor<T[] | undefined>;- isPending: Accessor<boolean>;- isError: Accessor<boolean>;- isPaused?: Accessor<boolean>;-}--/** Permission errors and scope changes must hide old payloads, even during failed refreshes. */-export function createTeamCalendarState<T>(- source: TeamCalendarSource<T>,- enabled: Accessor<boolean>-) {- const items = createMemo(() =>- enabled() && !source.isError() && !source.isPaused?.()- ? (source.data() ?? [])- : []- );- return {- items,- isLoading: () => enabled() && source.isPending() && !source.isPaused?.(),- isError: () =>- enabled() && (source.isError() || Boolean(source.isPaused?.())),- };-}diff --git a/apps/web/src/features/calendar-team/queries/map.test.ts b/apps/web/src/features/calendar-team/queries/map.test.tsdeleted file mode 100644index 512579d839..0000000000--- a/apps/web/src/features/calendar-team/queries/map.test.ts+++ /dev/null@@ -1,144 +0,0 @@-import type { TeamCalendarItem } from '@service-storage/generated/schemas/teamCalendarItem';-import { describe, expect, it } from 'vitest';-import { mapCalendarEventToFullCalendar } from '../../calendar/types';-import { canEditCalendarEventTime } from '../../calendar/utils/event-interaction';-import { mergeCalendarOverlays } from '../core/merge';-import { mapTeamCalendarItem } from './map';--const busy = {- id: 'opaque',- ownerId: 'alice',- kind: 'busy',- contributesToAvailability: true,- time: {- kind: 'timed',- startsAt: '2026-10-07T12:00:00Z',- endsAt: '2026-10-07T13:00:00Z',- timeZone: null,- },-} satisfies TeamCalendarItem;--describe('team calendar grid projection', () => {- it('retains the exact nonbusy instant of a detailed shared point', () => {- const point = mapTeamCalendarItem(- {- ...busy,- kind: 'details',- contributesToAvailability: false,- time: { ...busy.time, endsAt: busy.time.startsAt },- details: {- title: 'Point event',- description: null,- location: null,- conferenceUrl: null,- organizerEmail: null,- organizerName: null,- attendees: [],- calendarName: 'Shared calendar',- },- },- 'Alice'- );- const rendered = mapCalendarEventToFullCalendar(point);-- expect(point.start).toBe(point.end);- expect(point.teamProjection?.contributesToAvailability).toBe(false);- expect(point.title).toBe('Alice: Point event');- expect(rendered.end).toBe('2026-10-07T12:00:00.001Z');- expect(rendered.startEditable).toBe(false);- expect(rendered.durationEditable).toBe(false);- });- it('keeps redacted blocks separate from canonical event identities and provider actions', () => {- const event = mapTeamCalendarItem(busy, 'Alice');- expect(event.id).toBe(JSON.stringify(['team-calendar', 'alice', 'opaque']));- expect(event.isReadOnly).toBe(true);- expect(event.calendarId).toBeUndefined();- expect(event.title).toBe('Alice: Busy');- expect(event.attendees).toEqual([]);- expect(event.description).toBeUndefined();- expect(event.conferenceUrl).toBeUndefined();- expect(event.eventType).toBeUndefined();- expect(canEditCalendarEventTime({ ...event, isReadOnly: false })).toBe(- false- );- });-- it('does not describe a followed calendar as the sharer being busy', () => {- const event = mapTeamCalendarItem(- { ...busy, contributesToAvailability: false },- 'Alice'- );- expect(event.title).toBe('Alice: Shared calendar block');- expect(event.teamProjection?.contributesToAvailability).toBe(false);- });-- it('does not let another sharer overwrite the first sharer', () => {- expect(mapTeamCalendarItem(busy, 'Alice').id).not.toBe(- mapTeamCalendarItem({ ...busy, ownerId: 'bob' }, 'Bob').id- );- });-- it('preserves source-specific masking and busy status when copies share a time', () => {- const personal = mapTeamCalendarItem(- { ...busy, id: 'opaque-personal-source' },- 'Alice'- );- const followed = mapTeamCalendarItem(- {- ...busy,- id: 'opaque-followed-source',- kind: 'details',- contributesToAvailability: false,- details: {- title: 'Shared calendar meeting',- description: 'Visible on the followed source',- location: null,- conferenceUrl: null,- organizerEmail: null,- organizerName: null,- attendees: [],- calendarName: 'Followed calendar',- },- },- 'Alice'- );- const own = {- ...personal,- id: 'direct-copy',- eventId: 'canonical-event',- teamProjection: undefined,- isReadOnly: false,- };-- const events = mergeCalendarOverlays([own], [], [personal, followed]);-- expect(events).toEqual([own, personal, followed]);- expect(new Set(events.map((event) => event.id)).size).toBe(3);- expect(personal.start).toBe(followed.start);- expect(personal.end).toBe(followed.end);- expect(personal.title).toBe('Alice: Busy');- expect(personal.description).toBeUndefined();- expect(personal.teamProjection?.contributesToAvailability).toBe(true);- expect(followed.title).toBe('Alice: Shared calendar meeting');- expect(followed.teamProjection?.contributesToAvailability).toBe(false);- expect(events[0].isReadOnly).toBe(false);- expect(canEditCalendarEventTime(personal)).toBe(false);- expect(canEditCalendarEventTime(followed)).toBe(false);- });-- it('ignores any accidental detail fields on the busy variant', () => {- const withUnexpectedDetails = {- ...busy,- details: {- title: 'Secret',- attendees: [],- description: 'Hidden body',- conferenceUrl: 'https://example.com',- },- };- const event = mapTeamCalendarItem(withUnexpectedDetails, 'Alice');- expect(event.title).toBe('Alice: Busy');- expect(event.description).toBeUndefined();- expect(event.conferenceUrl).toBeUndefined();- });-});diff --git a/apps/web/src/features/calendar-team/queries/map.ts b/apps/web/src/features/calendar-team/queries/map.tsdeleted file mode 100644index a2def4ac39..0000000000--- a/apps/web/src/features/calendar-team/queries/map.ts+++ /dev/null@@ -1,52 +0,0 @@-import type { TeamCalendarItem } from '@service-storage/generated/schemas/teamCalendarItem';-import type { CalendarEvent } from '../../calendar/types';-import {- teamCalendarColor,- teamCalendarRenderId,- teamCalendarSourceId,-} from '../core/model';--/** Only the server-authorized DTO enters this adapter; never normalize it as an own event. */-export function mapTeamCalendarItem(- item: TeamCalendarItem,- ownerName: string-): CalendarEvent {- const time = item.time;- const details = item.kind === 'details' ? item.details : undefined;- const calendar = {- id: teamCalendarSourceId(item.ownerId),- name: ownerName,- color: teamCalendarColor(item.ownerId),- };- const renderId = teamCalendarRenderId(item.ownerId, item.id);- return {- id: renderId,- // These opaque placeholders satisfy the grid contract; teamProjection- // prevents every canonical-event action and navigation path from using them.- eventId: renderId,- occurrenceKey: item.id,- teamProjection: {- ownerId: item.ownerId,- kind: item.kind,- contributesToAvailability: item.contributesToAvailability,- },- ...(time.kind === 'timed'- ? { allDay: false, start: time.startsAt, end: time.endsAt }- : { allDay: true, start: time.startDate, end: time.endDate }),- timeZone: time.kind === 'timed' ? (time.timeZone ?? undefined) : undefined,- isCancelled: false,- isReadOnly: true,- // The endpoint recomputes these flags for the requesting viewer.- attendees: details?.attendees ?? [],- recurrenceLines: [],- sourceCalendarIds: [calendar.id],- calendar,- visibleCalendars: [calendar],- title: `${ownerName}: ${details?.title ?? (item.contributesToAvailability ? 'Busy' : 'Shared calendar block')}`,- description: details?.description ?? undefined,- location: details?.location ?? undefined,- conferenceUrl: details?.conferenceUrl ?? undefined,- organizerEmail: details?.organizerEmail ?? undefined,- organizerName: details?.organizerName ?? undefined,- };-}diff --git a/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx b/apps/web/src/features/calendar-view/components/CalendarSidebar.tsxindex fc42765e61..33f5996889 100644--- a/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx+++ b/apps/web/src/features/calendar-view/components/CalendarSidebar.tsx@@ -9,12 +9,10 @@ import { CalendarSettingsDropdown } from '@app/features/calendar/components/Caleimport { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';import { SourceControls } from '@app/features/calendar/components/SourceControls';import {- TEAM_OOO_SOURCE_ID,type TeamOooWindow,useHasTeammates,useUpcomingTeamOoo,} from '@app/features/calendar/hooks/use-team-ooo';-import { CalendarTeamSidebar } from '@app/features/calendar-team/calendar-team';import { ShowFeatureFlag } from '@app/lib/analytics/posthog';import { UserIcon } from '@core/component/UserIcon';import { enableCalendarTeamOoo } from '@core/constant/featureFlags';@@ -22,7 +20,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import CaretDownIcon from '@phosphor/caret-down.svg';import PlusIcon from '@phosphor/plus.svg';import CloseIcon from '@phosphor/x.svg';-import { cn, Calendar as MiniCalendar, ToggleSwitch } from '@ui';+import { cn, Calendar as MiniCalendar } from '@ui';import { tourTarget } from '@ui/components/Tour';import { format } from 'date-fns';import {@@ -121,6 +119,7 @@ function CalendarSourcesSection() {</CollapsibleSection.Trigger><CollapsibleSection.Content><SourceControls+ ref={tourTarget(CALENDAR_TOUR.sources)}sources={calendarView.sources()}isVisible={calendarView.isSourceVisible}onVisibilityChange={calendarView.setSourceVisibility}@@ -234,30 +233,16 @@ function TeamOooUpcomingList() {}function CalendarTeamOooSection() {- const calendarView = useCalendarView();const hasTeammates = useHasTeammates();const [open, setOpen] = createSignal(true);- const isOverlayVisible = () =>- calendarView.isSourceVisible(TEAM_OOO_SOURCE_ID);- const setOverlayVisible = (visible: boolean) =>- calendarView.setSourceVisibility(TEAM_OOO_SOURCE_ID, visible);return (<Show when={hasTeammates()}><CollapsibleSection.Root open={open()} onOpenChange={setOpen}>- <CollapsibleSection.Header>- <CollapsibleSection.Trigger class="min-w-0 flex-1">- <span class="min-w-0 truncate">Team out of office</span>- <CollapsibleSection.Indicator />- </CollapsibleSection.Trigger>- <span title="Show on calendar">- <ToggleSwitch- checked={isOverlayVisible()}- onChange={setOverlayVisible}- aria-label="Show team out of office on the calendar"- />- </span>- </CollapsibleSection.Header>+ <CollapsibleSection.Trigger>+ <span class="min-w-0 truncate">Team out of office</span>+ <CollapsibleSection.Indicator />+ </CollapsibleSection.Trigger><CollapsibleSection.Content><TeamOooUpcomingList /></CollapsibleSection.Content>@@ -318,7 +303,6 @@ export function CalendarSidebar() {<CalendarMiniCalendar /><UpcomingEventsSection /><CalendarSourcesSection />- <CalendarTeamSidebar /><ShowFeatureFlag flag={enableCalendarTeamOoo}><CalendarTeamOooSection /></ShowFeatureFlag>diff --git a/apps/web/src/features/calendar-view/components/Page.tsx b/apps/web/src/features/calendar-view/components/Page.tsxindex 21c5c651f2..da2b4c551e 100644--- a/apps/web/src/features/calendar-view/components/Page.tsx+++ b/apps/web/src/features/calendar-view/components/Page.tsx@@ -29,7 +29,6 @@ import {scrollEventChipIntoView,timeGridScroller,} from '@app/features/calendar/utils/time-grid-scroller';-import { useTeamCalendarOverlay } from '@app/features/calendar-team/calendar-team';import { mergeCalendarOverlays } from '@app/features/calendar-team/core/merge';import { useOpenEventComposer } from '@app/features/calendar-view/components/use-open-event-composer';import { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';@@ -234,24 +233,10 @@ export function Page(props: {});const teamOoo = useTeamOooEvents({range,- isSourceVisible: isRenderedSourceVisible,refetchOnWindowFocus: isActive,});- const teamCalendar = useTeamCalendarOverlay({- range,- enabled: () => calendarView.displaySettings.showTeamCalendars,- // Hide sensitive shared payloads immediately, before the deferred grid redraw.- isSourceVisible: calendarView.isSourceVisible,- });- const teamEvents = createMemo(() =>- mergeCalendarOverlays([], teamOoo.visibleEvents(), teamCalendar.events())- );const visibleEvents = createMemo(() =>- mergeCalendarOverlays(- data.visibleEvents(),- teamOoo.visibleEvents(),- teamCalendar.events()- )+ mergeCalendarOverlays(data.visibleEvents(), teamOoo.events()));const eventsById = createMemo(() => new Map(visibleEvents().map((event) => [event.id, event]))@@ -369,32 +354,13 @@ export function Page(props: {<CalendarPageHostid={props.id}data={data}- teamEvents={teamEvents}+ teamEvents={teamOoo.events}eventsById={eventsById}grid={grid}onLoadingBlockingChange={setLoadingDecorationBlocking}/>)}</CalendarGrid>- <Show when={teamCalendar.isError()}>- <div- role="status"- class="absolute bottom-2 right-2 z-10 max-w-sm rounded-lg border border-edge-muted bg-surface px-3 py-2 text-xs text-ink-muted"- >- Team calendars unavailable. Availability is unknown.{' '}- <button type="button" class="underline" onClick={teamCalendar.retry}>- Retry- </button>- </div>- </Show>- <Show when={teamCalendar.isLoading()}>- <div- role="status"- class="absolute bottom-2 right-2 z-10 rounded-lg border border-edge-muted bg-surface px-3 py-2 text-xs text-ink-muted"- >- Loading team calendars…- </div>- </Show></div>);}diff --git a/apps/web/src/features/calendar-view/copy-event-mention.test.ts b/apps/web/src/features/calendar-view/copy-event-mention.test.tsindex 07d20eb6cf..289a309ff6 100644--- a/apps/web/src/features/calendar-view/copy-event-mention.test.ts+++ b/apps/web/src/features/calendar-view/copy-event-mention.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { mapTeamCalendarItem } from '../calendar-team/queries/map';+import type { CalendarEvent } from '../calendar/types';import {copyCalendarEventMention,copyCalendarEventMentionTarget,@@ -20,20 +20,24 @@ describe('copyCalendarEventMentionTarget', () => {beforeEach(() => writeClipboardData.mockClear());it('never copies a team projection as an independently resolvable event', async () => {- const event = mapTeamCalendarItem(- {- id: 'opaque',- ownerId: 'alice',- kind: 'busy',- contributesToAvailability: true,- time: {- kind: 'timed',- startsAt: '2026-10-07T10:00:00Z',- endsAt: '2026-10-07T11:00:00Z',- },- },- 'Alice'- );+ const calendar = { id: 'team-ooo:alice', name: 'Alice', color: 'gray' };+ const event: CalendarEvent = {+ id: 'opaque',+ eventId: 'opaque',+ occurrenceKey: '2026-10-07T10:00:00Z',+ teamProjection: { ownerId: 'alice', kind: 'busy' },+ isCancelled: false,+ isReadOnly: true,+ attendees: [],+ recurrenceLines: [],+ sourceCalendarIds: [],+ title: 'Alice: Out of office',+ start: '2026-10-07T10:00:00Z',+ end: '2026-10-07T11:00:00Z',+ allDay: false,+ calendar,+ visibleCalendars: [calendar],+ };await copyCalendarEventMention(event);expect(writeClipboardData).not.toHaveBeenCalled();});diff --git a/apps/web/src/features/calendar/components/CalendarViewContext.tsx b/apps/web/src/features/calendar/components/CalendarViewContext.tsxindex fff3b7126c..022837aede 100644--- a/apps/web/src/features/calendar/components/CalendarViewContext.tsx+++ b/apps/web/src/features/calendar/components/CalendarViewContext.tsx@@ -24,7 +24,6 @@ interface CalendarDisplaySettings {readonly showWeekends: boolean;readonly weekStartsOn: CalendarWeekStart;readonly timeFormat: CalendarTimeFormat;- readonly showTeamCalendars: boolean;}type CalendarViewContextProps = ParentProps<{@@ -140,9 +139,6 @@ export const [CalendarViewContextProvider, useCalendarView] =get timeFormat() {return preferences.timeFormat;},- get showTeamCalendars() {- return preferences.showTeamCalendars;- },};const closeEventDetails = () => selection.close();@@ -216,11 +212,6 @@ export const [CalendarViewContextProvider, useCalendarView] =setPreferences('weekStartsOn', weekStartsOn),setTimeFormat: (timeFormat: CalendarTimeFormat) =>setPreferences('timeFormat', timeFormat),- setShowTeamCalendars: (visible: boolean) => {- setPreferences('showTeamCalendars', visible);- if (!visible && selection.event()?.teamProjection)- closeEventDetails();- },closeEventDetails,selectEvent: selection.select,refreshSelectedEvent: selection.refresh,diff --git a/apps/web/src/features/calendar/components/SourceControls.tsx b/apps/web/src/features/calendar/components/SourceControls.tsxindex 2200dec272..7eedad666f 100644--- a/apps/web/src/features/calendar/components/SourceControls.tsx+++ b/apps/web/src/features/calendar/components/SourceControls.tsx@@ -1,15 +1,14 @@import { ViewSidebar } from '@app/components/view-shell';-import { CALENDAR_TOUR } from '@app/features/calendar-view/tour';import CaretDownIcon from '@phosphor/caret-down.svg';import RssIcon from '@phosphor/rss.svg';import WarningIcon from '@phosphor/warning.svg';import { Checkbox } from '@ui';-import { tourTarget } from '@ui/components/Tour';import { createSignal, For, Show } from 'solid-js';import type { CalendarSource } from '../types';import { groupCalendarSourcesByAccount } from '../utils/calendar-source-groups';interface SourceControlsProps {+ ref?: (element: HTMLUListElement) => void;sources: CalendarSource[];isVisible: (sourceId: string) => boolean;onVisibilityChange: (sourceId: string, visible: boolean) => void;@@ -37,10 +36,7 @@ export function SourceControls(props: SourceControlsProps) {});return (- <ul- ref={tourTarget(CALENDAR_TOUR.sources)}- class="flex min-w-0 flex-col gap-(--sidebar-row-gap)"- >+ <ul ref={props.ref} class="flex min-w-0 flex-col gap-(--sidebar-row-gap)"><For each={groups()}>{(group) => {const visibleCount = () =>diff --git a/apps/web/src/features/calendar/hooks/use-team-ooo.ts b/apps/web/src/features/calendar/hooks/use-team-ooo.tsindex e94bd4c0e7..f2c3550bb6 100644--- a/apps/web/src/features/calendar/hooks/use-team-ooo.ts+++ b/apps/web/src/features/calendar/hooks/use-team-ooo.ts@@ -10,13 +10,10 @@ import { EventType } from '@service-storage/generated/schemas/eventType';import type { TeamOutOfOfficeItem } from '@service-storage/generated/schemas/teamOutOfOfficeItem';import { parseISO } from 'date-fns';import { type Accessor, createMemo } from 'solid-js';-import type { CalendarEvent } from '../types';+import { type CalendarEvent, TEAM_OOO_SOURCE_ID } from '../types';import { isCalendarRangeSupported } from '../utils/calendar-supported-range';import { useCalendarTeamOooFlag } from './use-calendar-ui-flag';-/** Visibility-source id gating the whole team out-of-office overlay. */-export const TEAM_OOO_SOURCE_ID = 'team-ooo';-/** Prefix of every per-teammate visibility-source id. */const TEAM_OOO_SOURCE_PREFIX = 'team-ooo:';@@ -78,13 +75,11 @@ function mapTeamOooItem(item: TeamOutOfOfficeItem): CalendarEvent {export interface TeamOooEventData {events: Accessor<CalendarEvent[]>;- visibleEvents: Accessor<CalendarEvent[]>;eventsById: Accessor<Map<string, CalendarEvent>>;}export interface TeamOooEventOptions {range: Accessor<CalendarOccurrenceQueryRange | undefined>;- isSourceVisible?: (sourceId: string) => boolean;refetchOnWindowFocus?: Accessor<boolean>;}@@ -98,12 +93,10 @@ export function useTeamOooEvents(const range = options.range();return range !== undefined && isCalendarRangeSupported(range);});- const isOverlayVisible = () =>- teamOooEnabled() && options.isSourceVisible?.(TEAM_OOO_SOURCE_ID) !== false;const query = useTeamOutOfOfficeQuery(() => ({ userId: userId(), range: options.range() }),() => ({- enabled: isRangeSupported() && isOverlayVisible(),+ enabled: isRangeSupported() && teamOooEnabled(),refetchOnWindowFocus: options.refetchOnWindowFocus?.(),}));@@ -121,12 +114,11 @@ export function useTeamOooEvents(}return query.data.map(mapTeamOooItem);});- const visibleEvents = createMemo(() => (isOverlayVisible() ? events() : []));const eventsById = createMemo(() => new Map(events().map((event) => [event.id, event])));- return { events, visibleEvents, eventsById };+ return { events, eventsById };}/** One teammate absence window for list surfaces. */diff --git a/apps/web/src/features/calendar/types.ts b/apps/web/src/features/calendar/types.tsindex d81a389efc..7b79f55b75 100644--- a/apps/web/src/features/calendar/types.ts+++ b/apps/web/src/features/calendar/types.ts@@ -134,6 +134,9 @@ export interface CalendarEvent {description?: string;}+/** Source id every teammate out-of-office event carries; it is always shown. */+export const TEAM_OOO_SOURCE_ID = 'team-ooo';+/** Shared presentation source until calendar/account metadata is exposed. */export const DEFAULT_CALENDAR_SOURCE: CalendarSource = {id: 'calendar',diff --git a/apps/web/src/features/calendar/utils/preferences.test.ts b/apps/web/src/features/calendar/utils/preferences.test.tsnew file mode 100644index 0000000000..bdfbc7c6ae--- /dev/null+++ b/apps/web/src/features/calendar/utils/preferences.test.ts@@ -0,0 +1,27 @@+import { createRoot } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { CALENDAR_PREFERENCES_KEY } from '../calendar-preferences';++afterEach(() => {+ localStorage.clear();+ vi.resetModules();+});++describe('calendar preferences', () => {+ it('drops a saved team out-of-office hide now that it has no switch', async () => {+ localStorage.setItem(+ CALENDAR_PREFERENCES_KEY,+ JSON.stringify({ hiddenSourceIds: ['team-ooo', 'holidays'] })+ );+ const { useCalendarPreferences } = await import('./preferences');++ const hidden = createRoot((dispose) => {+ const [preferences] = useCalendarPreferences();+ const ids = [...preferences.hiddenSourceIds];+ dispose();+ return ids;+ });++ expect(hidden).toEqual(['holidays']);+ });+});diff --git a/apps/web/src/features/calendar/utils/preferences.ts b/apps/web/src/features/calendar/utils/preferences.tsindex 421e7335c2..b01451149c 100644--- a/apps/web/src/features/calendar/utils/preferences.ts+++ b/apps/web/src/features/calendar/utils/preferences.ts@@ -5,10 +5,11 @@ import {CALENDAR_PREFERENCES_KEY,getPreferredCalendarPeriodView,} from '../calendar-preferences';-import type {- CalendarPeriodView,- CalendarTimeFormat,- CalendarWeekStart,+import {+ type CalendarPeriodView,+ type CalendarTimeFormat,+ type CalendarWeekStart,+ TEAM_OOO_SOURCE_ID,} from '../types';import { getDefaultCalendarTimeFormat } from './time-format';@@ -20,7 +21,6 @@ interface CalendarPreferences {showWeekends: boolean;weekStartsOn: CalendarWeekStart;timeFormat: CalendarTimeFormat;- showTeamCalendars: boolean;}/** One persisted store, so preference changes reach invitation cards outside the calendar. */@@ -33,16 +33,23 @@ export const useCalendarPreferences = createSharedRoot(() => {showWeekends: true,weekStartsOn: 0,timeFormat: getDefaultCalendarTimeFormat(),- showTeamCalendars: false,};const [preferences, setPreferences] = makePersisted(createStore<CalendarPreferences>(defaultPreferences),{name: CALENDAR_PREFERENCES_KEY,- deserialize: (value) => ({- ...defaultPreferences,- ...(JSON.parse(value) as Partial<CalendarPreferences>),- }),+ deserialize: (value) => {+ const stored = JSON.parse(value) as Partial<CalendarPreferences>;+ return {+ ...defaultPreferences,+ ...stored,+ // Team out of office has no off switch; an older saved hide would+ // otherwise keep it off for good.+ hiddenSourceIds: (stored.hiddenSourceIds ?? []).filter(+ (id) => id !== TEAM_OOO_SOURCE_ID+ ),+ };+ },});return [preferences, setPreferences] as const;diff --git a/apps/web/src/lib/queries/auth/user-info.test.ts b/apps/web/src/lib/queries/auth/user-info.test.tsindex ece237f03a..3000c70a08 100644--- a/apps/web/src/lib/queries/auth/user-info.test.ts+++ b/apps/web/src/lib/queries/auth/user-info.test.ts@@ -37,10 +37,8 @@ describe('login display-intent lifetime', () => {const identity = { userId: 'old-viewer', authenticated: true };queryClient.setQueryData(authKeys.userInfo.queryKey, identity);const teamKeys = [- calendarTeamKeys.events(- { userId: 'old-viewer', teamId: 'old-team' },- undefined- ).queryKey,+ calendarTeamKeys.sharing({ userId: 'old-viewer', teamId: 'old-team' })+ .queryKey,calendarKeys.teamOutOfOffice('old-viewer', undefined, 'old-team').queryKey,];diff --git a/apps/web/src/lib/queries/calendar/sync.ts b/apps/web/src/lib/queries/calendar/sync.tsindex 7a11a7cb44..ea4f4d51d0 100644--- a/apps/web/src/lib/queries/calendar/sync.ts+++ b/apps/web/src/lib/queries/calendar/sync.ts@@ -3,7 +3,7 @@ import { invalidateCalendarInvitations } from './invitations';import { calendarKeys, RSVP_MUTATION_KEY } from './keys';import { invalidateCalendarEventPreviews } from './mention-preview';import { invalidateCalendarOccurrences } from './occurrences';-import { resetTeamCalendarQueries } from './team-cache';+import { refreshTeamCalendarQueries } from './team-cache';import { invalidateTeamOutOfOffice } from './team-ooo';/**@@ -13,7 +13,7 @@ import { invalidateTeamOutOfOffice } from './team-ooo';* calendar mention chips.*/export function invalidateCalendarViews(): void {- void resetTeamCalendarQueries();+ void refreshTeamCalendarQueries();void invalidateCalendarInvitations();invalidateCalendarOccurrences();invalidateCalendarEventPreviews();@@ -37,11 +37,11 @@ export function handleRefreshCalendar(payload: unknown): void {? (payload as { event?: unknown; link_id?: unknown }): undefined;if (event?.event === 'team_sharing_changed') {- void resetTeamCalendarQueries();+ void refreshTeamCalendarQueries();return;}if (event?.event !== 'synced' || typeof event.link_id !== 'string') return;- void resetTeamCalendarQueries();+ void refreshTeamCalendarQueries();// An in-flight RSVP holds optimistic occurrence state a refetch would// clobber; the last RSVP to settle re-invalidates occurrences itself, sodiff --git a/apps/web/src/lib/queries/calendar/team-cache.ts b/apps/web/src/lib/queries/calendar/team-cache.tsindex cb1c347e5c..aa86606362 100644--- a/apps/web/src/lib/queries/calendar/team-cache.ts+++ b/apps/web/src/lib/queries/calendar/team-cache.ts@@ -1,7 +1,7 @@import type { Query, QueryKey } from '@tanstack/solid-query';import { queryClient } from '../client';import { calendarKeys } from './keys';-import { calendarTeamKeys } from './team-keys';+import { calendarTeamKeys, calendarTeamMutationKeys } from './team-keys';/** A missed poll may retain data briefly, but a hung request cannot retain it. */export const TEAM_CALENDAR_MAX_DATA_AGE_MS = 60_000;@@ -63,11 +63,30 @@ export function resetTeamCalendarSession() {}}-/** Clear payloads first: a revoked title must disappear even if refetch fails. */-export async function resetTeamCalendarQueries() {+/**+ * Clear teammates' payloads first: a revoked title must disappear even if the+ * refetch fails. The viewer's own team and settings only refetch, so their+ * controls never drop back to loading, and a setting with a save in flight+ * waits for that save to refetch it.+ */+export async function refreshTeamCalendarQueries() {+ const saving = (mutationKey: QueryKey) =>+ queryClient.isMutating({ mutationKey }) > 0;await Promise.all([- queryClient.resetQueries({ queryKey: calendarTeamKeys._def }),queryClient.resetQueries({ queryKey: calendarKeys.teamOutOfOffice._def }),+ queryClient.invalidateQueries({+ queryKey: calendarTeamKeys.identity._def,+ }),+ saving(calendarTeamMutationKeys.sharing)+ ? undefined+ : queryClient.invalidateQueries({+ queryKey: calendarTeamKeys.sharing._def,+ }),+ saving(calendarTeamMutationKeys.availabilityCalendar)+ ? undefined+ : queryClient.invalidateQueries({+ queryKey: calendarTeamKeys.availabilityCalendars._def,+ }),]);}diff --git a/apps/web/src/lib/queries/calendar/team-keys.ts b/apps/web/src/lib/queries/calendar/team-keys.tsindex 609c9de44d..9fa45aedaf 100644--- a/apps/web/src/lib/queries/calendar/team-keys.ts+++ b/apps/web/src/lib/queries/calendar/team-keys.ts@@ -1,5 +1,4 @@import { createQueryKeys } from '@lukemorales/query-key-factory';-import type { CalendarOccurrenceQueryRange } from './keys';export interface CalendarTeamIdentity {userId: string;@@ -10,12 +9,13 @@ export interface CalendarTeamIdentity {export const calendarTeamKeys = createQueryKeys('calendar-team', {identity: (userId: string) => [userId],sharing: (identity: CalendarTeamIdentity | undefined) => [identity],- members: (identity: CalendarTeamIdentity | undefined) => [identity],availabilityCalendars: (identity: CalendarTeamIdentity | undefined) => [identity,],- events: (- identity: CalendarTeamIdentity | undefined,- range: CalendarOccurrenceQueryRange | undefined- ) => [identity, range],});++/** Saves of the viewer's own settings; a refresh waits for them to settle. */+export const calendarTeamMutationKeys = {+ sharing: ['calendar-team', 'set-sharing'] as const,+ availabilityCalendar: ['calendar-team', 'set-availability-calendar'] as const,+};diff --git a/apps/web/src/lib/queries/calendar/team.ts b/apps/web/src/lib/queries/calendar/team.tsindex 9d5b722bbc..0a99d3eb39 100644--- a/apps/web/src/lib/queries/calendar/team.ts+++ b/apps/web/src/lib/queries/calendar/team.ts@@ -1,17 +1,18 @@import type { CalendarSharing } from '@app/features/calendar-team/core/model';import { throwOnErr } from '@core/util/result';import { authServiceClient } from '@service-auth/client';+import type { AvailabilityCalendarsResponse } from '@service-calendar/generated/schemas/availabilityCalendarsResponse';+import type { TeamCalendarSharingBody } from '@service-calendar/generated/schemas/teamCalendarSharingBody';import { emailClient } from '@service-email/client';-import { storageServiceClient } from '@service-storage/client';-import type { TeamCalendarPage } from '@service-storage/generated/schemas/teamCalendarPage';-import { useMutation, useQuery } from '@tanstack/solid-query';+import { type QueryKey, useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';-import type { CalendarOccurrenceQueryRange } from './keys';+import { queryClient } from '../client';+import { ensureTeamCalendarExpiry } from './team-cache';import {- ensureTeamCalendarExpiry,- resetTeamCalendarQueries,-} from './team-cache';-import { type CalendarTeamIdentity, calendarTeamKeys } from './team-keys';+ type CalendarTeamIdentity,+ calendarTeamKeys,+ calendarTeamMutationKeys,+} from './team-keys';const REFRESH_INTERVAL = 30_000;const freshness = {@@ -36,54 +37,6 @@ export function useCalendarTeamIdentityQuery(}));}-/** Read every page. A failed or cyclic continuation never looks like empty time. */-export async function fetchTeamCalendar(- range: CalendarOccurrenceQueryRange,- signal?: AbortSignal-): Promise<TeamCalendarPage> {- const items = new Map<string, TeamCalendarPage['items'][number]>();- const cursors = new Set<string>();- let cursor: string | undefined;- let members: TeamCalendarPage['members'] = [];- do {- const page = await throwOnErr(() =>- storageServiceClient.listTeamCalendar({- start: range.start,- end: range.end,- limit: 500,- cursor,- signal,- })- );- members = page.members;- for (const item of page.items)- items.set(JSON.stringify([item.ownerId, item.id]), item);- if (!page.nextCursor) break;- if (cursors.has(page.nextCursor))- throw new Error('Team calendar returned a repeated cursor');- cursors.add(page.nextCursor);- cursor = page.nextCursor;- } while (cursor);- return { members, items: [...items.values()], nextCursor: null };-}--export function useTeamCalendarQuery(- identity: Accessor<CalendarTeamIdentity | undefined>,- range: Accessor<CalendarOccurrenceQueryRange | undefined>,- enabled: Accessor<boolean>-) {- return useQuery(() => ({- queryKey: calendarTeamKeys.events(identity(), range()).queryKey,- queryFn: ({ signal }) => {- const current = range();- if (!current) throw new Error('Calendar range unavailable');- return fetchTeamCalendar(current, signal);- },- enabled: identity() !== undefined && range() !== undefined && enabled(),- ...freshness,- }));-}-export function useTeamCalendarSharingQuery(identity: Accessor<CalendarTeamIdentity | undefined>) {@@ -108,54 +61,169 @@ export function useAvailabilityCalendarsQuery(}));}-/** A zero-limit read authorizes the roster without scanning source events. */-export async function fetchTeamCalendarMembers(signal?: AbortSignal) {- const start = new Date();- start.setUTCHours(0, 0, 0, 0);- const end = new Date(start);- end.setUTCDate(end.getUTCDate() + 1);- const page = await throwOnErr(() =>- storageServiceClient.listTeamCalendar({- start: start.toISOString(),- end: end.toISOString(),- limit: 0,- signal,- })- );- return page.members;+/** Update one cached query now and restore it if the save fails; never blank it. */+interface CachedQuerySnapshot<T> {+ previous: T | undefined;}-/** The roster is present even in an empty viewport; retain no event payload. */-export function useTeamCalendarMembersQuery(- identity: Accessor<CalendarTeamIdentity | undefined>-) {- return useQuery(() => ({- queryKey: calendarTeamKeys.members(identity()).queryKey,- queryFn: ({ signal }) => fetchTeamCalendarMembers(signal),- enabled: identity() !== undefined,- ...freshness,- }));+async function replaceCachedQuery<T>(+ queryKey: QueryKey,+ update: (current: T) => T+): Promise<CachedQuerySnapshot<T>> {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData<T>(queryKey);+ if (previous !== undefined)+ queryClient.setQueryData<T>(queryKey, update(previous));+ return { previous };+}++/**+ * Saves of one setting share a scope, so their requests reach the server in+ * order. Only the last pending save rolls back or refetches; an earlier one+ * would overwrite the newer optimistic choice.+ */+const isLastPendingSave = (mutationKey: QueryKey) =>+ queryClient.isMutating({ mutationKey }) === 1;++const teamSharingMutationKey = calendarTeamMutationKeys.sharing;++interface TeamSharingChange {+ identity: CalendarTeamIdentity;+ sharing: CalendarSharing;}+const teamSharingMutationOptions = {+ mutationKey: teamSharingMutationKey,+ scope: { id: 'calendar-team-sharing' },+ mutationFn: ({ sharing }: TeamSharingChange) =>+ throwOnErr(() => emailClient.setTeamCalendarSharing({ sharing })),+ onMutate: ({ identity, sharing }: TeamSharingChange) =>+ replaceCachedQuery<TeamCalendarSharingBody>(+ calendarTeamKeys.sharing(identity).queryKey,+ () => ({ sharing })+ ),+ onError: (+ _error: unknown,+ { identity }: TeamSharingChange,+ snapshot: CachedQuerySnapshot<TeamCalendarSharingBody> | undefined+ ) => {+ if (snapshot?.previous && isLastPendingSave(teamSharingMutationKey))+ queryClient.setQueryData(+ calendarTeamKeys.sharing(identity).queryKey,+ snapshot.previous+ );+ },+ onSettled: (+ _data: unknown,+ _error: unknown,+ { identity }: TeamSharingChange+ ) =>+ isLastPendingSave(teamSharingMutationKey)+ ? queryClient.invalidateQueries({+ queryKey: calendarTeamKeys.sharing(identity).queryKey,+ })+ : undefined,+};++/** The viewer's own sharing never changes what they can read, so nothing else resets. */export function useSetTeamCalendarSharingMutation() {- return useMutation(() => ({- mutationFn: (sharing: CalendarSharing) =>- throwOnErr(() => emailClient.setTeamCalendarSharing({ sharing })),- onSuccess: resetTeamCalendarQueries,- }));+ return useMutation(() => teamSharingMutationOptions);}-export function useSetAvailabilityCalendarMutation() {- return useMutation(() => ({- mutationFn: (args: {- calendarId: string;- contributesToAvailability: boolean;- }) =>- throwOnErr(() =>- emailClient.setAvailabilityCalendar(args.calendarId, {- contributesToAvailability: args.contributesToAvailability,+const availabilityCalendarMutationKey =+ calendarTeamMutationKeys.availabilityCalendar;++interface AvailabilityCalendarChange {+ identity: CalendarTeamIdentity;+ calendarIds: string[];+ contributesToAvailability: boolean;+}++/**+ * Calendars whose save failed in a group change. The mutation rethrows the+ * client's own error so retry and auth handling still read its codes.+ */+const failedCalendarIds = new WeakMap<AvailabilityCalendarChange, string[]>();++const availabilityCalendarMutationOptions = {+ mutationKey: availabilityCalendarMutationKey,+ scope: { id: 'calendar-team-availability-calendar' },+ mutationFn: async (change: AvailabilityCalendarChange) => {+ // Settle every request before reconciling, so no save can land after the+ // refetch that follows a failure.+ const results = await Promise.allSettled(+ change.calendarIds.map((calendarId) =>+ throwOnErr(() =>+ emailClient.setAvailabilityCalendar(calendarId, {+ contributesToAvailability: change.contributesToAvailability,+ })+ )+ )+ );+ const failures = results.flatMap((result, index) =>+ result.status === 'rejected'+ ? [{ calendarId: change.calendarIds[index], reason: result.reason }]+ : []+ );+ if (failures.length === 0) return;+ failedCalendarIds.set(+ change,+ failures.map((failure) => failure.calendarId)+ );+ throw failures[0].reason;+ },+ onMutate: ({+ identity,+ calendarIds,+ contributesToAvailability,+ }: AvailabilityCalendarChange) =>+ replaceCachedQuery<AvailabilityCalendarsResponse>(+ calendarTeamKeys.availabilityCalendars(identity).queryKey,+ (current) => ({+ calendars: current.calendars.map((calendar) =>+ calendarIds.includes(calendar.calendarId)+ ? { ...calendar, contributesToAvailability }+ : calendar+ ),+ })+ ),+ onError: (+ _error: unknown,+ change: AvailabilityCalendarChange,+ snapshot: CachedQuerySnapshot<AvailabilityCalendarsResponse> | undefined+ ) => {+ const previous = snapshot?.previous;+ if (!previous || !isLastPendingSave(availabilityCalendarMutationKey))+ return;+ const failed = new Set(failedCalendarIds.get(change) ?? change.calendarIds);+ const before = new Map(+ previous.calendars.map((calendar) => [calendar.calendarId, calendar])+ );+ queryClient.setQueryData<AvailabilityCalendarsResponse>(+ calendarTeamKeys.availabilityCalendars(change.identity).queryKey,+ (current) =>+ current && {+ calendars: current.calendars.map((calendar) =>+ failed.has(calendar.calendarId)+ ? (before.get(calendar.calendarId) ?? calendar)+ : calendar+ ),+ }+ );+ },+ onSettled: (+ _data: unknown,+ _error: unknown,+ { identity }: AvailabilityCalendarChange+ ) =>+ isLastPendingSave(availabilityCalendarMutationKey)+ ? queryClient.invalidateQueries({+ queryKey: calendarTeamKeys.availabilityCalendars(identity).queryKey,})- ),- onSuccess: resetTeamCalendarQueries,- }));+ : undefined,+};++/** Group changes save every calendar of an account in one optimistic step. */+export function useSetAvailabilityCalendarMutation() {+ return useMutation(() => availabilityCalendarMutationOptions);}diff --git a/apps/web/src/lib/queries/calendar/tests/sync.test.ts b/apps/web/src/lib/queries/calendar/tests/sync.test.tsindex 4ff8f05282..b0de7abee2 100644--- a/apps/web/src/lib/queries/calendar/tests/sync.test.ts+++ b/apps/web/src/lib/queries/calendar/tests/sync.test.ts@@ -5,10 +5,10 @@ import { handleRefreshCalendar } from '../sync';const invalidateQueriesMock = vi.hoisted(() => vi.fn());const isMutatingMock = vi.hoisted(() => vi.fn());const invalidateCalendarOccurrencesMock = vi.hoisted(() => vi.fn());-const resetTeamCalendarQueriesMock = vi.hoisted(() => vi.fn());+const refreshTeamCalendarQueriesMock = vi.hoisted(() => vi.fn());vi.mock('../team-cache', () => ({- resetTeamCalendarQueries: resetTeamCalendarQueriesMock,+ refreshTeamCalendarQueries: refreshTeamCalendarQueriesMock,}));vi.mock('../../client', () => ({@@ -35,7 +35,7 @@ describe('handleRefreshCalendar', () => {});expect(invalidateCalendarOccurrencesMock).toHaveBeenCalledTimes(1);- expect(resetTeamCalendarQueriesMock).toHaveBeenCalledTimes(1);+ expect(refreshTeamCalendarQueriesMock).toHaveBeenCalledTimes(1);expect(invalidateQueriesMock).toHaveBeenCalledWith({queryKey: calendarKeys.invitations._def,});@@ -81,7 +81,7 @@ describe('handleRefreshCalendar', () => {it('clears team projections on sharing changes without touching own optimistic events', () => {handleRefreshCalendar({ event: 'team_sharing_changed' });- expect(resetTeamCalendarQueriesMock).toHaveBeenCalledTimes(1);+ expect(refreshTeamCalendarQueriesMock).toHaveBeenCalledTimes(1);expect(invalidateCalendarOccurrencesMock).not.toHaveBeenCalled();});});diff --git a/apps/web/src/lib/queries/calendar/tests/team-cache.test.ts b/apps/web/src/lib/queries/calendar/tests/team-cache.test.tsindex 3a9bc5c28d..99bc1d015b 100644--- a/apps/web/src/lib/queries/calendar/tests/team-cache.test.ts+++ b/apps/web/src/lib/queries/calendar/tests/team-cache.test.ts@@ -5,7 +5,7 @@ import { calendarKeys } from '../keys';import {clearTeamCalendarQueries,ensureTeamCalendarExpiry,- resetTeamCalendarQueries,+ refreshTeamCalendarQueries,resetTeamCalendarSession,subscribeToTeamCalendarReset,TEAM_CALENDAR_MAX_DATA_AGE_MS,@@ -24,12 +24,13 @@ describe('team authorization invalidation', () => {vi.useRealTimers();});- it('removes already rendered data before a failing refetch settles', async () => {- const queryKey = calendarTeamKeys.sharing({- userId: 'alice',- teamId: 'team',- }).queryKey;- queryClient.setQueryData(queryKey, { sharing: 'all' });+ it('removes teammate data before a failing refetch settles', async () => {+ const queryKey = calendarKeys.teamOutOfOffice(+ 'alice',+ undefined,+ 'team'+ ).queryKey;+ queryClient.setQueryData(queryKey, { items: [{ title: 'Private' }] });const observer = new QueryObserver(queryClient, {queryKey,queryFn: async () => {@@ -38,14 +39,50 @@ describe('team authorization invalidation', () => {staleTime: Infinity,});const unsubscribe = observer.subscribe(() => {});- const reset = resetTeamCalendarQueries();+ const refresh = refreshTeamCalendarQueries();expect(observer.getCurrentResult().data).toBeUndefined();- await reset;+ await refresh;expect(observer.getCurrentResult().isError).toBe(true);expect(observer.getCurrentResult().data).toBeUndefined();unsubscribe();});+ it("keeps the viewer's own team and settings visible while they refetch", async () => {+ const identity = { userId: 'alice', teamId: 'team' };+ const keys = [+ calendarTeamKeys.identity('alice').queryKey,+ calendarTeamKeys.sharing(identity).queryKey,+ calendarTeamKeys.availabilityCalendars(identity).queryKey,+ ];+ let finish!: () => void;+ const pending = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const observers = keys.map((queryKey) => {+ queryClient.setQueryData(queryKey, 'cached');+ const observer = new QueryObserver(queryClient, {+ queryKey,+ queryFn: async () => {+ await pending;+ return 'fresh';+ },+ staleTime: Infinity,+ });+ return { observer, unsubscribe: observer.subscribe(() => {}) };+ });+ const refresh = refreshTeamCalendarQueries();+ for (const { observer } of observers) {+ expect(observer.getCurrentResult().data).toBe('cached');+ expect(observer.getCurrentResult().isFetching).toBe(true);+ }+ finish();+ await refresh;+ for (const { observer, unsubscribe } of observers) {+ expect(observer.getCurrentResult().data).toBe('fresh');+ unsubscribe();+ }+ });+it('purges all team scopes on logout while preserving own occurrences', () => {const first = calendarTeamKeys.sharing({userId: 'alice',@@ -159,17 +196,18 @@ describe('team authorization invalidation', () => {it('clears detached selections on authorization reset, not ordinary cache writes', async () => {const onReset = vi.fn();const unsubscribe = subscribeToTeamCalendarReset(onReset);- const team = calendarTeamKeys.sharing({- userId: 'alice',- teamId: 'team',- }).queryKey;+ const team = calendarKeys.teamOutOfOffice(+ 'alice',+ undefined,+ 'team'+ ).queryKey;const own = calendarKeys.occurrences('alice', undefined).queryKey;- queryClient.setQueryData(team, { sharing: 'all' });+ queryClient.setQueryData(team, { items: [] });queryClient.setQueryData(own, []);expect(onReset).not.toHaveBeenCalled();await queryClient.resetQueries({ queryKey: own });expect(onReset).not.toHaveBeenCalled();- await resetTeamCalendarQueries();+ await refreshTeamCalendarQueries();expect(onReset).toHaveBeenCalledOnce();unsubscribe();});diff --git a/apps/web/src/lib/queries/calendar/tests/team.test.ts b/apps/web/src/lib/queries/calendar/tests/team.test.tsdeleted file mode 100644index d533a0374b..0000000000--- a/apps/web/src/lib/queries/calendar/tests/team.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { storageServiceClient } from '@service-storage/client';-import { err, ok } from 'neverthrow';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fetchTeamCalendar, fetchTeamCalendarMembers } from '../team';-import { calendarTeamKeys } from '../team-keys';--vi.mock('@service-storage/client', () => ({- storageServiceClient: { listTeamCalendar: vi.fn() },-}));-vi.mock('@service-auth/client', () => ({ authServiceClient: {} }));-vi.mock('@service-email/client', () => ({ emailClient: {} }));-vi.mock('../team-cache', () => ({ resetTeamCalendarQueries: vi.fn() }));--const range = {- start: '2026-10-07T00:00:00Z',- end: '2026-10-08T00:00:00Z',- startDate: '2026-10-07',- endDate: '2026-10-08',-};-const item = {- id: 'opaque',- ownerId: 'alice',- kind: 'busy' as const,- contributesToAvailability: true,- time: {- kind: 'timed' as const,- startsAt: range.start,- endsAt: range.end,- timeZone: null,- },-};--describe('team calendar query boundaries', () => {- beforeEach(() => vi.clearAllMocks());-- it('partitions every policy and event query by viewer and team', () => {- const first = { userId: 'alice', teamId: 'team-a' };- const otherUser = { ...first, userId: 'bob' };- const otherTeam = { ...first, teamId: 'team-b' };- for (const key of [- calendarTeamKeys.sharing,- calendarTeamKeys.availabilityCalendars,- ]) {- expect(key(first).queryKey).not.toEqual(key(otherUser).queryKey);- expect(key(first).queryKey).not.toEqual(key(otherTeam).queryKey);- }- expect(calendarTeamKeys.events(first, range).queryKey).not.toEqual(- calendarTeamKeys.events(otherTeam, range).queryKey- );- });-- it('follows all pages and replaces a duplicate projection whole', async () => {- const updated = { ...item, contributesToAvailability: false };- vi.mocked(storageServiceClient.listTeamCalendar)- .mockResolvedValueOnce(- ok({ members: [], items: [item], nextCursor: 'cursor' })- )- .mockResolvedValueOnce(- ok({ members: [], items: [updated], nextCursor: null })- );- const controller = new AbortController();- expect((await fetchTeamCalendar(range, controller.signal)).items).toEqual([- updated,- ]);- expect(storageServiceClient.listTeamCalendar).toHaveBeenLastCalledWith({- start: range.start,- end: range.end,- cursor: 'cursor',- limit: 500,- signal: controller.signal,- });- });-- it('retains distinct source copies across pages without combining masking or availability', async () => {- const followed = {- ...item,- id: 'opaque-followed-source',- kind: 'details' as const,- contributesToAvailability: false,- details: {- title: 'Shared calendar meeting',- description: 'Visible on the followed source',- location: null,- conferenceUrl: null,- organizerEmail: null,- organizerName: null,- attendees: [],- calendarName: 'Followed calendar',- },- };- const personal = { ...item, id: 'opaque-personal-source' };- vi.mocked(storageServiceClient.listTeamCalendar)- .mockResolvedValueOnce(- ok({ members: [], items: [followed], nextCursor: 'next-source' })- )- .mockResolvedValueOnce(- ok({ members: [], items: [personal], nextCursor: null })- );-- const page = await fetchTeamCalendar(range);-- expect(page.items).toEqual([followed, personal]);- expect(page.items[1]).not.toHaveProperty('details');- });-- it('loads the roster without asking the server to scan source events', async () => {- const members = [- {- userId: 'alice',- sharing: 'busy_only' as const,- coverage: 'ready' as const,- },- ];- vi.mocked(storageServiceClient.listTeamCalendar).mockResolvedValueOnce(- ok({ members, items: [], nextCursor: null })- );- const controller = new AbortController();-- expect(await fetchTeamCalendarMembers(controller.signal)).toEqual(members);- expect(storageServiceClient.listTeamCalendar).toHaveBeenCalledTimes(1);- expect(storageServiceClient.listTeamCalendar).toHaveBeenCalledWith({- start: expect.stringMatching(/T00:00:00\.000Z$/),- end: expect.stringMatching(/T00:00:00\.000Z$/),- limit: 0,- signal: controller.signal,- });- });-- it('rejects a partial range when access changes or continuation repeats', async () => {- vi.mocked(storageServiceClient.listTeamCalendar)- .mockResolvedValueOnce(- ok({ members: [], items: [item], nextCursor: 'cursor' })- )- .mockResolvedValueOnce(- err([{ code: 'FORBIDDEN' as const, message: 'Access changed' }])- );- await expect(fetchTeamCalendar(range)).rejects.toThrow();- vi.mocked(storageServiceClient.listTeamCalendar).mockResolvedValue(- ok({ members: [], items: [item], nextCursor: 'cursor' })- );- await expect(fetchTeamCalendar(range)).rejects.toThrow('repeated cursor');- });-});diff --git a/apps/web/src/lib/queries/calendar/tests/team.test.tsx b/apps/web/src/lib/queries/calendar/tests/team.test.tsxnew file mode 100644index 0000000000..3616e2df7a--- /dev/null+++ b/apps/web/src/lib/queries/calendar/tests/team.test.tsx@@ -0,0 +1,288 @@+import { ThrownResultError } from '@core/util/result';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, 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 {+ useSetAvailabilityCalendarMutation,+ useSetTeamCalendarSharingMutation,+} from '../team';+import { refreshTeamCalendarQueries } from '../team-cache';+import { calendarTeamKeys } from '../team-keys';++const setTeamCalendarSharing = vi.hoisted(() => vi.fn());+const setAvailabilityCalendar = vi.hoisted(() => vi.fn());++vi.mock('@service-email/client', () => ({+ emailClient: { setTeamCalendarSharing, setAvailabilityCalendar },+}));+vi.mock('@service-auth/client', () => ({ authServiceClient: {} }));++let testQueryClient: QueryClient;++vi.mock('../../client', () => ({+ get queryClient() {+ return testQueryClient;+ },+}));++const identity = { userId: 'alice', teamId: 'team-a' };+const sharingKey = calendarTeamKeys.sharing(identity).queryKey;+const calendarsKey = calendarTeamKeys.availabilityCalendars(identity).queryKey;++let dispose: (() => void) | undefined;++function renderHook<T>(factory: () => T): T {+ let hook!: T;+ dispose = render(+ () => (+ <QueryClientProvider client={testQueryClient}>+ {(() => {+ hook = factory();+ return null as unknown as JSX.Element;+ })()}+ </QueryClientProvider>+ ),+ document.body+ );+ return hook;+}++const failure = () => err([{ code: 'HTTP_ERROR' as const, message: 'no' }]);++beforeEach(() => {+ vi.clearAllMocks();+ testQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+ testQueryClient.clear();+});++describe('team calendar query boundaries', () => {+ it('partitions every policy query by viewer and team', () => {+ const otherUser = { ...identity, userId: 'bob' };+ const otherTeam = { ...identity, teamId: 'team-b' };+ for (const key of [+ calendarTeamKeys.sharing,+ calendarTeamKeys.availabilityCalendars,+ ]) {+ expect(key(identity).queryKey).not.toEqual(key(otherUser).queryKey);+ expect(key(identity).queryKey).not.toEqual(key(otherTeam).queryKey);+ }+ });+});++describe('team sharing changes', () => {+ it('shows the new choice while saving and never clears the setting', async () => {+ testQueryClient.setQueryData(sharingKey, { sharing: 'busy_only' });+ let resolve!: (value: unknown) => void;+ setTeamCalendarSharing.mockReturnValue(+ new Promise((res) => {+ resolve = res;+ })+ );+ const mutation = renderHook(() => useSetTeamCalendarSharingMutation());++ const saving = mutation.mutateAsync({ identity, sharing: 'all' });+ await vi.waitFor(() =>+ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'all',+ })+ );+ resolve(ok({ sharing: 'all' }));+ await saving;++ expect(setTeamCalendarSharing).toHaveBeenCalledWith({ sharing: 'all' });+ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'all',+ });+ });++ it('restores the saved choice when the change fails', async () => {+ testQueryClient.setQueryData(sharingKey, { sharing: 'busy_only' });+ setTeamCalendarSharing.mockResolvedValue(failure());+ const mutation = renderHook(() => useSetTeamCalendarSharingMutation());++ await expect(+ mutation.mutateAsync({ identity, sharing: 'none' })+ ).rejects.toBeDefined();++ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'busy_only',+ });+ });++ it('leaves a saving choice to its save when a sharing push arrives', async () => {+ testQueryClient.setQueryData(sharingKey, { sharing: 'busy_only' });+ let finish!: (value: unknown) => void;+ setTeamCalendarSharing.mockReturnValue(+ new Promise((res) => {+ finish = res;+ })+ );+ const mutation = renderHook(() => useSetTeamCalendarSharingMutation());++ const saving = mutation.mutateAsync({ identity, sharing: 'all' });+ await vi.waitFor(() =>+ expect(setTeamCalendarSharing).toHaveBeenCalledTimes(1)+ );+ await refreshTeamCalendarQueries();+ expect(testQueryClient.getQueryState(sharingKey)?.isInvalidated).toBe(+ false+ );+ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'all',+ });++ finish(ok({ sharing: 'all' }));+ await saving;+ expect(testQueryClient.getQueryState(sharingKey)?.isInvalidated).toBe(true);+ });++ it('sends quick changes in order and keeps the newest choice when an earlier one fails', async () => {+ testQueryClient.setQueryData(sharingKey, { sharing: 'busy_only' });+ let failFirst!: (value: unknown) => void;+ setTeamCalendarSharing+ .mockReturnValueOnce(+ new Promise((res) => {+ failFirst = res;+ })+ )+ .mockResolvedValueOnce(ok({ sharing: 'none' }));+ const mutation = renderHook(() => useSetTeamCalendarSharingMutation());++ const first = mutation.mutateAsync({ identity, sharing: 'all' });+ await vi.waitFor(() =>+ expect(setTeamCalendarSharing).toHaveBeenCalledTimes(1)+ );+ const second = mutation.mutateAsync({ identity, sharing: 'none' });+ await vi.waitFor(() =>+ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'none',+ })+ );+ expect(setTeamCalendarSharing).toHaveBeenCalledTimes(1);++ failFirst(failure());+ await expect(first).rejects.toBeDefined();+ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'none',+ });+ await second;+ expect(setTeamCalendarSharing).toHaveBeenLastCalledWith({+ sharing: 'none',+ });+ expect(testQueryClient.getQueryData(sharingKey)).toEqual({+ sharing: 'none',+ });+ });+});++describe('availability calendar changes', () => {+ const calendars = {+ calendars: [+ {+ calendarId: 'primary',+ name: 'Primary',+ isPrimary: true,+ contributesToAvailability: true,+ },+ {+ calendarId: 'holidays',+ name: 'Holidays',+ isPrimary: false,+ contributesToAvailability: false,+ },+ {+ calendarId: 'other-account',+ name: 'Other account',+ isPrimary: true,+ contributesToAvailability: true,+ },+ ],+ };+ const included = () =>+ (+ testQueryClient.getQueryData(calendarsKey) as typeof calendars+ ).calendars.map((calendar) => calendar.contributesToAvailability);++ it('saves an account group in one step and updates only its calendars', async () => {+ testQueryClient.setQueryData(calendarsKey, calendars);+ setAvailabilityCalendar.mockResolvedValue(ok({}));+ const mutation = renderHook(() => useSetAvailabilityCalendarMutation());++ await mutation.mutateAsync({+ identity,+ calendarIds: ['primary', 'holidays'],+ contributesToAvailability: false,+ });++ expect(setAvailabilityCalendar).toHaveBeenCalledTimes(2);+ expect(setAvailabilityCalendar).toHaveBeenCalledWith('holidays', {+ contributesToAvailability: false,+ });+ expect(included()).toEqual([false, false, true]);+ });++ it('waits for every save and restores only the calendars that failed', async () => {+ testQueryClient.setQueryData(calendarsKey, calendars);+ let finishPrimary!: (value: unknown) => void;+ setAvailabilityCalendar+ .mockReturnValueOnce(+ new Promise((res) => {+ finishPrimary = res;+ })+ )+ .mockResolvedValueOnce(failure());+ const mutation = renderHook(() => useSetAvailabilityCalendarMutation());++ let settled = false;+ const save = async () => {+ try {+ await mutation.mutateAsync({+ identity,+ calendarIds: ['primary', 'holidays'],+ contributesToAvailability: false,+ });+ } finally {+ settled = true;+ }+ };+ const saving = save();+ await vi.waitFor(() =>+ expect(setAvailabilityCalendar).toHaveBeenCalledTimes(2)+ );+ await Promise.resolve();+ expect(settled).toBe(false);++ finishPrimary(ok({}));+ // The client's own error keeps the codes retry and auth handling read.+ await expect(saving).rejects.toBeInstanceOf(ThrownResultError);++ expect(included()).toEqual([false, false, true]);+ });++ it('restores a failed calendar to its previous value', async () => {+ testQueryClient.setQueryData(calendarsKey, calendars);+ setAvailabilityCalendar+ .mockResolvedValueOnce(failure())+ .mockResolvedValueOnce(ok({}));+ const mutation = renderHook(() => useSetAvailabilityCalendarMutation());++ await expect(+ mutation.mutateAsync({+ identity,+ calendarIds: ['primary', 'other-account'],+ contributesToAvailability: false,+ })+ ).rejects.toBeDefined();++ expect(included()).toEqual([true, false, false]);+ });+});diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex ed7427079a..fe0f19da53 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -168,7 +168,6 @@ import type { StorageRowsQuery } from './generated/schemas/storageRowsQuery';import type { StoredGithubPullRequest } from './generated/schemas/storedGithubPullRequest';import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';import type { TableDetail } from './generated/schemas/tableDetail';-import type { TeamCalendarPage } from './generated/schemas/teamCalendarPage';import type { TeamOutOfOfficeResponse } from './generated/schemas/teamOutOfOfficeResponse';import type { TypedSuccessResponse } from './generated/schemas/typedSuccessResponse';import type { UpdateAgentRequest } from './generated/schemas/updateAgentRequest';@@ -595,22 +594,6 @@ export const storageServiceClient = {).map((result) => result);},- async listTeamCalendar(args: {- start: string;- end: string;- cursor?: string;- limit?: number;- signal?: AbortSignal;- }) {- const params = new URLSearchParams({ start: args.start, end: args.end });- if (args.cursor) params.set('cursor', args.cursor);- if (args.limit !== undefined) params.set('limit', String(args.limit));- return dssFetch<TeamCalendarPage>(- `/calendar-events/team?${params.toString()}`,- { method: 'GET', signal: args.signal }- );- },-async getBatchCalendarEventPreviews(args: CalendarMentionPreviewRequest) {return (await dssFetch<CalendarMentionPreviewResponse>(diff --git a/apps/web/tests/calendar-team/README.md b/apps/web/tests/calendar-team/README.mdindex 9e10e62085..6ba7fa9ac3 100644--- a/apps/web/tests/calendar-team/README.md+++ b/apps/web/tests/calendar-team/README.md@@ -1,11 +1,11 @@# Team calendar browser verification-This harness loads the complete bundled app and intercepts auth, team, and calendar HTTP traffic with synthetic identities. It blocks nonlocal requests and websocket traffic. It does not verify the Rust service or Google permissions. Own-calendar reads use the existing REST fallback; team projections use their production REST query, mapping, and UI paths.+This harness loads the complete bundled app and intercepts auth, team, and calendar HTTP traffic with synthetic identities. It blocks nonlocal requests and websocket traffic. It does not verify the Rust service or Google permissions. Own-calendar reads use the existing REST fallback.-It uses a live clock and checks that loading placeholders disappear and event chips are opaque and in the viewport before capture. It exercises sharing and availability settings, read-only event details, revocation, membership loss, a viewer without any connected Google account, and automatic data/popover expiry while refresh requests hang. The expiry check waits up to 65 seconds with the browser clock running normally.+It uses a live clock and checks that loading placeholders disappear before capture. It checks that no surface reads teammate calendars or shows team calendar controls, and exercises the Team sharing select and the account-grouped "Calendars that count as busy" list, failing if any change flashes a loading state.-Imported own and shared point events must render compactly with a single time,-without drag/resize. Editing the own point's title must omit time from its request.+Imported own point events must render compactly with a single time,+without drag/resize. Editing the point's title must omit time from its request.Adding a Macro call to a point must show a duration error before any mutation.From `apps/web`, with Chromium installed:diff --git a/apps/web/tests/calendar-team/browser.ts b/apps/web/tests/calendar-team/browser.tsindex 2a039a2fef..f83319fa93 100644--- a/apps/web/tests/calendar-team/browser.ts+++ b/apps/web/tests/calendar-team/browser.ts@@ -39,7 +39,6 @@ await page.addInitScript(() =>'macro:pref:calendar:settings',JSON.stringify({periodView: 'timeGridWeek',- showTeamCalendars: true,hiddenSourceIds: [],sourceColors: {},accountColors: {},@@ -54,17 +53,9 @@ const ALICE = 'macro|[email protected]';const BOB = 'macro|[email protected]';const TEAM = '00000000-0000-0000-0000-000000001111';let sharing = 'busy_only';-let included = false;-let revoked = false;-let member = true;-let connected = true;-let hangTeamRequests = false;+const included: Record<string, boolean> = { primary: true, followed: false };const mutations: unknown[] = [];-const teamReadLimits: string[] = [];-const teamMembers = [- { userId: ALICE, sharing: 'all', coverage: 'ready' },- { userId: BOB, sharing: 'busy_only', coverage: 'ready' },-];+const teamReads: string[] = [];// Keep the browser clock live: calendar loading transitions compare elapsed time.const fixtureDate = new Date().toISOString().slice(0, 10);const time = (hour: number) => ({@@ -102,64 +93,6 @@ const ownPoint = {time: pointTime(11),},};-const items = [- {- id: 'opaque-details',- ownerId: ALICE,- kind: 'details',- time: time(10),- contributesToAvailability: true,- details: {- title: 'Team planning',- description: '<p>Review roadmap</p>',- location: 'Room 2',- conferenceUrl: 'https://meet.google.com/abc-defg-hij',- organizerEmail: '[email protected]',- organizerName: 'Alice',- attendees: [- {- email: '[email protected]',- displayName: 'Offline Fixture',- isSelf: true,- isOrganizer: false,- responseStatus: 'accepted',- },- ],- calendarName: 'Alice primary',- },- },- {- id: 'opaque-busy',- ownerId: BOB,- kind: 'busy',- time: time(12),- contributesToAvailability: true,- },- {- id: 'opaque-point',- ownerId: ALICE,- kind: 'details',- time: pointTime(13),- contributesToAvailability: false,- details: {- title: 'Shared point',- description: null,- location: null,- conferenceUrl: null,- organizerEmail: null,- organizerName: null,- attendees: [],- calendarName: 'Alice primary',- },- },- {- id: 'opaque-followed',- ownerId: BOB,- kind: 'busy',- time: time(14),- contributesToAvailability: false,- },-];await page.route('**/*', async (route) => {const request = route.request();const url = new URL(request.url());@@ -173,30 +106,24 @@ await page.route('**/*', async (route) => {if (url.origin !== origin) return route.abort();if (path.startsWith('/app') || path === '/') return route.continue();if (path === '/auth/jwt/refresh') return respond({});- if (!connected && path === '/email/email/links')- return respond({ links: [] });- if (!connected && path === '/calendar/calendars')- return respond({ calendars: [] });if (path === '/auth/team')- return member- ? respond({- team: {- id: TEAM,- name: 'Calendar fixtures',- owner_id: USER_ID,- slug: 'fixture',- enterprise: false,- crm_enabled: false,- allow_non_admin_invites: true,- },- members: [USER_ID, ALICE, BOB].map((user_id) => ({- user_id,- team_id: TEAM,- role: 'member',- plan: 'free',- })),- })- : respond({}, 404);+ return respond({+ team: {+ id: TEAM,+ name: 'Calendar fixtures',+ owner_id: USER_ID,+ slug: 'fixture',+ enterprise: false,+ crm_enabled: false,+ allow_non_admin_invites: true,+ },+ members: [USER_ID, ALICE, BOB].map((user_id) => ({+ user_id,+ team_id: TEAM,+ role: 'member',+ plan: 'free',+ })),+ });if (path === '/auth/user/get_names_with_email')return respond({names: [@@ -219,19 +146,26 @@ await page.route('**/*', async (route) => {calendarId: 'primary',name: 'My primary',isPrimary: true,- contributesToAvailability: true,+ contributesToAvailability: included.primary,},{calendarId: 'followed',name: 'Subscribed coworker',isPrimary: false,- contributesToAvailability: included,+ contributesToAvailability: included.followed,},],});- if (path === '/calendar/availability-calendars/followed') {- included = request.postDataJSON().contributesToAvailability;- mutations.push(request.postDataJSON());+ const availabilityChange = path.match(+ /^\/calendar\/availability-calendars\/([^/]+)$/+ );+ if (availabilityChange) {+ included[availabilityChange[1]] =+ request.postDataJSON().contributesToAvailability;+ mutations.push({+ calendarId: availabilityChange[1],+ ...request.postDataJSON(),+ });return route.fulfill({ status: 204 });}if (path === '/calendar/calendars')@@ -247,18 +181,21 @@ await page.route('**/*', async (route) => {isSubscription: false,defaultReminders: [],},+ {+ id: 'followed',+ emailAddress: '[email protected]',+ emailLinkId: '00000000-0000-0000-0000-000000001000',+ name: 'Subscribed coworker',+ isPrimary: false,+ isWritable: false,+ isSubscription: false,+ defaultReminders: [],+ },],});if (path === '/dss/calendar-events/team') {- teamReadLimits.push(url.searchParams.get('limit') ?? 'default');- if (hangTeamRequests) return new Promise<void>(() => {});- return revoked- ? respond({ message: 'Access revoked' }, 403)- : respond({- members: teamMembers,- items: url.searchParams.get('limit') === '0' ? [] : items,- nextCursor: null,- });+ teamReads.push(url.search);+ return respond({}, 404);}if (path === '/dss/calendar-events/team-out-of-office')return respond({ items: [], hasMore: false });@@ -273,7 +210,7 @@ await page.route('**/*', async (route) => {}if (path === '/dss/calendar-events')return respond({- items: connected ? [ownPoint] : [],+ items: [ownPoint],hasMore: false,nextCursor: null,syncStatus: 'ready',@@ -298,48 +235,55 @@ async function expectRevealedCalendar() {'[data-calendar-loading-state]:not([data-calendar-loading-state="hidden"])')).toHaveCount(0, { timeout: 15000 });- const titles = [- 'Alice Fixture: Team planning',- 'Bob Fixture: Busy',- 'Bob Fixture: Shared calendar block',- ];- await activePage- .getByText(titles[2], { exact: true })- .scrollIntoViewIfNeeded();- for (const title of titles) {- const chip = activePage.getByText(title, { exact: true });- await expect(chip).toBeInViewport();- await expect- .poll(() =>- chip.evaluate((element) => {- for (- let parent: Element | null = element;- parent;- parent = parent.parentElement- ) {- const style = getComputedStyle(parent);- if (Number(style.opacity) === 0 || style.visibility === 'hidden')- return false;- }- return true;- })- )- .toBe(true);- }}+/** Record every loading placeholder that appears, however briefly. */+async function watchLoadingText() {+ await page.evaluate(() => {+ const seen: string[] = [];+ const placeholders = [+ 'Loading your team…',+ 'Loading calendars…',+ 'Loading team calendar settings…',+ ];+ const check = () => {+ const text = document.body.innerText;+ for (const placeholder of placeholders)+ if (text.includes(placeholder)) seen.push(placeholder);+ };+ new MutationObserver(check).observe(document.body, {+ childList: true,+ subtree: true,+ characterData: true,+ });+ (window as unknown as { __loadingSeen: string[] }).__loadingSeen = seen;+ });+}++const loadingSeen = () =>+ page.evaluate(+ () => (window as unknown as { __loadingSeen: string[] }).__loadingSeen+ );+try {await page.goto(`${origin}/app/calendar/week`, {waitUntil: 'domcontentloaded',});await page- .getByText('Team planning', { exact: false })+ .getByText('Imported point', { exact: true }).first().waitFor({ timeout: 60000 });await expectRevealedCalendar();- await expect.poll(() => teamReadLimits.includes('0')).toBe(true);- assert.equal(teamReadLimits.includes('500'), true);- assert.equal(teamReadLimits.includes('1'), false);+ const sidebar = page.getByRole('complementary', {+ name: 'Calendar navigation',+ });+ await expect(sidebar.getByText('Calendars', { exact: true })).toBeVisible();+ await expect(page.getByText('Team calendars', { exact: true })).toHaveCount(+ 0+ );+ await expect(+ page.getByRole('switch', { name: 'Show team calendars' })+ ).toHaveCount(0);await page.screenshot({path: '/tmp/calendar-team-grid.png',fullPage: true,@@ -409,186 +353,98 @@ try {page.getByRole('textbox', { name: 'Title', exact: true })).toHaveCount(0);await page.keyboard.press('Escape');- const sharedPointChip = activeCalendar- .getByText('Alice Fixture: Shared point', { exact: true })- .locator(- 'xpath=ancestor::*[contains(concat(" ", normalize-space(@class), " "), " fc-event ")][1]'- );- await expect(sharedPointChip).toBeInViewport();- const sharedPointBounds = await sharedPointChip.boundingBox();- assert.ok(- sharedPointBounds &&- sharedPointBounds.height > 0 &&- sharedPointBounds.height < 30- );- await expect(sharedPointChip).not.toHaveClass(- /fc-event-draggable|fc-event-resizable/- );- await sharedPointChip.click();- await expect(- page.locator('section[aria-label="Shared event details"]')- ).toContainText('No duration');- await expect(- page.locator('section[aria-label="Shared event details"]')- ).toContainText('Does not count toward their busy time');- await page.screenshot({- path: '/tmp/calendar-team-points.png',- fullPage: true,- });- await page.keyboard.press('Escape');- await page.getByText('Team planning', { exact: false }).first().click();- const detail = page.locator('section[aria-label="Shared event details"]');- await expect(detail).toContainText('Shared in Macro · Read only');- await expect(detail).toContainText('Offline Fixture (you)');- for (const name of [- 'Edit event',- 'Delete event',- 'Copy event',- 'Copy guest emails',- 'Email guests',- ]) {- await expect(page.getByRole('button', { name, exact: true })).toHaveCount(- 0- );- }- assert.equal(- new URL(page.url()).searchParams.has('s0.calendar.eventId'),- false- );- await page.screenshot({- path: '/tmp/calendar-team-details.png',- fullPage: true,- });- await page.keyboard.press('Escape');- await page- .getByText(/: Busy$/, { exact: false })- .first()- .click();- await expect(detail).toContainText('Counts toward this teammate');- await expect(detail).not.toContainText('Organizer:');- await expect(- detail.getByRole('button', { name: 'Join meeting' })- ).toHaveCount(0);- await page.keyboard.press('Escape');- await page- .getByText(/: Shared calendar block$/, { exact: false })- .first()- .click();- await expect(detail).toContainText('Does not count toward their busy time');- await page.keyboard.press('Escape');+ mutations.length = 0;await page.goto(`${origin}/app/settings/calendar`, {waitUntil: 'domcontentloaded',});+ const sharingSelect = page.getByRole('button', {+ name: 'Share with teammates',+ });+ await expect(sharingSelect).toContainText('Busy blocks', { timeout: 30000 });await expect(- page.getByRole('radio', { name: 'Busy blocks', exact: true })- ).toBeChecked({ timeout: 30000 });- await expect(- page.getByText(- 'including subscribed or delegated calendars, birthdays and holidays',- {- exact: false,- }- )+ page.getByText('Teammates see when you are busy, not what.', {+ exact: true,+ })).toBeVisible();await expect(- page.getByText(- 'Calendars unchecked in Google Calendar are included if synced.',- {- exact: false,- }+ page.getByRole('switch', { name: 'Show team calendars' })+ ).toHaveCount(0);+ // The innermost section that holds the heading; the page nests sections.+ const busySection = page+ .locator('section')+ .filter({+ has: page.getByRole('heading', { name: 'Calendars that count as busy' }),+ })+ .last();+ const account = busySection.getByRole('checkbox', {+ name: '[email protected]',+ exact: true,+ });+ await expect+ .poll(() =>+ account.evaluate((element) => (element as HTMLInputElement).indeterminate))- ).toBeVisible();+ .toBe(true);+ await busySection+ .getByRole('button', { name: 'Expand [email protected]', exact: true })+ .click();+ const followed = busySection.getByRole('checkbox', {+ name: 'Subscribed coworker',+ exact: true,+ });await expect(- page.getByText(- 'Hiding a calendar in your Macro view does not change sharing.',- {- exact: false,- }- )- ).toBeVisible();+ busySection.getByRole('checkbox', { name: 'My primary' })+ ).toBeChecked();+ await expect(followed).not.toBeChecked();await page.screenshot({path: '/tmp/calendar-team-settings.png',fullPage: true,});- await page.getByRole('radio', { name: 'Event details', exact: true }).check();- await expect(- page.getByRole('radio', { name: 'Event details', exact: true })- ).toBeChecked();- assert.equal(sharing, 'all');- const availabilityToggle = page.getByRole('switch', {- name: 'Count Subscribed coworker toward my availability',- });- await availabilityToggle.press('Space');- await expect.poll(() => included).toBe(true);- await expect(availabilityToggle).toBeChecked();- await expect(availabilityToggle).toBeEnabled();- await page.getByRole('radio', { name: 'Nothing', exact: true }).check();- await expect.poll(() => sharing).toBe('none');- await page.getByRole('radio', { name: 'Busy blocks', exact: true }).check();- await expect.poll(() => sharing).toBe('busy_only');- await page.goto(`${origin}/app/calendar/week`, {- waitUntil: 'domcontentloaded',- });- await page.getByText('Team planning', { exact: false }).first().click();- await expect(detail).toBeVisible();- revoked = true;- // A normal focus refresh must discard a now-forbidden range and detached popover.- const focusTab = await context.newPage();- await focusTab.bringToFront();- await page.bringToFront();- await focusTab.close();- await expect(detail).toHaveCount(0, { timeout: 40000 });- await expect(page.getByText('Team planning', { exact: false })).toHaveCount(- 0- );+ await watchLoadingText();+ await sharingSelect.click();+ await page+ .getByRole('option', { name: 'Event details', exact: true })+ .click();+ await expect(sharingSelect).toContainText('Event details');+ await expect.poll(() => sharing).toBe('all');await expect(- page- .getByText('Team calendars unavailable. Availability is unknown.', {- exact: false,- })- .filter({ visible: true })- .first()+ page.getByText(+ 'Teammates see your events. Private events stay busy blocks.',+ { exact: true }+ )).toBeVisible();- revoked = false;- await page.reload({ waitUntil: 'domcontentloaded' });- await page.getByText('Team planning', { exact: false }).first().click();- await expect(detail).toBeVisible();- member = false;- const membershipTab = await context.newPage();- await membershipTab.bringToFront();- await page.bringToFront();- await membershipTab.close();- await expect(detail).toHaveCount(0, { timeout: 40000 });- await expect(page.getByText('Team planning', { exact: false })).toHaveCount(- 0+ await sharingSelect.click();+ await page.getByRole('option', { name: 'Nothing', exact: true }).click();+ await expect.poll(() => sharing).toBe('none');+ await busySection.getByText('Subscribed coworker', { exact: true }).click();+ await expect.poll(() => included.followed).toBe(true);+ await expect(followed).toBeChecked();+ await expect(account).toBeChecked();+ await busySection.getByText('[email protected]', { exact: true }).click();+ await expect.poll(() => included.primary).toBe(false);+ await expect.poll(() => included.followed).toBe(false);+ await expect(account).not.toBeChecked();+ await sharingSelect.click();+ await page.getByRole('option', { name: 'Busy blocks', exact: true }).click();+ await expect.poll(() => sharing).toBe('busy_only');+ // Let the post-save refetches settle before checking for a flash.+ await page.waitForTimeout(1500);+ assert.deepEqual(+ await loadingSeen(),+ [],+ 'Changing a setting must not flash a loading state');- assert.deepEqual(errors, []);- member = true;- connected = false;- await page.reload({ waitUntil: 'domcontentloaded' });- await expect(- page.getByText('Team planning', { exact: false }).first()- ).toBeVisible({ timeout: 30000 });- await expectRevealedCalendar();- await page.getByText('Team planning', { exact: false }).first().click();- await expect(detail).toContainText('Shared in Macro · Read only');await page.screenshot({- path: '/tmp/calendar-team-no-google.png',+ path: '/tmp/calendar-team-settings-after.png',fullPage: true,});- // Stay online but leave every new team read unresolved. The independent- // expiry must remove already visible data and the detached popover anyway.- hangTeamRequests = true;- await expect(detail).toHaveCount(0, { timeout: 65000 });- await expect(page.getByText('Team planning', { exact: false })).toHaveCount(- 0- );+ assert.deepEqual(teamReads, [], 'No surface reads teammate calendars');assert.deepEqual(errors, []);assert.deepEqual(requestFailures, []);console.log(- 'PASS: imported own/shared points and metadata-only edit, full-app team settings, sanitized blocks, read-only details, revoked-data removal, membership loss, viewer without Google, and expiry during hung refresh'+ 'PASS: imported point rendering and metadata-only edit, no team calendar overlay or controls, team sharing select, account-grouped busy calendars, and settings changes without a loading flash');} catch (error) {console.error(error);@@ -600,7 +456,7 @@ try {errors,requestFailures,unknown: [...new Set(unknown)],- teamReadLimits: [...new Set(teamReadLimits)],+ teamReads,mutations,},null,diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex f6c020fd7f..ad101a5226 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -205,8 +205,8 @@ Collapsible `Upcoming events` and `Calendars` sections follow; calendaraccount rows use Drive-style trailing disclosure buttons and animated nestedbranches. Their 14px visibility checkboxes precede the swatch and label, withseparate account and individual-calendar visibility controls. `Team out of office`-is feature-gated and lists teammates with 24px avatars; its section switch-toggles the entire grid overlay. Clicking a teammate's row navigates to that+is feature-gated and lists teammates with 24px avatars; it is a plain+collapsible section, and the grid overlay always shows. Clicking a teammate's row navigates to thatdate, opens read-only event details, and marks the row active. The icon-only`Calendar settings` control fills the sidebar footer.An account checkbox toggles its calendars together in one update. The checkbox@@ -223,44 +223,30 @@ another sidebar; their left header island has a compact New menu because thebottom New action follows the foreground host view.With `enable-calendar-team-sharing` enabled, **Settings → Calendar** also has-**Team sharing**: `Busy blocks` (the default), `Event details`, and `Nothing`.+**Team sharing**: one `Share with teammates` row whose select offers+`Busy blocks` (the default), `Event details`, and `Nothing`, with a one-line+description of the current choice under the label. A new choice shows at once+and saves in the background; a failed save restores the previous choice and+shows a toast. Neither settings section returns to a loading state after a+change, including when the server's `team_sharing_changed` push arrives.These are Macro read permissions. They do not change Google Calendar ACLs,invite teammates to meetings, or let teammates edit, RSVP, or manage reminders.The sharing choice covers every currently authorized calendar synced to Macro.-Private/confidential events only expose generic time blocks; event details-come from one authorized source copy. Disconnecting an account or losing-source access removes its team projection.--**Calendars that count as busy** controls which calendars represent the user's-personal schedule. Primary calendars count by default; other calendars require-explicit inclusion. Meetings the user attends also contribute, except declined-meetings. Following a coworker's calendar does not automatically make that-coworker's events occupy the user's time. In team overlays, `Busy` means the-block contributes to that teammate's availability; `Shared calendar block`-means it belongs to a calendar the teammate can access and does not count-toward their busy time. Event details show the same distinction explicitly.--The sidebar's **Team calendars** section has a master `Show team calendars`-switch and per-teammate checkboxes; Settings exposes the same display controls.-Display toggles affect this viewer's grid only. Team chips are prefixed with-the sharer's name and open read-only details. Copy-event links, guest-email-actions, RSVP, editing, and deletion are unavailable on team projections.-A directly accessible copy retains its own actions; another person's projection-of the same meeting may appear separately, with its sharing provenance.-Distinct authorized source copies may also appear separately for the same-teammate and meeting: their detail masking and availability contribution can differ.-Team projections and availability use server-confirmed copies. An offline queued-edit appears in the editor's own calendar, but reaches teammates only after the-server commits the provider-backed change and their shared projection refreshes.-An unavailable team fetch displays a warning and removes stale shared details.-Sharing-change notifications clear open shared details before refetching;-focus/reconnect and a 30-second refresh provide a fallback. Shared details also-disappear when an offline refresh is paused; they are not persisted for offline-use. While the app is running, team responses and in-flight requests expire-after 60 seconds, so a hung refresh cannot retain old details. Replacing a login-session clears team data and open shared details before the new identity loads.-Legacy out-of-office rows are read-only status displays and do not claim-that every absence blocks availability.+Private/confidential events only expose generic time blocks.++**Calendars that count as busy** reuses the sidebar's `Calendars` list: each+connected account is a folded row with a checkbox, color swatch, and disclosure+button that expands to its calendars. An account checkbox includes or excludes+all of its calendars at once. These choices decide which calendars represent the+user's personal schedule. Primary calendars count by default; other calendars+require explicit inclusion. Meetings the user attends also contribute, except+declined meetings. Following a coworker's calendar does not automatically make+that coworker's events occupy the user's time.++Teammates' shared events do not render on the grid; `Team out of office` is the+only teammate overlay. Replacing a login session clears team data and open+teammate details before the new identity loads. Legacy out-of-office rows are+read-only status displays and do not claim that every absence blocks availability.The `GetTeamAvailability` AI tool checks the requester together with the selectedteammates. It reports confirmed free windows only when every participant has@@ -454,8 +440,8 @@ touch devices — and is hidden when you are the only guest.With the `enable-calendar-team-ooo` flag on, teammates' Google Calendar out-of-office eventsoverlay the grid as read-only chips titled `<name>: <event title>`. The sidebar's`Team out of office` section (shown only when the user belongs to a team with other members)-has a checkbox in its header row toggling the whole overlay on or off — all teammates or-none — and lists the next 90 days of teammate absences; clicking a row navigates the grid to+is a collapsible list of the next 90 days of teammate absences, with no switch: the overlay+always shows; clicking a row navigates the grid tothat date. Coverage depends on each teammate having connected their own calendar and usingGoogle's out-of-office event type.