Skip to content

🀯 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.

πŸ› fix(knowledge): use file ids for chunk actions (#16274)

marun1c04be109c71
diff --git a/packages/types/src/files/list.ts b/packages/types/src/files/list.ts
index a730729d953..f0676ce6c7b 100644
--- a/packages/types/src/files/list.ts
+++ b/packages/types/src/files/list.ts
@@ -18,6 +18,7 @@ export interface FileListItem {
editorData?: Record<string, any> | null;
embeddingError: any | null;
embeddingStatus?: AsyncTaskStatus | null;
+ fileId?: string | null;
fileType: string;
finishEmbedding: boolean;
id: string;
diff --git a/src/features/ResourceManager/components/ChunkDrawer/index.tsx b/src/features/ResourceManager/components/ChunkDrawer/index.tsx
index f075d89b421..935c4743fe0 100644
--- a/src/features/ResourceManager/components/ChunkDrawer/index.tsx
+++ b/src/features/ResourceManager/components/ChunkDrawer/index.tsx
@@ -19,7 +19,7 @@ const ChunkDrawer = memo(() => {
!!s.chunkDetailId,
s.closeChunkDrawer,
]);
- const file = useFileStore(fileManagerSelectors.getFileById(fileId));
+ const file = useFileStore(fileManagerSelectors.getFileByChunkTargetId(fileId));
return (
<Drawer
@@ -36,7 +36,7 @@ const ChunkDrawer = memo(() => {
<Flexbox horizontal height={'100%'} style={{ overflow: 'hidden' }}>
{file && (
<Flexbox flex={2} style={{ overflow: 'scroll' }}>
- <FileViewer {...file} />
+ <FileViewer {...file} id={file.fileId ?? file.id} />
</Flexbox>
)}
<Flexbox flex={1} style={{ borderInlineStart: `1px solid ${cssVar.colorSplit}` }}>
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
index 5b8fb49383f..ebdc06e1c2b 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
@@ -1,7 +1,7 @@
-import { render } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import type { ItemType } from 'antd/es/menu/interface';
import React from 'react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import FileListItemActions, { appendTransferMenuItemsBeforeDelete } from './FileListItemActions';
@@ -45,6 +45,10 @@ describe('appendTransferMenuItemsBeforeDelete', () => {
});
describe('FileListItemActions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
const baseProps = {
id: 'resource-1',
isCreatingFileParseTask: false,
@@ -63,4 +67,23 @@ describe('FileListItemActions', () => {
expect(mocks.useFileTransferMenuItem).toHaveBeenCalledWith('resource-1', 'document');
});
+
+ it('uses fileId for initial chunk parsing when the resource id is a document id', () => {
+ const parseFiles = vi.fn();
+ mocks.useFileTransferMenuItem.mockReturnValue([]);
+
+ render(
+ React.createElement(FileListItemActions, {
+ ...baseProps,
+ fileId: 'file_1',
+ id: 'docs_1',
+ isSupportedForChunking: true,
+ parseFiles,
+ }),
+ );
+
+ fireEvent.click(screen.getByText('FileManager.actions.chunking'));
+
+ expect(parseFiles).toHaveBeenCalledWith(['file_1']);
+ });
});
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
index 95ef6ecbe3a..5c65cb83c97 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.tsx
@@ -7,6 +7,7 @@ import { useMemo } from 'react';
import { useFileTransferMenuItem } from '@/business/client/hooks/useFileTransferMenuItem';
import { usePermission } from '@/hooks/usePermission';
+import { getChunkTargetId } from '@/store/file';
import DropdownMenu from '../../ItemDropdown/DropdownMenu';
import ChunksBadge from './ChunkTag';
@@ -18,6 +19,7 @@ interface FileListItemActionsProps {
chunkingStatus?: unknown;
embeddingError?: IAsyncTaskError | null;
embeddingStatus?: unknown;
+ fileId?: string | null;
finishEmbedding?: boolean;
id: string;
isCreatingFileParseTask: boolean;
@@ -62,6 +64,7 @@ const FileListItemActions = ({
chunkingStatus,
embeddingError,
embeddingStatus,
+ fileId,
finishEmbedding,
id,
isCreatingFileParseTask,
@@ -73,6 +76,7 @@ const FileListItemActions = ({
t,
}: FileListItemActionsProps) => {
const { allowed: canEditResources } = usePermission('edit_own_content');
+ const chunkTargetId = getChunkTargetId({ fileId, id });
const transferMenuItems = useFileTransferMenuItem(
id,
isPage ? 'document' : isFolder ? 'folder' : 'file',
@@ -111,7 +115,7 @@ const FileListItemActions = ({
size={'small'}
type={'text'}
onClick={() => {
- parseFiles([id]);
+ parseFiles([chunkTargetId]);
}}
>
{t(
@@ -131,7 +135,7 @@ const FileListItemActions = ({
embeddingError={embeddingError}
embeddingStatus={embeddingStatus as any}
finishEmbedding={finishEmbedding}
- id={id}
+ id={chunkTargetId}
/>
</div>
))}
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
index 45f39aca1e5..50a2bbf93e0 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.tsx
@@ -7,7 +7,7 @@ import { shallow } from 'zustand/shallow';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
import { isExplorerItemSelected } from '@/routes/(main)/resource/features/store/selectors';
-import { fileManagerSelectors, useFileStore } from '@/store/file';
+import { fileManagerSelectors, getChunkTargetId, useFileStore } from '@/store/file';
import type { FileListItem as FileListItemType } from '@/types/files';
import { formatSize } from '@/utils/format';
@@ -126,6 +126,7 @@ const FileListItem = ({
createdAt,
embeddingError,
embeddingStatus,
+ fileId,
fileType,
finishEmbedding,
id,
@@ -138,12 +139,12 @@ const FileListItem = ({
slug,
sourceType,
url,
- userId,
}: FileListItemProps) => {
const { t } = useTranslation(['components', 'file']);
+ const chunkTargetId = getChunkTargetId({ fileId, id });
const fileStoreState = useFileStore(
(s) => ({
- isCreatingFileParseTask: fileManagerSelectors.isCreatingFileParseTask(id)(s),
+ isCreatingFileParseTask: fileManagerSelectors.isCreatingFileParseTask(chunkTargetId)(s),
parseFiles: s.parseFilesToChunks,
refreshFileList: s.refreshFileList,
updateResource: s.updateResource,
@@ -310,6 +311,7 @@ const FileListItem = ({
chunkingStatus={chunkingStatus}
embeddingError={embeddingError}
embeddingStatus={embeddingStatus}
+ fileId={fileId}
finishEmbedding={finishEmbedding}
id={id}
isCreatingFileParseTask={fileStoreState.isCreatingFileParseTask}
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
index 3b4145bd3bc..7a3d3975f45 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/index.tsx
@@ -13,7 +13,7 @@ import {
useSetCurrentDrag,
} from '@/routes/(main)/resource/features/DndContextWrapper';
import { documentService } from '@/services/document';
-import { useFileStore } from '@/store/file';
+import { getChunkTargetId, useFileStore } from '@/store/file';
import { type FileListItem } from '@/types/files';
import { useFileItemClick } from '../../hooks/useFileItemClick';
@@ -195,6 +195,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
url,
name,
fileType,
+ fileId,
id,
selected,
chunkingStatus,
@@ -206,6 +207,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
sourceType,
slug,
}) => {
+ const chunkTargetId = getChunkTargetId({ fileId, id });
const [markdownContent, setMarkdownContent] = useState<string>('');
const [isLoadingMarkdown, setIsLoadingMarkdown] = useState(false);
@@ -437,7 +439,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
embeddingStatus={embeddingStatus ?? undefined}
fileType={fileType}
finishEmbedding={finishEmbedding}
- id={id}
+ id={chunkTargetId}
isInView={isInView}
name={name}
size={size}
@@ -455,7 +457,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
embeddingStatus={embeddingStatus ?? undefined}
fileType={fileType}
finishEmbedding={finishEmbedding}
- id={id}
+ id={chunkTargetId}
isLoadingMarkdown={isLoadingMarkdown}
markdownContent={markdownContent}
metadata={metadata}
@@ -473,7 +475,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
embeddingStatus={embeddingStatus ?? undefined}
fileType={fileType}
finishEmbedding={finishEmbedding}
- id={id}
+ id={chunkTargetId}
isLoadingMarkdown={isLoadingMarkdown}
markdownContent={markdownContent}
name={name}
@@ -491,7 +493,7 @@ const MasonryFileItem = memo<MasonryFileItemProps>(
embeddingStatus={embeddingStatus ?? undefined}
fileType={fileType}
finishEmbedding={finishEmbedding}
- id={id}
+ id={chunkTargetId}
name={name}
size={size}
/>
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx
index ccfdd050129..7fdf98ec844 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/index.tsx
@@ -90,28 +90,19 @@ const MasonryView = memo(function MasonryView({
}, [currentQueryParams, queryParams]);
// Map ResourceItem[] to FileListItem[] for compatibility
+ // Spread `item` first so file-backed fields (e.g. `fileId`) are preserved β€”
+ // chunk actions need `fileId` to resolve `docs_*` ids to `file_*` ids (#16267).
const rawData = useMemo(
() =>
resourceList?.map(
(item): FileListItem => ({
+ ...item,
chunkCount: item.chunkCount ?? null,
chunkingError: item.chunkingError ?? null,
chunkingStatus: (item.chunkingStatus as any) ?? null,
- content: item.content,
- createdAt: item.createdAt,
- editorData: item.editorData,
embeddingError: item.embeddingError ?? null,
embeddingStatus: (item.embeddingStatus as any) ?? null,
- fileType: item.fileType,
finishEmbedding: item.finishEmbedding ?? false,
- id: item.id,
- metadata: item.metadata,
- name: item.name,
- parentId: item.parentId,
- size: item.size,
- slug: item.slug,
- sourceType: item.sourceType,
- updatedAt: item.updatedAt,
url: item.url ?? '',
}),
) ?? [],
diff --git a/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts b/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts
index dbbed4192f2..a992d295a7a 100644
--- a/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts
+++ b/src/features/ResourceManager/components/Explorer/useCheckTaskStatus.ts
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { resourceService } from '@/services/resource';
-import { useFileStore } from '@/store/file';
+import { getChunkTargetId, useFileStore } from '@/store/file';
import { AsyncTaskStatus } from '@/types/asyncTask';
import { type FileListItem } from '@/types/files';
@@ -14,7 +14,7 @@ export const useCheckTaskStatus = (data: FileListItem[] | undefined) => {
(item.chunkingStatus === AsyncTaskStatus.Processing ||
item.embeddingStatus === AsyncTaskStatus.Processing),
)
- .map((item) => item.id) ?? [];
+ .map(getChunkTargetId) ?? [];
const processingKey = processingFileIds.join(',');
// Poll every 5s to check if chunking/embedding status has changed
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index 81a9526b4b3..2cf3b240ff6 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -92,6 +92,7 @@ export class FileService {
editorData: doc.editorData,
embeddingError: null,
embeddingStatus: null,
+ fileId: doc.fileId,
fileType: doc.fileType || CUSTOM_DOCUMENT_FILE_TYPE,
finishEmbedding: false,
id: doc.id,
diff --git a/src/services/resource/index.ts b/src/services/resource/index.ts
index 900931db72e..c1bde1affd6 100644
--- a/src/services/resource/index.ts
+++ b/src/services/resource/index.ts
@@ -34,6 +34,8 @@ const mapToResourceItem = (item: FileListItem): ResourceItem => {
embeddingTaskId: item.embeddingStatus ? 'placeholder' : null,
+ fileId: item.fileId,
+
fileType: item.fileType,
finishEmbedding: item.finishEmbedding,
diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.ts
index 04ded7e3968..2695ea06e5b 100644
--- a/src/store/file/slices/fileManager/action.test.ts
+++ b/src/store/file/slices/fileManager/action.test.ts
@@ -267,6 +267,45 @@ describe('FileManagerActions', () => {
expect(refreshSpy).toHaveBeenCalled();
expect(toggleSpy).toHaveBeenCalledWith(['file-1'], false);
});
+
+ it('should use linked file id when embedding a file-backed document resource', async () => {
+ const { result } = renderHook(() => useStore());
+
+ act(() => {
+ useStore.setState({
+ resourceMap: new Map([
+ [
+ 'docs_1',
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Document-backed file',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ ]),
+ });
+ });
+
+ const createTaskSpy = vi
+ .spyOn(ragService, 'createEmbeddingChunksTask')
+ .mockResolvedValue(undefined as any);
+ const refreshSpy = vi.spyOn(result.current, 'refreshFileList').mockResolvedValue();
+ const toggleSpy = vi.spyOn(result.current, 'toggleEmbeddingIds');
+
+ await act(async () => {
+ await result.current.embeddingChunks(['docs_1']);
+ });
+
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1']);
+ expect(createTaskSpy).toHaveBeenCalledWith('file_1');
+ expect(refreshSpy).toHaveBeenCalled();
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1'], false);
+ });
});
describe('parseFilesToChunks', () => {
@@ -306,6 +345,66 @@ describe('FileManagerActions', () => {
expect(createTaskSpy).toHaveBeenCalledWith('file-1', true);
});
+ it('should use linked file id when parsing a file-backed document resource', async () => {
+ const { result } = renderHook(() => useStore());
+
+ act(() => {
+ useStore.setState({
+ resourceMap: new Map([
+ [
+ 'docs_1',
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Document-backed file',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ ]),
+ });
+ });
+
+ const createTaskSpy = vi
+ .spyOn(ragService, 'createParseFileTask')
+ .mockResolvedValue(undefined as any);
+ const refreshSpy = vi.spyOn(result.current, 'refreshFileList').mockResolvedValue();
+ const toggleSpy = vi.spyOn(result.current, 'toggleParsingIds');
+
+ await act(async () => {
+ await result.current.parseFilesToChunks(['docs_1'], { skipExist: true });
+ });
+
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1']);
+ expect(createTaskSpy).toHaveBeenCalledWith('file_1', true);
+ expect(refreshSpy).toHaveBeenCalled();
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1'], false);
+ });
+
+ it('should resolve off-screen document ids before creating parse tasks', async () => {
+ const { result } = renderHook(() => useStore());
+
+ vi.spyOn(fileService, 'getKnowledgeItem').mockResolvedValue({
+ fileId: 'file_1',
+ id: 'docs_1',
+ } as any);
+ const createTaskSpy = vi
+ .spyOn(ragService, 'createParseFileTask')
+ .mockResolvedValue(undefined as any);
+ const refreshSpy = vi.spyOn(result.current, 'refreshFileList').mockResolvedValue();
+
+ await act(async () => {
+ await result.current.parseFilesToChunks(['docs_1'], { skipExist: true });
+ });
+
+ expect(fileService.getKnowledgeItem).toHaveBeenCalledWith('docs_1');
+ expect(createTaskSpy).toHaveBeenCalledWith('file_1', true);
+ expect(refreshSpy).toHaveBeenCalled();
+ });
+
it('should handle errors gracefully', async () => {
const { result } = renderHook(() => useStore());
@@ -691,6 +790,49 @@ describe('FileManagerActions', () => {
expect(refreshSpy).toHaveBeenCalledTimes(2);
expect(toggleSpy).toHaveBeenCalledWith(['file-1'], false);
});
+
+ it('should use linked file id when retrying embedding for a file-backed document', async () => {
+ const { result } = renderHook(() => useStore());
+
+ act(() => {
+ useStore.setState({
+ resourceMap: new Map([
+ [
+ 'docs_1',
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Document-backed file',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ ]),
+ });
+ });
+
+ const toggleSpy = vi.spyOn(result.current, 'toggleEmbeddingIds');
+ vi.mocked(lambdaClient.file.removeFileAsyncTask.mutate).mockResolvedValue(undefined as any);
+ const createTaskSpy = vi
+ .spyOn(ragService, 'createEmbeddingChunksTask')
+ .mockResolvedValue(undefined as any);
+ vi.spyOn(result.current, 'refreshFileList').mockResolvedValue();
+
+ await act(async () => {
+ await result.current.reEmbeddingChunks('docs_1');
+ });
+
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1']);
+ expect(lambdaClient.file.removeFileAsyncTask.mutate).toHaveBeenCalledWith({
+ id: 'file_1',
+ type: 'embedding',
+ });
+ expect(createTaskSpy).toHaveBeenCalledWith('file_1');
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1'], false);
+ });
});
describe('reParseFile', () => {
@@ -710,6 +852,42 @@ describe('FileManagerActions', () => {
expect(refreshSpy).toHaveBeenCalled();
expect(toggleSpy).toHaveBeenCalledWith(['file-1'], false);
});
+
+ it('should use linked file id when retrying parse for a file-backed document', async () => {
+ const { result } = renderHook(() => useStore());
+
+ act(() => {
+ useStore.setState({
+ resourceMap: new Map([
+ [
+ 'docs_1',
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Document-backed file',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ ]),
+ });
+ });
+
+ const toggleSpy = vi.spyOn(result.current, 'toggleParsingIds');
+ const retrySpy = vi.spyOn(ragService, 'retryParseFile').mockResolvedValue(undefined as any);
+ vi.spyOn(result.current, 'refreshFileList').mockResolvedValue();
+
+ await act(async () => {
+ await result.current.reParseFile('docs_1');
+ });
+
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1']);
+ expect(retrySpy).toHaveBeenCalledWith('file_1');
+ expect(toggleSpy).toHaveBeenCalledWith(['file_1'], false);
+ });
});
describe('refreshFileList', () => {
diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.ts
index dd0eec7462b..5eb6d26ae30 100644
--- a/src/store/file/slices/fileManager/action.ts
+++ b/src/store/file/slices/fileManager/action.ts
@@ -52,6 +52,24 @@ export class FileManageActionImpl {
this.#get = get;
}
+ #resolveChunkTargetId = async (id: string): Promise<string> => {
+ // Reuse the selector so local resolution consults every store list
+ // (fileList β†’ resourceMap β†’ resourceMap-by-fileId β†’ resourceList).
+ const localResource = fileManagerSelectors.getFileByChunkTargetId(id)(this.#get());
+ if (localResource?.fileId) return localResource.fileId;
+ if (!id.startsWith('docs_')) return id;
+
+ try {
+ const resource = await fileService.getKnowledgeItem(id);
+ return resource?.fileId ?? id;
+ } catch {
+ return id;
+ }
+ };
+
+ #resolveChunkTargetIds = async (ids: string[]): Promise<string[]> =>
+ Promise.all(ids.map((id) => this.#resolveChunkTargetId(id)));
+
#buildOptimisticUploadResource = (
file: File,
result: { id: string; url: string },
@@ -146,11 +164,12 @@ export class FileManageActionImpl {
};
embeddingChunks = async (fileIds: string[]): Promise<void> => {
+ const chunkTargetIds = await this.#resolveChunkTargetIds(fileIds);
// toggle file ids
- this.#get().toggleEmbeddingIds(fileIds);
+ this.#get().toggleEmbeddingIds(chunkTargetIds);
// parse files
- const pools = fileIds.map(async (id) => {
+ const pools = chunkTargetIds.map(async (id) => {
try {
await ragService.createEmbeddingChunksTask(id);
} catch (e) {
@@ -160,7 +179,7 @@ export class FileManageActionImpl {
await Promise.all(pools);
await this.#get().refreshFileList();
- this.#get().toggleEmbeddingIds(fileIds, false);
+ this.#get().toggleEmbeddingIds(chunkTargetIds, false);
};
loadMoreKnowledgeItems = async (): Promise<void> => {
@@ -219,11 +238,12 @@ export class FileManageActionImpl {
};
parseFilesToChunks = async (ids: string[], params?: { skipExist?: boolean }): Promise<void> => {
+ const chunkTargetIds = await this.#resolveChunkTargetIds(ids);
// toggle file ids
- this.#get().toggleParsingIds(ids);
+ this.#get().toggleParsingIds(chunkTargetIds);
// parse files
- const pools = ids.map(async (id) => {
+ const pools = chunkTargetIds.map(async (id) => {
try {
await ragService.createParseFileTask(id, params?.skipExist);
} catch (e) {
@@ -233,7 +253,7 @@ export class FileManageActionImpl {
await Promise.all(pools);
await this.#get().refreshFileList();
- this.#get().toggleParsingIds(ids, false);
+ this.#get().toggleParsingIds(chunkTargetIds, false);
};
pushDockFileList = async (
@@ -339,31 +359,33 @@ export class FileManageActionImpl {
};
reEmbeddingChunks = async (id: string): Promise<void> => {
- if (fileManagerSelectors.isCreatingChunkEmbeddingTask(id)(this.#get())) return;
+ const chunkTargetId = await this.#resolveChunkTargetId(id);
+ if (fileManagerSelectors.isCreatingChunkEmbeddingTask(chunkTargetId)(this.#get())) return;
// toggle file ids
- this.#get().toggleEmbeddingIds([id]);
+ this.#get().toggleEmbeddingIds([chunkTargetId]);
- await serverFileService.removeFileAsyncTask(id, 'embedding');
+ await serverFileService.removeFileAsyncTask(chunkTargetId, 'embedding');
await this.#get().refreshFileList();
- await ragService.createEmbeddingChunksTask(id);
+ await ragService.createEmbeddingChunksTask(chunkTargetId);
await this.#get().refreshFileList();
- this.#get().toggleEmbeddingIds([id], false);
+ this.#get().toggleEmbeddingIds([chunkTargetId], false);
};
reParseFile = async (id: string): Promise<void> => {
+ const chunkTargetId = await this.#resolveChunkTargetId(id);
// toggle file ids
- this.#get().toggleParsingIds([id]);
+ this.#get().toggleParsingIds([chunkTargetId]);
- await ragService.retryParseFile(id);
+ await ragService.retryParseFile(chunkTargetId);
await this.#get().refreshFileList();
- this.#get().toggleParsingIds([id], false);
+ this.#get().toggleParsingIds([chunkTargetId], false);
};
#refreshKnowledgeListCaches = async (): Promise<void> => {
diff --git a/src/store/file/slices/fileManager/selectors.test.ts b/src/store/file/slices/fileManager/selectors.test.ts
new file mode 100644
index 00000000000..8b6fa124a7c
--- /dev/null
+++ b/src/store/file/slices/fileManager/selectors.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+
+import { initialState } from '@/store/file/initialState';
+
+import { fileManagerSelectors, getChunkTargetId } from './selectors';
+
+describe('fileManagerSelectors', () => {
+ describe('getFileByChunkTargetId', () => {
+ it('should find resources by linked file id when they are not in fileList', () => {
+ const state = {
+ ...initialState,
+ fileList: [],
+ resourceList: [
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Document-backed file',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ } as any;
+
+ expect(fileManagerSelectors.getFileByChunkTargetId('file_1')(state)).toMatchObject({
+ fileId: 'file_1',
+ id: 'docs_1',
+ });
+ });
+
+ it('should prefer fileList items over resourceList items', () => {
+ const state = {
+ ...initialState,
+ fileList: [
+ {
+ createdAt: new Date(),
+ embeddingError: null,
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ finishEmbedding: false,
+ id: 'file_1',
+ name: 'File list item',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ url: 'files/file-1.txt',
+ },
+ ],
+ resourceList: [
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Resource list item',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ } as any;
+
+ expect(fileManagerSelectors.getFileByChunkTargetId('file_1')(state)).toMatchObject({
+ id: 'file_1',
+ name: 'File list item',
+ });
+ });
+
+ it('should find resources from resourceMap when they are off the visible list', () => {
+ const state = {
+ ...initialState,
+ fileList: [],
+ resourceList: [],
+ resourceMap: new Map([
+ [
+ 'docs_1',
+ {
+ createdAt: new Date(),
+ fileId: 'file_1',
+ fileType: 'text/plain',
+ id: 'docs_1',
+ name: 'Mapped resource',
+ size: 1,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ },
+ ],
+ ]),
+ } as any;
+
+ expect(fileManagerSelectors.getFileByChunkTargetId('file_1')(state)).toMatchObject({
+ fileId: 'file_1',
+ id: 'docs_1',
+ });
+ });
+ });
+
+ describe('getChunkTargetId', () => {
+ // For file-backed resources the item id can be a coalesced docs_* id while
+ // chunk APIs need the underlying file_* id. See issue #16267.
+ it('returns the linked fileId when present', () => {
+ expect(getChunkTargetId({ fileId: 'file_TaLrbfD61pNv', id: 'docs_B2x3zYnRUttC' })).toBe(
+ 'file_TaLrbfD61pNv',
+ );
+ });
+
+ it('falls back to the item id when there is no fileId', () => {
+ expect(getChunkTargetId({ id: 'docs_B2x3zYnRUttC' })).toBe('docs_B2x3zYnRUttC');
+ });
+
+ it('falls back to the item id when fileId is null', () => {
+ expect(getChunkTargetId({ fileId: null, id: 'file_1' })).toBe('file_1');
+ });
+ });
+});
diff --git a/src/store/file/slices/fileManager/selectors.ts b/src/store/file/slices/fileManager/selectors.ts
index 76a2f2a0a18..3fcf49f9789 100644
--- a/src/store/file/slices/fileManager/selectors.ts
+++ b/src/store/file/slices/fileManager/selectors.ts
@@ -1,4 +1,5 @@
import { type FilesStoreState } from '@/store/file/initialState';
+import { type FileListItem } from '@/types/files';
import { type FileUploadStatus } from '@/types/files/upload';
const uploadStatusArray = new Set(['uploading', 'pending', 'processing']);
@@ -11,6 +12,29 @@ const getFileById = (id?: string | null) => (s: FilesStoreState) => {
return s.fileList.find((item) => item.id === id);
};
+const getFileByChunkTargetId = (id?: string | null) => (s: FilesStoreState) => {
+ if (!id) return;
+
+ return (
+ getFileById(id)(s) ??
+ (s.resourceMap.get(id) as FileListItem | undefined) ??
+ ([...s.resourceMap.values()].find((item) => item.fileId === id) as FileListItem | undefined) ??
+ (s.resourceList.find((item) => item.id === id || item.fileId === id) as
+ | FileListItem
+ | undefined)
+ );
+};
+
+/**
+ * Resolve the id to pass into chunk/embedding/search APIs.
+ *
+ * File-backed knowledge resources can expose a coalesced `docs_*` id while chunk
+ * operations expect the underlying `file_*` id, so prefer `fileId` when present.
+ * @see https://github.com/lobehub/lobehub/issues/16267
+ */
+export const getChunkTargetId = (item: { fileId?: string | null; id: string }): string =>
+ item.fileId ?? item.id;
+
const isUploadingFiles = (s: FilesStoreState) =>
s.dockUploadFileList.some((file) => uploadStatusArray.has(file.status));
@@ -51,6 +75,7 @@ export const fileManagerSelectors = {
dockFileList,
dockRawFileList,
fileListHasMore,
+ getFileByChunkTargetId,
getFileById,
isCreatingChunkEmbeddingTask,
isCreatingFileParseTask,
diff --git a/src/store/file/slices/resource/action.test.ts b/src/store/file/slices/resource/action.test.ts
index 4e4fcaaa53c..fb403fb731c 100644
--- a/src/store/file/slices/resource/action.test.ts
+++ b/src/store/file/slices/resource/action.test.ts
@@ -99,4 +99,43 @@ describe('resource actions', () => {
expect(resourceList).toEqual([]);
expect(resourceMap.has(rootResource.id)).toBe(false);
});
+
+ it('should patch a file-backed document resource with statuses returned by file id', () => {
+ const resource = createResource({
+ chunkCount: null,
+ fileId: 'file-1',
+ id: 'docs-1',
+ });
+
+ useFileStore.setState({
+ resourceList: [resource],
+ resourceMap: new Map([[resource.id, resource]]),
+ });
+
+ useFileStore.getState().patchLocalResourceStatuses([
+ {
+ chunkCount: 10,
+ chunkingError: null,
+ chunkingStatus: 'success',
+ embeddingError: null,
+ embeddingStatus: 'success',
+ finishEmbedding: true,
+ id: 'file-1',
+ },
+ ]);
+
+ const { resourceList, resourceMap } = useFileStore.getState();
+
+ expect(resourceList[0]).toMatchObject({
+ chunkCount: 10,
+ chunkingStatus: 'success',
+ embeddingStatus: 'success',
+ finishEmbedding: true,
+ id: 'docs-1',
+ });
+ expect(resourceMap.get('docs-1')).toMatchObject({
+ chunkCount: 10,
+ embeddingStatus: 'success',
+ });
+ });
});
diff --git a/src/store/file/slices/resource/action.ts b/src/store/file/slices/resource/action.ts
index 7c52891d42a..e024d897aa6 100644
--- a/src/store/file/slices/resource/action.ts
+++ b/src/store/file/slices/resource/action.ts
@@ -479,11 +479,30 @@ export class ResourceActionImpl {
if (items.length === 0) return;
const statusMap = new Map(items.map((item) => [item.id, item]));
+ const statusByResourceId = new Map<
+ string,
+ Pick<
+ ResourceItem,
+ | 'id'
+ | 'chunkCount'
+ | 'chunkingError'
+ | 'chunkingStatus'
+ | 'embeddingError'
+ | 'embeddingStatus'
+ | 'finishEmbedding'
+ >
+ >();
+
+ for (const resource of this.#get().resourceList) {
+ const status =
+ statusMap.get(resource.id) ?? (resource.fileId && statusMap.get(resource.fileId));
+ if (status) statusByResourceId.set(resource.id, status);
+ }
this.#patchLocalResourceEntries(
- new Set(statusMap.keys()),
+ new Set(statusByResourceId.keys()),
(resource) => {
- const patch = statusMap.get(resource.id);
+ const patch = statusByResourceId.get(resource.id);
if (!patch) return resource;
return {
diff --git a/src/types/resource.ts b/src/types/resource.ts
index 624e4d920a9..c2933d0cb88 100644
--- a/src/types/resource.ts
+++ b/src/types/resource.ts
@@ -29,6 +29,7 @@ export interface ResourceItem {
embeddingStatus?: string | null;
embeddingTaskId?: string | null;
+ fileId?: string | null;
fileType: string;
finishEmbedding?: boolean;
// Identity