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(email): eliminate duplicate requests on thread load and mark-done (#4930)
Evan Hutnik7db675613516
diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsxindex 1aa63af383..8445f90d50 100644--- a/apps/web/src/features/block-email/component/EmailContext.tsx+++ b/apps/web/src/features/block-email/component/EmailContext.tsx@@ -29,6 +29,7 @@ import {blockSenderWithToast,markSenderNoiseWithToast,markSenderSignalWithToast,+ trackExternalThreadArchive,useArchiveThreadMutation,useThreadQuery,} from '@queries/email/thread';@@ -398,44 +399,62 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {if (!thread?.db_id) return false;- archiveMutation.mutate({- threadId: thread.db_id,- archive: thread.inbox_visible,- linkId: toHeaderLinkId(thread.link_id),- });-- if (!props) return false;+ // Unarchiving ('e' on an already-done thread) is a plain toggle back to+ // the inbox; the mark-done action doesn't apply.+ if (!thread.inbox_visible) {+ archiveMutation.mutate({+ threadId: thread.db_id,+ archive: false,+ linkId: toHeaderLinkId(thread.link_id),+ });+ return true;+ }+ // Mark done issues the /archived request itself (with undo support), so+ // the paths below skip archiveMutation and only mirror its thread-cache+ // handling via trackExternalThreadArchive.const selectedRow = soup?.items.get(thread.db_id);+ const cachedItem = selectedRow+ ? undefined+ : getSoupEntityById(thread.db_id);if (soup && selectedRow) {- markAsDoneAction.executeWithSoup(- [selectedRow.original],- soup,- (nextEntity) => {- const splitHandle = splitPanel?.handle;- if (!splitHandle || previewPanel !== undefined) return;- void openEntityInSplitFromUnifiedList(nextEntity, {- splitHandle,- mergeHistory: true,- referredFrom: splitHandle.referredFrom(),- });- },- markDoneOpts+ void trackExternalThreadArchive(+ thread.db_id,+ markAsDoneAction.executeWithSoup(+ [selectedRow.original],+ soup,+ (nextEntity) => {+ const splitHandle = splitPanel?.handle;+ if (!splitHandle || previewPanel !== undefined) return;+ void openEntityInSplitFromUnifiedList(nextEntity, {+ splitHandle,+ mergeHistory: true,+ referredFrom: splitHandle.referredFrom(),+ });+ },+ markDoneOpts+ ));- } else {+ } else if (cachedItem && cachedItem.tag !== 'channelThread') {// Not rendered inside a soup list (e.g. thread opened in a split): no// row to drive the action from, so mark done via the cached soup entity- // so soup views drop the thread and its notifications settle. The- // archive itself already ran above.- const cachedItem = getSoupEntityById(thread.db_id);- if (cachedItem && cachedItem.tag !== 'channelThread') {- void markAsDoneAction.execute(+ // so soup views drop the thread and its notifications settle.+ void trackExternalThreadArchive(+ thread.db_id,+ markAsDoneAction.execute([mapApiSoupItemToEntity(cachedItem)],undefined,markDoneOpts- );- }+ )+ );+ } else {+ // No soup entity to drive mark-done from: archive directly.+ archiveMutation.mutate({+ threadId: thread.db_id,+ archive: true,+ linkId: toHeaderLinkId(thread.link_id),+ });}return true;diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex f0d6b41c6c..e0b38f3b1f 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -1166,5 +1166,11 @@ export async function executeMarkEntitiesUndone(args: {queryKey: notificationKeys.user._def,refetchType: 'none',}),+ // Refetch open thread views so the unarchive restores `inbox_visible`.+ ...emailIds.map((id) =>+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(id).queryKey,+ })+ ),]);}diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex e6b0b38d1d..1e74fd90e6 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -47,7 +47,7 @@ type UseThreadQueryOptions = Omit</*** Shared infinite query options for thread fetching.*/-function threadQueryOptions(threadId: string) {+export function threadQueryOptions(threadId: string) {return {queryKey: emailKeys.threadMessages(threadId).queryKey,queryFn: async ({ pageParam }: { pageParam: number }) => {@@ -234,6 +234,38 @@ async function threadArchiveOnMutate(params: ArchiveThreadParams) {return { previousData };}+/**+ * Cache bookkeeping for an archive performed by another mutation (e.g. the+ * mark-done action, which issues its own /archived request): optimistically+ * flips `inbox_visible`, rolls back if the request fails, and invalidates the+ * thread + preview queries once it settles. Mirrors useArchiveThreadMutation+ * without firing a second request.+ */+export async function trackExternalThreadArchive(+ threadId: string,+ archived: Promise<unknown>+): Promise<void> {+ const { previousData } = await threadArchiveOnMutate({+ threadId,+ archive: true,+ });+ try {+ await archived;+ } catch {+ if (previousData) {+ queryClient.setQueryData(+ emailKeys.threadMessages(threadId).queryKey,+ previousData+ );+ }+ } finally {+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(threadId).queryKey,+ });+ queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });+ }+}+/*** Mutation to archive or unarchive a thread.* Uses optimistic updates to immediately reflect the change in UI.diff --git a/apps/web/src/lib/queries/preview/fetchers.ts b/apps/web/src/lib/queries/preview/fetchers.tsindex cceb44eaae..874359add8 100644--- a/apps/web/src/lib/queries/preview/fetchers.ts+++ b/apps/web/src/lib/queries/preview/fetchers.ts@@ -2,10 +2,15 @@ import { itemToSafeName } from '@core/constant/allBlocks';import { cognitionApiServiceClient } from '@service-cognition/client';import { emailClient } from '@service-email/client';+import type { ApiThread } from '@service-email/generated/schemas';import { storageServiceClient } from '@service-storage/client';import type { FileType } from '@service-storage/generated/schemas/fileType';import { formatDocumentName } from '@service-storage/util/filename';+import type { InfiniteData } from '@tanstack/solid-query';import { normalizeMessageSender } from '../channel/message-sender';+import { queryClient } from '../client';+import { emailKeys } from '../email/keys';+import { threadQueryOptions } from '../email/thread';import type { ItemEntity, MessageContext, PreviewItem } from './types';async function fetchChannelPreviews(@@ -278,30 +283,61 @@ async function fetchCrmCompanyPreviews();}+/**+ * Reuse the thread-messages query the email block fetches on open: returns+ * cached data (any staleness — previews tolerate 24h), or joins an in-flight+ * fetch, so the preview doesn't issue a separate getThread request.+ */+async function threadFromOpenThreadQuery(+ threadId: string+): Promise<ApiThread | undefined> {+ const queryKey = emailKeys.threadMessages(threadId).queryKey;+ const cached =+ queryClient.getQueryData<InfiniteData<ApiThread, number>>(queryKey);+ if (cached?.pages[0]) return cached.pages[0];++ if (queryClient.getQueryState(queryKey)?.fetchStatus !== 'fetching') {+ return undefined;+ }+ try {+ const data = await queryClient.fetchInfiniteQuery(+ threadQueryOptions(threadId)+ );+ return data.pages[0];+ } catch {+ // Fall through to the limit=1 fetch so access errors map per-id.+ return undefined;+ }+}+async function fetchEmailPreviews(threadIds: string[]): Promise<PreviewItem[]> {const results = await Promise.all(threadIds.map(async (threadId) => {- const result = await emailClient.getThread({- thread_id: threadId,- offset: 0,- limit: 1,- });-const base = {id: threadId,type: 'email',} as const;- if (result.isErr()) {- return {- ...base,- access: 'no_access' as const,- loading: false as const,- };+ let thread = await threadFromOpenThreadQuery(threadId);++ if (!thread) {+ const result = await emailClient.getThread({+ thread_id: threadId,+ offset: 0,+ limit: 1,+ });++ if (result.isErr()) {+ return {+ ...base,+ access: 'no_access' as const,+ loading: false as const,+ };+ }+ thread = result.value.thread;}- const data = result.value;- const firstMessage = data.thread.messages[0];+ const firstMessage = thread.messages[0];const subject = firstMessage?.subject ?? 'No Subject';const sender =firstMessage?.from?.email ?? firstMessage?.from?.name ?? undefined;@@ -313,7 +349,7 @@ async function fetchEmailPreviews(threadIds: string[]): Promise<PreviewItem[]> {rawName: subject,name: subject,owner: sender as string | undefined,- updatedAt: data.thread.updated_at,+ updatedAt: thread.updated_at,};}));diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.tsindex 348b6862f5..45acb51ad6 100644--- a/apps/web/src/lib/queries/properties/entity.ts+++ b/apps/web/src/lib/queries/properties/entity.ts@@ -43,15 +43,16 @@ export function useEntityPropertiesQuery(queryKey: propertiesKeys.entity({entityType: type,entityId: id,- includeMetadata,}).queryKey,queryFn: async () => {+ // Always fetch with metadata so consumers with different+ // `includeMetadata` values share one cache entry and one request.const data = await throwOnErr(async () =>await propertiesServiceClient.getEntityProperties({entity_type: type,entity_id: id,- query: { include_metadata: includeMetadata },+ query: { include_metadata: true },}));return data.properties.flatMap((property) => {@@ -63,6 +64,10 @@ export function useEntityPropertiesQuery(}});},+ select: (properties: Property[]) =>+ includeMetadata+ ? properties+ : properties.filter((property) => property.isMetadata !== true),staleTime: 0,};},diff --git a/apps/web/src/lib/queries/properties/keys.ts b/apps/web/src/lib/queries/properties/keys.tsindex e72f40a512..b4ade7382a 100644--- a/apps/web/src/lib/queries/properties/keys.ts+++ b/apps/web/src/lib/queries/properties/keys.ts@@ -5,15 +5,8 @@ import type { PropertyScope } from '../../service-clients/service-properties/genexport const propertiesKeys = createQueryKeys('properties', {all: null,tags: null,- entity: (params: {- entityType: EntityType;- entityId: string;- includeMetadata?: boolean;- }) => ({- queryKey:- params.includeMetadata !== undefined- ? ['entity', params.entityType, params.entityId, params.includeMetadata]- : ['entity', params.entityType, params.entityId],+ entity: (params: { entityType: EntityType; entityId: string }) => ({+ queryKey: ['entity', params.entityType, params.entityId],}),options: (params: { propertyDefinitionId: string }) => ({queryKey: ['options', params.propertyDefinitionId],