π€― 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(resource): enable multi-select and batch actions on drive search results (#21576)
Arvin Xua11e748b6edb
diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex 8038ee50aff..b1e766f790f 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -1030,7 +1030,6 @@"src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/WebpageFileItem.tsx","src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx","src/features/ResourceManager/components/Explorer/MasonryView/Skeleton.tsx",- "src/features/ResourceManager/components/Explorer/MasonryView/index.tsx","src/features/ResourceManager/components/Explorer/ToolBar/SourceFilter.tsx","src/features/ResourceManager/components/FolderTree/index.tsx","src/features/ResourceManager/components/LibraryHierarchy/TreeSkeleton.tsx",diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsxindex a05959ab7a3..1ddac82df52 100644--- a/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx@@ -24,6 +24,8 @@ interface ListViewHeaderProps {data: FileListItem[];hasMore: boolean;showUploader?: boolean;+ /** Size of the listed pool; defaults to the folder list's total. */+ total?: number;}const ListViewHeader = ({@@ -31,6 +33,7 @@ const ListViewHeader = ({data,hasMore,showUploader = true,+ total: poolTotal,}: ListViewHeaderProps) => {const { t } = useTranslation(['components', 'file']);const updateColumnWidth = useGlobalStore((s) => s.updateResourceManagerColumnWidth);@@ -47,6 +50,7 @@ const ListViewHeader = ({} = useExplorerSelectionSummary({data,hasMore,+ total: poolTotal,});const isAllResultsSelected = selectAllState === 'all' && total === selectedCount;const selectedLabelKey =diff --git a/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx b/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsxindex 69ace31af40..c8af3dbfc64 100644--- a/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/VirtualizedFileList.tsx@@ -20,6 +20,15 @@ interface VirtualizedFileListProps {};data: FileListItem[];hasMore: boolean;+ /**+ * Viewport height. Defaults to the folder list's viewport-derived height; a+ * consumer inside a sized flex container passes `'100%'` to fill it.+ */+ height?: string;+ /** Next-page loader; defaults to the folder list's. */+ loadMore?: () => Promise<void>;+ /** Failure of a page past the head, rendered as a retry row in the footer. */+ loadMoreError?: unknown;showUploader?: boolean;virtuosoRef: RefObject<VirtuosoHandle | null>;}@@ -28,6 +37,9 @@ const VirtualizedFileList = ({columnWidths,data,hasMore,+ height = 'calc(100vh - 100px)',+ loadMore,+ loadMoreError,showUploader = true,virtuosoRef,}: VirtualizedFileListProps) => {@@ -43,6 +55,8 @@ const VirtualizedFileList = ({columnWidths,dataLength: data.length,hasMore,+ loadMore,+ loadMoreError,showUploader,});const dataRef = useRef<FileListItem[]>(data);@@ -101,7 +115,7 @@ const VirtualizedFileList = ({initialItemCount={30}overscan={48 * 5}ref={virtuosoRef}- style={{ height: 'calc(100vh - 100px)' }}+ style={{ height }}itemContent={useCallback((index: number, item: FileListItem) => {if (!item) return null;diff --git a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsx b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsxnew file mode 100644index 00000000000..938ba4c3b54--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.test.tsx@@ -0,0 +1,49 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useExplorerInfiniteScroll } from './useExplorerInfiniteScroll';++const columnWidths = { date: 100, name: 200, size: 80, uploader: 80 };+const failedPage = new Error('page 2 failed');++describe('useExplorerInfiniteScroll', () => {+ // Auto-loading must stop on a failed page, otherwise every scroll frame+ // re-issues the request that just failed.+ it('should stop auto-loading while the next page is in error', async () => {+ const loadMore = vi.fn().mockResolvedValue(undefined);+ const { result } = renderHook(() =>+ useExplorerInfiniteScroll({+ columnWidths,+ dataLength: 2,+ hasMore: true,+ loadMore,+ loadMoreError: failedPage,+ }),+ );++ await act(() => result.current.handleEndReached());++ expect(loadMore).not.toHaveBeenCalled();+ });++ // Regression: the retry path went through the guarded handler, so the Retry+ // action on the failed footer did nothing at all.+ it('should let an explicit retry through the error guard', async () => {+ const loadMore = vi.fn().mockResolvedValue(undefined);+ const { result } = renderHook(() =>+ useExplorerInfiniteScroll({+ columnWidths,+ dataLength: 2,+ hasMore: true,+ loadMore,+ loadMoreError: failedPage,+ }),+ );++ await act(async () => {+ await result.current.retryLoadMore();+ });++ expect(loadMore).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsxindex e683469a704..339b8721054 100644--- a/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx+++ b/src/features/ResourceManager/components/Explorer/ListView/useExplorerInfiniteScroll.tsx@@ -1,5 +1,6 @@import { useCallback, useState } from 'react';+import AsyncError from '@/components/AsyncError';import { useFileStore } from '@/store/file';import ListViewSkeleton from './Skeleton';@@ -13,6 +14,14 @@ interface UseExplorerInfiniteScrollOptions {};dataLength: number;hasMore: boolean;+ /** Next-page loader; defaults to the folder list's. */+ loadMore?: () => Promise<void>;+ /**+ * Failure of a page past the head. The list stops auto-loading while it is+ * set, so scrolling cannot hammer a failing request, and the footer turns into+ * an explicit retry instead of a missing loading row.+ */+ loadMoreError?: unknown;showUploader?: boolean;}@@ -20,32 +29,58 @@ export const useExplorerInfiniteScroll = ({columnWidths,dataLength,hasMore,+ loadMore,+ loadMoreError,showUploader = true,}: UseExplorerInfiniteScrollOptions) => {const loadMoreResources = useFileStore((s) => s.loadMoreResources);+ const loadNextPage = loadMore ?? loadMoreResources;const [isLoadingMore, setIsLoadingMore] = useState(false);- const handleEndReached = useCallback(async () => {+ // The loader itself, without the guards: a manual retry has to run while the+ // recorded error is still set β the replica only clears it when the request+ // starts, so guarding on it here would make the Retry action a no-op.+ const runLoadMore = useCallback(async () => {if (!hasMore || isLoadingMore) return;setIsLoadingMore(true);try {- await loadMoreResources();+ await loadNextPage();} finally {setIsLoadingMore(false);}- }, [hasMore, isLoadingMore, loadMoreResources]);+ }, [hasMore, isLoadingMore, loadNextPage]);++ const handleEndReached = useCallback(async () => {+ // Auto-loading stops on a failed page so scrolling cannot hammer it; the+ // footer's retry is the way back.+ if (loadMoreError) return;++ await runLoadMore();+ }, [loadMoreError, runLoadMore]);++ const retryLoadMore = useCallback(() => runLoadMore(), [runLoadMore]);const Footer = useCallback(() => {+ if (loadMoreError)+ return (+ <AsyncError+ error={loadMoreError}+ retrying={isLoadingMore}+ variant={'inline'}+ onRetry={retryLoadMore}+ />+ );if (isLoadingMore && hasMore)return <ListViewSkeleton columnWidths={columnWidths} showUploader={showUploader} />;if (hasMore === false && dataLength > 0) return <div aria-hidden style={{ height: 96 }} />;return null;- }, [columnWidths, dataLength, hasMore, isLoadingMore, showUploader]);+ }, [columnWidths, dataLength, hasMore, isLoadingMore, loadMoreError, retryLoadMore, showUploader]);return {Footer,handleEndReached,+ retryLoadMore,};};diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/SelectionToolbar.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/SelectionToolbar.tsxnew file mode 100644index 00000000000..472ce1642d0--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/MasonryView/SelectionToolbar.tsx@@ -0,0 +1,146 @@+import { Button, Checkbox, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { type ReactNode, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { type FileListItem } from '@/types/files';++import {+ useExplorerSelectionActions,+ useExplorerSelectionSummary,+} from '../hooks/useExplorerSelection';++const styles = stylex.create({+ selectAllHint: {+ backgroundColor: cssVar.colorFillTertiary,+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ color: cssVar.colorTextDescription,+ fontSize: 12,+ insetBlockStart: 53,+ paddingBlock: 8,+ paddingInline: 4,+ position: 'sticky',+ zIndex: 1,+ },+ toolbar: {+ backgroundColor: cssVar.colorBgContainer,+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ insetBlockStart: 0,+ paddingBlock: 12,+ paddingInline: 4,+ position: 'sticky',+ zIndex: 1,+ },+});++interface SelectionToolbarProps {+ data: FileListItem[];+ /** Shown after the count, e.g. the source filter chips. */+ extra?: ReactNode;+ hasMore: boolean;+ /** Item count shown while nothing is selected. */+ itemCount: number;+ /** Size of the listed pool; defaults to the folder list's total. */+ total?: number;+}++/**+ * Select-all checkbox, selected count and "select all N" hint above a grid of+ * resources. Selection lives in the ResourceManager store, so the header's+ * batch actions act on whatever is checked here.+ */+const SelectionToolbar = ({+ data,+ extra,+ hasMore,+ itemCount,+ total: poolTotal,+}: SelectionToolbarProps) => {+ const { t } = useTranslation('components');+ const { handleSelectAll, handleSelectAllResources } = useExplorerSelectionActions(data);+ const {+ allSelected,+ hasSelectableItems,+ indeterminate,+ selectAllState,+ selectableCount,+ selectedCount,+ showSelectAllHint,+ total,+ } = useExplorerSelectionSummary({ data, hasMore, total: poolTotal });++ const isAllResultsSelected = selectAllState === 'all' && total === selectedCount;+ const allSelectedLabelKey = total+ ? isAllResultsSelected+ ? 'FileManager.total.allSelectedCount'+ : 'FileManager.total.selectedCount'+ : 'FileManager.total.allSelectedFallback';++ const handleSelectAllResults = useCallback(+ (checked?: boolean) => {+ if (checked !== false && !hasMore) {+ void handleSelectAllResources();+ return;+ }++ handleSelectAll(checked);+ },+ [handleSelectAll, handleSelectAllResources, hasMore],+ );++ return (+ <>+ <Flexbox horizontal align={'center'} gap={8} {...stylex.props(styles.toolbar)}>+ <Checkbox+ checked={allSelected}+ disabled={!hasSelectableItems}+ indeterminate={indeterminate}+ onChange={handleSelectAllResults}+ />+ <span>+ {selectedCount > 0 || selectAllState === 'all'+ ? t(+ selectAllState === 'all' ? allSelectedLabelKey : 'FileManager.total.selectedCount',+ { count: selectedCount },+ )+ : t('FileManager.total.fileCount', { count: itemCount })}+ </span>+ <Flexbox flex={1} />+ {extra}+ </Flexbox>+ {showSelectAllHint && (+ <Flexbox+ horizontal+ align={'center'}+ gap={6}+ paddingInline={4}+ wrap={'wrap'}+ {...stylex.props(styles.selectAllHint)}+ >+ <span>+ {t(+ selectAllState === 'all'+ ? allSelectedLabelKey+ : 'FileManager.total.loadedSelectedCount',+ { count: selectedCount },+ )}+ </span>+ {selectAllState !== 'all' && (+ <Button size={'small'} type={'link'} onClick={handleSelectAllResources}>+ {total && total > selectableCount+ ? t('FileManager.total.selectAll', { count: total })+ : t('FileManager.total.selectAllFallback')}+ </Button>+ )}+ </Flexbox>+ )}+ </>+ );+};++export default SelectionToolbar;diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsxindex b704d235dc4..c1b8650ae29 100644--- a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx+++ b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx@@ -1,6 +1,6 @@'use client';-import { Button, Center, Checkbox, createStaticStyles, cssVar, Flexbox } from '@lobehub/ui';+import { Center, cssVar } from '@lobehub/ui';import { VirtuosoMasonry } from '@virtuoso.dev/masonry';import { type UIEvent } from 'react';import { memo, useCallback, useMemo, useState } from 'react';@@ -12,45 +12,15 @@ import { useFileStore } from '@/store/file';import { type FileListItem } from '@/types/files';import type { ResourceQueryParams } from '@/types/resource';-import {- useExplorerSelectionActions,- useExplorerSelectionSummary,-} from '../hooks/useExplorerSelection';+import { useExplorerSelectionActions } from '../hooks/useExplorerSelection';import { isQueryNavigation } from '../isQueryNavigation';import SourceFilter from '../ToolBar/SourceFilter';import { useContainerMasonryColumnCount } from '../useMasonryColumnCount';import MasonryItemWrapper from './MasonryItem/MasonryItemWrapper';+import SelectionToolbar from './SelectionToolbar';import MasonryViewSkeleton from './Skeleton';import { useMasonryViewState } from './useMasonryViewState';-const styles = createStaticStyles(({ css }) => ({- selectAllHint: css`- position: sticky;- z-index: 1;- inset-block-start: 53px;-- padding-block: 8px;- padding-inline: 4px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- font-size: 12px;- color: ${cssVar.colorTextDescription};-- background: ${cssVar.colorFillTertiary};- `,- toolbar: css`- position: sticky;- z-index: 1;- inset-block-start: 0;-- padding-block: 12px;- padding-inline: 4px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- background: ${cssVar.colorBgContainer};- `,-}));-interface MasonryViewProps {isLoading?: boolean;isValidating?: boolean;@@ -121,38 +91,8 @@ const MasonryView = memo(function MasonryView({isValidating: effectiveIsValidating,viewMode,});- const {- handleSelectAll,- handleSelectAllResources,- isItemSelectable,- selectAllState,- selectedFileIds,- toggleItemSelection,- } = useExplorerSelectionActions(data);- const {- allSelected,- hasSelectableItems,- indeterminate,- selectableCount,- selectedCount,- showSelectAllHint,- total,- } = useExplorerSelectionSummary({- data,- hasMore,- });- const isAllResultsSelected = selectAllState === 'all' && total === selectedCount;- const handleSelectAllResults = useCallback(- (checked?: boolean) => {- if (checked !== false && !hasMore) {- void handleSelectAllResources();- return;- }-- handleSelectAll(checked);- },- [handleSelectAll, handleSelectAllResources, hasMore],- );+ const { isItemSelectable, selectAllState, selectedFileIds, toggleItemSelection } =+ useExplorerSelectionActions(data);// Handle automatic load more when scrolling to bottomconst handleLoadMore = useCallback(async () => {@@ -217,74 +157,12 @@ const MasonryView = memo(function MasonryView({ref={setContainer}style={{ paddingBlockEnd: 24, paddingBlockStart: 12, paddingInline: 24 }}>- <Flexbox horizontal align={'center'} className={styles.toolbar} gap={8}>- <Checkbox- checked={allSelected}- disabled={!hasSelectableItems}- indeterminate={indeterminate}- onChange={handleSelectAllResults}- />- <span>- {selectedCount > 0 || selectAllState === 'all'- ? t(- selectAllState === 'all'- ? total- ? isAllResultsSelected- ? 'FileManager.total.allSelectedCount'- : 'FileManager.total.selectedCount'- : 'FileManager.total.allSelectedFallback'- : 'FileManager.total.selectedCount',- {- count: selectedCount,- ns: 'components',- },- )- : t('FileManager.total.fileCount', {- count: resourceTotal || dataLength,- ns: 'components',- })}- </span>- <Flexbox flex={1} />- <SourceFilter />- </Flexbox>- {showSelectAllHint && (- <Flexbox- horizontal- align={'center'}- className={styles.selectAllHint}- gap={6}- paddingInline={4}- wrap={'wrap'}- >- <span>- {t(- selectAllState === 'all'- ? total- ? isAllResultsSelected- ? 'FileManager.total.allSelectedCount'- : 'FileManager.total.selectedCount'- : 'FileManager.total.allSelectedFallback'- : 'FileManager.total.loadedSelectedCount',- {- count: selectedCount,- ns: 'components',- },- )}- </span>- {selectAllState !== 'all' && (- <Button size={'small'} type={'link'} onClick={handleSelectAllResources}>- {total && total > selectableCount- ? t('FileManager.total.selectAll', {- count: total,- ns: 'components',- })- : t('FileManager.total.selectAllFallback', {- ns: 'components',- })}- </Button>- )}- </Flexbox>- )}+ <SelectionToolbar+ data={data}+ extra={<SourceFilter />}+ hasMore={hasMore}+ itemCount={resourceTotal || dataLength}+ /><VirtuosoMasonryItemContent={MasonryItemWrapper}columnCount={columnCount}diff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsxindex 13e59abeb83..5d1fc6c1be7 100644--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx@@ -1,137 +1,96 @@'use client';-import { Center, Checkbox, cssVar, Flexbox, Spin } from '@lobehub/ui';+import { Center, cssVar, Flexbox, Spin } from '@lobehub/ui';import { VirtuosoMasonry } from '@virtuoso.dev/masonry';import { SearchIcon } from 'lucide-react';-import { memo, useMemo, useState } from 'react';+import { memo, type UIEvent, useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Virtuoso } from 'react-virtuoso';+import type { VirtuosoHandle } from 'react-virtuoso';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncError from '@/components/AsyncError';import { useResourceManagerStore } from '@/features/ResourceManager/store';-import {- DEFAULT_SEARCH_PAGE_SIZE,- type ExplorerSearchParams,- explorerSearchResource,-} from '@/features/ResourceManager/store/projection';-import {- getResourceQueryVisibility,- getResourceSourceFilter,-} from '@/features/ResourceManager/store/selectors';import { useGlobalStore } from '@/store/global';import {DEFAULT_RESOURCE_MANAGER_COLUMN_WIDTHS,INITIAL_STATUS,} from '@/store/global/initialState';-import type { AsyncTaskStatus } from '@/types/asyncTask';-import { type FileListItem } from '@/types/files';-import { useExplorerSelectionEligibility } from './hooks/useExplorerSelection';-import FileListItemComponent from './ListView/ListItem';-import { getListViewMinWidth } from './ListView/ListItem/constants';+import { useExplorerSearchResults } from './hooks/useExplorerSearchResults';+import { useExplorerSelectionActions } from './hooks/useExplorerSelection';+import ListViewHeader from './ListView/ListViewHeader';+import VirtualizedFileList from './ListView/VirtualizedFileList';import MasonryItemWrapper from './MasonryView/MasonryItem/MasonryItemWrapper';-import { useMasonryColumnCount } from './useMasonryColumnCount';+import SelectionToolbar from './MasonryView/SelectionToolbar';+import { useContainerMasonryColumnCount } from './useMasonryColumnCount';const SearchResultsOverlay = memo(() => {const { t } = useTranslation('components');- const [searchQuery, libraryId, category, viewMode, listVisibility, sourceFilter] =- useResourceManagerStore((s) => [- s.searchQuery,- s.libraryId,- s.category,- s.viewMode,- s.listVisibility,- getResourceSourceFilter(s),- ]);-- const [selectedFileIds, setSelectedFileIds] = useState<string[]>([]);- const { isItemSelectable } = useExplorerSelectionEligibility();+ const [libraryId, viewMode, listVisibility] = useResourceManagerStore((s) => [+ s.libraryId,+ s.viewMode,+ s.listVisibility,+ ]);+ const {+ data,+ error,+ hasMore,+ isLoading,+ isLoadingMore,+ loadMore,+ loadMoreError,+ revalidate,+ searchParams,+ total,+ } = useExplorerSearchResults();+ const virtuosoRef = useRef<VirtuosoHandle>(null);const columnWidths = useGlobalStore((s) => ({...DEFAULT_RESOURCE_MANAGER_COLUMN_WIDTHS,...(s.status.resourceManagerColumnWidths || INITIAL_STATUS.resourceManagerColumnWidths),}));- const columnCount = useMasonryColumnCount();+ const [masonryContainer, setMasonryContainer] = useState<HTMLDivElement | null>(null);+ const columnCount = useContainerMasonryColumnCount(masonryContainer);- const isActive = !!searchQuery && searchQuery.length > 0;// Personal account has only one uploader (the user themselves), so hide the// column entirely there β it only makes sense in a workspace with multiple members.const activeWorkspaceId = useActiveWorkspaceId();const showUploader = !!activeWorkspaceId && (!!libraryId || listVisibility !== 'private');- const visibility = getResourceQueryVisibility(libraryId, listVisibility);- // Search results are a `@lobechat/replica` entry owned by the ResourceManager- // store: the head page is persisted, so re-opening a search paints the rows it- // had before the request lands. The keyword is part of the query identity, so- // the painted rows are only used while they still answer the request on screen.- const searchParams = useMemo<ExplorerSearchParams | null>(- () =>- isActive- ? {- category: libraryId ? undefined : category,- includeContentPreview: viewMode === 'masonry',- libraryId,- pageSize: DEFAULT_SEARCH_PAGE_SIZE,- q: searchQuery!,- sourceFilter,- visibility,- }- : null,- [isActive, category, libraryId, searchQuery, sourceFilter, viewMode, visibility],- );-- const { error, revalidate } = useResourceManagerStore((s) => s.useFetchExplorerSearch)(- searchParams,- );- const explorerSearchEntries = useResourceManagerStore((s) => s.explorerSearchEntries);-- // One entry per query: the entry key IS the query identity, so the rows read- // here always answer the request on screen.- const current = searchParams- ? explorerSearchEntries[explorerSearchResource.key(searchParams)]- : undefined;-- const rawData = current?.items;- const isLoading = !current && !error;- const mutate = revalidate;-- const data: FileListItem[] | undefined = useMemo(- () =>- rawData?.map((item) => ({- ...item,- chunkCount: item.chunkCount ?? null,- chunkingError: item.chunkingError ?? null,- chunkingStatus: (item.chunkingStatus ?? null) as AsyncTaskStatus | null,- embeddingError: item.embeddingError ?? null,- embeddingStatus: (item.embeddingStatus ?? null) as AsyncTaskStatus | null,- finishEmbedding: item.finishEmbedding ?? false,- url: item.url ?? '',- })),- [rawData],- );+ // Selection lives in the ResourceManager store, like the folder list's, so the+ // header's batch actions (delete, chunking, add to library) act on the hits+ // checked here.+ const { isItemSelectable, selectAllState, selectedFileIds, toggleItemSelection } =+ useExplorerSelectionActions(data);const masonryContext = useMemo(() => ({isItemSelectable,knowledgeBaseId: libraryId ?? undefined,- onSelectedChange: (id: string, checked: boolean) => {- const item = data?.find((entry) => entry.id === id);- if (!item || !isItemSelectable(item)) return;-- if (checked) {- setSelectedFileIds((prev) => [...prev, id]);- } else {- setSelectedFileIds((prev) => prev.filter((fid) => fid !== id));- }- },- selectAllState: 'loaded' as const,+ onSelectedChange: toggleItemSelection,+ selectAllState,selectFileIds: selectedFileIds,}),- [data, isItemSelectable, libraryId, selectedFileIds],+ [isItemSelectable, libraryId, selectAllState, selectedFileIds, toggleItemSelection],);- if (!isActive) return null;+ const handleMasonryScroll = useCallback(+ (e: UIEvent<HTMLDivElement>) => {+ const { clientHeight, scrollHeight, scrollTop } = e.currentTarget;+ // While a page failed, stop auto-fetching: the tail shows a retry and+ // scrolling must not re-issue the failing request on every frame.+ if (+ hasMore &&+ !isLoadingMore &&+ !loadMoreError &&+ scrollHeight - scrollTop - clientHeight < 300+ )+ void loadMore();+ },+ [hasMore, isLoadingMore, loadMore, loadMoreError],+ );++ if (!searchParams) return null;return (<div@@ -151,15 +110,15 @@ const SearchResultsOverlay = memo(() => {<Center height="100%"><Spin size="large" /></Center>- ) : error && (!data || data.length === 0) ? (+ ) : error && data.length === 0 ? (// A failed search fetch used to fall through to the "no results" state, telling// the user their query matched nothing when the request actually errored// (Read Β§1.1). Branch the failure before the no-match state; the no-match// variant below is untouched and still handles a genuine zero-result search.<Center height="100%">- <AsyncError error={error} variant={'block'} onRetry={() => mutate()} />+ <AsyncError error={error} variant={'block'} onRetry={() => revalidate()} /></Center>- ) : !data || data.length === 0 ? (+ ) : data.length === 0 ? (<Center height="100%"><Flexbox align="center" gap={8}><SearchIcon size={32} style={{ color: cssVar.colorTextQuaternary as string }} />@@ -169,118 +128,42 @@ const SearchResultsOverlay = memo(() => {</Flexbox></Center>) : viewMode === 'list' ? (- <Flexbox height={'100%'}>- <div style={{ flex: 1, overflow: 'auto hidden' }}>- <Flexbox- horizontal- align="center"- paddingInline={8}- style={{- borderBlockEnd: `1px solid ${cssVar.colorBorderSecondary}`,- color: cssVar.colorTextDescription as string,- fontSize: 12,- height: 40,- minHeight: 40,- minWidth: getListViewMinWidth(showUploader),- }}- >- <Center height={40} style={{ paddingInline: 4 }}>- <Checkbox disabled checked={false} />- </Center>- <Flexbox- justify="center"- style={{- flexShrink: 0,- height: '100%',- maxWidth: columnWidths.name,- minWidth: columnWidths.name,- paddingBlock: 6,- paddingInline: '20px 16px',- width: columnWidths.name,- }}- >- {t('FileManager.title.title')}- </Flexbox>- <Flexbox- justify="center"- style={{- flexShrink: 0,- height: '100%',- paddingBlock: 6,- paddingInlineEnd: 16,- width: columnWidths.date,- }}- >- {t('FileManager.title.createdAt')}- </Flexbox>- {showUploader && (- <Flexbox- justify="center"- style={{- flexShrink: 0,- height: '100%',- paddingBlock: 6,- paddingInlineEnd: 16,- width: columnWidths.uploader,- }}- >- {t('FileManager.title.uploader')}- </Flexbox>- )}- <Flexbox- justify="center"- style={{- flexShrink: 0,- height: '100%',- paddingBlock: 6,- paddingInlineEnd: 16,- width: columnWidths.size,- }}- >- {t('FileManager.title.size')}- </Flexbox>- </Flexbox>- <div style={{ height: 'calc(100% - 40px)', overflow: 'hidden', position: 'relative' }}>- <Virtuoso- data={data}- defaultItemHeight={48}- style={{ height: '100%' }}- itemContent={(index, item) => {- if (!item) return null;- const selectable = isItemSelectable(item);- return (- <FileListItemComponent- columnWidths={columnWidths}- index={index}- key={item.id}- selectable={selectable}- selected={selectable && selectedFileIds.includes(item.id)}- showUploader={showUploader}- onSelectedChange={(id, checked) => {- if (!selectable) return;- if (checked) {- setSelectedFileIds((prev) => [...prev, id]);- } else {- setSelectedFileIds((prev) => prev.filter((fid) => fid !== id));- }- }}- {...item}- />- );- }}- />- </div>+ // Size the list to the overlay's remaining height (below the header and+ // select-all hint): a library hero sits above the overlay, so a+ // viewport-derived height would push the last rows below the clip.+ <Flexbox height={'100%'} style={{ overflow: 'auto hidden' }}>+ <ListViewHeader+ columnWidths={columnWidths}+ data={data}+ hasMore={hasMore}+ showUploader={showUploader}+ total={total}+ />+ <div style={{ flex: 1, minHeight: 0 }}>+ <VirtualizedFileList+ columnWidths={columnWidths}+ data={data}+ hasMore={hasMore}+ height={'100%'}+ loadMore={loadMore}+ loadMoreError={loadMoreError}+ showUploader={showUploader}+ virtuosoRef={virtuosoRef}+ /></div></Flexbox>) : (- <div- style={{- flex: 1,- height: '100%',- overflowY: 'auto',- }}- >- <div style={{ paddingBlockEnd: 24, paddingBlockStart: 12, paddingInline: 24 }}>+ <div style={{ flex: 1, height: '100%', overflowY: 'auto' }} onScroll={handleMasonryScroll}>+ <div+ ref={setMasonryContainer}+ style={{ paddingBlockEnd: 24, paddingBlockStart: 12, paddingInline: 24 }}+ >+ <SelectionToolbar+ data={data}+ hasMore={hasMore}+ itemCount={total ?? data.length}+ total={total}+ /><VirtuosoMasonryItemContent={MasonryItemWrapper}columnCount={columnCount}@@ -291,6 +174,16 @@ const SearchResultsOverlay = memo(() => {overflow: 'hidden',}}/>+ {loadMoreError ? (+ <div style={{ paddingBlockStart: 8 }}>+ <AsyncError+ error={loadMoreError}+ retrying={isLoadingMore}+ variant={'inline'}+ onRetry={() => void loadMore()}+ />+ </div>+ ) : null}</div></div>)}diff --git a/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.test.ts b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.test.tsnew file mode 100644index 00000000000..56db8701384--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.test.ts@@ -0,0 +1,89 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { initialState } from '@/features/ResourceManager/store/initialState';+import { explorerSearchResource } from '@/features/ResourceManager/store/projection';+import { getExplorerSearchParams } from '@/features/ResourceManager/store/selectors';+import type { ResourceItem } from '@/types/resource';++import { useExplorerSearchResults } from './useExplorerSearchResults';++const row = (id: string): ResourceItem => ({ fileType: 'application/pdf', id, name: `${id}.pdf` });++const seedSearch = (hasMore: boolean) => {+ useResourceManagerStore.setState({ searchQuery: 'report' });+ const params = getExplorerSearchParams(useResourceManagerStore.getState())!;+ const key = explorerSearchResource.key(params);++ useResourceManagerStore.setState({+ explorerSearchEntries: {+ [key]: {+ currentPage: 0,+ hasMore,+ items: [row('hit-1'), row('hit-2')],+ pageSize: 50,+ searchParams: params,+ total: hasMore ? 120 : 2,+ },+ },+ });++ return key;+};++describe('useExplorerSearchResults', () => {+ const loadMoreExplorerSearch = vi.fn();++ beforeEach(() => {+ loadMoreExplorerSearch.mockReset().mockResolvedValue(undefined);+ useResourceManagerStore.setState({+ ...initialState,+ loadMoreExplorerSearch,+ useFetchExplorerSearch: () => ({ error: undefined, revalidate: vi.fn() }) as any,+ });+ });++ it('should stay idle while no keyword is typed', () => {+ const { result } = renderHook(() => useExplorerSearchResults());++ expect(result.current).toMatchObject({ data: [], isLoading: false, searchParams: null });+ });++ it('should expose the hits of the query on screen', () => {+ seedSearch(true);++ const { result } = renderHook(() => useExplorerSearchResults());++ expect(result.current.data.map((item) => item.id)).toEqual(['hit-1', 'hit-2']);+ expect(result.current).toMatchObject({ hasMore: true, isLoading: false, total: 120 });+ });++ // Regression: a failed page past the head was dropped on the floor β the+ // loading row disappeared while more rows remained. The overlay needs the+ // error to render a retry at the tail.+ it('should surface a failed next page of the query on screen', () => {+ const key = seedSearch(true);+ const loadMoreError = new Error('page 2 failed');+ const entry = useResourceManagerStore.getState().explorerSearchEntries[key];++ useResourceManagerStore.setState({+ explorerSearchEntries: { [key]: { ...entry, loadMoreError } },+ });++ const { result } = renderHook(() => useExplorerSearchResults());++ expect(result.current.loadMoreError).toBe(loadMoreError);+ });++ // Regression: the overlay never requested the next page, so a keyword with+ // more than one page of hits only ever showed the first 50.+ it('should load the next page of the query on screen', async () => {+ const key = seedSearch(true);++ const { result } = renderHook(() => useExplorerSearchResults());+ await act(() => result.current.loadMore());++ expect(loadMoreExplorerSearch).toHaveBeenCalledWith(key);+ });+});diff --git a/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.ts b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.tsnew file mode 100644index 00000000000..ebecf37b4d7--- /dev/null+++ b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSearchResults.ts@@ -0,0 +1,69 @@+import { useCallback, useMemo } from 'react';++import { useResourceManagerStore } from '@/features/ResourceManager/store';+import { explorerSearchResource } from '@/features/ResourceManager/store/projection';+import { getExplorerSearchParams } from '@/features/ResourceManager/store/selectors';+import type { AsyncTaskStatus } from '@/types/asyncTask';+import { type FileListItem } from '@/types/files';++/**+ * Rows of the explorer's search overlay, or `searchParams: null` while no+ * keyword is typed.+ *+ * Search results are a `@lobechat/replica` entry owned by the ResourceManager+ * store: the head page is persisted, so re-opening a search paints the rows it+ * had before the request lands. The keyword is part of the query identity, so+ * the painted rows are only used while they still answer the request on screen.+ */+export const useExplorerSearchResults = () => {+ const searchParams = useResourceManagerStore(getExplorerSearchParams);+ const loadMoreExplorerSearch = useResourceManagerStore((s) => s.loadMoreExplorerSearch);+ const { error, revalidate } = useResourceManagerStore((s) => s.useFetchExplorerSearch)(+ searchParams,+ );++ // One entry per query: the entry key IS the query identity, so the rows read+ // here always answer the request on screen.+ const searchKey = searchParams ? explorerSearchResource.key(searchParams) : undefined;+ const current = useResourceManagerStore((s) =>+ searchKey ? s.explorerSearchEntries[searchKey] : undefined,+ );++ const rawData = current?.items;+ const data: FileListItem[] = useMemo(+ () =>+ rawData?.map((item) => ({+ ...item,+ chunkCount: item.chunkCount ?? null,+ chunkingError: item.chunkingError ?? null,+ chunkingStatus: (item.chunkingStatus ?? null) as AsyncTaskStatus | null,+ embeddingError: item.embeddingError ?? null,+ embeddingStatus: (item.embeddingStatus ?? null) as AsyncTaskStatus | null,+ finishEmbedding: item.finishEmbedding ?? false,+ url: item.url ?? '',+ })) ?? [],+ [rawData],+ );++ // Hits beyond the first page used to be unreachable: the overlay never asked+ // for the next page, so a keyword matching hundreds of files showed 50.+ const loadMore = useCallback(async () => {+ if (searchKey) await loadMoreExplorerSearch(searchKey);+ }, [loadMoreExplorerSearch, searchKey]);++ return {+ data,+ error,+ hasMore: current?.hasMore ?? false,+ isLoading: !!searchParams && !current && !error,+ isLoadingMore: current?.isLoadingMore ?? false,+ loadMore,+ // A page past the head can fail on its own; the head error never covers it.+ // Returning it lets the overlay stop scrolling into the failure and offer a+ // retry at the tail instead of silently dropping the remaining rows.+ loadMoreError: current?.loadMoreError,+ revalidate,+ searchParams,+ total: current?.total,+ };+};diff --git a/src/features/ResourceManager/components/Explorer/hooks/useExplorerSelection.ts b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSelection.tsindex 84342965ed9..6829e1f9c05 100644--- a/src/features/ResourceManager/components/Explorer/hooks/useExplorerSelection.ts+++ b/src/features/ResourceManager/components/Explorer/hooks/useExplorerSelection.ts@@ -13,6 +13,8 @@ import { useFileStore } from '@/store/file';interface ExplorerSelectionOptions {data: ExplorerSelectableItem[];hasMore: boolean;+ /** Size of the listed pool; defaults to the folder list's total. */+ total?: number;}interface ExplorerSelectableItem {@@ -30,7 +32,11 @@ export const useExplorerSelectionEligibility = () => {};};-export const useExplorerSelectionSummary = ({ data, hasMore }: ExplorerSelectionOptions) => {+export const useExplorerSelectionSummary = ({+ data,+ hasMore,+ total: poolTotal,+}: ExplorerSelectionOptions) => {const [selectAllState, selectedFileIds, selectionTotal] = useResourceManagerStore((s) => [s.selectAllState,s.selectedFileIds,@@ -38,8 +44,8 @@ export const useExplorerSelectionSummary = ({ data, hasMore }: ExplorerSelection]);const { isItemSelectable, isWorkspaceOwner } = useExplorerSelectionEligibility();const selectableData = useMemo(() => data.filter(isItemSelectable), [data, isItemSelectable]);- const total = useFileStore((s) => s.total);- const effectiveTotal = selectionTotal ?? total;+ const listTotal = useFileStore((s) => s.total);+ const effectiveTotal = selectionTotal ?? poolTotal ?? listTotal;const selectedCount = useMemo(() =>getExplorerSelectedCount({diff --git a/src/features/ResourceManager/store/action.test.ts b/src/features/ResourceManager/store/action.test.tsindex fe2e7d13066..1afef10ecdd 100644--- a/src/features/ResourceManager/store/action.test.ts+++ b/src/features/ResourceManager/store/action.test.ts@@ -13,13 +13,13 @@ const {mockDropNodes,mockForgetSnapshot,mockResolveSelectionIds,- mockRevalidateTree,+ mockRevalidateLoaded,} = vi.hoisted(() => ({mockDeleteResourcesByQuery: vi.fn(),mockDropNodes: vi.fn(async () => undefined),mockForgetSnapshot: vi.fn(),mockResolveSelectionIds: vi.fn(),- mockRevalidateTree: vi.fn(async () => undefined),+ mockRevalidateLoaded: vi.fn(async () => undefined),}));vi.mock('@/store/tree', () => ({@@ -27,7 +27,7 @@ vi.mock('@/store/tree', () => ({getState: () => ({dropNodes: mockDropNodes,forgetSnapshot: mockForgetSnapshot,- revalidate: mockRevalidateTree,+ revalidateLoaded: mockRevalidateLoaded,}),},}));@@ -258,7 +258,7 @@ describe('resource manager store actions', () => {expect(useResourceManagerStore.getState().explorerSearchEntries[key]).toBeUndefined();});- it('should refresh the listed folder when the deleted set is only known to the server', async () => {+ it('should refresh every loaded folder when the deleted set is only known to the server', async () => {useResourceManagerStore.setState({ selectAllState: 'all', selectedFileIds: [] });useFileStore.setState({deleteResources: vi.fn(),@@ -269,12 +269,116 @@ describe('resource manager store actions', () => {await useResourceManagerStore.getState().onActionClick('delete');- // Individual ids never reach the client here, so the whole folder is refetched.- expect(mockRevalidateTree).toHaveBeenCalledWith('folder-a');+ // Individual ids never reach the client here. A library-wide search also+ // matched rows in other expanded folders, so every loaded folder is refetched+ // β not only the one behind the explorer.+ expect(mockRevalidateLoaded).toHaveBeenCalledWith('folder-a');expect(mockDropNodes).not.toHaveBeenCalled();// A refetch that never lands must not leave the deleted rows in the persisted tree.expect(mockForgetSnapshot).toHaveBeenCalledTimes(1);});++ // Regression: removing search hits from the library only refreshed the+ // folder list, so the removed rows and the old count stayed in the library's+ // search results.+ it('should refresh the cached library searches after removing hits from the library', async () => {+ const { useKnowledgeBaseStore } = await import('@/store/library');+ const removeFilesFromKnowledgeBase = vi.fn().mockResolvedValue(undefined);+ useKnowledgeBaseStore.setState({ removeFilesFromKnowledgeBase } as any);++ const params = { libraryId: 'lib-1', pageSize: 50, q: 'report' } as any;+ const key = explorerSearchResource.key(params);+ useResourceManagerStore.setState({+ explorerSearchEntries: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ items: [{ fileType: 'application/pdf', id: 'hit-1', name: 'hit-1' }],+ pageSize: 50,+ searchParams: params,+ total: 1,+ },+ },+ libraryId: 'lib-1',+ selectAllState: 'loaded',+ selectedFileIds: ['hit-1'],+ });++ await useResourceManagerStore.getState().onActionClick('removeFromKnowledgeBase');++ expect(removeFilesFromKnowledgeBase).toHaveBeenCalledWith('lib-1', ['hit-1']);+ await vi.waitFor(() =>+ expect(useResourceManagerStore.getState().explorerSearchEntries[key]).toBeUndefined(),+ );+ });++ // Regression: while the search overlay was up, "select all" and the batch+ // delete resolved against the folder list behind it, so they acted on rows+ // the user had never seen instead of the search hits.+ describe('while the search overlay is up', () => {+ beforeEach(() => {+ useResourceManagerStore.setState({ searchQuery: 'report' });+ useFileStore.setState({ queryParams: { parentId: 'folder-a' } as any });+ });++ it('should select every search hit, not the folder list', async () => {+ mockResolveSelectionIds.mockResolvedValue({ ids: ['hit-1', 'hit-2'], total: 2 });++ await useResourceManagerStore.getState().selectAllResources();++ const query = mockResolveSelectionIds.mock.calls[0][0];+ expect(query).toMatchObject({ filesOnly: true, q: 'report' });+ expect(query).not.toHaveProperty('parentId');+ expect(useResourceManagerStore.getState().selectionTotal).toBe(2);+ });++ it('should delete the whole search query instead of a lookup per hit', async () => {+ const deleteResources = vi.fn().mockResolvedValue(undefined);+ useResourceManagerStore.setState({ selectAllState: 'all', selectedFileIds: ['hit-2'] });+ useFileStore.setState({ deleteResources } as any);+ mockDeleteResourcesByQuery.mockResolvedValue({ count: 2 });++ await useResourceManagerStore.getState().onActionClick('delete');++ // The exclusions ride along with the query: no id resolution, and no+ // per-hit detail lookup inside `deleteResources` for every hit.+ expect(mockDeleteResourcesByQuery).toHaveBeenCalledWith(+ expect.objectContaining({ filesOnly: true, q: 'report' }),+ ['hit-2'],+ );+ expect(mockDeleteResourcesByQuery.mock.calls[0][0]).not.toHaveProperty('parentId');+ expect(mockResolveSelectionIds).not.toHaveBeenCalled();+ expect(deleteResources).not.toHaveBeenCalled();+ // The deleted ids are only known to the server now, so the tree is+ // dropped and refetched instead of patched row by row.+ expect(mockDropNodes).not.toHaveBeenCalled();+ expect(mockForgetSnapshot).toHaveBeenCalledTimes(1);+ });++ it('should chunk search hits that live outside the listed folder', async () => {+ const parseFilesToChunks = vi.fn().mockResolvedValue(undefined);+ const params = { pageSize: 50, q: 'report' } as any;+ useResourceManagerStore.setState({+ explorerSearchEntries: {+ [explorerSearchResource.key(params)]: {+ currentPage: 0,+ hasMore: false,+ items: [{ fileType: 'application/pdf', id: 'hit-1', name: 'report.pdf' }],+ pageSize: 50,+ searchParams: params,+ total: 1,+ },+ },+ selectAllState: 'loaded',+ selectedFileIds: ['hit-1'],+ });+ useFileStore.setState({ parseFilesToChunks } as any);++ await useResourceManagerStore.getState().onActionClick('batchChunking');++ expect(parseFilesToChunks).toHaveBeenCalledWith(['hit-1'], { skipExist: true });+ });+ });});describe('library sidebar search', () => {diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.tsindex 7157673fd54..d8153c2f3a3 100644--- a/src/features/ResourceManager/store/action.ts+++ b/src/features/ResourceManager/store/action.ts@@ -15,7 +15,7 @@ import { useFileStore } from '@/store/file';import type { StoreSetter } from '@/store/types';import { flattenActions } from '@/store/utils/flattenActions';import type { FilesTabs, ResourceSourceFilter, SortType } from '@/types/files';-import type { ResourceItem } from '@/types/resource';+import type { ResourceItem, ResourceQueryParams } from '@/types/resource';import { setNamespace } from '@/utils/storeDebug';import type { ResourceListVisibilityFilter, SelectAllState, State, ViewMode } from './initialState';@@ -30,6 +30,7 @@ import {hierarchySearchResource,type HierarchySearchValue,} from './projection';+import { getExplorerSearchParams } from './selectors';const n = setNamespace('resourceManager');@@ -75,6 +76,17 @@ const toSearchPageResult = ((response.hasMore ? undefined : (cursor ?? 0) * pageSize + response.items.length),});+/** The resource query an explorer search narrows to, without paging or preview. */+const toExplorerSearchQuery = (params: ExplorerSearchParams): ResourceQueryParams => ({+ category: params.category,+ filesOnly: !params.libraryId,+ libraryId: params.libraryId,+ q: params.q,+ showFilesInKnowledgeBase: !params.libraryId,+ sourceFilter: params.sourceFilter,+ visibility: params.visibility,+});+const fetchExplorerSearchPage = async (params: ExplorerSearchParams,cursor?: number,@@ -83,16 +95,10 @@ const fetchExplorerSearchPage = async (const pageSize = params.pageSize ?? DEFAULT_SEARCH_PAGE_SIZE;const response = await resourceService.queryResources({- category: params.category,- filesOnly: !params.libraryId,+ ...toExplorerSearchQuery(params),includeContentPreview: params.includeContentPreview,- libraryId: params.libraryId,limit: pageSize,offset: (cursor ?? 0) * pageSize,- q: params.q,- showFilesInKnowledgeBase: !params.libraryId,- sourceFilter: params.sourceFilter,- visibility: params.visibility,});return toSearchPageResult(response, cursor, pageSize);@@ -354,6 +360,25 @@ export class ResourceManagerStoreActionImpl {void this.#searchHits.revalidate();};+ /**+ * The query "select all" stands for: the search overlay's while a keyword is+ * typed, the folder list's otherwise. Resolving against the folder list while+ * the overlay is up would act on rows the user never saw.+ */+ #selectionQuery = (): ResourceQueryParams | undefined => {+ const searchParams = getExplorerSearchParams(this.#get());+ if (searchParams) return toExplorerSearchQuery(searchParams);++ return useFileStore.getState().queryParams;+ };++ #findSearchHit = (id: string): ResourceItem | undefined => {+ for (const entry of Object.values(this.#get().explorerSearchEntries)) {+ const hit = entry?.items.find((item) => item.id === id);+ if (hit) return hit;+ }+ };+clearSelectAllState = (): void => {this.#set({ selectAllState: 'none', selectedFileIds: [], selectionTotal: undefined });};@@ -379,13 +404,17 @@ export class ResourceManagerStoreActionImpl {const { useTreeStore } = await import('@/store/tree');const currentFolderKey = fileStore.queryParams?.parentId ?? '';- if (selectAllState === 'all' && fileStore.queryParams) {+ // Delete-by-query stands for whichever list the user acted on: the+ // folder list, or the search overlay's query while a keyword is typed.+ // Resolving a select-all into ids first would run one detail lookup per+ // hit inside `deleteResources` before the batch delete starts, so a+ // large search paid a lookup for every row it was about to delete.+ const deleteQuery = selectAllState === 'all' ? this.#selectionQuery() : undefined;++ if (deleteQuery) {const { resourceService } = await import('@/services/resource');- await resourceService.deleteResourcesByQuery(- fileStore.queryParams as any,- selectedFileIds,- );+ await resourceService.deleteResourcesByQuery(deleteQuery, selectedFileIds);// The deleted set is only known to the server, so the cached searches// cannot drop those rows by id: invalidate the surfaces instead and// let the refetch paint whatever survived.@@ -396,12 +425,15 @@ export class ResourceManagerStoreActionImpl {// caller's workspace role β members delete only their own rows, owners// the full query scope β so the revalidation repaints the survivors.await fileStore.evictResourceLists();- // The deleted set is only known to the server here, and every row in- // it was a child of the listed folder, so refetch that one folder.- // The persisted tree is dropped first: if that refetch never lands,- // a reload must not repaint the deleted rows.+ // The deleted set is only known to the server here, so the persisted+ // tree cannot drop those rows by id either: drop the snapshot and+ // refetch every loaded folder β a library-wide search hits rows in+ // folders the sidebar has expanded, and refreshing only the folder+ // behind the explorer would leave those painting the deleted rows.+ // Dropping it first means a refetch that never lands still cannot+ // repaint the deleted rows on reload.useTreeStore.getState().forgetSnapshot();- void useTreeStore.getState().revalidate(currentFolderKey);+ void useTreeStore.getState().revalidateLoaded(currentFolderKey);this.clearSelectAllState();return;@@ -425,6 +457,11 @@ export class ResourceManagerStoreActionImpl {if (!libraryId) return;await kbStore.removeFilesFromKnowledgeBase(libraryId, resourceIds);+ // The rows still exist, so they cannot be dropped from every cached+ // search by id; but they no longer match this library's searches.+ // Refetch the search surfaces so the hits and counts follow the server.+ void this.#invalidateExplorerSearch();+ void this.collapseHierarchySearch();this.clearSelectAllState();return;}@@ -437,7 +474,8 @@ export class ResourceManagerStoreActionImpl {case 'batchChunking': {const resourceIds = await resolveSelectedResourceIds();const chunkableFileIds = resourceIds.filter((id) => {- const resource = fileStore.resourceMap?.get(id);+ // Search hits from other folders are not in the folder list's map.+ const resource = fileStore.resourceMap?.get(id) ?? this.#findSearchHit(id);// For server-resolved IDs not yet in the local map, include them// and let the server handle unsupported type filteringif (!resource) return selectAllState === 'all';@@ -466,12 +504,11 @@ export class ResourceManagerStoreActionImpl {if (selectAllState !== 'all') return selectedFileIds;const { resourceService } = await import('@/services/resource');- const { useFileStore } = await import('@/store/file');- const queryParams = useFileStore.getState().queryParams;+ const queryParams = this.#selectionQuery();if (!queryParams) return selectedFileIds;- const result = await resourceService.resolveSelectionIds(queryParams as any);+ const result = await resourceService.resolveSelectionIds(queryParams);return result.ids.filter((id) => !selectedFileIds.includes(id));};@@ -481,11 +518,11 @@ export class ResourceManagerStoreActionImpl {selectAllResources = async (): Promise<void> => {const { resourceService } = await import('@/services/resource');- const queryParams = useFileStore.getState().queryParams;+ const queryParams = this.#selectionQuery();if (!queryParams) return;- const { total } = await resourceService.resolveSelectionIds(queryParams as any);+ const { total } = await resourceService.resolveSelectionIds(queryParams);this.#set({ selectAllState: 'all', selectedFileIds: [], selectionTotal: total });};diff --git a/src/features/ResourceManager/store/selectors.ts b/src/features/ResourceManager/store/selectors.tsindex 66ff60b1513..e4aecd36dac 100644--- a/src/features/ResourceManager/store/selectors.ts+++ b/src/features/ResourceManager/store/selectors.ts@@ -3,6 +3,7 @@ import { type FileListItem, FilesTabs, ResourceSourceFilter } from '@/types/fileimport { SortType } from '@/types/files';import type { ResourceListVisibilityFilter, SelectAllState, State } from './initialState';+import { DEFAULT_SEARCH_PAGE_SIZE, type ExplorerSearchParams } from './projection';/*** The Private / Workspace switch scopes the resource home only. Once the user@@ -59,6 +60,26 @@ export const getResourceSourceFilter = (s: State): ResourceSourceFilter => {);};+/**+ * Query of the explorer's search overlay, or `null` while no keyword is typed.+ * The overlay lists these rows and a select-all resolves against the same+ * params, so a batch action acts on the search results, never on the folder+ * list behind the overlay.+ */+export const getExplorerSearchParams = (s: State): ExplorerSearchParams | null => {+ if (!s.searchQuery) return null;++ return {+ category: s.libraryId ? undefined : s.category,+ includeContentPreview: s.viewMode === 'masonry',+ libraryId: s.libraryId,+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ q: s.searchQuery,+ sourceFilter: getResourceSourceFilter(s),+ visibility: getResourceQueryVisibility(s.libraryId, s.listVisibility),+ };+};+/*** Sort a file list based on sort settings* This is a pure function that can be used with any file listdiff --git a/src/store/tree/actions.persist.test.ts b/src/store/tree/actions.persist.test.tsindex d80ce3e0a77..14ce525aa99 100644--- a/src/store/tree/actions.persist.test.ts+++ b/src/store/tree/actions.persist.test.ts@@ -446,3 +446,98 @@ describe('buildLibraryTreeSnapshot', () => {expect(buildLibraryTreeSnapshot({}, {})).toBeUndefined();});});++describe('TreeActionImpl.revalidateLoaded β a delete only the server can enumerate', () => {+ beforeEach(() => {+ mockGetKnowledgeItems.mockReset();+ });++ /** Root holding two folders, both expanded and loaded, with one row each. */+ const loadTwoFolders = async () => {+ const { actions, state } = setup();+ mockGetKnowledgeItems.mockResolvedValue({+ items: [serverRow('folder-a', true), serverRow('folder-b', true)],+ });+ actions.init('kb-1');+ await vi.waitFor(() => expect(state.children['']).toHaveLength(2));+ state.expanded = { 'folder-a': true, 'folder-b': true };+ state.children['folder-a'] = [file('doc-a')];+ state.children['folder-b'] = [file('doc-b')];+ return { actions, state };+ };++ it('refetches every loaded folder, not only the one behind the explorer', async () => {+ const { actions, state } = await loadTwoFolders();++ // The search-wide delete matched rows in both folders; the server's answer no+ // longer lists them. The sidebar has to follow in each of them.+ mockGetKnowledgeItems.mockReset().mockResolvedValue({ items: [] });+ await actions.revalidateLoaded('');++ const requested = mockGetKnowledgeItems.mock.calls.map(([args]) => args.parentId);+ expect(new Set(requested)).toEqual(new Set([null, 'folder-a', 'folder-b']));+ expect(state.children['folder-a']).toEqual([]);+ expect(state.children['folder-b']).toEqual([]);++ const stored = JSON.stringify(state.snapshotMap['kb-1'] ?? {});+ expect(stored).not.toContain('doc-a');+ expect(stored).not.toContain('doc-b');+ });++ it('writes the snapshot once, after every folder settled', async () => {+ const { actions, state } = await loadTwoFolders();+ actions.forgetSnapshot();++ const pending = deferred();+ mockGetKnowledgeItems+ .mockReset()+ .mockImplementation(({ parentId }) =>+ parentId === 'folder-b' ? pending.promise : Promise.resolve({ items: [] }),+ );++ const batch = actions.revalidateLoaded('');+ await vi.waitFor(() => expect(state.children['folder-a']).toEqual([]));+ // folder-b still holds the deleted row: persisting now would store it again.+ expect(state.snapshotMap['kb-1']).toBeUndefined();++ pending.resolve({ items: [] });+ await batch;++ const stored = JSON.stringify(state.snapshotMap['kb-1'] ?? {});+ expect(stored).not.toContain('doc-a');+ expect(stored).not.toContain('doc-b');+ });+ // Regression: a failed folder refresh keeps its old rows on screen, and the+ // batch's closing snapshot write used to persist them, so a reload repainted+ // the rows the search-wide delete had just removed.+ it('keeps a folder whose refresh failed out of the stored snapshot', async () => {+ const { actions, state } = await loadTwoFolders();+ const rootFolders = [serverRow('folder-a', true), serverRow('folder-b', true)];+ actions.forgetSnapshot();++ mockGetKnowledgeItems+ .mockReset()+ .mockImplementation(({ parentId }) => {+ if (parentId === 'folder-b') return Promise.reject(new Error('network'));+ if (parentId === null) return Promise.resolve({ items: rootFolders });+ return Promise.resolve({ items: [] });+ });++ await actions.revalidateLoaded('');++ // The failed folder keeps its rows on screen; only the persisted copy drops them.+ expect(state.children['folder-b']).toEqual([file('doc-b')]);+ const stored = JSON.stringify(state.snapshotMap['kb-1'] ?? {});+ expect(stored).not.toContain('doc-a');+ expect(stored).not.toContain('doc-b');++ // A later successful refresh confirms the folder and persists it again.+ mockGetKnowledgeItems+ .mockReset()+ .mockImplementation(({ parentId }) =>+ Promise.resolve({ items: parentId === 'folder-b' ? [serverRow('doc-c')] : rootFolders }),+ );+ await actions.revalidate('folder-b');+ expect(JSON.stringify(state.snapshotMap['kb-1'] ?? {})).toContain('doc-c');+ });+});diff --git a/src/store/tree/actions.ts b/src/store/tree/actions.tsindex 76a8594e21e..059e6f5a0f0 100644--- a/src/store/tree/actions.ts+++ b/src/store/tree/actions.ts@@ -103,15 +103,25 @@ export class TreeActionImpl {#queuedRevalidate = new Set<string>();/**- * Folders whose rendered rows came from an explorer list with optimistic- * overlays still pending (see `reconcile`). The snapshot keeps their last- * confirmed rows; the explorer's settle or a server answer for the folder clears it.+ * Folders whose rendered rows are not confirmed by the server: an explorer+ * list with optimistic overlays still pending (see `reconcile`), or a folder+ * whose refresh failed during `revalidateLoaded`. The snapshot keeps their+ * last confirmed rows; the explorer's settle or a server answer for the+ * folder clears it.*/#unconfirmedFolders = new Set<string>();/** Sidebar transactions (move, rename, delete) whose optimistic patch is not confirmed. */#pendingTx = new Set<symbol>();+ /**+ * Batched refreshes in flight (`revalidateLoaded`). The snapshot is written+ * once they all settle: persisting after each folder would store the rows of+ * the folders that have not been refetched yet, and for a delete only the+ * server can enumerate those rows are exactly the deleted ones.+ */+ #pendingBatch = 0;+/*** Commit with the snapshot paused, then persist what survived (applied or* rolled back). Resolves `false` when the tree was reset meanwhile: the@@ -163,7 +173,7 @@ export class TreeActionImpl {* change, so a revalidation that confirms the tree costs no storage write.*/#persistSnapshot = () => {- if (this.#pendingTx.size > 0) return;+ if (this.#pendingTx.size > 0 || this.#pendingBatch > 0) return;const { children, expanded, knowledgeBaseId, snapshotMap } = this.#get();if (!knowledgeBaseId) return;// A folder showing the explorer's optimistic overlay keeps its last stored@@ -403,15 +413,47 @@ export class TreeActionImpl {await this.#revalidateFolder(this.#resolveFolderKey(folderKey));};+ /**+ * Refetch every loaded folder, for a mutation whose scope only the server+ * knows: a library-wide search reaches rows in folders the sidebar has+ * expanded, so refreshing the folder behind the explorer leaves the other+ * cached folders painting the deleted rows β and the snapshot written after+ * that single refresh would persist them too. `fallbackKey` keeps the+ * explorer's own folder in the batch when the sidebar never loaded it (a+ * deep link before its ancestors arrive).+ */+ revalidateLoaded = async (fallbackKey = ''): Promise<void> => {+ void revalidateHierarchySearch();+ const targets = new Set(this.#loadedVisibleFolders());+ targets.add(this.#resolveFolderKey(fallbackKey));++ this.#pendingBatch += 1;+ try {+ const refreshed = await Promise.all(+ [...targets].map((folderId) => this.#revalidateFolder(folderId)),+ );+ // A folder that failed (or was deferred behind an in-flight load) still+ // shows its pre-deletion rows: keep it out of the snapshot until a later+ // refresh confirms it, or a reload would repaint the deleted rows.+ [...targets].forEach((folderId, index) => {+ if (!refreshed[index]) this.#unconfirmedFolders.add(folderId);+ });+ } finally {+ this.#pendingBatch -= 1;+ this.#persistSnapshot();+ }+ };+/*** Refetch one folder while its current rows stay on screen. A failure keeps* them (status back to idle) rather than flagging the folder as errored.+ * Resolves `true` only when the folder's rows now come from this refetch.*/- #revalidateFolder = async (folderId: string) => {+ #revalidateFolder = async (folderId: string): Promise<boolean> => {const { epoch, knowledgeBaseId, status } = this.#get();if (status[folderId] === 'loading' || status[folderId] === 'revalidating') {this.#queuedRevalidate.add(folderId);- return;+ return false;}this.#set(@@ -428,7 +470,7 @@ export class TreeActionImpl {showFilesInKnowledgeBase: false,});- if (this.#get().epoch !== epoch) return;+ if (this.#get().epoch !== epoch) return false;this.#set({@@ -444,14 +486,16 @@ export class TreeActionImpl {this.#unconfirmedFolders.delete(folderId);this.#persistSnapshot();this.#runQueuedRevalidate(folderId);+ return true;} catch {- if (this.#get().epoch !== epoch) return;+ if (this.#get().epoch !== epoch) return false;this.#set({ status: { ...this.#get().status, [folderId]: 'idle' } },false,'tree/revalidate/error',);this.#runQueuedRevalidate(folderId);+ return false;}};diff --git a/src/store/tree/types.ts b/src/store/tree/types.tsindex 323f8b06be8..32921f3ec82 100644--- a/src/store/tree/types.ts+++ b/src/store/tree/types.ts@@ -76,6 +76,8 @@ export interface TreeState extends TreeDataState {renameItem: (itemId: string, parentId: string, newName: string) => Promise<void>;reset: () => void;revalidate: (folderId: string) => Promise<void>;+ /** Refetch every loaded folder β for a bulk mutation whose scope only the server knows. */+ revalidateLoaded: (fallbackKey?: string) => Promise<void>;snapshotMap: Record<string, LibraryTreeSnapshot>;snapshotReplica: ReplicaState<LibraryTreeSnapshot>;toggle: (folderId: string) => void;