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(soup/queries) normalization and generic updates, inserts and removes (#1450)

teod4d53c6aa101
diff --git a/js/app/bun.lock b/js/app/bun.lock
index 24a2677495..286aa0b5fd 100644
--- a/js/app/bun.lock
+++ b/js/app/bun.lock
@@ -36,6 +36,7 @@
"@lexical/table": "^0.32.1",
"@lexical/utils": "^0.32.1",
"@lukemorales/query-key-factory": "^1.3.4",
+ "@normy/query-core": "^0.21.0",
"@panzoom/panzoom": "^4.6.0",
"@phosphor-icons/core": "^2.1.1",
"@solid-primitives/audio": "^1.4.2",
@@ -845,6 +846,10 @@
"@nodelib/fs.walk": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
+ "@normy/core": ["@normy/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.23.5", "deepmerge": "4.3.1" } }, "sha512-3I0S62BNEIlvSL10TutHsLvTxguRoXEjs6b/udSUnxlKFVgrAIdW4F4tJDiZsJQrWRi6A6V3Eo5Dzji3zyn40Q=="],
+
+ "@normy/query-core": ["@normy/[email protected]", "", { "dependencies": { "@normy/core": "0.14.0" }, "peerDependencies": { "@tanstack/query-core": ">=5.4.3" } }, "sha512-O1GM0wqXIHHiWremrbvGG3ZuDxPsg+k9DDin+7sjkK/jHT2ER2MVodoMG40sB3I+zCKCdGVDi+/nZlb36m/mmA=="],
+
"@nothing-but/utils": ["@nothing-but/[email protected]", "", {}, "sha512-TuCHcHLOqDL0SnaAxACfuRHBNRgNJcNn9X0GiH5H3YSDBVquCr3qEIG3FOQAuMyZCbu9w8nk2CHhOsn7IvhIwQ=="],
"@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
diff --git a/js/app/package.json b/js/app/package.json
index b771be431b..1a591e2733 100644
--- a/js/app/package.json
+++ b/js/app/package.json
@@ -52,6 +52,7 @@
"@lexical/table": "^0.32.1",
"@lexical/utils": "^0.32.1",
"@lukemorales/query-key-factory": "^1.3.4",
+ "@normy/query-core": "^0.21.0",
"@panzoom/panzoom": "^4.6.0",
"@phosphor-icons/core": "^2.1.1",
"@solid-primitives/audio": "^1.4.2",
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index e1f6c0b73a..321bececea 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -21,7 +21,12 @@ import {
PROPERTY_OPTION_IDS,
SYSTEM_PROPERTY_IDS,
} from '@core/component/Properties/constants';
-import { soupKeys } from '@queries/soup/keys';
+import {
+ removeSoupEntities,
+ getSoupEntityById,
+ optimisticUpdateSoupEntity,
+ invalidateSoupEntity,
+} from '@queries/soup/cache';
import { match } from 'ts-pattern';
const mergeSearchEntities = <T extends EntityData>(
@@ -369,24 +374,26 @@ export async function archiveEmail(
id: string,
options: { isDone: boolean; optimisticallyExclude?: boolean }
) {
- await Promise.all([
- queryClient.cancelQueries({ queryKey: queryKeys.all.email }),
- queryClient.cancelQueries({ queryKey: soupKeys.items._def }),
- ]);
+ await queryClient.cancelQueries({ queryKey: queryKeys.all.email });
const previousEmail = queryClient.getQueriesData<{
pages: { items: EntityData[] }[];
}>({
queryKey: queryKeys.all.email,
});
- const previousEmailThreadItemFromDss = queryClient.getQueriesData<{
- pages: { items: EntityData[] }[];
- }>({
- queryKey: soupKeys.items._def,
- });
- const applyOptimistic = (data?: {
- pages: { items: (EntityData | { data: EntityData })[] }[];
+ const current = getSoupEntityById(id);
+ const soupTxn = options.optimisticallyExclude
+ ? removeSoupEntities(new Set([id]))
+ : optimisticUpdateSoupEntity({
+ tag: 'emailThread',
+ data: { id, inboxVisible: false },
+ frecency_score: current?.frecency_score ?? 0,
+ });
+
+ // Optimistic update for email queries
+ const applyEmailOptimistic = (data?: {
+ pages: { items: EntityData[] }[];
}) => {
if (!data) return data;
@@ -395,58 +402,29 @@ export async function archiveEmail(
pages: data.pages.map((page) => ({
...page,
items: options.optimisticallyExclude
- ? page.items.filter((item) => {
- if ('data' in item) {
- return item.data.id !== id;
- }
- return item.id !== id;
- })
- : page.items.map((item) => {
- if ('data' in item) {
- return item.data.id === id
- ? {
- ...item,
- data: {
- ...item.data,
- inboxVisible: false,
- },
- }
- : item;
- }
- return item.id === id
- ? {
- ...item,
- inboxVisible: false,
- }
- : item;
- }),
+ ? page.items.filter((item) => item.id !== id)
+ : page.items.map((item) =>
+ item.id === id ? { ...item, inboxVisible: false } : item
+ ),
})),
};
};
- for (const [key, data] of [
- ...previousEmailThreadItemFromDss,
- ...previousEmail,
- ]) {
- queryClient.setQueryData(key, applyOptimistic(data));
+ for (const [key, data] of previousEmail) {
+ queryClient.setQueryData(key, applyEmailOptimistic(data));
}
try {
- // server mutation
await emailClient.flagArchived({ value: !options.isDone, id });
} catch (_err) {
- // rollback on error
+ soupTxn.rollback();
for (const [key, data] of previousEmail) {
queryClient.setQueryData(key, data);
}
- for (const [key, data] of previousEmailThreadItemFromDss) {
- queryClient.setQueryData(key, data);
- }
} finally {
- // revalidate
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.all.email }),
- queryClient.invalidateQueries({ queryKey: soupKeys.items._def }),
+ invalidateSoupEntity(id),
]);
}
}
diff --git a/js/app/packages/app/util/handleFileUpload.ts b/js/app/packages/app/util/handleFileUpload.ts
index ed91dd948c..f9f882eadb 100644
--- a/js/app/packages/app/util/handleFileUpload.ts
+++ b/js/app/packages/app/util/handleFileUpload.ts
@@ -1,8 +1,7 @@
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { type UploadInput, uploadFiles } from '@core/util/upload';
-import { useQueryClient as useEntityQueryClient } from '@macro-entity';
import { useSplitLayout } from '../component/split-layout/layout';
-import { soupKeys } from '@queries/soup/keys';
+import { refetchSoupEntity } from '@queries/soup/cache';
export function useHandleFileUpload({
projectId,
@@ -10,7 +9,6 @@ export function useHandleFileUpload({
projectId?: string;
} = {}) {
const { replaceOrInsertSplit } = useSplitLayout();
- const entityQueryClient = useEntityQueryClient();
return async (files: UploadInput[]) => {
const results = await uploadFiles(files, 'dss', {
@@ -28,16 +26,13 @@ export function useHandleFileUpload({
.filter((result) => result.pending)
.filter((result) => result.type === 'folder');
- // update soup list folders once all pending uploads are done
+ // refetch soup for folders once all pending uploads are done
Promise.allSettled(pendingUploads.map((upload) => upload.projectId)).then(
(results) => {
- const uploaded = results.filter(
- (result) => result.status === 'fulfilled' && result.value
- );
- if (uploaded.length > 0) {
- entityQueryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ for (const result of results) {
+ if (result.status === 'fulfilled' && result.value) {
+ refetchSoupEntity(result.value, 'project');
+ }
}
}
);
@@ -47,13 +42,10 @@ export function useHandleFileUpload({
return;
}
- // this refreshes the uploaded data into the soup list
- entityQueryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
-
const upload = successfulUploads[0];
+ // refetch the uploaded document into soup
if (upload.type === 'document') {
+ refetchSoupEntity(upload.documentId, 'document');
replaceOrInsertSplit(
{
type: fileTypeToBlockName(upload.fileType),
diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsx
index a39ac137dd..f514205a06 100644
--- a/js/app/packages/block-email/component/Compose.tsx
+++ b/js/app/packages/block-email/component/Compose.tsx
@@ -67,8 +67,7 @@ import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';
import { useMaybeEmailContext } from '@block-email/component/EmailContext';
import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';
import { stickyGate } from '@core/util/debounce';
-import { queryClient } from '@queries/client';
-import { soupKeys } from '@queries/soup/keys';
+import { invalidateSoupEntity } from '@queries/soup/cache';
const DRAFT_DEBOUNCE_MS = 1000;
@@ -573,11 +572,9 @@ export function EmailCompose(props: EmailComposeProps) {
};
const unscheduleMessageMutation = useUnscheduleMessageMutation({
- onSuccess: () => {
+ onSuccess: (_data, vars) => {
toast.success('Email unscheduled');
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ invalidateSoupEntity(vars.draftID);
},
onError: () => {
toast.failure('Failed to unschedule email');
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index 6f0f1392f6..c8a393dc30 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -13,8 +13,7 @@ import { VideoPreview } from '@core/component/VideoPreview';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
import { tryMacroId, useDisplayName } from '@core/user';
import { isErr } from '@core/util/maybeResult';
-import { useQueryClient } from '@queries/client';
-import { soupKeys } from '@queries/soup/keys';
+import { refetchSoupEntity } from '@queries/soup/cache';
import { logger } from '@observability';
import { emailClient } from '@service-email/client';
import type {
@@ -136,7 +135,6 @@ export function MessageContainer(props: MessageContainerProps) {
});
const { openWithSplit } = useSplitLayout();
- const queryClient = useQueryClient();
const draftAttachments = createMemo(() => {
return props.message.attachments_draft ?? [];
});
@@ -178,9 +176,7 @@ export function MessageContainer(props: MessageContainerProps) {
);
}
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ refetchSoupEntity(document_id, 'document');
const blockName = fileType ? fileTypeToBlockName(fileType) : 'unknown';
openWithSplit(
diff --git a/js/app/packages/block-md/component/ComposeTask.tsx b/js/app/packages/block-md/component/ComposeTask.tsx
index 83f90ab043..30e14cda8e 100644
--- a/js/app/packages/block-md/component/ComposeTask.tsx
+++ b/js/app/packages/block-md/component/ComposeTask.tsx
@@ -37,8 +37,7 @@ import { buildSimpleEntityUrl } from '@core/util/url';
import LinkIcon from '@icon/regular/link-simple.svg';
import TrashIcon from '@icon/regular/trash.svg';
import XIcon from '@icon/regular/x.svg';
-import { useQueryClient } from '@queries/client';
-import { soupKeys } from '@queries/soup/keys';
+import { refetchSoupEntity } from '@queries/soup/cache';
import { useUpsertToHistoryMutation } from '@queries/history/history';
import { useUserId } from '@core/context/user';
import { propertiesServiceClient } from '@service-properties/client';
@@ -108,11 +107,8 @@ async function createTaskWithProperties(
}
);
- // Invalidate queries to refresh soup items and add to history
- const queryClient = useQueryClient();
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ // refetchSoupEntity is already called inside createTask — just upsert to history
+ refetchSoupEntity(documentId, 'document');
// Upsert the new task to history
upsertToHistory({
diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsx
index cddb416948..5ca746a73f 100644
--- a/js/app/packages/block-project/component/Block.tsx
+++ b/js/app/packages/block-project/component/Block.tsx
@@ -15,8 +15,7 @@ import {
type UploadInput,
uploadFiles,
} from '@core/util/upload';
-import { useQueryClient } from '@queries/client';
-import { soupKeys } from '@queries/soup/keys';
+import { refetchSoupEntity } from '@queries/soup/cache';
import { refetchResources } from '@service-storage/util/refetchResources';
import { toast } from 'core/component/Toast/Toast';
import { type Component, createSignal, Show } from 'solid-js';
@@ -40,7 +39,6 @@ const Block: Component = () => {
const [isDragging, setIsDragging] = createSignal(false);
const projectId = useBlockId();
const isSpecialProject = getIsSpecialProject(projectId);
- const queryClient = useQueryClient();
const handleFileUpload = async (files: UploadInput[]) => {
if (files.length === 0) return;
@@ -58,12 +56,14 @@ const Block: Component = () => {
const uploads = results.filter((result) => !result.failed);
- // show documents that were immediately uploaded
+ // refetch successfully uploaded documents into soup
const successfulUploads = uploads.filter((result) => !result.pending);
+ for (const upload of successfulUploads) {
+ if (upload.type === 'document') {
+ refetchSoupEntity(upload.documentId, 'document');
+ }
+ }
if (successfulUploads.length > 0) {
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
refetchResources();
}
@@ -73,10 +73,12 @@ const Block: Component = () => {
.filter((result) => result.type === 'folder')
.map((result) => result.projectId);
if (pendingFolderUploads.length > 0) {
- await Promise.all(pendingFolderUploads);
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ const resolved = await Promise.all(pendingFolderUploads);
+ for (const projectId of resolved) {
+ if (projectId) {
+ refetchSoupEntity(projectId, 'project');
+ }
+ }
refetchResources();
}
} catch (error) {
diff --git a/js/app/packages/core/internal/trackBlockOpened.ts b/js/app/packages/core/internal/trackBlockOpened.ts
index 49cbd5c7ae..5fb14f18f1 100644
--- a/js/app/packages/core/internal/trackBlockOpened.ts
+++ b/js/app/packages/core/internal/trackBlockOpened.ts
@@ -1,10 +1,11 @@
import type { BlockName } from '../block';
import { useUpsertToHistoryMutation } from '@queries/history/history';
+import { optimisticUpdateDssItemViewedAt } from '@macro-entity';
import {
- optimisticUpdateDssItemViewedAt,
- hasSoupItem,
- invalidateSoup,
-} from '@macro-entity';
+ hasSoupEntity,
+ refetchSoupEntity,
+ type SoupEntityTag,
+} from '@queries/soup/cache';
import {
blockNameToItemType,
isCloudStorageItem,
@@ -27,11 +28,11 @@ export function track({
}) {
const itemType = blockNameToItemType(blockName);
- const inSoup = hasSoupItem(itemId);
+ const inSoup = hasSoupEntity(itemId);
if (inSoup) {
optimisticUpdateDssItemViewedAt(itemId);
- } else {
- invalidateSoup();
+ } else if (itemType) {
+ refetchSoupEntity(itemId, itemType as SoupEntityTag);
}
if (!isCloudStorageItem(itemType)) return;
diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.ts
index 4f0eb71517..0ea5f24b3f 100644
--- a/js/app/packages/core/util/create.ts
+++ b/js/app/packages/core/util/create.ts
@@ -19,6 +19,7 @@ import {
isCodeEditorLanguageSupported,
} from './languageQuery';
import { err, isErr, ok } from './maybeResult';
+import { refetchSoupEntity } from '@queries/soup/cache';
/**
* Generate a fake sha256 hash
@@ -78,6 +79,7 @@ export async function createMarkdownFile(
if (isErr(res)) {
return;
}
+ refetchSoupEntity(documentId, 'document');
return documentId;
}
@@ -128,6 +130,7 @@ export async function createTask(
// Task was created, just without content - still return the id
}
+ refetchSoupEntity(documentId, 'document');
return documentId;
}
@@ -194,6 +197,7 @@ export async function createCodeFileFromText({
});
if (isErr(uploadResult)) return err('SERVER_ERROR', 'Failed to upload file');
postNewHistoryItem('document', document.metadata.documentId);
+ refetchSoupEntity(document.metadata.documentId, 'document');
return ok({ documentId: document.metadata.documentId });
}
@@ -227,6 +231,7 @@ export async function createCanvasFileFromJsonString(args: {
if (isErr(uploadResult)) return { error: 'Failed to upload file.' };
postNewHistoryItem('document', canvas.metadata.documentId);
+ refetchSoupEntity(canvas.metadata.documentId, 'document');
return { documentId: canvas.metadata.documentId };
}
@@ -243,6 +248,7 @@ export async function createChat(args?: CreateChatRequest) {
}
const [, chat] = maybeChat;
postNewHistoryItem('chat', chat.id);
+ refetchSoupEntity(chat.id, 'chat');
return { chatId: chat.id };
}
diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsx
index 3b3c172c41..155655c74a 100644
--- a/js/app/packages/macro-entity/src/index.tsx
+++ b/js/app/packages/macro-entity/src/index.tsx
@@ -12,8 +12,6 @@ export {
createMoveToProjectDssEntityMutation,
createCopyDssEntityMutation,
optimisticUpdateDssItemViewedAt,
- hasSoupItem,
- invalidateSoup,
} from './queries/dss';
export { createEmailsInfiniteQuery } from './queries/email';
export type { EntityInfiniteQuery, EntityQuery } from './queries/entity';
diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.ts
index 353069f6a4..4996bc8e78 100644
--- a/js/app/packages/macro-entity/src/queries/dss.ts
+++ b/js/app/packages/macro-entity/src/queries/dss.ts
@@ -5,11 +5,9 @@ import {
} from '@core/component/FileList/itemOperations';
import { itemToSafeName } from '@core/constant/allBlocks';
import { toast } from '@core/component/Toast/Toast';
-import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
import type {
PostItemsSoupParams,
PostSoupRequest,
- SoupApiItem,
SoupApiSort,
SoupDocument,
} from '@service-storage/generated/schemas';
@@ -42,15 +40,14 @@ import {
import { queryClient } from './client';
import { type DssQueryKey, dssQueryKeyHashFn, queryKeys } from './key';
import { soupKeys } from '@queries/soup/keys';
-
-const getSoupItemId = (item: SoupApiItem): string => {
- switch (item.tag) {
- case 'channel':
- return item.data.channel.id;
- default:
- return item.data.id;
- }
-};
+import {
+ removeSoupEntities,
+ removeSearchEntities,
+ getSoupEntityById,
+ optimisticUpdateSoupEntity,
+ invalidateSoupEntity,
+ refetchSoupEntity,
+} from '@queries/soup/cache';
const resolveDocumentEntityName = (
entity: DocumentEntity | SoupDocument
@@ -393,38 +390,16 @@ export function createDeleteDssItemMutation() {
return { success };
},
onMutate: async ({ id }: EntityData) => {
- queryClient.cancelQueries({
- queryKey: soupKeys.items._def,
- });
-
- function removeEntityFromQueryData(
- prev: { pages: { items: EntityData[] }[] } | undefined
- ): { pages: { items: EntityData[] }[] } | undefined {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.filter((item) => item.id !== id),
- }));
- return {
- ...prev,
- pages,
- };
- }
- queryClient.setQueriesData({ queryKey: soupKeys.items._def }, (prev) =>
- removeEntityFromQueryData(
- prev as { pages: { items: EntityData[] }[] } | undefined
- )
- );
+ return removeSoupEntities(new Set([id]));
},
- onSettled: (data, error, entity) => {
+ onSettled: (data, error, entity, context) => {
if (data?.success === false || error) {
+ context?.rollback();
console.error(`Failed to delete dss item ${entity}`, data, error);
toast.failure('Failed to delete item');
}
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ invalidateSoupEntity(entity.id);
},
}));
}
@@ -447,122 +422,32 @@ export function createBulkDeleteDssItemsMutation() {
);
},
onMutate: async (entities: EntityData[]) => {
- const deletedIDs = entities.map((e) => e.id);
-
- queryClient.cancelQueries({
- queryKey: soupKeys.items._def,
- });
- queryClient.cancelQueries({
- queryKey: soupKeys.search._def,
- });
-
- function removeEntitiesFromQueryData(
- prev: InfiniteData<SoupPage, unknown> | undefined
- ): InfiniteData<SoupPage, unknown> | undefined {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.filter((item) => {
- const itemId = getSoupItemId(item);
- return !deletedIDs.includes(itemId);
- }),
- }));
- return {
- ...prev,
- pages,
- };
- }
-
- function getSearchResultId(result: UnifiedSearchResponseItem): string {
- switch (result.type) {
- case 'document':
- return result.document_id;
- case 'chat':
- return result.chat_id;
- case 'channel':
- return result.channel_id;
- case 'email':
- return result.thread_id;
- case 'project':
- return result.id;
- }
- }
-
- function removeEntitiesFromSearchData(
- prev:
- | InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
- | undefined
- ):
- | InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
- | undefined {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- results: page.results.filter((result) => {
- const id = getSearchResultId(result);
- return !deletedIDs.includes(id);
- }),
- }));
- return {
- ...prev,
- pages,
- };
- }
-
- queryClient.setQueriesData({ queryKey: soupKeys.items._def }, (prev) =>
- removeEntitiesFromQueryData(
- prev as InfiniteData<SoupPage, unknown> | undefined
- )
- );
-
- queryClient.setQueriesData({ queryKey: soupKeys.search._def }, (prev) =>
- removeEntitiesFromSearchData(
- prev as
- | InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
- | undefined
- )
- );
+ const ids = new Set(entities.map((e) => e.id));
+ const soupSnapshot = removeSoupEntities(ids);
+ const searchSnapshot = removeSearchEntities(ids);
+ return { soupSnapshot, searchSnapshot };
},
- onError: (error, entities, _context) => {
+ onError: (error, entities, context) => {
+ context?.soupSnapshot.rollback();
+ context?.searchSnapshot.rollback();
console.error(`Failed to delete dss items`, entities, error);
toast.failure('Failed to delete items');
- // Rollback on error - restore the deleted items
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
- queryClient.invalidateQueries({
- queryKey: soupKeys.search._def,
- });
},
}));
}
-function createMoveOptimisticUpdate(entityIds: string[], projectId: string) {
- return (
- prev: { pages: { items: EntityData[] }[] } | undefined
- ): { pages: { items: EntityData[] }[] } | undefined => {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.map((item) =>
- entityIds.includes(item.id) ? { ...item, projectId } : item
- ),
- }));
- return {
- ...prev,
- pages,
- };
- };
-}
-
-function invalidateAfterMove(hasProjects: boolean, failed?: boolean) {
+function invalidateAfterMove(
+ entityIds: string[],
+ hasProjects: boolean,
+ failed?: boolean
+) {
if (failed) {
toast.failure('Failed to move item');
}
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ for (const id of entityIds) {
+ invalidateSoupEntity(id);
+ }
queryClient.invalidateQueries({ queryKey: ['entity'] });
// If moving a project, invalidate all project queries since nested projects' breadcrumbs change too
if (hasProjects) {
@@ -596,26 +481,23 @@ export function createMoveToProjectDssEntityMutation() {
entity: EntityData & { type: 'document' | 'chat' | 'project' };
project: { id: string };
}) => {
- queryClient.cancelQueries({
- queryKey: soupKeys.items._def,
- });
-
- // Only do optimistic updates for documents and chats
- // Projects have complex path data that we can't compute client-side
if (type !== 'project') {
- queryClient.setQueriesData(
- { queryKey: soupKeys.items._def },
- createMoveOptimisticUpdate([id], projectId)
- );
+ const current = getSoupEntityById(id);
+ return optimisticUpdateSoupEntity({
+ tag: type,
+ data: { id, projectId },
+ frecency_score: current?.frecency_score ?? 0,
+ });
}
},
- onSettled: (data, error, { entity: { id, type } }) => {
+ onSettled: (data, error, { entity: { id, type } }, context) => {
const failed = data?.success === false || !!error;
if (failed) {
+ context?.rollback();
console.error(`Failed to move dss item ${id}`, data, error);
}
- invalidateAfterMove(type === 'project', failed);
+ invalidateAfterMove([id], type === 'project', failed);
},
}));
}
@@ -646,14 +528,14 @@ export function createCopyDssEntityMutation() {
// For copy operations, we don't need optimistic updates since we're creating a new item
// The new item will be added when the mutation completes and queries are invalidated
},
- onSettled: (data, error, { entity: { id } }) => {
+ onSettled: (data, error, { entity: { id, type } }) => {
if (error) {
console.error(`Failed to copy dss item ${id}`, data, error);
toast.failure('Failed to copy item');
}
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ if (data) {
+ refetchSoupEntity(data, type as 'document' | 'chat');
+ }
queryClient.invalidateQueries({ queryKey: ['entity'] });
},
}));
@@ -759,31 +641,29 @@ export function createBulkMoveToProjectDssEntityMutation() {
entities: (EntityData & { name: string })[];
project: { id: string; name: string };
}) => {
- queryClient.cancelQueries({
- queryKey: soupKeys.items._def,
+ const moveableEntities = entities.filter(
+ (e): e is typeof e & { type: 'document' | 'chat' } =>
+ e.type === 'document' || e.type === 'chat'
+ );
+ return moveableEntities.map((e) => {
+ const current = getSoupEntityById(e.id);
+ return optimisticUpdateSoupEntity({
+ tag: e.type,
+ data: { id: e.id, projectId: project.id },
+ frecency_score: current?.frecency_score ?? 0,
+ });
});
-
- // Only do optimistic updates for documents and chats
- // Projects have complex path data that we can't compute client-side
- const nonProjectIds = entities
- .filter((e) => e.type !== 'project')
- .map((e) => e.id);
-
- if (nonProjectIds.length > 0) {
- queryClient.setQueriesData(
- { queryKey: soupKeys.items._def },
- createMoveOptimisticUpdate(nonProjectIds, project.id)
- );
- }
},
- onSettled: (data, error, { entities }) => {
+ onSettled: (data, error, { entities }, context) => {
const failed = data?.success === false || !!error;
if (failed) {
+ context?.forEach((txn) => txn.rollback());
console.error(`Failed to bulk move dss items`, entities, data, error);
}
invalidateAfterMove(
+ entities.map((e) => e.id),
entities.some((e) => e.type === 'project'),
failed
);
@@ -796,72 +676,22 @@ export function createBulkMoveToProjectDssEntityMutation() {
* Updates the item across all DSS queries if it exists.
*/
export function optimisticUpdateDssItemViewedAt(itemId: string) {
- const now = new Date();
-
- queryClient.setQueriesData(
- { queryKey: soupKeys.items._def },
- (prev: InfiniteData<SoupPage, unknown> | undefined) => {
- if (!prev) return prev;
-
- const pages = prev.pages.map((page) => {
- return {
- ...page,
- items: page.items.map((item): SoupApiItem => {
- const currentItemId = getSoupItemId(item);
- if (currentItemId !== itemId) return item;
-
- switch (item.tag) {
- case 'document':
- case 'chat':
- case 'project':
- case 'emailThread':
- item.data.viewedAt = now.getTime();
- break;
- case 'channel':
- item.data.viewed_at = now.toISOString();
- break;
- }
-
- return item;
- }),
- };
- });
-
- return {
- ...prev,
- pages,
- };
- }
- );
-}
+ const current = getSoupEntityById(itemId);
+ if (!current) return;
-/** Finds a soup item in the cache and returns its location. */
-export function hasSoupItem(itemId: string) {
- const queries = queryClient.getQueriesData<InfiniteData<SoupPage, unknown>>({
- queryKey: soupKeys.items._def,
- });
-
- for (const [, data] of queries) {
- if (!data) continue;
+ const now = new Date();
- for (let pageIndex = 0; pageIndex < data.pages.length; pageIndex++) {
- const page = data.pages[pageIndex];
- const itemIndex = page.items.findIndex(
- (item) => getSoupItemId(item) === itemId
- );
- if (itemIndex >= 0) return true;
- }
+ if (current.tag === 'channel') {
+ optimisticUpdateSoupEntity({
+ tag: 'channel',
+ data: { channel: { id: itemId }, viewed_at: now.toISOString() },
+ frecency_score: current.frecency_score,
+ });
+ } else {
+ optimisticUpdateSoupEntity({
+ tag: current.tag,
+ data: { id: itemId, viewedAt: now.getTime() },
+ frecency_score: current.frecency_score,
+ });
}
-
- return false;
-}
-
-/**
- * Invalidates all DSS soup queries, marking them as stale.
- * If the query is currently being rendered, it will also be refetched in the background
- */
-export function invalidateSoup() {
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
}
diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.ts
index bc5f78004f..0b6f3137d7 100644
--- a/js/app/packages/macro-entity/src/queries/rename.ts
+++ b/js/app/packages/macro-entity/src/queries/rename.ts
@@ -8,14 +8,16 @@ import { type MutationCallbacks, withCallbacks } from '@queries/utils';
import type { ItemType } from '@service-storage/client';
import { ChannelTypeEnum } from '@service-comms/client';
import type { EntityData } from '../types/entity';
-import { queryClient } from './client';
-import { type InfiniteData, useMutation } from '@tanstack/solid-query';
+import { useMutation } from '@tanstack/solid-query';
import { toast } from '@core/component/Toast/Toast';
-import type { SoupPage } from '@service-storage/generated/schemas';
import { setPreviewName } from '@queries/preview';
import { setHistoryItemName } from '@queries/history/history';
import { createCognitionWebsocketEffect } from '@service-cognition/websocket';
-import { soupKeys } from '@queries/soup/keys';
+import {
+ getSoupEntityById,
+ optimisticUpdateSoupEntity,
+ type SoupTransaction,
+} from '@queries/soup/cache';
type RenamableEntity = Pick<EntityData, 'id' | 'type' | 'name'> &
Partial<EntityData>;
@@ -32,8 +34,12 @@ type EntityRenameOperationResult = {
// Maps channel ID to its update context, which lets us rollback the updated at timestamp as well as name
type ChannelRenameContexts = Map<string, UpdateChannelNameContext | undefined>;
+// Keyed by entity ID so rollback indices stay aligned even when flatMap filters out types
+type SoupTransactionMap = Map<string, SoupTransaction>;
+
type RenameRollbackContext = {
channels: ChannelRenameContexts;
+ soupTransactions: SoupTransactionMap;
};
type EntityRenameData = {
@@ -45,8 +51,6 @@ type EntityRenameData = {
type EntityRenameOptimisticInfo = Omit<EntityRenameData, 'oldName'>;
-type EntityIdToNameMap = Map<string, string>;
-
type RenameDssEntityMutationVariables = EntityRenameOperation;
type BulkRenameDssEntityMutationVariables = RenameDssEntityMutationVariables[];
@@ -95,59 +99,34 @@ const validateEntityRename = (entity: EntityData): void => {
}
};
-// TODO: move item to front of list with updatedAt timestamp
-function updateEntityNamesInDssQueryData(
- prev: InfiniteData<SoupPage, unknown> | undefined,
- updates: EntityIdToNameMap
-): InfiniteData<SoupPage, unknown> | undefined {
- if (!prev) return prev;
- const pages = prev.pages.map((page) => ({
- ...page,
- items: page.items.map((item) => {
- // NOTE: reactivity does not seem to be a problem here so no spread is needed?
- switch (item.tag) {
- case 'channel': {
- const itemId = item.data.channel.id;
- const newName = updates.get(itemId);
- if (newName === undefined) return item;
- item.data.channel.name = newName;
- break;
- }
- case 'document':
- case 'chat':
- case 'project': {
- const itemId = item.data.id;
- const newName = updates.get(itemId);
- if (newName === undefined) return item;
- item.data.name = newName;
- break;
- }
- default:
- break;
- }
- return item;
- }),
- }));
- return {
- ...prev,
- pages,
- };
-}
-
-const renameDssSetData = (entities: EntityRenameOptimisticInfo[]) => {
- const updates: EntityIdToNameMap = new Map(
- entities.map((e) => [e.id, e.newName])
- );
-
- queryClient.cancelQueries({
- queryKey: soupKeys.items._def,
- });
- queryClient.setQueriesData({ queryKey: soupKeys.items._def }, (prev) =>
- updateEntityNamesInDssQueryData(
- prev as InfiniteData<SoupPage, unknown> | undefined,
- updates
- )
- );
+const renameDssSetData = (
+ entities: EntityRenameOptimisticInfo[]
+): SoupTransactionMap => {
+ const txns: SoupTransactionMap = new Map();
+ for (const { id, itemType, newName } of entities) {
+ const current = getSoupEntityById(id);
+ const score = current?.frecency_score ?? 0;
+ if (itemType === 'channel') {
+ txns.set(
+ id,
+ optimisticUpdateSoupEntity({
+ tag: 'channel',
+ data: { channel: { id, name: newName } },
+ frecency_score: score,
+ })
+ );
+ } else if (itemType !== 'email') {
+ txns.set(
+ id,
+ optimisticUpdateSoupEntity({
+ tag: itemType,
+ data: { id, name: newName },
+ frecency_score: score,
+ })
+ );
+ }
+ }
+ return txns;
};
const renameChannelSetData = (
@@ -191,23 +170,23 @@ function performOptimisticRenameUpdates(
): RenameRollbackContext {
renamePreviewSetData(entities);
renameHistorySetData(entities);
- renameDssSetData(entities);
- const channelContexts = renameChannelSetData(entities);
+ const soupTransactions = renameDssSetData(entities);
+ const channels = renameChannelSetData(entities);
- return {
- channels: channelContexts,
- };
+ return { channels, soupTransactions };
}
function rollbackOptimisticRenameUpdates({
contexts,
updates,
}: RenameOnMutateResult): void {
+ for (const [, txn] of contexts.soupTransactions) {
+ txn.rollback();
+ }
+
updates.forEach(({ id, oldName, itemType }) => {
- const reverseUpdate = { id, itemType, newName: oldName, oldName };
- renameDssSetData([reverseUpdate]);
- renameHistorySetData([reverseUpdate]);
- renamePreviewSetData([reverseUpdate]);
+ renameHistorySetData([{ id, itemType, newName: oldName }]);
+ renamePreviewSetData([{ id, itemType, newName: oldName }]);
if (itemType === 'channel') {
const context = contexts.channels.get(id);
@@ -263,16 +242,18 @@ const bulkRenameOnSettled = (
return;
}
- // Rollback only the failed items by matching indices
+ // Rollback only the failed items by entity ID
const failedUpdates: EntityRenameData[] = [];
const failedChannelContexts: ChannelRenameContexts = new Map();
+ const failedSoupTransactions: SoupTransactionMap = new Map();
data.forEach((result, index) => {
if (!result.success) {
const update = onMutateResult.updates[index];
if (update) {
failedUpdates.push(update);
- // Preserve channel context for failed channels
+ const txn = onMutateResult.contexts.soupTransactions.get(update.id);
+ if (txn) failedSoupTransactions.set(update.id, txn);
if (update.itemType === 'channel') {
const context = onMutateResult.contexts.channels.get(update.id);
if (context !== undefined) {
@@ -286,7 +267,10 @@ const bulkRenameOnSettled = (
// Rollback only the failed items
if (failedUpdates.length > 0) {
rollbackOptimisticRenameUpdates({
- contexts: { channels: failedChannelContexts },
+ contexts: {
+ channels: failedChannelContexts,
+ soupTransactions: failedSoupTransactions,
+ },
updates: failedUpdates,
});
}
diff --git a/js/app/packages/queries/client.ts b/js/app/packages/queries/client.ts
index 5ec7bccee7..9bbe547d01 100644
--- a/js/app/packages/queries/client.ts
+++ b/js/app/packages/queries/client.ts
@@ -2,6 +2,7 @@ import { QueryClient } from '@tanstack/solid-query';
import { createPerQueryIDBStore } from './persistence/per-query-idb';
import { partialMatchKey } from '@tanstack/query-core';
import { createPersistenceKey, setupQueryPersistence } from './persistence';
+import { initSoupNormalizer } from './soup/cache';
export const queryClient = new QueryClient({
defaultOptions: {
@@ -45,6 +46,9 @@ setupQueryPersistence({
],
});
+// Subscribe to query cache events for automatic normalization of soup entities
+initSoupNormalizer(queryClient);
+
export function useQueryClient() {
return queryClient;
}
diff --git a/js/app/packages/queries/email/draft.ts b/js/app/packages/queries/email/draft.ts
index 8eb523ec2e..1af72e4db1 100644
--- a/js/app/packages/queries/email/draft.ts
+++ b/js/app/packages/queries/email/draft.ts
@@ -9,7 +9,7 @@ import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { emailKeys } from './keys';
-import { soupKeys } from '@queries/soup/keys';
+import { invalidateSoupEntity, invalidateAllSoup } from '@queries/soup/cache';
type CreateDraftParams = {
draft: MessageToSend;
@@ -42,9 +42,7 @@ export function useSaveDraftMutation(
queryClient.invalidateQueries({
queryKey: emailKeys.previews._def,
});
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ invalidateAllSoup();
},
},
callbacks
@@ -74,13 +72,11 @@ export function useDeleteDraftMutation(
console.error('Failed to delete draft', error);
toast.failure('Failed to delete draft');
},
- onSuccess() {
+ onSuccess(_data, vars) {
queryClient.invalidateQueries({
queryKey: emailKeys.previews._def,
});
- queryClient.invalidateQueries({
- queryKey: soupKeys.items._def,
- });
+ invalidateSoupEntity(vars.draftId);
},
},
callbacks
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index b80df75e83..f441663039 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -1,6 +1,6 @@
import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';
import { catchToResult, isErr, ok, throwOnErr } from '@core/util/maybeResult';
-import { soupKeys } from '../soup/keys';
+import { optimisticUpdateSoupEntity } from '../soup/cache';
import { emailClient } from '@service-email/client';
import type {
MessageToSend,
@@ -8,7 +8,6 @@ import type {
APIThread as Thread,
UpsertScheduledResponse,
} from '@service-email/generated/schemas';
-import type { SoupPage } from '@service-storage/generated/schemas';
import {
type InfiniteData,
type SolidInfiniteQueryOptions,
@@ -157,33 +156,11 @@ type MarkThreadAsSeenParams = { threadId: string };
* email view anyway - only the soup/list view needs it.
*/
function threadSeenOnMutate(params: MarkThreadAsSeenParams): void {
- queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
- { queryKey: soupKeys.items._def },
- (old) => {
- if (!old) return old;
- return {
- ...old,
- pages: old.pages.map((page) => ({
- ...page,
- items: page.items.map((item) => {
- if (
- item.tag === 'emailThread' &&
- item.data.id === params.threadId
- ) {
- return {
- ...item,
- data: {
- ...item.data,
- isRead: true,
- },
- };
- }
- return item;
- }),
- })),
- };
- }
- );
+ optimisticUpdateSoupEntity({
+ tag: 'emailThread',
+ data: { id: params.threadId, isRead: true },
+ frecency_score: 0,
+ });
}
/**
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 229b3dc959..25a3dddce4 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -4,12 +4,7 @@ import {
SYSTEM_PROPERTY_IDS,
} from '@core/component/Properties/constants';
import { throwOnErr } from '@core/util/maybeResult';
-import {
- type InfiniteData,
- type QueryKey,
- useMutation,
- useQuery,
-} from '@tanstack/solid-query';
+import { type QueryKey, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import {
entityPropertyFromApi,
@@ -24,13 +19,17 @@ import {
propertiesServiceClient,
} from '../../service-clients/service-properties/client';
import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
-import type { SoupPage } from '../../service-clients/service-storage/generated/schemas/soupPage';
-import type { SoupProperty } from '../../service-clients/service-storage/generated/schemas/soupProperty';
+import type { SoupPropertyValue } from '../../service-clients/service-storage/generated/schemas/soupPropertyValue';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { propertiesKeys } from './keys';
-import { soupKeys } from '../soup/keys';
import type { BulkEntityPropertiesData } from './bulk';
+import {
+ getSoupEntityById,
+ optimisticUpdateSoupEntity,
+ invalidateSoupEntity,
+ type SoupTransaction,
+} from '../soup/cache';
export function useEntityPropertiesQuery(
entityType: Accessor<EntityType>,
@@ -96,16 +95,14 @@ export type SaveEntityPropertyParams = {
apiValues: PropertyApiValues;
};
-type SaveEntityPropertyContext = {
- previousDss: [QueryKey, InfiniteData<SoupPage, unknown> | undefined][];
-};
+type SaveEntityPropertyContext = SoupTransaction | undefined;
/**
* Converts PropertyApiValues to the SoupProperty value format for optimistic updates.
*/
function apiValuesToSoupPropertyValue(
apiValues: PropertyApiValues
-): { type: string; value: unknown } | null {
+): SoupPropertyValue {
switch (apiValues.valueType) {
case 'STRING':
return apiValues.value != null
@@ -141,53 +138,6 @@ function apiValuesToSoupPropertyValue(
}
}
-/**
- * Updates a specific property in DSS data for optimistic updates.
- */
-function updateDssProperty(
- data: InfiniteData<SoupPage, unknown> | undefined,
- entityId: string,
- propertyDefinitionId: string,
- newValue: { type: string; value: unknown } | null
-): InfiniteData<SoupPage, unknown> | undefined {
- if (!data) return data;
-
- return {
- ...data,
- pages: data.pages.map((page) => ({
- ...page,
- items: page.items.map((item) => {
- if ('data' in item && item.data && 'id' in item.data) {
- const itemData = item.data as {
- id: string;
- properties?: SoupProperty[];
- };
- if (itemData.id === entityId && itemData.properties) {
- const updatedProperties = itemData.properties.map((prop) => {
- if (prop.definition.id === propertyDefinitionId) {
- return {
- ...prop,
- value: newValue,
- };
- }
- return prop;
- });
- return {
- ...item,
- data: {
- ...item.data,
- properties: updatedProperties,
- },
- } as typeof item;
- }
- }
- return item;
- }),
- })),
- pageParams: data.pageParams,
- };
-}
-
export function useSaveEntityPropertyMutation(
callbacks?: MutationCallbacks<
void,
@@ -218,53 +168,37 @@ export function useSaveEntityPropertyMutation(
onMutate: async (
vars: SaveEntityPropertyParams
): Promise<SaveEntityPropertyContext> => {
- // Cancel any in-flight DSS queries that might overwrite our optimistic update
- await queryClient.cancelQueries({ queryKey: soupKeys.items._def });
-
- // Snapshot previous DSS data for rollback
- const previousDss = queryClient.getQueriesData<
- InfiniteData<SoupPage, unknown>
- >({
- queryKey: soupKeys.items._def,
- });
+ const current = getSoupEntityById(vars.entityId);
+ if (!current || current.tag === 'channel') return;
- // Convert API values to soup property value format
const soupValue = apiValuesToSoupPropertyValue(vars.apiValues);
-
- // Optimistically update DSS queries
- queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
- { queryKey: soupKeys.items._def },
- (old) =>
- updateDssProperty(
- old,
- vars.entityId,
- vars.property.propertyDefinitionId,
- soupValue
- )
- );
-
- return { previousDss };
+ if (current.data.properties) {
+ return optimisticUpdateSoupEntity({
+ tag: current.tag,
+ data: {
+ id: current.data.id,
+ properties: current.data.properties.map((prop) =>
+ prop.definition.id === vars.property.propertyDefinitionId
+ ? { ...prop, value: soupValue }
+ : prop
+ ),
+ },
+ frecency_score: current.frecency_score,
+ });
+ }
},
onError: (
error: Error,
_vars: SaveEntityPropertyParams,
- context: SaveEntityPropertyContext | undefined
+ context: SaveEntityPropertyContext
) => {
+ context?.rollback();
console.error('Failed to save property', error);
toast.failure('Failed to save property');
-
- // Rollback optimistic updates
- if (context) {
- for (const [key, data] of context.previousDss) {
- queryClient.setQueryData(key, data);
- }
- }
},
onSettled: (_data, _error, variables) => {
invalidatePropertiesForEntity(variables.entityType, variables.entityId);
-
- // Invalidate DSS to ensure consistency with server state
- queryClient.invalidateQueries({ queryKey: soupKeys.items._def });
+ invalidateSoupEntity(variables.entityId);
},
...(callbacks
? withCallbacks<
@@ -363,7 +297,7 @@ export type SetPropertyStatusCompleteParams = {
type SetPropertyStatusCompleteContext = {
previousEntityProperties: [QueryKey, Property[] | undefined][];
previousBulkProperties: [QueryKey, BulkEntityPropertiesData | undefined][];
- previousDss: [QueryKey, InfiniteData<SoupPage, unknown> | undefined][];
+ soupTxn?: SoupTransaction;
};
/**
@@ -402,45 +336,6 @@ function updateStatusPropertyToCompleted<
});
}
-/**
- * Updates DSS query data to set the status property to COMPLETED for a given entity.
- */
-function updateDssStatusToCompleted(
- data: InfiniteData<SoupPage, unknown> | undefined,
- entityId: string
-): InfiniteData<SoupPage, unknown> | undefined {
- if (!data) return data;
-
- return {
- ...data,
- pages: data.pages.map((page) => ({
- ...page,
- items: page.items.map((item) => {
- // SoupApiItem has { tag, data } structure where data contains the entity
- if ('data' in item && item.data && 'id' in item.data) {
- const itemData = item.data as {
- id: string;
- properties?: SoupProperty[];
- };
- if (itemData.id === entityId && itemData.properties) {
- // Use Object.assign to preserve the original type while updating properties
- const updatedData = {
- ...item.data,
- properties: updateStatusPropertyToCompleted(itemData.properties),
- };
- return {
- ...item,
- data: updatedData,
- } as typeof item;
- }
- }
- return item;
- }),
- })),
- pageParams: data.pageParams,
- };
-}
-
/** Sets the status property to complete for an entity (mark as done) */
export function useSetPropertyStatusCompleteMutation(
callbacks?: MutationCallbacks<
@@ -463,7 +358,7 @@ export function useSetPropertyStatusCompleteMutation(
onMutate: async (
vars: SetPropertyStatusCompleteParams
): Promise<SetPropertyStatusCompleteContext> => {
- // Cancel any in-flight queries that might overwrite our optimistic update
+ // Cancel any in-flight property queries
await Promise.all([
queryClient.cancelQueries({
queryKey: propertiesKeys.entity({
@@ -475,10 +370,9 @@ export function useSetPropertyStatusCompleteMutation(
predicate: ({ queryKey }) =>
bulkIncludesEntityPredicate(queryKey, vars.entityId),
}),
- queryClient.cancelQueries({ queryKey: soupKeys.items._def }),
]);
- // Snapshot previous data for rollback
+ // Snapshot previous property data for rollback
const previousEntityProperties = queryClient.getQueriesData<Property[]>({
queryKey: propertiesKeys.entity({
entityType: vars.entityType,
@@ -492,12 +386,6 @@ export function useSetPropertyStatusCompleteMutation(
bulkIncludesEntityPredicate(queryKey, vars.entityId),
});
- const previousDss = queryClient.getQueriesData<
- InfiniteData<SoupPage, unknown>
- >({
- queryKey: soupKeys.items._def,
- });
-
// Optimistically update entity properties query
queryClient.setQueriesData<Property[]>(
{
@@ -527,15 +415,26 @@ export function useSetPropertyStatusCompleteMutation(
);
// Optimistically update soup queries (embedded properties on entities)
- queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
- { queryKey: soupKeys.items._def },
- (old) => updateDssStatusToCompleted(old, vars.entityId)
- );
+ const current = getSoupEntityById(vars.entityId);
+
+ let soupTxn: SoupTransaction | undefined;
+ if (current && current.tag !== 'channel' && current.data.properties) {
+ soupTxn = optimisticUpdateSoupEntity({
+ tag: current.tag,
+ data: {
+ id: current.data.id,
+ properties: updateStatusPropertyToCompleted(
+ current.data.properties
+ ),
+ },
+ frecency_score: current.frecency_score,
+ });
+ }
return {
previousEntityProperties,
previousBulkProperties,
- previousDss,
+ soupTxn,
};
},
onError: (
@@ -545,23 +444,19 @@ export function useSetPropertyStatusCompleteMutation(
) => {
console.error('Failed to set status complete', error);
- // Rollback optimistic updates
if (context) {
+ context.soupTxn?.rollback();
for (const [key, data] of context.previousEntityProperties) {
queryClient.setQueryData(key, data);
}
for (const [key, data] of context.previousBulkProperties) {
queryClient.setQueryData(key, data);
}
- for (const [key, data] of context.previousDss) {
- queryClient.setQueryData(key, data);
- }
}
},
onSettled: (_data, _error, variables) => {
invalidatePropertiesForEntity(variables.entityType, variables.entityId);
- // Also invalidate soup items to ensure consistency
- queryClient.invalidateQueries({ queryKey: soupKeys.items._def });
+ invalidateSoupEntity(variables.entityId);
},
...(callbacks
? withCallbacks<
@@ -635,11 +530,9 @@ export function useBulkSaveEntityPropertiesMutation(
entityGroups.forEach((entityIds, entityType) => {
entityIds.forEach((entityId) => {
invalidatePropertiesForEntity(entityType, entityId);
+ invalidateSoupEntity(entityId);
});
});
-
- // Invalidate soup/DSS queries to ensure UI updates reactively
- queryClient.invalidateQueries({ queryKey: soupKeys.items._def });
},
},
callbacks
diff --git a/js/app/packages/queries/soup/cache.ts b/js/app/packages/queries/soup/cache.ts
new file mode 100644
index 0000000000..3bc5289238
--- /dev/null
+++ b/js/app/packages/queries/soup/cache.ts
@@ -0,0 +1 @@
+export * from './normalized-cache';
diff --git a/js/app/packages/queries/soup/normalized-cache/index.ts b/js/app/packages/queries/soup/normalized-cache/index.ts
new file mode 100644
index 0000000000..8857f09203
--- /dev/null
+++ b/js/app/packages/queries/soup/normalized-cache/index.ts
@@ -0,0 +1,19 @@
+export { initSoupNormalizer, getSoupNormalizer } from './normalizer';
+export type { NormalizerData } from './normalizer';
+export type {
+ SoupTransaction,
+ SoupEntityTag,
+ SoupEntityPartial,
+} from './types';
+export {
+ optimisticUpdateSoupEntity,
+ insertSoupEntity,
+ getSoupEntityById,
+ invalidateSoupEntity,
+ invalidateAllSoup,
+ hasSoupEntity,
+ getSoupItemId,
+ removeSoupEntities,
+ removeSearchEntities,
+ refetchSoupEntity,
+} from './operations';
diff --git a/js/app/packages/queries/soup/normalized-cache/normalizer.ts b/js/app/packages/queries/soup/normalized-cache/normalizer.ts
new file mode 100644
index 0000000000..2afe974bbc
--- /dev/null
+++ b/js/app/packages/queries/soup/normalized-cache/normalizer.ts
@@ -0,0 +1,47 @@
+import { createQueryNormalizer } from '@normy/query-core';
+import type { QueryClient } from '@tanstack/solid-query';
+
+export type NormalizerData = Parameters<
+ ReturnType<typeof createQueryNormalizer>['setNormalizedData']
+>[0];
+
+/**
+ * Extracts a normalization key from SoupApiItem wrappers.
+ * Only objects with `tag + data + frecency_score` are normalized.
+ */
+export const getNormalizationObjectKey = (
+ obj: Record<string, unknown>
+): string | undefined => {
+ if ('tag' in obj && 'data' in obj && 'frecency_score' in obj) {
+ const data = obj.data as Record<string, unknown>;
+ if (obj.tag === 'channel') {
+ const channel = data?.channel as Record<string, unknown> | undefined;
+ return channel?.id ? `soup:${channel.id}` : undefined;
+ }
+ return data?.id ? `soup:${data.id}` : undefined;
+ }
+ return undefined;
+};
+
+let _normalizer: ReturnType<typeof createQueryNormalizer> | undefined;
+
+export function getSoupNormalizer() {
+ if (!_normalizer) {
+ throw new Error(
+ 'soupNormalizer not initialized — call initSoupNormalizer() first'
+ );
+ }
+ return _normalizer;
+}
+
+/**
+ * Create and subscribe the normalizer. Call once at app startup.
+ * Accepts queryClient as a parameter to avoid circular imports.
+ */
+export function initSoupNormalizer(qc: QueryClient): () => void {
+ _normalizer = createQueryNormalizer(qc, {
+ getNormalizationObjectKey,
+ });
+ _normalizer.subscribe();
+ return () => _normalizer!.unsubscribe();
+}
diff --git a/js/app/packages/queries/soup/normalized-cache/operations.test.ts b/js/app/packages/queries/soup/normalized-cache/operations.test.ts
new file mode 100644
index 0000000000..5053f49183
--- /dev/null
+++ b/js/app/packages/queries/soup/normalized-cache/operations.test.ts
@@ -0,0 +1,346 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { InfiniteData } from '@tanstack/solid-query';
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+import type { SoupPage } from '@service-storage/generated/schemas/soupPage';
+import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
+import { QueryClient } from '@tanstack/solid-query';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+let testQueryClient: QueryClient;
+
+vi.mock('../../client', () => ({
+ get queryClient() {
+ return testQueryClient;
+ },
+}));
+
+const mockNormalizer = {
+ setNormalizedData: vi.fn(),
+ getDependentQueriesByIds: vi.fn<(ids: string[]) => unknown[][]>(() => []),
+ getObjectById: vi.fn<(id: string) => unknown>(() => null),
+};
+
+vi.mock('./normalizer', () => ({
+ getSoupNormalizer: () => mockNormalizer,
+ getNormalizationObjectKey: (obj: Record<string, unknown>) => {
+ if ('tag' in obj && 'data' in obj) {
+ const data = obj.data as Record<string, unknown>;
+ if (obj.tag === 'channel') {
+ const channel = data?.channel as Record<string, unknown> | undefined;
+ return channel?.id ? `soup:${channel.id}` : undefined;
+ }
+ return data?.id ? `soup:${data.id}` : undefined;
+ }
+ return undefined;
+ },
+}));
+
+// biome-ignore lint/correctness/noPrivateImports: testing private export
+import { buildSingleEntityFilter } from './operations';
+import {
+ getSoupItemId,
+ insertSoupEntity,
+ removeSoupEntities,
+ removeSearchEntities,
+ optimisticUpdateSoupEntity,
+} from './operations';
+import { soupKeys } from '../keys';
+
+// -- Fixtures --
+
+function mockDocumentItem(id: string): SoupApiItem {
+ return {
+ tag: 'document',
+ data: { id, title: 'doc' },
+ frecency_score: 1,
+ } as unknown as SoupApiItem;
+}
+
+function mockChannelItem(id: string): SoupApiItem {
+ return {
+ tag: 'channel',
+ data: { channel: { id, name: 'ch' } },
+ frecency_score: 1,
+ } as unknown as SoupApiItem;
+}
+
+function mockChatItem(id: string): SoupApiItem {
+ return {
+ tag: 'chat',
+ data: { id, title: 'chat' },
+ frecency_score: 1,
+ } as unknown as SoupApiItem;
+}
+
+function mockSoupCache(
+ pages: SoupApiItem[][]
+): InfiniteData<SoupPage, unknown> {
+ return {
+ pages: pages.map((items) => ({ items })),
+ pageParams: pages.map((_, i) => (i === 0 ? null : `cursor-${i}`)),
+ };
+}
+
+function mockSearchResult(type: string, id: string): UnifiedSearchResponseItem {
+ switch (type) {
+ case 'document':
+ return {
+ type: 'document',
+ document_id: id,
+ } as unknown as UnifiedSearchResponseItem;
+ case 'chat':
+ return {
+ type: 'chat',
+ chat_id: id,
+ } as unknown as UnifiedSearchResponseItem;
+ case 'channel':
+ return {
+ type: 'channel',
+ channel_id: id,
+ } as unknown as UnifiedSearchResponseItem;
+ case 'project':
+ return { type: 'project', id } as unknown as UnifiedSearchResponseItem;
+ default:
+ throw new Error(`Unknown search type: ${type}`);
+ }
+}
+
+function mockSearchCache(
+ pages: UnifiedSearchResponseItem[][]
+): InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown> {
+ return {
+ pages: pages.map((results) => ({ results })),
+ pageParams: pages.map((_, i) => (i === 0 ? null : `cursor-${i}`)),
+ };
+}
+
+const soupSeedKey = [...soupKeys.items._def, 'seed'];
+const searchSeedKey = [...soupKeys.search._def, 'seed'];
+
+function seedSoupQuery(data: InfiniteData<SoupPage, unknown>) {
+ testQueryClient.setQueryData(soupSeedKey, data);
+}
+
+function getSoupQuery(): InfiniteData<SoupPage, unknown> | undefined {
+ return testQueryClient.getQueryData(soupSeedKey);
+}
+
+function seedSearchQuery(
+ data: InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
+) {
+ testQueryClient.setQueryData(searchSeedKey, data);
+}
+
+function getSearchQuery() {
+ return testQueryClient.getQueryData<
+ InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
+ >(searchSeedKey);
+}
+
+// -- Shared setup --
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+});
+
+afterEach(() => {
+ testQueryClient.clear();
+});
+
+// -- Tests --
+
+describe('getSoupItemId', () => {
+ it('returns data.id for standard tags', () => {
+ expect(getSoupItemId(mockDocumentItem('abc-123'))).toBe('abc-123');
+ });
+
+ it('returns data.channel.id for channel tag', () => {
+ expect(getSoupItemId(mockChannelItem('ch-456'))).toBe('ch-456');
+ });
+});
+
+describe('buildSingleEntityFilter', () => {
+ const NIL_ID = '00000000-0000-0000-0000-000000000000';
+
+ it.each([
+ {
+ entityType: 'document' as const,
+ filterKey: 'document_filters',
+ idKey: 'document_ids',
+ },
+ {
+ entityType: 'chat' as const,
+ filterKey: 'chat_filters',
+ idKey: 'chat_ids',
+ },
+ {
+ entityType: 'channel' as const,
+ filterKey: 'channel_filters',
+ idKey: 'channel_ids',
+ },
+ {
+ entityType: 'project' as const,
+ filterKey: 'project_filters',
+ idKey: 'project_ids',
+ },
+ ])(
+ 'unblocks only $entityType filter with the real entityId',
+ ({ entityType, filterKey, idKey }) => {
+ const filter = buildSingleEntityFilter(entityType, 'entity-1')!;
+ expect(filter).not.toBeNull();
+ expect(filter.limit).toBe(1);
+
+ // The target filter uses the real entityId
+ expect((filter as any)[filterKey][idKey]).toEqual(['entity-1']);
+
+ // All other ID-based filters use NIL_ID
+ const otherFilters = [
+ 'document_filters',
+ 'chat_filters',
+ 'channel_filters',
+ 'project_filters',
+ ].filter((k) => k !== filterKey);
+
+ for (const key of otherFilters) {
+ const ids = Object.values((filter as any)[key])[0];
+ expect(ids).toEqual([NIL_ID]);
+ }
+ }
+ );
+
+ it('returns null for emailThread', () => {
+ expect(buildSingleEntityFilter('emailThread', 'e-1')).toBeNull();
+ });
+});
+
+describe('insertSoupEntity', () => {
+ it('prepends item to first page only', () => {
+ const page0 = [mockDocumentItem('d-1')];
+ const page1 = [mockDocumentItem('d-2')];
+ seedSoupQuery(mockSoupCache([page0, page1]));
+
+ const newItem = mockChatItem('c-1');
+ insertSoupEntity(newItem);
+
+ const cached = getSoupQuery()!;
+ expect(cached.pages[0].items).toHaveLength(2);
+ expect(getSoupItemId(cached.pages[0].items[0])).toBe('c-1');
+ expect(getSoupItemId(cached.pages[0].items[1])).toBe('d-1');
+ expect(cached.pages[1].items).toHaveLength(1);
+ expect(getSoupItemId(cached.pages[1].items[0])).toBe('d-2');
+ });
+
+ it('rollback restores original state', () => {
+ const original = mockSoupCache([[mockDocumentItem('d-1')]]);
+ seedSoupQuery(original);
+
+ const tx = insertSoupEntity(mockChatItem('c-1'));
+ expect(getSoupQuery()!.pages[0].items).toHaveLength(2);
+
+ tx.rollback();
+ const restored = getSoupQuery()!;
+ expect(restored.pages[0].items).toHaveLength(1);
+ expect(getSoupItemId(restored.pages[0].items[0])).toBe('d-1');
+ });
+});
+
+describe('removeSoupEntities', () => {
+ it('filters matching IDs from all pages', () => {
+ seedSoupQuery(
+ mockSoupCache([
+ [mockDocumentItem('d-1'), mockChatItem('c-1')],
+ [mockDocumentItem('d-2'), mockChannelItem('ch-1')],
+ ])
+ );
+
+ removeSoupEntities(new Set(['d-1', 'ch-1']));
+
+ const cached = getSoupQuery()!;
+ expect(cached.pages[0].items).toHaveLength(1);
+ expect(getSoupItemId(cached.pages[0].items[0])).toBe('c-1');
+ expect(cached.pages[1].items).toHaveLength(1);
+ expect(getSoupItemId(cached.pages[1].items[0])).toBe('d-2');
+ });
+
+ it('rollback restores removed items', () => {
+ seedSoupQuery(
+ mockSoupCache([[mockDocumentItem('d-1'), mockChatItem('c-1')]])
+ );
+
+ const tx = removeSoupEntities(new Set(['d-1']));
+ expect(getSoupQuery()!.pages[0].items).toHaveLength(1);
+
+ tx.rollback();
+ const restored = getSoupQuery()!;
+ expect(restored.pages[0].items).toHaveLength(2);
+ expect(getSoupItemId(restored.pages[0].items[0])).toBe('d-1');
+ });
+});
+
+describe('removeSearchEntities', () => {
+ it('filters matching IDs from search results', () => {
+ seedSearchQuery(
+ mockSearchCache([
+ [
+ mockSearchResult('document', 'doc-1'),
+ mockSearchResult('chat', 'chat-1'),
+ ],
+ [mockSearchResult('channel', 'ch-1')],
+ ])
+ );
+
+ removeSearchEntities(new Set(['doc-1', 'ch-1']));
+
+ const cached = getSearchQuery()!;
+ expect(cached.pages[0].results).toHaveLength(1);
+ expect(cached.pages[0].results[0].type).toBe('chat');
+ expect(cached.pages[1].results).toHaveLength(0);
+ });
+
+ it('rollback restores removed search results', () => {
+ seedSearchQuery(
+ mockSearchCache([
+ [
+ mockSearchResult('document', 'doc-1'),
+ mockSearchResult('chat', 'chat-1'),
+ ],
+ ])
+ );
+
+ const tx = removeSearchEntities(new Set(['doc-1']));
+ expect(getSearchQuery()!.pages[0].results).toHaveLength(1);
+
+ tx.rollback();
+ const restored = getSearchQuery()!;
+ expect(restored.pages[0].results).toHaveLength(2);
+ });
+});
+
+describe('optimisticUpdateSoupEntity', () => {
+ it('rollback restores dependent query data', () => {
+ const dependentKey = [...soupKeys.items._def, 'dependent'];
+ const originalData = mockSoupCache([[mockDocumentItem('d-1')]]);
+ testQueryClient.setQueryData(dependentKey, originalData);
+
+ mockNormalizer.getDependentQueriesByIds.mockReturnValueOnce([dependentKey]);
+
+ const tx = optimisticUpdateSoupEntity(mockDocumentItem('d-1'));
+
+ tx.rollback();
+
+ const restored =
+ testQueryClient.getQueryData<InfiniteData<SoupPage, unknown>>(
+ dependentKey
+ );
+ expect(restored).toEqual(originalData);
+ });
+});
diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.ts
new file mode 100644
index 0000000000..517a275592
--- /dev/null
+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts
@@ -0,0 +1,297 @@
+import type { InfiniteData, QueryKey } from '@tanstack/solid-query';
+import type {
+ PostSoupRequest,
+ SoupApiItem,
+} from '@service-storage/generated/schemas';
+import type { SoupPage } from '@service-storage/generated/schemas/soupPage';
+import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
+import { isErr } from '@core/util/maybeResult';
+import { match } from 'ts-pattern';
+import { queryClient } from '../../client';
+import { soupKeys } from '../keys';
+import {
+ getSoupNormalizer,
+ getNormalizationObjectKey,
+ type NormalizerData,
+} from './normalizer';
+import type {
+ SoupTransaction,
+ SoupEntityTag,
+ SoupEntityPartial,
+} from './types';
+
+/**
+ * Optimistically update a single soup entity across all queries that reference it.
+ * Returns a transaction whose `rollback()` restores only the affected queries
+ * Channels: `{ tag: 'channel', data: { channel: { id, ...fields } }, frecency_score }`
+ * Everything else: `{ tag, data: { id, ...fields }, frecency_score }`
+ */
+export function optimisticUpdateSoupEntity<T extends SoupEntityTag>(
+ partial: SoupEntityPartial<T>
+): SoupTransaction {
+ const normalizer = getSoupNormalizer();
+ const normKey = getNormalizationObjectKey(partial);
+
+ const dependentKeys = normKey
+ ? normalizer.getDependentQueriesByIds([normKey])
+ : [];
+
+ const previous = dependentKeys.map(
+ (key) =>
+ [
+ key,
+ queryClient.getQueryData<InfiniteData<SoupPage, unknown>>(key),
+ ] as const
+ );
+
+ normalizer.setNormalizedData(partial as NormalizerData);
+
+ return {
+ rollback: () => {
+ for (const [key, data] of previous) {
+ queryClient.setQueryData(key, data);
+ }
+ },
+ };
+}
+
+/** Read an entity from normy's normalized store by ID. Returns `undefined` if not cached. */
+export function getSoupEntityById(entityId: string): SoupApiItem | undefined {
+ return (getSoupNormalizer().getObjectById(`soup:${entityId}`) ?? undefined) as
+ | SoupApiItem
+ | undefined;
+}
+
+/**
+ * Mark stale only the soup queries containing a specific entity.
+ * Prefer this over `invalidateAllSoup` when you know the affected entity ID.
+ */
+export function invalidateSoupEntity(entityId: string): void {
+ const normalizer = getSoupNormalizer();
+ const keys = normalizer.getDependentQueriesByIds([`soup:${entityId}`]);
+ for (const queryKey of keys) {
+ queryClient.invalidateQueries({ queryKey });
+ }
+}
+
+/** Mark every soup list query stale. Use `invalidateSoupEntity` when the entity ID is known. */
+export function invalidateAllSoup(): void {
+ queryClient.invalidateQueries({
+ queryKey: soupKeys.items._def,
+ });
+}
+
+/** O(1) check whether an entity exists in normy's normalized store. */
+export function hasSoupEntity(entityId: string): boolean {
+ return getSoupNormalizer().getObjectById(`soup:${entityId}`) != null;
+}
+
+/** Extract the canonical entity ID from a SoupApiItem (handles channel's nested `data.channel.id`). */
+export function getSoupItemId(item: SoupApiItem): string {
+ switch (item.tag) {
+ case 'channel':
+ return item.data.channel.id;
+ default:
+ return item.data.id;
+ }
+}
+
+/**
+ * Insert a new entity into the first page of every active soup list query.
+ * Normy auto-normalizes the entry on insertion, making it available via `getSoupEntityById`.
+ * Use for entities that don't yet exist in the cache. For existing entities use
+ * `optimisticUpdateSoupEntity` (deep-merge) instead.
+ */
+export function insertSoupEntity(item: SoupApiItem): SoupTransaction {
+ const previous = snapshotSoup();
+
+ queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
+ { queryKey: soupKeys.items._def },
+ (prev) => {
+ if (!prev) return prev;
+ return {
+ ...prev,
+ pages: prev.pages.map((p, i) => {
+ if (i !== 0) return p;
+ return { ...p, items: [item, ...p.items] };
+ }),
+ };
+ }
+ );
+
+ return { rollback: () => restoreSnapshot(previous) };
+}
+
+/**
+ * Optimistically remove entities from all soup list queries.
+ * Cancels in-flight fetches first to prevent them from re-adding removed items.
+ * Snapshots the full soup cache before mutating — rollback restores everything.
+ */
+export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {
+ queryClient.cancelQueries({ queryKey: soupKeys.items._def });
+
+ const previous = snapshotSoup();
+
+ queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
+ { queryKey: soupKeys.items._def },
+ (prev) => {
+ if (!prev) return prev;
+ return {
+ ...prev,
+ pages: prev.pages.map((page) => {
+ const items = page.items.filter(
+ (item) => !entityIds.has(getSoupItemId(item))
+ );
+ return items.length === page.items.length ? page : { ...page, items };
+ }),
+ };
+ }
+ );
+
+ return { rollback: () => restoreSnapshot(previous) };
+}
+
+/**
+ * Optimistically remove entities from all search result queries.
+ * Same cancel-snapshot-mutate pattern as `removeSoupEntities` but targets search queries.
+ */
+export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {
+ queryClient.cancelQueries({ queryKey: soupKeys.search._def });
+
+ const previous = queryClient.getQueriesData<
+ InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
+ >({
+ queryKey: soupKeys.search._def,
+ });
+
+ queryClient.setQueriesData<
+ InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>
+ >({ queryKey: soupKeys.search._def }, (prev) => {
+ if (!prev) return prev;
+ return {
+ ...prev,
+ pages: prev.pages.map((page) => {
+ const results = page.results.filter(
+ (result) => !entityIds.has(getSearchResultId(result))
+ );
+ return results.length === page.results.length
+ ? page
+ : { ...page, results };
+ }),
+ };
+ });
+
+ return {
+ rollback: () => {
+ for (const [key, data] of previous) {
+ queryClient.setQueryData(key, data);
+ }
+ },
+ };
+}
+
+/**
+ * Fetch a single entity from the server and merge it into the cache.
+ * If the entity is already cached, updates it via normy (deep-merge).
+ * If it's new, prepends it to the first page of every active soup list query.
+ * Falls back to `invalidateSoupEntity` for unsupported entity types (e.g. emailThread).
+ */
+export async function refetchSoupEntity(
+ entityId: string,
+ entityType: SoupEntityTag
+): Promise<void> {
+ const { storageServiceClient } = await import('@service-storage/client');
+
+ const filter = buildSingleEntityFilter(entityType, entityId);
+
+ if (!filter) {
+ invalidateSoupEntity(entityId);
+ return;
+ }
+
+ const result = await storageServiceClient.getSoupItems({
+ params: {},
+ body: filter,
+ });
+
+ if (isErr(result)) return;
+
+ const [, page] = result;
+ if (!page.items.length) return;
+
+ const item = page.items[0];
+
+ if (hasSoupEntity(entityId)) {
+ optimisticUpdateSoupEntity(item);
+ } else {
+ insertSoupEntity(item);
+ }
+}
+
+// UUID that matches no real entity — used to zero out soup filters
+// so omitted entity types return nothing instead of everything.
+const NIL_ID = '00000000-0000-0000-0000-000000000000';
+
+/** @private */
+export function buildSingleEntityFilter(
+ entityType: SoupEntityTag,
+ entityId: string
+): PostSoupRequest | null {
+ const base: PostSoupRequest = {
+ limit: 1,
+ document_filters: { document_ids: [NIL_ID] },
+ chat_filters: { chat_ids: [NIL_ID] },
+ channel_filters: { channel_ids: [NIL_ID] },
+ project_filters: { project_ids: [NIL_ID] },
+ email_filters: { importance: false },
+ };
+ return (
+ match(entityType)
+ .with('document', () => ({
+ ...base,
+ document_filters: { document_ids: [entityId] },
+ }))
+ .with('chat', () => ({ ...base, chat_filters: { chat_ids: [entityId] } }))
+ .with('channel', () => ({
+ ...base,
+ channel_filters: { channel_ids: [entityId] },
+ }))
+ .with('project', () => ({
+ ...base,
+ project_filters: { project_ids: [entityId] },
+ }))
+ //TODO: need to add backend support for email threads
+ .with('emailThread', () => null)
+ .exhaustive()
+ );
+}
+
+/** @private */
+function getSearchResultId(result: UnifiedSearchResponseItem): string {
+ return match(result)
+ .with({ type: 'document' }, (r) => r.document_id)
+ .with({ type: 'chat' }, (r) => r.chat_id)
+ .with({ type: 'channel' }, (r) => r.channel_id)
+ .with({ type: 'email' }, (r) => r.thread_id)
+ .with({ type: 'project' }, (r) => r.id)
+ .exhaustive();
+}
+
+/** @private */
+function snapshotSoup(): [
+ QueryKey,
+ InfiniteData<SoupPage, unknown> | undefined,
+][] {
+ return queryClient.getQueriesData<InfiniteData<SoupPage, unknown>>({
+ queryKey: soupKeys.items._def,
+ });
+}
+
+/** @private */
+function restoreSnapshot(
+ snapshot: [QueryKey, InfiniteData<SoupPage, unknown> | undefined][]
+): void {
+ for (const [key, data] of snapshot) {
+ queryClient.setQueryData(key, data);
+ }
+}
diff --git a/js/app/packages/queries/soup/normalized-cache/types.ts b/js/app/packages/queries/soup/normalized-cache/types.ts
new file mode 100644
index 0000000000..189b62e1ab
--- /dev/null
+++ b/js/app/packages/queries/soup/normalized-cache/types.ts
@@ -0,0 +1,30 @@
+import type { SoupApiItem } from '@service-storage/generated/schemas';
+
+export interface SoupTransaction {
+ rollback(): void;
+}
+
+export type SoupEntityTag = SoupApiItem['tag'];
+
+type SoupItemData<T extends SoupEntityTag> = Extract<
+ SoupApiItem,
+ { tag: T }
+>['data'];
+
+// Channel's inner Channel object (for partial nested updates like { channel: { id, name } })
+type ChannelInner = SoupItemData<'channel'>['channel'];
+
+// Partial data: require the entity ID, all else optional.
+// Channel is special — ID lives at data.channel.id.
+type SoupPartialData<T extends SoupEntityTag> = T extends 'channel'
+ ? { channel: Partial<ChannelInner> & Pick<ChannelInner, 'id'> } & Partial<
+ Omit<SoupItemData<'channel'>, 'channel'>
+ >
+ : Partial<SoupItemData<T>> & { id: string };
+
+// A partial soup entity for optimistic updates.
+export type SoupEntityPartial<T extends SoupEntityTag = SoupEntityTag> = {
+ tag: T;
+ data: SoupPartialData<T>;
+ frecency_score: number;
+};