Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(core): replace history-based item lookups with preview API calls (#4048)

teoc8fb03b5a34d
diff --git a/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx b/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
index 9f598c38b5..c6bfb346ad 100644
--- a/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
+++ b/js/app/packages/core/component/AI/component/input/ChatAttachMenu.tsx
@@ -190,14 +190,7 @@ export function ChatAttachMenu(props: ChatAttachMenuProps) {
return;
}
- // TODO: add overrides to getDocumentAttachment if we already have the data
- // const attachment = getDocumentAttachment({
- // itemType: 'document',
- // itemId: item.id,
- // fileType: item.fileType ?? undefined,
- // documentName: item.name,
- // });
- const attachment = getDocumentAttachment(item.id);
+ const attachment = getDocumentAttachment(item.id, item.fileType);
if (attachment) {
props.onAttach(attachment);
diff --git a/js/app/packages/core/component/AI/signal/attachment.ts b/js/app/packages/core/component/AI/signal/attachment.ts
index fb107d6aa4..11be40c6cf 100644
--- a/js/app/packages/core/component/AI/signal/attachment.ts
+++ b/js/app/packages/core/component/AI/signal/attachment.ts
@@ -5,6 +5,10 @@ import { asFileType } from '@core/component/AI/util';
import type { ItemMention } from '@core/component/LexicalMarkdown/plugins/mentions';
import { ENABLE_CHAT_CHANNEL_ATTACHMENT } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
+import {
+ getCachedItemPreview,
+ isAccessiblePreviewItem,
+} from '@queries/preview';
import { createSignal } from 'solid-js';
export function useAttachments(initial?: Attachment[]): Attachments {
@@ -42,35 +46,43 @@ export const useChatAttachableHistory = () => {
};
export const useGetChatAttachmentInfo = () => {
- const history = useChatAttachableHistory();
const { channels } = useChannelsContext();
- const getDocumentAttachment = (id: string): Attachment | undefined => {
- const item = history().find((item) => item.id === id);
- if (!item) return;
- if (item.type !== 'document') return;
+ // fallback for callers that only have an id: the mentions menu and
+ // attachment pickers render previews, so the item is usually cached
+ const cachedDocumentFileType = (id: string): string | undefined => {
+ const preview = getCachedItemPreview(id);
+ if (!preview || !isAccessiblePreviewItem(preview)) return;
+ if (preview.type !== 'document') return;
+ return preview.fileType;
+ };
- const fileType = asFileType(item.fileType);
+ const getDocumentAttachment = (
+ id: string,
+ fileType?: string | null
+ ): Attachment | undefined => {
+ // mention nodes use '' when the block name has no file type mapping,
+ // so empty string falls back to the cache too
+ const knownFileType = fileType || cachedDocumentFileType(id);
+ const validFileType = asFileType(knownFileType);
- if (!fileType) {
- console.error('Invalid file type', item.fileType);
+ if (!validFileType) {
+ console.error('Invalid file type', knownFileType);
return;
- } else if (!SUPPORTED_ATTACHMENT_EXTENSIONS.includes(fileType)) {
- console.error('Invalid file type', item.fileType);
+ } else if (!SUPPORTED_ATTACHMENT_EXTENSIONS.includes(validFileType)) {
+ console.error('Invalid file type', knownFileType);
return;
}
return {
- entity_id: item.id,
+ entity_id: id,
entity_type: 'document',
};
};
const getProjectAttachment = (id: string): Attachment | undefined => {
- const item = history().find((item) => item.id === id);
- if (!item || item.type !== 'project') return;
return {
- entity_id: item.id,
+ entity_id: id,
entity_type: 'project',
};
};
@@ -100,7 +112,7 @@ export const useGetChatAttachmentInfo = () => {
mention: ItemMention
): Attachment | undefined => {
if (mention.itemType === 'document') {
- return getDocumentAttachment(mention.itemId);
+ return getDocumentAttachment(mention.itemId, mention.fileType);
} else if (mention.itemType === 'channel') {
return getChannelAttachment(mention);
} else if (mention.itemType === 'thread') {
diff --git a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
index a2946ba4e5..2d52d3170a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/citationsUtils.ts
@@ -3,17 +3,33 @@ import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/signal/location';
import { itemToBlockName } from '@core/constant/allBlocks';
import { useChannelsContext } from '@core/context/channels';
-import { getHistoryItems } from '@queries/history/history';
+import {
+ type AccessiblePreviewItem,
+ getItemPreview,
+ isAccessiblePreviewItem,
+} from '@queries/preview';
import { cognitionApiServiceClient } from '@service-cognition/client';
+import type { ItemType } from '@service-storage/client';
import { validate as uuidValidate } from 'uuid';
export const jsonToXML = (tag: string, data: object) => {
return `<${tag}>${JSON.stringify(data)}</${tag}>`;
};
-const createDocumentMentionXML = (documentId: string) => {
- const history = getHistoryItems();
- const item = history.find((item) => item.id === documentId);
+const fetchMentionPreview = async (
+ id: string,
+ type: Exclude<ItemType, 'channel'>
+): Promise<AccessiblePreviewItem | undefined> => {
+ try {
+ const preview = await getItemPreview({ id, type });
+ return isAccessiblePreviewItem(preview) ? preview : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const createDocumentMentionXML = async (documentId: string) => {
+ const item = await fetchMentionPreview(documentId, 'document');
if (!item) {
if (import.meta.env.DEV) {
console.error('Could not find item', documentId);
@@ -34,9 +50,8 @@ const createDocumentMentionXML = (documentId: string) => {
});
};
-const createChatMentionXML = (chatId: string) => {
- const chats = getHistoryItems();
- const chat = chats.find((c) => c.id === chatId);
+const createChatMentionXML = async (chatId: string) => {
+ const chat = await fetchMentionPreview(chatId, 'chat');
if (!chat) {
if (import.meta.env.DEV) {
console.error('Could not find chat', chatId);
@@ -78,9 +93,8 @@ const createChannelMentionXML = (channelId: string) => {
});
};
-const createProjectMentionXML = (projectId: string) => {
- const projects = getHistoryItems();
- const project = projects.find((p) => p.id === projectId);
+const createProjectMentionXML = async (projectId: string) => {
+ const project = await fetchMentionPreview(projectId, 'project');
if (!project) {
if (import.meta.env.DEV) {
console.error('Could not find project', projectId);
@@ -148,12 +162,11 @@ const getPdfCitationInfo = async (citationId: string) => {
return '';
};
-const getMdNodeCitationInfo = (documentId: string, nodeId: string) => {
+const getMdNodeCitationInfo = async (documentId: string, nodeId: string) => {
const blockParams = {
[MD_URL_PARAMS.nodeId]: nodeId,
};
- const history = getHistoryItems();
- const item = history.find((item) => item.id === documentId);
+ const item = await fetchMentionPreview(documentId, 'document');
const blockName = item ? (itemToBlockName(item) ?? 'md') : 'md';
return jsonToXML('m-document-mention', {
documentId,
@@ -230,12 +243,16 @@ const splitMdCitation = (
export const replaceCitations = async (input: string): Promise<string> => {
const citationRegex = /\[\[(.*?)\]\]/g;
- const pdfCitations = new Set<string>();
const citationCache = new Map<string, string>();
+ // async lookups, started concurrently so the preview dataloader can batch them
+ const pendingCitations = new Map<string, Promise<string>>();
const matches = [...input.matchAll(citationRegex)];
for (const match of matches) {
const citation = match[1];
+ if (citationCache.has(citation) || pendingCitations.has(citation)) {
+ continue;
+ }
if (isMdCitation(citation)) {
const splitCitation = splitMdCitation(citation);
if (!splitCitation) {
@@ -255,26 +272,22 @@ export const replaceCitations = async (input: string): Promise<string> => {
continue;
}
- const xml = getMdNodeCitationInfo(documentId, nodeId);
- citationCache.set(citation, xml);
+ pendingCitations.set(citation, getMdNodeCitationInfo(documentId, nodeId));
} else if (isDocumentMention(citation)) {
const [, itemId] = citation.split(';', 2);
- const xml = createDocumentMentionXML(itemId);
- citationCache.set(citation, xml);
+ pendingCitations.set(citation, createDocumentMentionXML(itemId));
} else if (isChannelMention(citation)) {
const [, channelId] = citation.split(';', 2);
const xml = createChannelMentionXML(channelId);
citationCache.set(citation, xml);
} else if (isChatMention(citation)) {
const [, chatId] = citation.split(';', 2);
- const xml = createChatMentionXML(chatId);
- citationCache.set(citation, xml);
+ pendingCitations.set(citation, createChatMentionXML(chatId));
} else if (isProjectMention(citation)) {
const [, projectId] = citation.split(';', 2);
- const xml = createProjectMentionXML(projectId);
- citationCache.set(citation, xml);
+ pendingCitations.set(citation, createProjectMentionXML(projectId));
} else if (isPdfCitation(citation)) {
- pdfCitations.add(citation);
+ pendingCitations.set(citation, getPdfCitationInfo(citation));
} else {
if (import.meta.env.DEV) {
console.error('Invalid citation', citation);
@@ -284,8 +297,8 @@ export const replaceCitations = async (input: string): Promise<string> => {
}
await Promise.all(
- [...pdfCitations].map(async (citationId) => {
- citationCache.set(citationId, await getPdfCitationInfo(citationId));
+ [...pendingCitations].map(async ([citation, xml]) => {
+ citationCache.set(citation, await xml);
})
);
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
index 8a055c4909..b20ad9a499 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
@@ -159,6 +159,10 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {
if (blockName === 'pdf') fileType = 'pdf';
else if (blockName === 'write') fileType = 'docx';
else if (blockName === 'md') fileType = 'md';
+ // task/snippet aliases are markdown documents
+ else if (blockName === 'task') fileType = 'md';
+ else if (blockName === 'snippet') fileType = 'md';
+ else if (blockName === 'csv') fileType = 'csv';
else if (blockName === 'canvas') fileType = 'canvas';
else if (blockName === 'code') {
const blockParams = node.getBlockParams();
diff --git a/js/app/packages/core/util/currentBlockDocumentName.ts b/js/app/packages/core/util/currentBlockDocumentName.ts
index 335ff26cb0..9d3e3248ac 100644
--- a/js/app/packages/core/util/currentBlockDocumentName.ts
+++ b/js/app/packages/core/util/currentBlockDocumentName.ts
@@ -6,7 +6,8 @@ import {
} from '@core/block';
import { blockNameToDefaultFile } from '@core/constant/allBlocks';
import { blockMetadataSignal } from '@core/signal/load';
-import { useHistoryItemRawName } from '@queries/history/history';
+import { useItemRawName } from '@queries/preview';
+import { blockNameToItemType } from '@service-storage/client';
import { formatDocumentName } from '@service-storage/util/filename';
export const useBlockDocumentName = (defaultName?: string) => {
@@ -19,7 +20,10 @@ export const useBlockDocumentName = (defaultName?: string) => {
const blockName = useBlockAliasedName();
const isFileBlock = !NonDocumentBlockTypes.includes(blockName);
- const updatedName = useHistoryItemRawName(blockId);
+ const updatedName = useItemRawName(() => ({
+ id: blockId,
+ type: blockNameToItemType(blockName),
+ }));
return () => {
const current = updatedName();
diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.ts
index a0b75490c9..a272b9856f 100644
--- a/js/app/packages/queries/history/history.ts
+++ b/js/app/packages/queries/history/history.ts
@@ -195,20 +195,6 @@ export async function removeHistoryItem(
return maybeRemoved.isOk() && !!maybeRemoved.value.success;
}
-/** Hook to get the updated raw name (no transform) of a HistoryItem */
-export function useHistoryItemRawName(itemId: string) {
- const historyQuery = useHistoryQuery();
-
- return () => {
- if (historyQuery.isLoading) return undefined;
- const history = historyQuery.data;
- if (!history) return undefined;
-
- const item = history.find((item) => item.id === itemId);
- return item?.rawName;
- };
-}
-
/**
* Get history items from cache.
* For use in standalone functions outside component context.
diff --git a/js/app/packages/queries/preview/index.ts b/js/app/packages/queries/preview/index.ts
index 22c69e550c..46f74326db 100644
--- a/js/app/packages/queries/preview/index.ts
+++ b/js/app/packages/queries/preview/index.ts
@@ -5,6 +5,7 @@ export {
setPreviewFileType,
setPreviewName,
useItemPreview,
+ useItemRawName,
} from './preview';
export type {
AccessiblePreviewItem,
diff --git a/js/app/packages/queries/preview/preview.ts b/js/app/packages/queries/preview/preview.ts
index 55e2e188fc..c164f34993 100644
--- a/js/app/packages/queries/preview/preview.ts
+++ b/js/app/packages/queries/preview/preview.ts
@@ -8,7 +8,12 @@ import { queryClient } from '../client';
import { previewDataLoader } from './dataloader';
import { defaultNameTransform, fetchMessageContext } from './fetchers';
import { previewKeys } from './keys';
-import type { AccessiblePreviewItem, ItemEntity, PreviewItem } from './types';
+import {
+ type AccessiblePreviewItem,
+ type ItemEntity,
+ isAccessiblePreviewItem,
+ type PreviewItem,
+} from './types';
// DEBUG VARS
const SIMULATE_BACKEND_DELAY_MS = 0;
@@ -93,6 +98,37 @@ export function useItemPreview(item: Accessor<ItemEntity>) {
return [preview] as const;
}
+/** Stale time for live display names (e.g. open-document titles), which
+ * should pick up external renames on remount rather than waiting out the
+ * 24h preview default. */
+const RAW_NAME_STALE_TIME = 5 * 60 * 1000;
+
+/**
+ * Subscribe to an item's raw (untransformed) display name.
+ * Returns undefined while loading or when the item is inaccessible, so
+ * callers can fall through to their own defaults. Optimistic rename and
+ * file-type mutations write to this cache via `setPreviewName` /
+ * `setPreviewFileType`.
+ */
+export function useItemRawName(
+ item: Accessor<{ id: string; type?: ItemType }>
+): Accessor<string | undefined> {
+ const query = useQuery(() => {
+ const { id, type } = item();
+ const entity: ItemEntity = type === 'channel' ? { id, type } : { id, type };
+ return {
+ ...itemPreviewQueryOptions(entity),
+ staleTime: RAW_NAME_STALE_TIME,
+ };
+ });
+
+ return () => {
+ const data = queryReadyGate(query) ? query.data : undefined;
+ if (!data || !isAccessiblePreviewItem(data)) return undefined;
+ return data.rawName;
+ };
+}
+
/** Invalidate preview for the given item id. if no id is provided, invalidates all previews */
export function invalidatePreview(itemId?: string) {
if (!itemId)
@@ -139,14 +175,17 @@ export function setPreviewName({
itemType?: ItemType;
}) {
const prev = getPreviewData(itemId);
- if (prev)
+ // only merge into accessible entries: a cached no_access/does_not_exist
+ // (e.g. a fetch that raced backend propagation of a new item) would
+ // otherwise swallow the optimistic name, so fall through and overwrite
+ if (prev && isAccessiblePreviewItem(prev))
return setPreviewData(itemId, (prev) => ({
...prev,
rawName: name,
name,
}));
- if (!itemType) {
+ if (!itemType && !prev) {
console.warn('no preview item type provided for cache miss, using default');
}
@@ -156,16 +195,18 @@ export function setPreviewName({
name,
loading: false,
access: 'access',
- type: itemType ?? DEFAULT_ITEM_TYPE,
+ type: itemType ?? prev?.type ?? DEFAULT_ITEM_TYPE,
};
// if the item isn't in the cache, we can optimistically create a new item
const res = setPreviewData(itemId, (_prev) => defaultPreviewItem);
- // invalidate the item so that we can refetch on next render
- // note that we cannot directly call the fetch here because the item name is not necessarily updated on the backend
+ // mark stale for the next natural refetch (mount/focus) without refetching
+ // active observers now: the backend may not have processed the rename yet,
+ // so an immediate refetch could clobber the optimistic name with the old one
queryClient.invalidateQueries({
queryKey: previewKeys.item(itemId).queryKey,
+ refetchType: 'none',
});
return res;
@@ -177,7 +218,11 @@ export function setPreviewName({
* before the backend has fully propagated the new item.
*
* Call this immediately after creating an item to ensure the preview cache
- * has valid data before any components try to fetch it.
+ * has valid data before any components try to fetch it. The seed is stored
+ * as fresh data: it carries exactly what was sent to the backend
+ * (name/fileType/subType), so there is nothing to refetch, and an immediate
+ * revalidation could race propagation and clobber the seed with
+ * 'does_not_exist'. Server truth reconciles through normal staleness.
*
* @param itemId - The unique identifier of the newly created item
* @param itemType - The type of item ('document', 'chat', 'project', etc.)
@@ -232,14 +277,5 @@ export function setPreviewOnCreate({
updatedAt: new Date().toISOString(),
};
- // Optimistically set the preview data
setPreviewData(itemId, (_prev) => defaultPreviewItem);
-
- // Schedule a background refetch to get the real data from the server
- // Use a small delay to give the backend time to propagate
- setTimeout(() => {
- queryClient.invalidateQueries({
- queryKey: previewKeys.item(itemId).queryKey,
- });
- }, 100);
}