Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(web): stop cached queries from keeping closed views in memory (#9020)
Peter Chinmane90c5651f32c
diff --git a/apps/web/src/features/block-form/queries/booking-sources.ts b/apps/web/src/features/block-form/queries/booking-sources.tsindex 4638290dd2..81155c84b1 100644--- a/apps/web/src/features/block-form/queries/booking-sources.ts+++ b/apps/web/src/features/block-form/queries/booking-sources.ts@@ -4,7 +4,7 @@ import { schedulingKeys } from '@app/features/scheduling/queries/keys';import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';import { useCurrentTeamQuery } from '@queries/team/teams';import { schedulingClient } from '@service-email/scheduling';-import { useQuery } from '@tanstack/solid-query';+import { queryOptions, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import type {FormBookingEvent,@@ -29,6 +29,31 @@ function bookingLinksOf(}));}+// Cached callbacks stay at module scope so they never retain the form.+function bookingSettingsQueryOptions(+ scopeId: string,+ teamId: string | undefined,+ enabled: boolean+) {+ return queryOptions({+ queryKey: schedulingKeys.settings(scopeId).queryKey,+ queryFn: async () =>+ (await throwOnErr(() => schedulingClient.settings(teamId))).profile,+ enabled,+ retry: false,+ });+}++function publicProfileQueryOptions(profileId: string, enabled: boolean) {+ return queryOptions({+ queryKey: schedulingKeys.publicProfile(profileId).queryKey,+ queryFn: async () =>+ (await throwOnErr(() => schedulingClient.profile(profileId))).profile,+ enabled,+ retry: false,+ });+}+/*** The viewer's booking links: their own, then their team's. Read through* the Calendar settings' own cache entries, so a link created there shows@@ -38,22 +63,22 @@ export function createBookingLinksSource(userId: Accessor<string | undefined>,enabled: Accessor<boolean>): ReadSource<FormBookingLink[]> {- const personal = useQuery(() => ({- queryKey: schedulingKeys.settings(userId() ?? 'me').queryKey,- queryFn: async () =>- (await throwOnErr(() => schedulingClient.settings())).profile,- enabled: enabled() && !!userId(),- retry: false,- }));+ const personal = useQuery(() =>+ bookingSettingsQueryOptions(+ userId() ?? 'me',+ undefined,+ enabled() && !!userId()+ )+ );const team = useCurrentTeamQuery(enabled);const teamId = () => (team.isSuccess ? team.data?.team.id : undefined);- const teamProfile = useQuery(() => ({- queryKey: schedulingKeys.settings(teamId() ?? '').queryKey,- queryFn: async () =>- (await throwOnErr(() => schedulingClient.settings(teamId()))).profile,- enabled: enabled() && !!teamId(),- retry: false,- }));+ const teamProfile = useQuery(() =>+ bookingSettingsQueryOptions(+ teamId() ?? '',+ teamId(),+ enabled() && !!teamId()+ )+ );return {value: () => {if (!personal.isSuccess) return undefined;@@ -79,16 +104,9 @@ export function createBookingLinksSource(export function createBookingEventSource(target: Accessor<FormBookingTarget | undefined>): ReadSource<FormBookingEvent | null> {- const profile = useQuery(() => ({- queryKey: schedulingKeys.publicProfile(target()?.profileId ?? '').queryKey,- queryFn: async () => {- const profileId = target()?.profileId ?? '';- return (await throwOnErr(() => schedulingClient.profile(profileId)))- .profile;- },- enabled: !!target(),- retry: false,- }));+ const profile = useQuery(() =>+ publicProfileQueryOptions(target()?.profileId ?? '', !!target())+ );return {value: () => {const current = target();diff --git a/apps/web/src/features/email-thread/queries/thread-operations.ts b/apps/web/src/features/email-thread/queries/thread-operations.tsindex c5252c0df3..777c4395b2 100644--- a/apps/web/src/features/email-thread/queries/thread-operations.ts+++ b/apps/web/src/features/email-thread/queries/thread-operations.ts@@ -2,33 +2,47 @@ import { throwOnErr } from '@core/util/result';import { refreshEmailThreadCache } from '@queries/email/cache-cleanup';import { emailKeys } from '@queries/email/keys';import { emailClient } from '@service-email/client';-import { useQuery } from '@tanstack/solid-query';+import type { MailboxOperation } from '@service-email/generated/schemas';+import {+ type QueryFunctionContext,+ queryOptions,+ useQuery,+} from '@tanstack/solid-query';import type { Accessor } from 'solid-js';-export function useThreadOperations(- threadId: Accessor<string>,- enabled: Accessor<boolean>-) {- let previous: { thread: string; pending: boolean } | undefined;- const query = useQuery(() => ({- queryKey: emailKeys.threadOperations(threadId()).queryKey,- enabled: enabled(),+function hasPending(operations: readonly MailboxOperation[] | undefined) {+ return (+ operations?.some((operation) => operation.state === 'pending') ?? false+ );+}++// Cached callbacks outlive the thread view, so they close over the plain thread+// ID only; the previous result comes from the cache, not hook state.+function threadOperationsQueryOptions(threadId: string, enabled: boolean) {+ const { queryKey } = emailKeys.threadOperations(threadId);+ return queryOptions({+ queryKey,+ enabled,retry: false,- queryFn: async () => {- const thread = threadId();- const operations = await throwOnErr(() =>- emailClient.threadOperations(thread)+ queryFn: async ({ client }: QueryFunctionContext) => {+ const wasPending = hasPending(+ client.getQueryData<MailboxOperation[]>(queryKey));- const pending = operations.some(- (operation) => operation.state === 'pending'+ const operations = await throwOnErr(() =>+ emailClient.threadOperations(threadId));- if (previous?.thread === thread && previous.pending && !pending)- void refreshEmailThreadCache(thread).catch(() => {});- previous = { thread, pending };+ if (wasPending && !hasPending(operations))+ void refreshEmailThreadCache(threadId).catch(() => {});return operations;},// Keep an open thread current after actions from another window or client.refetchInterval: 5000,- }));- return query;+ });+}++export function useThreadOperations(+ threadId: Accessor<string>,+ enabled: Accessor<boolean>+) {+ return useQuery(() => threadOperationsQueryOptions(threadId(), enabled()));}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useBookingLinkMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useBookingLinkMention.tsindex 40aaa37e2f..5b011ac4ce 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useBookingLinkMention.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useBookingLinkMention.ts@@ -7,7 +7,7 @@ import { throwOnErr } from '@core/util/result';import { useCurrentTeamQuery } from '@queries/team/teams';import { schedulingClient } from '@service-email/scheduling';import { createLazyMemo } from '@solid-primitives/memo';-import { useQuery } from '@tanstack/solid-query';+import { queryOptions, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import type { BookingLinkMentionItem } from '../../../../utils/mentionsUtils';@@ -27,32 +27,42 @@ function profileBookingLinks(.map((event) => ({ event, owner, profileId: profile.id }));}+// Cached callbacks stay at module scope so they never retain the composer.+function bookingSettingsQueryOptions(+ scopeId: string,+ teamId: string | undefined,+ enabled: boolean+) {+ return queryOptions({+ queryKey: schedulingKeys.settings(scopeId).queryKey,+ queryFn: async () =>+ (await throwOnErr(() => schedulingClient.settings(teamId))).profile,+ enabled,+ retry: false,+ staleTime: 30_000,+ });+}+export function useBookingLinkMention(options: UseBookingLinkMentionOptions) {const { enabled, searchTerm } = options;const shouldFetch = () => enabled() && searchTerm().trim() === '';- const personal = useQuery(() => ({- queryKey: schedulingKeys.settings('me').queryKey,- queryFn: async () =>- (await throwOnErr(() => schedulingClient.settings())).profile,- enabled: shouldFetch(),- retry: false,- staleTime: 30_000,- }));+ const personal = useQuery(() =>+ bookingSettingsQueryOptions('me', undefined, shouldFetch())+ );const team = useCurrentTeamQuery(shouldFetch);const teamId = () => (team.isSuccess ? team.data?.team.id : undefined);const teamName = () => (team.isSuccess ? team.data?.team.name : undefined);- const teamProfile = useQuery(() => ({- queryKey: schedulingKeys.settings(teamId() ?? '').queryKey,- queryFn: async () =>- (await throwOnErr(() => schedulingClient.settings(teamId()))).profile,- enabled: shouldFetch() && !!teamId(),- retry: false,- staleTime: 30_000,- }));+ const teamProfile = useQuery(() =>+ bookingSettingsQueryOptions(+ teamId() ?? '',+ teamId(),+ shouldFetch() && !!teamId()+ )+ );const bookingLinks = createLazyMemo((): BookingLinkMentionItem[] => {if (!shouldFetch()) return [];diff --git a/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx b/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsxindex d2f0b8e2a7..fd68118a16 100644--- a/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx+++ b/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx@@ -151,7 +151,10 @@ const FullCalendarContext = createContext<FullCalendarController>();*/export function FullCalendarRoot(props: FullCalendarRootProps) {const [local, options] = splitProps(props, ['children']);- const controller = createFullCalendarController(() => ({ ...options }));+ const controller = createFullCalendarController(+ () => ({ ...options }),+ () => options.datesSet+ );onCleanup(() => controller.destroy());@@ -260,7 +263,8 @@ function useFullCalendarController(): FullCalendarController {}function createFullCalendarController(- getOptions: Accessor<FullCalendarOptions>+ getOptions: Accessor<FullCalendarOptions>,+ getDatesSet: Accessor<FullCalendarOptions['datesSet']>): FullCalendarController {const [calendar, setCalendar] = createSignal<Calendar>();const [dateInfo, setDateInfo] = createSignal<DatesSetArg>();@@ -274,9 +278,11 @@ function createFullCalendarController(const [listenForContentRegistrationChange, notifyContentRegistrationChange] =createSignal<void>(undefined, { equals: false });let appliedOptions: CalendarOptions | undefined;+ // FullCalendar calls this outside any Solid owner. Reading every option+ // here would evaluate prop getters into memos that are never disposed.const handleDatesSet = (info: DatesSetArg) => {setDateInfo(info);- untrack(getOptions).datesSet?.(info);+ untrack(getDatesSet)?.(info);};// Metadata identities must stay stable across event-only updates. Rebuilding// them causes FullCalendar to remount unrelated headers and content slots.diff --git a/apps/web/src/lib/queries/preview/preview.ts b/apps/web/src/lib/queries/preview/preview.tsindex b4a8adb325..1df388ad6b 100644--- a/apps/web/src/lib/queries/preview/preview.ts+++ b/apps/web/src/lib/queries/preview/preview.ts@@ -48,11 +48,19 @@ const PREVIEW_STALE_TIME = 60 * 1000 * 60 * 24; // 24 hours* stale on the mention-preview cadence rather than the 24h default. */const CALENDAR_EVENT_PREVIEW_STALE_TIME = 60 * 1000;+// Callers may pass component props; the cached queryFn keeps only a plain copy.+function itemRequest(entity: ItemEntity): ItemEntity {+ return entity.type === 'channel'+ ? { id: entity.id, type: 'channel', messageId: entity.messageId }+ : { id: entity.id, type: entity.type };+}+function itemPreviewQueryOptions(- item: ItemEntity,+ entity: ItemEntity,enabled = true,staleTime = PREVIEW_STALE_TIME) {+ const item = itemRequest(entity);if (item.type === 'agent_session') staleTime = Math.min(staleTime, 30_000);if (item.type === 'calendar_event') {staleTime = Math.min(staleTime, CALENDAR_EVENT_PREVIEW_STALE_TIME);diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-done.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-done.tsindex 4abf8e67a3..b8b6eecf3f 100644--- a/apps/web/src/lib/queries/soup/graphql/optimistic-done.ts+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-done.ts@@ -53,6 +53,10 @@ function currentViewerId(): string | undefined {);}+function createDoneSessionId(): string {+ return crypto.randomUUID();+}+/** Immediate display state, independent of durable enqueue and list recomputation. */export function hideGraphqlSoupEntitiesAsDone(args: {entityIds: readonly string[];@@ -262,13 +266,16 @@ export function hideGraphqlSoupEntitiesAsDone(args: {export function usePendingGraphqlSoupDone(): Accessor<readonly PendingGraphqlSoupDone[]> {+ // These queries live for the whole session and keep the options of their+ // last observer, so their callbacks stay at module scope: an inline one would+ // retain this hook's scope, and with it the closed view that called it.const viewer = useQuery(() => ({queryKey: authKeys.userInfo.queryKey,// Observe only. Unlike the private intent keys below, this key already// has an auth fetcher: skipToken would overwrite it during invalidation.enabled: false,- select: (info: DoneIntentViewer) => viewerIdFromInfo(info),+ select: viewerIdFromInfo,}),() => queryClient);@@ -279,7 +286,7 @@ export function usePendingGraphqlSoupDone(): Accessor<() => ({queryKey: graphqlSoupKeys.doneSession.queryKey,queryFn: skipToken,- initialData: () => crypto.randomUUID(),+ initialData: createDoneSessionId,gcTime: Infinity,}),() => queryClient