π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(resourceManager): propagate deleted and renamed hits into the persisted search replicas (#20763)
Arvin Xuc6d2f1c12939
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsxindex 20ed62316f0..978e24e61f0 100644--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({publishFileToWorkspace: vi.fn(async (_id: string) => undefined),setFileVisibility: vi.fn(async (_id: string, _visibility: string) => undefined),refreshFileList: vi.fn(async () => undefined),+ removeSearchHits: vi.fn(),revalidateTree: vi.fn(async () => undefined),useSendToMessengerMenuItem: vi.fn((_params: SendToMessengerParams) => undefined),}));@@ -40,6 +41,9 @@ vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: truevi.mock('@/features/ResourceManager/components/KnowledgeBaseListProvider', () => ({useKnowledgeBaseListContext: () => [],}));+vi.mock('@/features/ResourceManager/store', () => ({+ useResourceManagerStore: { getState: () => ({ removeSearchHits: mocks.removeSearchHits }) },+}));vi.mock('@/store/user', () => ({ useUserStore: () => 'user-1' }));vi.mock('@/store/user/selectors', () => ({ userProfileSelectors: { userId: vi.fn() } }));vi.mock('@/store/file', () => ({@@ -330,6 +334,32 @@ describe('useFileItemDropdown β workspace resource permissions', () => {);});+ it('drops the deleted row from the cached search results', async () => {+ // Regression: deleting a hit from the search overlay updated the file store+ // and the sidebar tree only, so the persisted search replica kept the hit+ // and repainted it on the next revisit or reload.+ const { result } = renderHook(() => useFileItemDropdown(baseParams as any));+ const deleteItem = result.current.menuItems().find((item) => item?.key === 'delete') as any;+ await deleteItem.onClick({ domEvent: { stopPropagation: vi.fn() } });++ mocks.confirmModal.mock.calls.at(-1)![0].onOk();++ await waitFor(() => expect(mocks.removeSearchHits).toHaveBeenCalledWith(['resource-id']));+ });++ it('keeps the cached search results when the delete fails', async () => {+ mocks.deleteResource.mockRejectedValueOnce(new Error('boom'));+ const { result } = renderHook(() => useFileItemDropdown(baseParams as any));+ const deleteItem = result.current.menuItems().find((item) => item?.key === 'delete') as any;+ await deleteItem.onClick({ domEvent: { stopPropagation: vi.fn() } });++ mocks.confirmModal.mock.calls.at(-1)![0].onOk();++ await waitFor(() => expect(mocks.deleteResource).toHaveBeenCalled());+ await Promise.resolve();+ expect(mocks.removeSearchHits).not.toHaveBeenCalled();+ });+it("falls back to the explorer's folder for a row the tree does not own", async () => {const { result } = renderHook(() => useFileItemDropdown(baseParams as any));const deleteItem = result.current.menuItems().find((item) => item?.key === 'delete') as any;diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsxindex d041c81c2e7..a304fd43bf2 100644--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.tsx@@ -24,6 +24,7 @@ import RepoIcon from '@/components/LibIcon';import { useSendToMessengerMenuItem } from '@/features/Messenger/PushResourceModal/useSendToMessengerMenuItem';import { useKnowledgeBaseListContext } from '@/features/ResourceManager/components/KnowledgeBaseListProvider';import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';+import { useResourceManagerStore } from '@/features/ResourceManager/store';import { buildPagePath } from '@/features/ResourceManager/utils/resourcePath';import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';import { useAppOrigin } from '@/hooks/useAppOrigin';@@ -486,6 +487,9 @@ export const useFileItemDropdown = ({// `dropNodes` forgets the whole subtree synchronously.onDeleted?.();void useTreeStore.getState().dropNodes([id], treeParentKey);+ // The search overlays persist their hits per query, so the+ // deleted row must leave those too or it repaints there.+ useResourceManagerStore.getState().removeSearchHits([id]);await refreshFileList({ revalidateResources: false });toast.success(t('FileManager.actions.deleteSuccess'));diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.test.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.test.tsnew file mode 100644index 00000000000..0e068bd50d2--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.test.ts@@ -0,0 +1,78 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ patchSearchHit: vi.fn(),+ revalidateTree: vi.fn(),+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { error: vi.fn(), success: vi.fn() },+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock('@/features/ResourceManager/store', () => ({+ useResourceManagerStore: { getState: () => ({ patchSearchHit: mocks.patchSearchHit }) },+}));+vi.mock('@/store/tree', () => ({+ useTreeStore: { getState: () => ({ revalidate: mocks.revalidateTree }) },+}));+vi.mock('@/store/file', () => ({+ useFileStore: { getState: () => ({ queryParams: { parentId: 'parent-id' } }) },+}));++const { useFileListItemRename } = await import('./useFileListItemRename');++const renderRename = (+ updateResource: (id: string, payload: { name: string }) => Promise<unknown>,+) =>+ renderHook(() =>+ useFileListItemRename({+ id: 'file-1',+ isFolder: false,+ name: 'old name',+ refreshFileList: vi.fn(async () => undefined),+ setPendingRenameItemId: vi.fn(),+ updateResource,+ }),+ );++const rename = async (result: ReturnType<typeof renderRename>['result'], value: string) => {+ act(() => result.current.handleRenameStart());+ act(() => result.current.setRenamingValue(value));+ await act(async () => {+ await result.current.handleRenameConfirm();+ });+};++describe('useFileListItemRename', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('carries the new name into the cached search results', async () => {+ // Regression: renaming a search hit updated the file store and the tree+ // only, while the search overlay kept rendering its own persisted replica+ // with the old name (and old query membership).+ const updateResource = vi.fn(async () => undefined);+ const { result } = renderRename(updateResource);++ await rename(result, ' new name ');++ expect(updateResource).toHaveBeenCalledWith('file-1', { name: 'new name' });+ expect(mocks.patchSearchHit).toHaveBeenCalledWith('file-1', { name: 'new name' });+ });++ it('leaves the cached search results alone when the rename fails', async () => {+ const { result } = renderRename(+ vi.fn(async () => {+ throw new Error('boom');+ }),+ );++ await rename(result, 'new name');++ expect(mocks.patchSearchHit).not.toHaveBeenCalled();+ });+});diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.tsindex 4356762480d..42c12d6df86 100644--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.ts+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemRename.ts@@ -2,6 +2,7 @@ import { toast } from '@lobehub/ui/base-ui';import { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useResourceManagerStore } from '@/features/ResourceManager/store';import { useEventCallback } from '@/hooks/useEventCallback';import { useTreeStore } from '@/store/tree';@@ -59,7 +60,12 @@ export const useFileListItemRename = ({}try {- await updateResource(id, { name: renamingValue.trim() });+ const nextName = renamingValue.trim();+ await updateResource(id, { name: nextName });+ // The search overlays render their own persisted replica, not the file+ // store: carry the new name into every cached query (and let the mounted+ // one refetch, since a rename can change which queries the hit matches).+ useResourceManagerStore.getState().patchSearchHit(id, { name: nextName });// Revalidate tree for the parent folder β the explorer subscription will reconcileconst { queryParams } = await import('@/store/file').then((m) => m.useFileStore.getState());const parentId = queryParams?.parentId ?? '';diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.tsindex 80f7975383f..f6471caa7f1 100644--- a/src/features/ResourceManager/store/action.ts+++ b/src/features/ResourceManager/store/action.ts@@ -4,6 +4,7 @@ import type { StateCreator } from 'zustand/vanilla';import type { ResourceManagerMode } from '@/features/ResourceManager';import {createReplicaSlice,+ linkReplicaEntity,readReplicaStoredKeys,recordLens,type ReplicaPageResult,@@ -145,6 +146,11 @@ export class ResourceManagerStoreActionImpl {readonly #set: Setter;readonly #explorerSearch;readonly #hierarchySearch;+ /**+ * A resource as a search hit: both search surfaces hold copies of the same+ * `ResourceItem`, in every query variant they have loaded or persisted.+ */+ readonly #searchHits;/** Query entry keys each surface has used, oldest first (see `#trackRecentSearch`). */readonly #recentExplorerSearches: string[] = [];readonly #recentHierarchySearches: string[] = [];@@ -186,6 +192,11 @@ export class ResourceManagerStoreActionImpl {view: hierarchySearchLens,viewFields: (params) => ({ searchParams: params }),});++ this.#searchHits = linkReplicaEntity<ResourceItem>([+ this.#explorerSearch,+ this.#hierarchySearch,+ ]);}/**@@ -313,6 +324,35 @@ export class ResourceManagerStoreActionImpl {await revalidateReplica(explorerSearchResource);};+ /**+ * Drop deleted resources from every cached search, after the delete landed.+ *+ * The search replicas persist each query's head page, so a deleted hit has to+ * leave every variant β the one on screen, the ones left in memory and the+ * ones only IndexedDB still holds β or a revisit / reload paints it again. An+ * entity removal also guards hydrates already in flight, so a row read before+ * the delete cannot bring the hit back. The mounted searches then refetch, so+ * their totals and paging follow the server.+ */+ removeSearchHits = (ids: string[]): void => {+ if (ids.length === 0) return;+ for (const id of ids) this.#searchHits.remove(id);+ void this.#searchHits.revalidate();+ };++ /**+ * Apply a confirmed resource change (e.g. a rename) to every cached search.+ *+ * Every loaded and persisted variant gets the new fields, so no revisit or+ * reload paints the old name. A rename can also move the hit into or out of a+ * query, which only the server can decide: the mounted searches refetch so+ * their membership is recomputed (unmounted ones refetch when shown again).+ */+ patchSearchHit = (id: string, patch: Partial<ResourceItem>): void => {+ this.#searchHits.update(id, (item) => ({ ...item, ...patch }));+ void this.#searchHits.revalidate();+ };+clearSelectAllState = (): void => {this.#set({ selectAllState: 'none', selectedFileIds: [], selectionTotal: undefined });};@@ -368,12 +408,9 @@ export class ResourceManagerStoreActionImpl {await fileStore.deleteResources(resourceIds);void useTreeStore.getState().dropNodes(resourceIds, currentFolderKey);- // The explorer's own list drops the rows optimistically; the overlay- // mirrors cached replica pages, so drop them there too β from memory and- // from every stored page, loaded here or not β or a deleted hit would be- // painted again, on screen and on the next reload.- for (const id of resourceIds) this.#explorerSearch.updateEntity(id, () => undefined);- void revalidateReplica(explorerSearchResource);+ // The explorer's own list drops the rows optimistically; the search+ // surfaces mirror cached replica pages, so drop them there too.+ this.removeSearchHits(resourceIds);this.clearSelectAllState();return;diff --git a/src/features/ResourceManager/store/replica.test.ts b/src/features/ResourceManager/store/replica.test.tsindex 2ee3ac9eccb..15ff27b4319 100644--- a/src/features/ResourceManager/store/replica.test.ts+++ b/src/features/ResourceManager/store/replica.test.ts@@ -595,4 +595,99 @@ describe('ResourceManager search replicas', () => {// against the new one, so the whole cleanup must be abandoned.expect(remove).not.toHaveBeenCalled();});+ /** Persist a search row an earlier session wrote, and list it in the index. */+ const seedStored = async (+ resource: typeof explorerSearchResource | typeof hierarchySearchResource,+ queryKey: string,+ searchParams: ExplorerSearchParams | HierarchySearchParams,+ items: ResourceItem[],+ ) => {+ await resource.storage!.set(+ { queryKey, scope },+ {+ data: {+ currentPage: 0,+ hasMore: false,+ items,+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ searchParams,+ total: items.length,+ } as any,+ updatedAt: 1,+ },+ );+ await resource.storage!.set(+ { queryKey: REPLICA_INDEX_KEY, scope },+ { data: [queryKey] as any, updatedAt: 1 },+ );+ };++ const storedIds = async (+ resource: typeof explorerSearchResource | typeof hierarchySearchResource,+ queryKey: string,+ ) => ids((await resource.storage!.get({ queryKey, scope }))?.data as any);++ it('drops a deleted hit from every loaded and persisted search variant', async () => {+ // Regression: deleting a hit only patched the file store and the tree, so+ // the persisted search rows kept it and a revisit / reload repainted it.+ const shownParams: ExplorerSearchParams = { pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'shown' };+ fetchSpy.mockResolvedValue(page([item('gone'), item('kept')], 2));+ await seedStored(explorerSearchResource, EXPLORER_KEY, EXPLORER_PARAMS, [+ item('gone'),+ item('other'),+ ]);+ await seedStored(hierarchySearchResource, HIERARCHY_KEY, HIERARCHY_PARAMS, [item('gone')]);++ renderHook(() => useResourceManagerStore((s) => s.useFetchExplorerSearch)(shownParams), {+ wrapper,+ });+ await waitFor(() => expect(ids(explorerEntry(shownParams))).toEqual(['gone', 'kept']));++ // The server no longer has the hit once the delete landed.+ fetchSpy.mockResolvedValue(page([item('kept')], 1));+ act(() => useResourceManagerStore.getState().removeSearchHits(['gone']));++ expect(ids(explorerEntry(shownParams))).toEqual(['kept']);+ await waitFor(async () => {+ expect(await storedIds(explorerSearchResource, EXPLORER_KEY)).toEqual(['other']);+ // A row holding nothing but the deleted hit has nothing left to paint.+ expect(await storedIds(hierarchySearchResource, HIERARCHY_KEY)).toEqual([]);+ });+ });++ it('carries a renamed hit into every search variant and refetches the mounted one', async () => {+ // Regression: renaming a hit left the old name in the search replicas, so+ // the overlay kept painting it (and its old query membership) from storage.+ const shownParams: ExplorerSearchParams = { pageSize: DEFAULT_SEARCH_PAGE_SIZE, q: 'shown' };+ fetchSpy.mockResolvedValue(page([item('hit')], 1));+ await seedStored(explorerSearchResource, EXPLORER_KEY, EXPLORER_PARAMS, [item('hit')]);+ await seedStored(hierarchySearchResource, HIERARCHY_KEY, HIERARCHY_PARAMS, [item('hit')]);++ renderHook(() => useResourceManagerStore((s) => s.useFetchExplorerSearch)(shownParams), {+ wrapper,+ });+ await waitFor(() => expect(ids(explorerEntry(shownParams))).toEqual(['hit']));+ const fetches = fetchSpy.mock.calls.length;++ // Renamed away from the keyword: only the server can say it left the query.+ fetchSpy.mockResolvedValue(page([], 0));+ act(() => useResourceManagerStore.getState().patchSearchHit('hit', { name: 'renamed' }));++ expect(explorerEntry(shownParams)?.items[0]?.name).toBe('renamed');+ await waitFor(async () => {+ const explorerRow = await explorerSearchResource.storage!.get({+ queryKey: EXPLORER_KEY,+ scope,+ });+ const hierarchyRow = await hierarchySearchResource.storage!.get({+ queryKey: HIERARCHY_KEY,+ scope,+ });+ expect((explorerRow?.data as any)?.items[0]?.name).toBe('renamed');+ expect((hierarchyRow?.data as any)?.items[0]?.name).toBe('renamed');+ });+ // The mounted search refetches, so the membership change lands.+ await waitFor(() => expect(fetchSpy.mock.calls.length).toBeGreaterThan(fetches));+ await waitFor(() => expect(ids(explorerEntry(shownParams))).toEqual([]));+ });});diff --git a/src/store/tree/actions.test.ts b/src/store/tree/actions.test.tsindex 3727bd9f27d..f6c0f32cb91 100644--- a/src/store/tree/actions.test.ts+++ b/src/store/tree/actions.test.ts@@ -12,6 +12,7 @@ const {mockCollapseHierarchySearch,mockDeleteResources,mockGetKnowledgeItems,+ mockPatchSearchHit,mockRefreshFileList,mockResourceMove,mockRevalidateReplica,@@ -22,6 +23,7 @@ const {mockCollapseHierarchySearch: vi.fn(),mockDeleteResources: vi.fn(),mockGetKnowledgeItems: vi.fn(),+ mockPatchSearchHit: vi.fn(),mockRefreshFileList: vi.fn(),mockResourceMove: vi.fn(),mockRevalidateReplica: vi.fn(),@@ -36,7 +38,10 @@ vi.mock('@/libs/replica', async () => ({vi.mock('@/features/ResourceManager/store', () => ({useResourceManagerStore: {- getState: () => ({ collapseHierarchySearch: mockCollapseHierarchySearch }),+ getState: () => ({+ collapseHierarchySearch: mockCollapseHierarchySearch,+ patchSearchHit: mockPatchSearchHit,+ }),},}));@@ -471,6 +476,10 @@ describe('TreeActionImpl optimistic moves (destination and other mutations)', ()mockRefreshFileList.mockReset();mockResourceMove.mockReset();mockStoreMove.mockReset();+ // Reset explicitly rather than relying on the runner's `clearMocks`: the+ // rename tests assert both a patch call and the absence of one.+ mockPatchSearchHit.mockReset();+ mockUpdateResource.mockReset();fileStoreState.resourceMap = new Map();mockResourceMove.mockResolvedValue({});mockRefreshFileList.mockResolvedValue(undefined);@@ -521,6 +530,24 @@ describe('TreeActionImpl optimistic moves (destination and other mutations)', ()expect(mockUpdateResource).toHaveBeenCalledWith('doc-a', { name: 'Renamed' });expect(state.children['']?.find((i) => i.id === 'doc-a')?.name).toBe('Renamed');expect(revalidateSpy).toHaveBeenCalledWith('');+ // Regression: the search surfaces keep their own persisted hits, so a+ // sidebar rename has to reach them or they repaint the old name.+ expect(mockPatchSearchHit).toHaveBeenCalledWith('doc-a', { name: 'Renamed' });+ });++ it('renameItem leaves the cached searches alone when the rename fails', async () => {+ const state = createState();+ state.children = { '': [folder, docA] };+ const actions = new TreeActionImpl(+ createSetter(() => state),+ () => state,+ );+ vi.spyOn(actions, 'revalidate').mockResolvedValue();+ mockUpdateResource.mockRejectedValue(new Error('boom'));++ await withTimeout(actions.renameItem('doc-a', '', 'Renamed')).catch(() => undefined);++ expect(mockPatchSearchHit).not.toHaveBeenCalled();});it('removeItems settles, drops the folder caches, and revalidates the parent', async () => {diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.tsindex 8760aec1dbd..a9657006075 100644--- a/src/store/tree/actions.ts+++ b/src/store/tree/actions.ts@@ -567,6 +567,9 @@ export class TreeActionImpl {tx.mutation = async () => {await resourceService.updateResource(itemId, { name: newName });+ // The search surfaces keep their own persisted copies of the hit.+ const { useResourceManagerStore } = await import('@/features/ResourceManager/store');+ useResourceManagerStore.getState().patchSearchHit(itemId, { name: newName });const { useFileStore } = await import('@/store/file');await useFileStore.getState().refreshFileList();};