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(file): skip chunking for formats no parser can handle (#20393)

Arvin Xua485f88e7f55
diff --git a/apps/server/src/services/chunk/index.test.ts b/apps/server/src/services/chunk/index.test.ts
index b1e59447cfa..979107f3e41 100644
--- a/apps/server/src/services/chunk/index.test.ts
+++ b/apps/server/src/services/chunk/index.test.ts
@@ -79,7 +79,7 @@ describe('ChunkService', () => {
},
});
mockEmbeddingChunks.mockResolvedValue(undefined);
- mockFileModelFindById.mockResolvedValue({ id: 'file-1' });
+ mockFileModelFindById.mockResolvedValue({ id: 'file-1', name: 'file-1.pdf' });
mockFileModelUpdate.mockResolvedValue(undefined);
mockParseFileToChunks.mockResolvedValue(undefined);
@@ -164,6 +164,7 @@ describe('ChunkService', () => {
it('should create an error task for files larger than the in-memory parser limit', async () => {
mockFileModelFindById.mockResolvedValue({
id: 'large-file',
+ name: 'large-file.pdf',
size: 64 * 1024 * 1024 + 1,
});
@@ -184,6 +185,21 @@ describe('ChunkService', () => {
expect(mockCreateAsyncCaller).not.toHaveBeenCalled();
});
+ // https://github.com/lobehub/lobehub/issues/19620
+ it('should not create a chunking task for a format no chunking loader can parse', async () => {
+ mockFileModelFindById.mockResolvedValue({
+ id: 'dwg-file',
+ name: 'floor-plan.dwg',
+ size: 1024,
+ });
+
+ await expect(service.asyncParseFileToChunks('dwg-file')).resolves.toBeUndefined();
+
+ expect(mockAsyncTaskModelCreate).not.toHaveBeenCalled();
+ expect(mockFileModelUpdate).not.toHaveBeenCalled();
+ expect(mockCreateAsyncCaller).not.toHaveBeenCalled();
+ });
+
it('should skip creating a new task when skipExist is true and task already exists', async () => {
mockFileModelFindById.mockResolvedValue({ chunkTaskId: 'existing-task', id: 'file-1' });
diff --git a/apps/server/src/services/chunk/index.ts b/apps/server/src/services/chunk/index.ts
index e469f1303da..e2b12009c97 100644
--- a/apps/server/src/services/chunk/index.ts
+++ b/apps/server/src/services/chunk/index.ts
@@ -3,6 +3,7 @@ import { type LobeChatDatabase } from '@lobechat/database';
import { FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE, MAX_FILE_PARSE_SIZE } from '@/const/file';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { FileModel } from '@/database/models/file';
+import { getChunkingLoaderType } from '@/libs/document-loaders/loaderType';
import { type ChunkContentParams } from '@/server/modules/ContentChunk';
import { ContentChunk } from '@/server/modules/ContentChunk';
import {
@@ -86,6 +87,10 @@ export class ChunkService {
// skip if already exist chunk tasks
if (skipExist && result.chunkTaskId) return;
+ // No chunking loader can parse this format (e.g. `.dwg`): creating a task would only
+ // surface a retryable "Chunking failed" for a limitation retrying cannot fix.
+ if (!getChunkingLoaderType(result.name)) return;
+
// 1. create a asyncTaskId
const asyncTaskId = await this.asyncTaskModel.create({
status:
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts
index aa3ca0fc92c..42e5601444c 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/useFileListItemMeta.ts
@@ -3,7 +3,7 @@ import dayjs from 'dayjs';
import { useMemo } from 'react';
import { PAGE_FILE_TYPE } from '@/features/ResourceManager/constants';
-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
+import { isChunkingSupported } from '@/libs/document-loaders/loaderType';
interface UseFileListItemMetaOptions {
createdAt: Date;
@@ -49,6 +49,6 @@ export const useFileListItemMeta = ({
!isPDF &&
!isOfficeFile &&
(sourceType === DERIVED_DOCUMENT_SOURCE_TYPE || fileType === PAGE_FILE_TYPE),
- isSupportedForChunking: !isChunkingUnsupported(fileType),
+ isSupportedForChunking: isChunkingSupported({ fileType, name }),
};
}, [createdAt, fileType, metadata?.emoji, name, sourceType]);
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
index 15cf42914c0..dd4a8b76fe6 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/DefaultFileItem.tsx
@@ -8,10 +8,10 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
+import { isChunkingSupported } from '@/libs/document-loaders/loaderType';
import { fileManagerSelectors, useFileStore } from '@/store/file';
import { type AsyncTaskStatus, type IAsyncTaskError } from '@/types/asyncTask';
import { formatSize } from '@/utils/format';
-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import ChunksBadge from '../../ListView/ListItem/ChunkTag';
@@ -77,7 +77,7 @@ const DefaultFileItem = memo<DefaultFileItemProps>(
]);
const isFolder = fileType === CUSTOM_FOLDER_FILE_TYPE;
- const isSupportedForChunking = !isChunkingUnsupported(fileType || '');
+ const isSupportedForChunking = isChunkingSupported({ fileType, name });
return (
<>
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
index 07ea4674d7d..97d2e38fbd9 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/ImageFileItem.tsx
@@ -6,10 +6,10 @@ import { FileBoxIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { isChunkingSupported } from '@/libs/document-loaders/loaderType';
import { fileManagerSelectors, useFileStore } from '@/store/file';
import { type AsyncTaskStatus, type IAsyncTaskError } from '@/types/asyncTask';
import { formatSize } from '@/utils/format';
-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import ChunksBadge from '../../ListView/ListItem/ChunkTag';
import { FALLBACK_ASPECT_RATIO, readAspectRatio } from './imageAspectRatio';
@@ -196,7 +196,7 @@ const ImageFileItem = memo<ImageFileItemProps>(
s.parseFilesToChunks,
]);
- const isSupportedForChunking = !isChunkingUnsupported(fileType || '');
+ const isSupportedForChunking = isChunkingSupported({ fileType, name });
const imageLoaded = status === 'loaded';
return (
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx
index 610e181a189..6d9b99deafb 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/MarkdownFileItem.tsx
@@ -7,10 +7,10 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
+import { isChunkingSupported } from '@/libs/document-loaders/loaderType';
import { fileManagerSelectors, useFileStore } from '@/store/file';
import { type AsyncTaskStatus, type IAsyncTaskError } from '@/types/asyncTask';
import { formatSize } from '@/utils/format';
-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import ChunksBadge from '../../ListView/ListItem/ChunkTag';
@@ -150,7 +150,7 @@ const MarkdownFileItem = memo<MarkdownFileItemProps>(
s.parseFilesToChunks,
]);
- const isSupportedForChunking = !isChunkingUnsupported(fileType || '');
+ const isSupportedForChunking = isChunkingSupported({ fileType, name });
return (
<>
diff --git a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx
index 8b20e48833d..6851b138a7f 100644
--- a/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx
+++ b/src/features/ResourceManager/components/Explorer/MasonryView/MasonryItem/NoteFileItem.tsx
@@ -6,9 +6,9 @@ import { FileBoxIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { isChunkingSupported } from '@/libs/document-loaders/loaderType';
import { fileManagerSelectors, useFileStore } from '@/store/file';
import { type AsyncTaskStatus, type IAsyncTaskError } from '@/types/asyncTask';
-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import ChunksBadge from '../../ListView/ListItem/ChunkTag';
@@ -106,7 +106,7 @@ const NoteFileItem = memo<NoteFileItemProps>(
s.parseFilesToChunks,
]);
- const isSupportedForChunking = !isChunkingUnsupported(fileType || '');
+ const isSupportedForChunking = isChunkingSupported({ fileType, name });
const displayTitle = name || t('file:pageList.untitled');
const emoji = metadata?.emoji;
diff --git a/src/features/ResourceManager/store/action.ts b/src/features/ResourceManager/store/action.ts
index 7aa84e44c15..a504a7b125f 100644
--- a/src/features/ResourceManager/store/action.ts
+++ b/src/features/ResourceManager/store/action.ts
@@ -50,7 +50,7 @@ export class ResourceManagerStoreActionImpl {
const { libraryId, resolveSelectedResourceIds, selectAllState, selectedFileIds } = this.#get();
const { useFileStore } = await import('@/store/file');
const { useKnowledgeBaseStore } = await import('@/store/library');
- const { isChunkingUnsupported } = await import('@/utils/isChunkingUnsupported');
+ const { isChunkingSupported } = await import('@/libs/document-loaders/loaderType');
const fileStore = useFileStore.getState();
const kbStore = useKnowledgeBaseStore.getState();
@@ -115,7 +115,7 @@ export class ResourceManagerStoreActionImpl {
// For server-resolved IDs not yet in the local map, include them
// and let the server handle unsupported type filtering
if (!resource) return selectAllState === 'all';
- return !isChunkingUnsupported(resource.fileType);
+ return isChunkingSupported(resource);
});
await fileStore.parseFilesToChunks(chunkableFileIds, { skipExist: true });
diff --git a/src/libs/document-loaders/loaderType.test.ts b/src/libs/document-loaders/loaderType.test.ts
new file mode 100644
index 00000000000..648d54ef3d2
--- /dev/null
+++ b/src/libs/document-loaders/loaderType.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+
+import { getChunkingLoaderType, isChunkingSupported } from './loaderType';
+
+describe('getChunkingLoaderType', () => {
+ it('resolves the loader the chunker dispatches on', () => {
+ expect(getChunkingLoaderType('Report.PDF')).toBe('pdf');
+ expect(getChunkingLoaderType('slides.pptx')).toBe('ppt');
+ expect(getChunkingLoaderType('notes.md')).toBe('markdown');
+ expect(getChunkingLoaderType('main.go')).toBe('code');
+ expect(getChunkingLoaderType('data.csv')).toBe('csv');
+ });
+
+ it('returns undefined for formats without a chunking loader', () => {
+ expect(getChunkingLoaderType('floor-plan.dwg')).toBeUndefined();
+ expect(getChunkingLoaderType('photo.png')).toBeUndefined();
+ expect(getChunkingLoaderType('no-extension')).toBeUndefined();
+ });
+});
+
+describe('isChunkingSupported', () => {
+ // https://github.com/lobehub/lobehub/issues/19620
+ it('rejects unknown extensions even when the MIME type is generic or empty', () => {
+ expect(isChunkingSupported({ fileType: 'application/octet-stream', name: 'a.dwg' })).toBe(
+ false,
+ );
+ expect(isChunkingSupported({ fileType: '', name: 'a.dwg' })).toBe(false);
+ });
+
+ it('follows the parser registry rather than the MIME prefix when the name is known', () => {
+ // browsers report `.ts` as MPEG transport stream video
+ expect(isChunkingSupported({ fileType: 'video/mp2t', name: 'index.ts' })).toBe(true);
+ expect(isChunkingSupported({ fileType: 'application/pdf', name: 'paper.pdf' })).toBe(true);
+ });
+
+ it('falls back to the MIME heuristic when the name is missing', () => {
+ expect(isChunkingSupported({ fileType: 'image/png' })).toBe(false);
+ expect(isChunkingSupported({ fileType: 'application/pdf', name: null })).toBe(true);
+ });
+});
diff --git a/src/libs/document-loaders/loaderType.ts b/src/libs/document-loaders/loaderType.ts
new file mode 100644
index 00000000000..7c7590e5f6b
--- /dev/null
+++ b/src/libs/document-loaders/loaderType.ts
@@ -0,0 +1,70 @@
+import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
+
+import { SUPPORT_TEXT_LIST } from './file';
+import { SUPPORTED_LANGUAGES, type SupportedLanguage } from './splitter/separators';
+import { type FileLoaderType } from './types';
+
+/**
+ * Resolve which built-in chunking loader handles a file, by filename.
+ * This is the single source of truth `ChunkingLoader.partitionContent` dispatches on:
+ * `undefined` means the chunking task is guaranteed to fail.
+ */
+export const getChunkingLoaderType = (filename: string): FileLoaderType | undefined => {
+ const name = filename.toLowerCase();
+
+ if (name.endsWith('pptx')) {
+ return 'ppt';
+ }
+
+ if (name.endsWith('docx') || name.endsWith('doc')) {
+ return 'doc';
+ }
+
+ if (name.endsWith('pdf')) {
+ return 'pdf';
+ }
+
+ if (name.endsWith('tex')) {
+ return 'latex';
+ }
+
+ if (name.endsWith('md') || name.endsWith('mdx')) {
+ return 'markdown';
+ }
+
+ if (name.endsWith('csv')) {
+ return 'csv';
+ }
+
+ if (name.endsWith('epub')) {
+ return 'epub';
+ }
+
+ if (name.endsWith('ipynb')) {
+ return 'ipynb';
+ }
+
+ const ext = name.split('.').pop();
+
+ if (ext && SUPPORTED_LANGUAGES.includes(ext as SupportedLanguage)) {
+ return 'code';
+ }
+
+ if (ext && SUPPORT_TEXT_LIST.includes(ext)) return 'text';
+};
+
+/**
+ * Whether a file is eligible for chunking. Uses the parser's own registry when the
+ * filename is known, and only falls back to the MIME heuristic when it is not.
+ */
+export const isChunkingSupported = ({
+ fileType,
+ name,
+}: {
+ fileType?: string | null;
+ name?: string | null;
+}): boolean => {
+ if (name) return !!getChunkingLoaderType(name);
+
+ return !isChunkingUnsupported(fileType ?? '');
+};
diff --git a/src/libs/document-loaders/loaders/index.ts b/src/libs/document-loaders/loaders/index.ts
index 2d6af993acf..e5b8b803e83 100644
--- a/src/libs/document-loaders/loaders/index.ts
+++ b/src/libs/document-loaders/loaders/index.ts
@@ -1,8 +1,7 @@
import { convertIpynbToMarkdown, scrubIpynbFallbackText } from '@lobechat/file-loaders';
-import { SUPPORT_TEXT_LIST } from '../file';
-import { SUPPORTED_LANGUAGES, type SupportedLanguage } from '../splitter';
-import { type DocumentChunk, type FileLoaderType } from '../types';
+import { getChunkingLoaderType } from '../loaderType';
+import { type DocumentChunk } from '../types';
import { CodeLoader } from './code';
import { CsVLoader } from './csv';
import { DocxLoader } from './docx';
@@ -26,7 +25,7 @@ export class ChunkingLoader {
const fileBlob = new Blob([Buffer.from(content)]);
const txt = this.uint8ArrayToString(content);
- const type = this.getType(filename?.toLowerCase());
+ const type = getChunkingLoaderType(filename ?? '');
switch (type) {
case 'code': {
@@ -86,48 +85,6 @@ export class ChunkingLoader {
}
};
- private getType = (filename: string): FileLoaderType | undefined => {
- if (filename.endsWith('pptx')) {
- return 'ppt';
- }
-
- if (filename.endsWith('docx') || filename.endsWith('doc')) {
- return 'doc';
- }
-
- if (filename.endsWith('pdf')) {
- return 'pdf';
- }
-
- if (filename.endsWith('tex')) {
- return 'latex';
- }
-
- if (filename.endsWith('md') || filename.endsWith('mdx')) {
- return 'markdown';
- }
-
- if (filename.endsWith('csv')) {
- return 'csv';
- }
-
- if (filename.endsWith('epub')) {
- return 'epub';
- }
-
- if (filename.endsWith('ipynb')) {
- return 'ipynb';
- }
-
- const ext = filename.split('.').pop();
-
- if (ext && SUPPORTED_LANGUAGES.includes(ext as SupportedLanguage)) {
- return 'code';
- }
-
- if (ext && SUPPORT_TEXT_LIST.includes(ext)) return 'text';
- };
-
private uint8ArrayToString(uint8Array: Uint8Array) {
const decoder = new TextDecoder();
return decoder.decode(uint8Array);
diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.ts
index b38f5e059ca..9ddde0e87f2 100644
--- a/src/store/file/slices/fileManager/action.test.ts
+++ b/src/store/file/slices/fileManager/action.test.ts
@@ -591,6 +591,27 @@ describe('FileManagerActions', () => {
expect(parseSpy).not.toHaveBeenCalled();
});
+ // https://github.com/lobehub/lobehub/issues/19620
+ it('should skip auto-embed for formats no chunking loader can parse', async () => {
+ const { result } = renderHook(() => useStore());
+
+ const dwgFile = new File(['dwg content'], 'floor-plan.dwg', { type: '' });
+ const binFile = new File(['bin content'], 'model.dxf', {
+ type: 'application/octet-stream',
+ });
+
+ vi.spyOn(result.current, 'uploadWithProgress')
+ .mockResolvedValueOnce({ id: 'file-1', url: 'http://example.com/file-1' })
+ .mockResolvedValueOnce({ id: 'file-2', url: 'http://example.com/file-2' });
+ const parseSpy = vi.spyOn(result.current, 'parseFilesToChunks').mockResolvedValue();
+
+ await act(async () => {
+ await result.current.pushDockFileList([dwgFile, binFile]);
+ });
+
+ expect(parseSpy).not.toHaveBeenCalled();
+ });
+
it('should auto-embed only supported files in mixed upload', async () => {
const { result } = renderHook(() => useStore());
diff --git a/src/store/file/slices/fileManager/action.ts b/src/store/file/slices/fileManager/action.ts
index b2621d4fb93..98bc8258294 100644
--- a/src/store/file/slices/fileManager/action.ts
+++ b/src/store/file/slices/fileManager/action.ts
@@ -10,6 +10,7 @@ import pMap from 'p-map';
import { type SWRResponse } from 'swr';
import { FILE_UPLOAD_BLACKLIST, MAX_UPLOAD_FILE_COUNT } from '@/const/file';
+import { isChunkingSupported } from '@/libs/document-loaders/loaderType';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { fileKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
@@ -20,7 +21,6 @@ import { uploadFileListReducer } from '@/store/file/reducers/uploadFileList';
import { type StoreSetter } from '@/store/types';
import { type FileListItem, type QueryFileListParams } from '@/types/files';
import { type ResourceItem } from '@/types/resource';
-import { isChunkingUnsupported } from '@/utils/isChunkingUnsupported';
import { unzipFile } from '@/utils/unzipFile';
import { type FileStore } from '../../store';
@@ -195,7 +195,7 @@ export class FileManageActionImpl {
if (!result) return;
await this.#get().refreshFileList({ revalidateResources: true });
- if (!isChunkingUnsupported(item.file.type)) {
+ if (isChunkingSupported({ fileType: item.file.type, name: item.file.name })) {
await this.#get().parseFilesToChunks([result.id], { skipExist: false });
}
} catch (error) {
@@ -415,7 +415,10 @@ export class FileManageActionImpl {
// 5. auto-embed files that support chunking
const fileIdsToEmbed = uploadResults
- .filter(({ fileType, fileId }) => fileId && !isChunkingUnsupported(fileType))
+ .filter(
+ ({ file, fileId }) =>
+ fileId && isChunkingSupported({ fileType: file.type, name: file.name }),
+ )
.map(({ fileId }) => fileId!);
if (fileIdsToEmbed.length > 0) {
@@ -733,7 +736,10 @@ export class FileManageActionImpl {
// 9. Auto-embed files that support chunking
const fileIdsToEmbed = uploadResults
- .filter(({ fileType, fileId }) => fileId && !isChunkingUnsupported(fileType))
+ .filter(
+ ({ file, fileId }) =>
+ fileId && isChunkingSupported({ fileType: file.type, name: file.name }),
+ )
.map(({ fileId }) => fileId!);
if (fileIdsToEmbed.length > 0) {