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(upload): support memory-safe large file uploads (#18945)

Innei295c7fe0af56
diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.ts
index 5fbfa74a6af..637480aff59 100644
--- a/apps/cli/src/utils/uploadLocalFile.ts
+++ b/apps/cli/src/utils/uploadLocalFile.ts
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
+import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import { resolveMimeType } from '@lobechat/utils/mimeType';
import type { TrpcClient } from '../api/client';
@@ -32,6 +33,8 @@ export const uploadFileBuffer = async (
{ buffer, fileName, fileType }: UploadFileBufferInput,
options: UploadLocalFileOptions = {},
) => {
+ if (buffer.length > MAX_UPLOAD_FILE_SIZE) throw new Error(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
+
// Compute SHA-256 hash for deduplication
const hash = crypto.createHash('sha256').update(buffer).digest('hex');
@@ -52,7 +55,10 @@ export const uploadFileBuffer = async (
} else {
// 2. Get a pre-signed upload URL and PUT the bytes to S3
pathname = ext ? `files/${date}/${hash}.${ext}` : `files/${date}/${hash}`;
- const presigned = await client.upload.createS3PreSignedUrl.mutate({ pathname });
+ const presigned = await client.upload.createS3PreSignedUrl.mutate({
+ pathname,
+ size: buffer.length,
+ });
const presignedUrl = typeof presigned === 'string' ? presigned : (presigned as any).url;
const uploadRes = await fetch(presignedUrl, {
@@ -105,6 +111,7 @@ export const uploadLocalFile = async (
if (!stat.isFile()) {
throw new Error(`Not a file: ${resolved}`);
}
+ if (stat.size > MAX_UPLOAD_FILE_SIZE) throw new Error(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
const fileName = path.basename(resolved);
const fileBuffer = fs.readFileSync(resolved);
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts
index 4295b2024da..ce17a54745f 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts
@@ -85,7 +85,7 @@ describe('createLambdaFileStorePort', () => {
...auth,
getServerUrl: async () => 'https://cloud.lobehub.com/',
});
- await port!.createS3PreSignedUrl({ pathname: 'files/a/b.png' });
+ await port!.createS3PreSignedUrl({ pathname: 'files/a/b.png', size: 123 });
expect(vi.mocked(fetch).mock.calls[0][0]).toBe(
'https://cloud.lobehub.com/trpc/lambda/upload.createS3PreSignedUrl',
diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.ts
index 4bcdbc1923d..121f1ea4fb4 100644
--- a/apps/server/src/modules/S3/index.test.ts
+++ b/apps/server/src/modules/S3/index.test.ts
@@ -1,11 +1,17 @@
// @vitest-environment node
+import type { ListPartsCommandOutput } from '@aws-sdk/client-s3';
import {
+ AbortMultipartUploadCommand,
+ CompleteMultipartUploadCommand,
+ CreateMultipartUploadCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
GetObjectCommand,
HeadObjectCommand,
+ paginateListParts,
PutObjectCommand,
S3Client,
+ UploadPartCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -398,6 +404,114 @@ describe('FileS3', () => {
});
});
+ describe('multipart uploads', () => {
+ it('should create an upload and sign individual parts', async () => {
+ const s3 = new FileS3();
+ mockS3ClientSend.mockResolvedValue({ UploadId: 'upload-1' });
+
+ await expect(s3.createMultipartUpload('large.bin', 'application/octet-stream')).resolves.toBe(
+ 'upload-1',
+ );
+ await expect(s3.createPreSignedUploadPartUrl('large.bin', 'upload-1', 2)).resolves.toBe(
+ 'https://presigned-url.example.com',
+ );
+
+ expect(CreateMultipartUploadCommand).toHaveBeenCalledWith({
+ ACL: 'public-read',
+ Bucket: 'test-bucket',
+ ContentType: 'application/octet-stream',
+ Key: 'large.bin',
+ });
+ expect(UploadPartCommand).toHaveBeenCalledWith({
+ Bucket: 'test-bucket',
+ Key: 'large.bin',
+ PartNumber: 2,
+ UploadId: 'upload-1',
+ });
+ });
+
+ it('should complete with ETags returned to the browser', async () => {
+ const s3 = new FileS3();
+ mockS3ClientSend.mockResolvedValue({});
+
+ await s3.completeMultipartUpload('large.bin', 'upload-1', 2, [
+ { ETag: 'etag-2', PartNumber: 2 },
+ { ETag: 'etag-1', PartNumber: 1 },
+ ]);
+
+ expect(paginateListParts).not.toHaveBeenCalled();
+ expect(CompleteMultipartUploadCommand).toHaveBeenCalledWith({
+ Bucket: 'test-bucket',
+ Key: 'large.bin',
+ MultipartUpload: {
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1 },
+ { ETag: 'etag-2', PartNumber: 2 },
+ ],
+ },
+ UploadId: 'upload-1',
+ });
+ });
+
+ it('should fall back to listing parts when CORS hides ETag', async () => {
+ const s3 = new FileS3();
+ vi.mocked(paginateListParts).mockReturnValue(
+ (async function* (): AsyncGenerator<ListPartsCommandOutput, undefined> {
+ yield {
+ Parts: [
+ { ETag: 'etag-2', PartNumber: 2 },
+ { ETag: 'etag-1', PartNumber: 1 },
+ ],
+ } as ListPartsCommandOutput;
+ return undefined;
+ })(),
+ );
+ mockS3ClientSend.mockResolvedValue({});
+
+ await s3.completeMultipartUpload('large.bin', 'upload-1', 2);
+
+ expect(CompleteMultipartUploadCommand).toHaveBeenCalledWith({
+ Bucket: 'test-bucket',
+ Key: 'large.bin',
+ MultipartUpload: {
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1 },
+ { ETag: 'etag-2', PartNumber: 2 },
+ ],
+ },
+ UploadId: 'upload-1',
+ });
+ });
+
+ it('should reject completion when a part is missing', async () => {
+ const s3 = new FileS3();
+ vi.mocked(paginateListParts).mockReturnValue(
+ (async function* (): AsyncGenerator<ListPartsCommandOutput, undefined> {
+ yield { Parts: [{ ETag: 'etag-1', PartNumber: 1 }] } as ListPartsCommandOutput;
+ return undefined;
+ })(),
+ );
+
+ await expect(s3.completeMultipartUpload('large.bin', 'upload-1', 2)).rejects.toThrow(
+ 'has 1/2 parts',
+ );
+ expect(CompleteMultipartUploadCommand).not.toHaveBeenCalled();
+ });
+
+ it('should abort an unfinished upload', async () => {
+ const s3 = new FileS3();
+ mockS3ClientSend.mockResolvedValue({});
+
+ await s3.abortMultipartUpload('large.bin', 'upload-1');
+
+ expect(AbortMultipartUploadCommand).toHaveBeenCalledWith({
+ Bucket: 'test-bucket',
+ Key: 'large.bin',
+ UploadId: 'upload-1',
+ });
+ });
+ });
+
describe('createPreSignedUrlForPreview', () => {
it('should create presigned URL for preview with default expiration', async () => {
const s3 = new FileS3();
diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.ts
index 1c95569ac85..52a99e821ba 100644
--- a/apps/server/src/modules/S3/index.ts
+++ b/apps/server/src/modules/S3/index.ts
@@ -1,10 +1,15 @@
import {
+ AbortMultipartUploadCommand,
+ CompleteMultipartUploadCommand,
+ CreateMultipartUploadCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
GetObjectCommand,
HeadObjectCommand,
+ paginateListParts,
PutObjectCommand,
S3Client,
+ UploadPartCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import mime from 'mime';
@@ -164,6 +169,87 @@ export class S3 {
};
}
+ public async createMultipartUpload(key: string, contentType?: string): Promise<string> {
+ const response = await this.client.send(
+ new CreateMultipartUploadCommand({
+ ACL: this.setAcl ? PUBLIC_READ_ACL_HEADER : undefined,
+ Bucket: this.bucket,
+ ContentType: contentType || undefined,
+ Key: key,
+ }),
+ );
+
+ if (!response.UploadId) throw new Error(`S3 did not return an upload id for ${key}`);
+
+ return response.UploadId;
+ }
+
+ public async createPreSignedUploadPartUrl(
+ key: string,
+ uploadId: string,
+ partNumber: number,
+ ): Promise<string> {
+ const command = new UploadPartCommand({
+ Bucket: this.bucket,
+ Key: key,
+ PartNumber: partNumber,
+ UploadId: uploadId,
+ });
+
+ return getSignedUrl(this.client, command, { expiresIn: 3600 });
+ }
+
+ public async completeMultipartUpload(
+ key: string,
+ uploadId: string,
+ expectedPartCount: number,
+ uploadedParts?: Array<{ ETag: string; PartNumber: number }>,
+ ) {
+ const parts = uploadedParts ? [...uploadedParts] : [];
+
+ if (!uploadedParts) {
+ for await (const page of paginateListParts(
+ { client: this.client },
+ { Bucket: this.bucket, Key: key, UploadId: uploadId },
+ )) {
+ for (const part of page.Parts ?? []) {
+ if (!part.ETag || !part.PartNumber) continue;
+ parts.push({ ETag: part.ETag, PartNumber: part.PartNumber });
+ }
+ }
+ }
+
+ parts.sort((a, b) => a.PartNumber - b.PartNumber);
+ const hasAllParts =
+ parts.length === expectedPartCount &&
+ parts.every((part, index) => part.PartNumber === index + 1);
+
+ if (!hasAllParts) {
+ throw new Error(
+ `S3 multipart upload ${uploadId} has ${parts.length}/${expectedPartCount} parts`,
+ );
+ }
+
+ return this.client.send(
+ new CompleteMultipartUploadCommand({
+ Bucket: this.bucket,
+ Key: key,
+ MultipartUpload: { Parts: parts },
+ UploadId: uploadId,
+ }),
+ );
+ }
+
+ public async abortMultipartUpload(key: string, uploadId: string) {
+ return this.client.send(
+ new AbortMultipartUploadCommand({
+ Bucket: this.bucket,
+ Key: key,
+ UploadId: uploadId,
+ }),
+ );
+ }
+
public async createPreSignedUrlForPreview(key: string, expiresIn?: number): Promise<string> {
const command = new GetObjectCommand({
Bucket: this.bucket,
diff --git a/apps/server/src/routers/async/__tests__/file.test.ts b/apps/server/src/routers/async/__tests__/file.test.ts
index b134d720863..5ca2c8d865a 100644
--- a/apps/server/src/routers/async/__tests__/file.test.ts
+++ b/apps/server/src/routers/async/__tests__/file.test.ts
@@ -9,7 +9,7 @@ import { FileModel } from '@/database/models/file';
import { ChunkService } from '@/server/services/chunk';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
-import { AsyncTaskStatus } from '@/types/asyncTask';
+import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';
import { fileRouter } from '../file';
@@ -96,6 +96,29 @@ describe('fileRouter.parseFileToChunks β€” NoSuchKey + internal:// branches', ()
);
});
+ it('rejects oversized files before reading them into memory', async () => {
+ fileModelMock.findById.mockResolvedValue({
+ id: 'large-file',
+ name: 'large.pdf',
+ size: 64 * 1024 * 1024 + 1,
+ url: 'https://example.com/large.pdf',
+ });
+
+ const caller = fileRouter.createCaller(mockCtx);
+
+ await expect(
+ caller.parseFileToChunks({ fileId: 'large-file', taskId: 'task-large' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(fileServiceMock.getFileByteArray).not.toHaveBeenCalled();
+ expect(asyncTaskModelMock.update).toHaveBeenCalledWith('task-large', {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.FileTooLargeToParse,
+ 'Files larger than 67108864 bytes cannot be parsed in memory',
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ });
+
it('skips storage fetch and returns gracefully when url is internal://', async () => {
fileModelMock.findById.mockResolvedValue({
id: 'file_inline',
diff --git a/apps/server/src/routers/async/file.ts b/apps/server/src/routers/async/file.ts
index 7994e75f992..8c3baab953f 100644
--- a/apps/server/src/routers/async/file.ts
+++ b/apps/server/src/routers/async/file.ts
@@ -6,6 +6,7 @@ import pMap from 'p-map';
import { z } from 'zod';
import { checkEmbeddingUsage } from '@/business/server/trpc-middlewares/async';
+import { FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE, MAX_FILE_PARSE_SIZE } from '@/const/file';
import { DEFAULT_FILE_EMBEDDING_MODEL_ITEM } from '@/const/settings/knowledge';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { ChunkModel } from '@/database/models/chunk';
@@ -209,6 +210,21 @@ export const fileRouter = router({
throw new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' });
}
+ if (file.size > MAX_FILE_PARSE_SIZE) {
+ await asyncTaskModel.update(input.taskId, {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.FileTooLargeToParse,
+ FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE,
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE,
+ });
+ }
+
// Inline documents (custom/document) keep a mirror file row whose url is the
// `internal://document/placeholder` marker. Their content lives on documents.content
// and is intentionally not chunked β€” searching is handled by BM25 instead.
@@ -304,14 +320,12 @@ export const fileRouter = router({
});
// after finish partition, we need to filter out some elements
- const chunks = chunkResult.chunks.map(
- ({ text, ...item }): NewChunkItem => ({
- ...item,
- text: text ? sanitizeUTF8(text) : '',
- userId: ctx.userId,
- workspaceId,
- }),
- );
+ const chunks = chunkResult.chunks.map(({ text, ...item }): NewChunkItem => ({
+ ...item,
+ text: text ? sanitizeUTF8(text) : '',
+ userId: ctx.userId,
+ workspaceId,
+ }));
const duration = Date.now() - startAt;
@@ -327,14 +341,12 @@ export const fileRouter = router({
await chunkModel.bulkCreate(chunks, input.fileId);
if (chunkResult.unstructuredChunks) {
- const unstructuredChunks = chunkResult.unstructuredChunks.map(
- (item): NewChunkItem => ({
- ...item,
- fileId: input.fileId,
- userId: ctx.userId,
- workspaceId,
- }),
- );
+ const unstructuredChunks = chunkResult.unstructuredChunks.map((item): NewChunkItem => ({
+ ...item,
+ fileId: input.fileId,
+ userId: ctx.userId,
+ workspaceId,
+ }));
await chunkModel.bulkCreateUnstructuredChunks(unstructuredChunks);
}
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index e9f8614f952..327c26f2d4a 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -1,3 +1,4 @@
+import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -612,6 +613,31 @@ describe('fileRouter', () => {
);
});
+ it('should reject actual storage objects larger than the database size range', async () => {
+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });
+ mockFileServiceGetFileMetadata.mockResolvedValue({
+ contentLength: MAX_UPLOAD_FILE_SIZE + 1,
+ contentType: 'application/octet-stream',
+ });
+
+ await expect(
+ caller.createFile({
+ hash: 'test-hash',
+ fileType: 'application/octet-stream',
+ metadata: {},
+ name: 'huge.bin',
+ size: 100,
+ url: 'files/huge.bin',
+ }),
+ ).rejects.toMatchObject({
+ code: 'PAYLOAD_TOO_LARGE',
+ message: UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE,
+ });
+
+ expect(mockFileModelCreate).not.toHaveBeenCalled();
+ expect(routerMocks.businessFileUploadCheck).not.toHaveBeenCalled();
+ });
+
it('should fallback to input size when getFileMetadata fails', async () => {
mockFileModelCheckHash.mockResolvedValue({ isExist: false });
mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index 0a1be06f0d6..817b070c6b1 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -1,4 +1,9 @@
-import { CUSTOM_FOLDER_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
+import {
+ CUSTOM_FOLDER_FILE_TYPE,
+ DERIVED_DOCUMENT_SOURCE_TYPE,
+ MAX_UPLOAD_FILE_SIZE,
+ UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE,
+} from '@lobechat/const';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -243,6 +248,13 @@ export const fileRouter = router({
throw new TRPCError({ code: 'BAD_REQUEST', message: 'File size cannot be negative' });
}
+ if (actualSize > MAX_UPLOAD_FILE_SIZE) {
+ throw new TRPCError({
+ code: 'PAYLOAD_TOO_LARGE',
+ message: UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE,
+ });
+ }
+
const { id } = await ctx.serverDB.transaction(async (trx) => {
await businessFileUploadCheck({
actualSize,
diff --git a/apps/server/src/routers/lambda/upload.test.ts b/apps/server/src/routers/lambda/upload.test.ts
new file mode 100644
index 00000000000..09400cbd087
--- /dev/null
+++ b/apps/server/src/routers/lambda/upload.test.ts
@@ -0,0 +1,89 @@
+import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { uploadRouter } from '@/server/routers/lambda/upload';
+
+const mockAbortMultipartUpload = vi.fn();
+const mockCompleteMultipartUpload = vi.fn();
+const mockCreateMultipartUpload = vi.fn();
+const mockCreatePreSignedUploadPartUrl = vi.fn();
+const mockCreatePreSignedUrl = vi.fn();
+
+vi.mock('@/server/modules/S3', () => ({
+ FileS3: vi.fn(() => ({
+ abortMultipartUpload: mockAbortMultipartUpload,
+ completeMultipartUpload: mockCompleteMultipartUpload,
+ createMultipartUpload: mockCreateMultipartUpload,
+ createPreSignedUploadPartUrl: mockCreatePreSignedUploadPartUrl,
+ createPreSignedUrl: mockCreatePreSignedUrl,
+ })),
+}));
+
+describe('uploadRouter', () => {
+ const caller = uploadRouter.createCaller({ userId: 'user-1' } as any);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCreateMultipartUpload.mockResolvedValue('upload-id');
+ mockCreatePreSignedUrl.mockResolvedValue('https://example.com/upload');
+ });
+
+ it('rejects oversized single upload presign requests', async () => {
+ await expect(
+ caller.createS3PreSignedUrl({
+ pathname: 'files/huge.bin',
+ size: MAX_UPLOAD_FILE_SIZE + 1,
+ }),
+ ).rejects.toThrow(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
+
+ expect(mockCreatePreSignedUrl).not.toHaveBeenCalled();
+ });
+
+ it('rejects oversized multipart upload creation requests', async () => {
+ await expect(
+ caller.createS3MultipartUpload({
+ contentType: 'application/octet-stream',
+ pathname: 'files/huge.bin',
+ size: MAX_UPLOAD_FILE_SIZE + 1,
+ }),
+ ).rejects.toThrow(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
+
+ expect(mockCreateMultipartUpload).not.toHaveBeenCalled();
+ });
+
+ it('passes valid upload sizes through to storage signing', async () => {
+ await expect(
+ caller.createS3PreSignedUrl({
+ pathname: 'files/ok.bin',
+ size: MAX_UPLOAD_FILE_SIZE,
+ }),
+ ).resolves.toBe('https://example.com/upload');
+
+ await expect(
+ caller.createS3MultipartUpload({
+ pathname: 'files/ok-large.bin',
+ size: MAX_UPLOAD_FILE_SIZE,
+ }),
+ ).resolves.toEqual({ uploadId: 'upload-id' });
+
+ expect(mockCreatePreSignedUrl).toHaveBeenCalledWith('files/ok.bin');
+ expect(mockCreateMultipartUpload).toHaveBeenCalledWith('files/ok-large.bin', undefined);
+ });
+
+ it('keeps upload size optional for released clients', async () => {
+ await expect(
+ caller.createS3PreSignedUrl({
+ pathname: 'files/legacy.bin',
+ }),
+ ).resolves.toBe('https://example.com/upload');
+
+ await expect(
+ caller.createS3MultipartUpload({
+ pathname: 'files/legacy-large.bin',
+ }),
+ ).resolves.toEqual({ uploadId: 'upload-id' });
+
+ expect(mockCreatePreSignedUrl).toHaveBeenCalledWith('files/legacy.bin');
+ expect(mockCreateMultipartUpload).toHaveBeenCalledWith('files/legacy-large.bin', undefined);
+ });
+});
diff --git a/apps/server/src/routers/lambda/upload.ts b/apps/server/src/routers/lambda/upload.ts
index 159173f6c75..7ce4ce8cb74 100644
--- a/apps/server/src/routers/lambda/upload.ts
+++ b/apps/server/src/routers/lambda/upload.ts
@@ -1,13 +1,90 @@
+import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { FileS3 } from '@/server/modules/S3';
+const multipartUploadSchema = z.object({
+ pathname: z.string().min(1),
+ uploadId: z.string().min(1),
+});
+
+const multipartPartSchema = z.object({
+ etag: z.string().min(1),
+ partNumber: z.number().int().min(1).max(10_000),
+});
+
+const uploadSizeSchema = z
+ .number()
+ .int()
+ .min(0)
+ .max(MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE)
+ .optional();
+
export const uploadRouter = router({
+ abortS3MultipartUpload: authedProcedure
+ .use(withScopedPermission('file:upload'))
+ .input(multipartUploadSchema)
+ .mutation(async ({ input }) => {
+ const s3 = new FileS3();
+
+ await s3.abortMultipartUpload(input.pathname, input.uploadId);
+ return { success: true };
+ }),
+
+ completeS3MultipartUpload: authedProcedure
+ .use(withScopedPermission('file:upload'))
+ .input(
+ multipartUploadSchema.extend({
+ partCount: z.number().int().min(1).max(10_000),
+ parts: z.array(multipartPartSchema).max(10_000).optional(),
+ }),
+ )
+ .mutation(async ({ input }) => {
+ const s3 = new FileS3();
+
+ await s3.completeMultipartUpload(
+ input.pathname,
+ input.uploadId,
+ input.partCount,
+ input.parts?.map(({ etag, partNumber }) => ({ ETag: etag, PartNumber: partNumber })),
+ );
+ return { success: true };
+ }),
+
+ createS3MultipartUpload: authedProcedure
+ .use(withScopedPermission('file:upload'))
+ .input(
+ z.object({
+ contentType: z.string().optional(),
+ pathname: z.string().min(1),
+ size: uploadSizeSchema,
+ }),
+ )
+ .mutation(async ({ input }) => {
+ const s3 = new FileS3();
+ const uploadId = await s3.createMultipartUpload(input.pathname, input.contentType);
+
+ return { uploadId };
+ }),
+
+ createS3MultipartUploadPartUrl: authedProcedure
+ .use(withScopedPermission('file:upload'))
+ .input(
+ multipartUploadSchema.extend({
+ partNumber: z.number().int().min(1).max(10_000),
+ }),
+ )
+ .mutation(async ({ input }) => {
+ const s3 = new FileS3();
+
+ return s3.createPreSignedUploadPartUrl(input.pathname, input.uploadId, input.partNumber);
+ }),
+
createS3PreSignedUrl: authedProcedure
.use(withScopedPermission('file:upload'))
- .input(z.object({ pathname: z.string() }))
+ .input(z.object({ pathname: z.string(), size: uploadSizeSchema }))
.mutation(async ({ input }) => {
const s3 = new FileS3();
diff --git a/apps/server/src/services/chunk/index.test.ts b/apps/server/src/services/chunk/index.test.ts
index 690342aef37..40613acda50 100644
--- a/apps/server/src/services/chunk/index.test.ts
+++ b/apps/server/src/services/chunk/index.test.ts
@@ -155,6 +155,29 @@ describe('ChunkService', () => {
expect(mockCreateAsyncCaller).not.toHaveBeenCalled();
});
+ it('should create an error task for files larger than the in-memory parser limit', async () => {
+ mockFileModelFindById.mockResolvedValue({
+ id: 'large-file',
+ size: 64 * 1024 * 1024 + 1,
+ });
+
+ await expect(service.asyncParseFileToChunks('large-file')).resolves.toBe('task-1');
+
+ expect(mockAsyncTaskModelCreate).toHaveBeenCalledWith({
+ status: AsyncTaskStatus.Error,
+ type: AsyncTaskType.Chunking,
+ });
+ expect(mockFileModelUpdate).toHaveBeenCalledWith('large-file', { chunkTaskId: 'task-1' });
+ expect(mockAsyncTaskModelUpdate).toHaveBeenCalledWith('task-1', {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.FileTooLargeToParse,
+ 'Files larger than 67108864 bytes cannot be parsed in memory',
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ 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 ca758cf21b9..e469f1303da 100644
--- a/apps/server/src/services/chunk/index.ts
+++ b/apps/server/src/services/chunk/index.ts
@@ -1,5 +1,6 @@
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 { type ChunkContentParams } from '@/server/modules/ContentChunk';
@@ -87,12 +88,25 @@ export class ChunkService {
// 1. create a asyncTaskId
const asyncTaskId = await this.asyncTaskModel.create({
- status: AsyncTaskStatus.Processing,
+ status:
+ result.size > MAX_FILE_PARSE_SIZE ? AsyncTaskStatus.Error : AsyncTaskStatus.Processing,
type: AsyncTaskType.Chunking,
});
await this.fileModel.update(fileId, { chunkTaskId: asyncTaskId });
+ if (result.size > MAX_FILE_PARSE_SIZE) {
+ await this.asyncTaskModel.update(asyncTaskId, {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.FileTooLargeToParse,
+ FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE,
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+
+ return asyncTaskId;
+ }
+
// Async router will read keyVaults from DB, no need to pass jwtPayload.
// Kept dynamic on purpose: the async router imports this chunk service, so a
// static import here would form a real module cycle that `lint:circular`
diff --git a/packages/const/src/file.ts b/packages/const/src/file.ts
index 3a29aca8b5d..3cc2c28e0e7 100644
--- a/packages/const/src/file.ts
+++ b/packages/const/src/file.ts
@@ -19,6 +19,14 @@ export const FILE_UPLOAD_BLACKLIST = SYSTEM_FILES_BLACKLIST;
export const MAX_UPLOAD_FILE_COUNT = 10;
+export const MAX_UPLOAD_FILE_SIZE = 2 * 1024 * 1024 * 1024 - 1;
+
+export const UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE = `Files larger than ${MAX_UPLOAD_FILE_SIZE} bytes cannot be uploaded`;
+
+export const MAX_FILE_PARSE_SIZE = 64 * 1024 * 1024;
+
+export const FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE = `Files larger than ${MAX_FILE_PARSE_SIZE} bytes cannot be parsed in memory`;
+
export const WORKSPACE_FILE_TREE_EXCLUDED_NAMES = [
...SYSTEM_FILES_BLACKLIST,
diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
index e52c4dcdbbe..c582b38dd54 100644
--- a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
@@ -36,6 +36,10 @@ describe('createFileStoreImageUploader', () => {
headers: { 'Content-Type': 'image/png' },
method: 'PUT',
});
+ expect(port.createS3PreSignedUrl).toHaveBeenCalledWith({
+ pathname: expect.stringMatching(/^files\/\d{4}-\d{2}-\d{2}\/[a-f0-9]{64}\.png$/),
+ size: Buffer.from(PNG_BASE64, 'base64').length,
+ });
const createFileInput = vi.mocked(port.createFile).mock.calls[0][0];
expect(createFileInput).toMatchObject({
diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts
index 26db3667d71..3ea0c116c12 100644
--- a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts
+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts
@@ -28,7 +28,10 @@ export interface FileStoreCreateFileInput {
export interface FileStorePort {
checkFileHash: (input: { hash: string }) => Promise<{ isExist?: boolean; url?: string }>;
createFile: (input: FileStoreCreateFileInput) => Promise<{ id: string; url: string }>;
- createS3PreSignedUrl: (input: { pathname: string }) => Promise<string | { url: string }>;
+ createS3PreSignedUrl: (input: {
+ pathname: string;
+ size: number;
+ }) => Promise<string | { url: string }>;
}
/**
@@ -60,7 +63,7 @@ export const createFileStoreImageUploader =
pathname = existing.url;
} else {
pathname = `files/${date}/${hash}.${ext}`;
- const presigned = await port.createS3PreSignedUrl({ pathname });
+ const presigned = await port.createS3PreSignedUrl({ pathname, size: buffer.length });
const presignedUrl = typeof presigned === 'string' ? presigned : presigned.url;
const uploadRes = await fetch(presignedUrl, {
diff --git a/packages/shared-tool-ui/src/styles.ts b/packages/shared-tool-ui/src/styles.ts
index d9a0b66c728..642390a4e99 100644
--- a/packages/shared-tool-ui/src/styles.ts
+++ b/packages/shared-tool-ui/src/styles.ts
@@ -1,6 +1,18 @@
-import { textGroupStyles, textStyles } from '@lobehub/ui/base-ui';
+import { textStyles } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
+const localTextGroupStyles = createStaticStyles(({ css }) => ({
+ shinyGroup: css`
+ @supports (-webkit-mask-clip: text) {
+ & {
+ --shiny-origin: static;
+
+ position: relative;
+ }
+ }
+ `,
+}));
+
/**
* Inspector text style β€” ellipsis + secondary color + flex align
*/
@@ -8,7 +20,7 @@ export const inspectorTextStyles = createStaticStyles(({ css, cssVar }) => ({
root: css`
/* Coordinate space for the shiny sweep: every shimmering span in the row
* resolves its overlay against this box, so they read as one wave. */
- ${textGroupStyles.shinyGroup}
+ ${localTextGroupStyles.shinyGroup}
overflow: hidden;
display: flex;
@@ -55,5 +67,5 @@ export const shinyTextStyles = {
};
export const shinyGroupStyles = {
- shinyGroup: textGroupStyles.shinyGroup,
+ shinyGroup: localTextGroupStyles.shinyGroup,
};
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index 4dd939a49e1..e2ae4ed8d60 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -17,6 +17,11 @@ export enum AsyncTaskStatus {
export enum AsyncTaskErrorType {
EmbeddingError = 'EmbeddingError',
+ /**
+ * File exceeds the in-memory parser limit and cannot be chunked.
+ */
+ FileTooLargeToParse = 'FileTooLargeToParse',
+
/* ↓ cloud slot | free plan limit error type ↓ */
/**
* Free plan users are not allowed to use this feature
diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsx
index 52741d40f97..b49def8a458 100644
--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx
@@ -321,15 +321,16 @@ const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {
setIsSearching(true);
setSearchEntries(undefined);
- void projectFileService
- .searchProjectFiles({
+ void Promise.resolve(
+ projectFileService.searchProjectFiles({
changedOnly,
deviceId,
excludeIgnored: hideIgnored,
limit: PROJECT_FILE_TREE_SEARCH_LIMIT,
query: normalizedDebouncedQuery,
scope: workingDirectory,
- })
+ }),
+ )
.then((result) => {
if (cancelled) return;
setSearchEntries(result?.entries ?? []);
diff --git a/src/services/__tests__/upload.test.ts b/src/services/__tests__/upload.test.ts
index 08829021f8d..742cd94ab46 100644
--- a/src/services/__tests__/upload.test.ts
+++ b/src/services/__tests__/upload.test.ts
@@ -1,9 +1,15 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { fileEnv } from '@/envs/file';
import { lambdaClient } from '@/libs/trpc/client';
-import { UPLOAD_NETWORK_ERROR, uploadService } from '../upload';
+import { hashFile, UPLOAD_NETWORK_ERROR, uploadService } from '../upload';
+
+const { mockHashHex, mockHashUpdate } = vi.hoisted(() => ({
+ mockHashHex: vi.fn(() => 'streamed-hash'),
+ mockHashUpdate: vi.fn(),
+}));
vi.mock('@lobechat/model-runtime', () => ({
parseDataUri: vi.fn(),
@@ -16,6 +22,18 @@ vi.mock('@lobechat/utils', () => ({
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
upload: {
+ abortS3MultipartUpload: {
+ mutate: vi.fn(),
+ },
+ completeS3MultipartUpload: {
+ mutate: vi.fn(),
+ },
+ createS3MultipartUpload: {
+ mutate: vi.fn(),
+ },
+ createS3MultipartUploadPartUrl: {
+ mutate: vi.fn(),
+ },
createS3PreSignedUrl: {
mutate: vi.fn(),
},
@@ -24,18 +42,32 @@ vi.mock('@/libs/trpc/client', () => ({
}));
vi.mock('js-sha256', () => ({
- sha256: vi.fn((data) => {
- if (data instanceof ArrayBuffer) {
- return 'mock-hash-' + data.byteLength;
- }
- return 'mock-hash';
- }),
+ sha256: {
+ create: vi.fn(() => ({ hex: mockHashHex, update: mockHashUpdate })),
+ },
}));
describe('UploadService', () => {
const mockFile = new File(['test'], 'test.png', { type: 'image/png' });
const mockPreSignUrl = 'https://example.com/presign';
+ beforeAll(() => {
+ Object.defineProperty(File.prototype, 'stream', {
+ configurable: true,
+ value: function () {
+ return new ReadableStream<Uint8Array>({
+ type: 'bytes',
+ start(controller) {
+ const byteController = controller as ReadableByteStreamController;
+ byteController.enqueue(new Uint8Array([1, 2, 3]));
+ byteController.close();
+ },
+ });
+ },
+ writable: true,
+ });
+ });
+
beforeEach(() => {
vi.clearAllMocks();
// Mock Date.now
@@ -51,6 +83,7 @@ describe('UploadService', () => {
setTimeout(() => handler({ target: { status: 200 } }), 0);
}
}),
+ getResponseHeader: vi.fn(() => 'etag-value'),
open: vi.fn(),
send: vi.fn(),
setRequestHeader: vi.fn(),
@@ -87,6 +120,22 @@ describe('UploadService', () => {
expect(result.data.path).toBe(customPath);
});
+ it('should reject files larger than the database size range before uploading', async () => {
+ const oversizedFile = new File(['test'], 'huge.bin', {
+ type: 'application/octet-stream',
+ });
+ Object.defineProperty(oversizedFile, 'size', {
+ configurable: true,
+ value: MAX_UPLOAD_FILE_SIZE + 1,
+ });
+
+ await expect(uploadService.uploadFileToS3(oversizedFile, {})).rejects.toThrow(
+ UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE,
+ );
+ expect(lambdaClient.upload.createS3PreSignedUrl.mutate).not.toHaveBeenCalled();
+ expect(lambdaClient.upload.createS3MultipartUpload.mutate).not.toHaveBeenCalled();
+ });
+
it('should use custom directory when provided', async () => {
const result = await uploadService.uploadFileToS3(mockFile, {
directory: 'custom/dir',
@@ -128,9 +177,6 @@ describe('UploadService', () => {
type: 'base64',
});
- const { sha256 } = await import('js-sha256');
- vi.mocked(sha256).mockReturnValue('base64-hash');
-
const base64Data = 'data:image/png;base64,dGVzdA==';
const result = await uploadService.uploadBase64ToS3(base64Data);
@@ -167,9 +213,6 @@ describe('UploadService', () => {
type: 'base64',
});
- const { sha256 } = await import('js-sha256');
- vi.mocked(sha256).mockReturnValue('custom-hash');
-
const base64Data = 'data:image/png;base64,dGVzdA==';
const result = await uploadService.uploadBase64ToS3(base64Data, {
filename: 'custom-image',
@@ -229,6 +272,7 @@ describe('UploadService', () => {
// Mock XMLHttpRequest
const xhrMock = {
addEventListener: vi.fn(),
+ getResponseHeader: vi.fn(() => 'etag-value'),
open: vi.fn(),
send: vi.fn(),
setRequestHeader: vi.fn(),
@@ -263,6 +307,7 @@ describe('UploadService', () => {
filename: 'mock-uuid.png',
path: `${fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/1/mock-uuid.png`,
});
+ expect(xhr.send).toHaveBeenCalledWith(mockFile);
});
it('should report progress during upload', async () => {
@@ -363,5 +408,98 @@ describe('UploadService', () => {
expect(result.path).toBe(customPath);
});
+
+ it('should upload large files as sequential S3 parts without buffering the whole file', async () => {
+ const largeFile = new File(['small fixture'], 'large.bin', {
+ type: 'application/octet-stream',
+ });
+ Object.defineProperty(largeFile, 'size', { value: 64 * 1024 * 1024 + 1 });
+ const slice = vi
+ .spyOn(largeFile, 'slice')
+ .mockImplementation(() => new Blob(['part'], { type: largeFile.type }));
+ const arrayBuffer = vi.fn();
+ Object.defineProperty(largeFile, 'arrayBuffer', { value: arrayBuffer });
+
+ vi.mocked(lambdaClient.upload.createS3MultipartUpload.mutate).mockResolvedValue({
+ uploadId: 'upload-1',
+ });
+ vi.mocked(lambdaClient.upload.createS3MultipartUploadPartUrl.mutate).mockResolvedValue(
+ 'https://example.com/part',
+ );
+ vi.mocked(lambdaClient.upload.completeS3MultipartUpload.mutate).mockResolvedValue({
+ success: true,
+ });
+
+ const xhr = new XMLHttpRequest();
+ vi.spyOn(xhr, 'addEventListener').mockImplementation((event, handler) => {
+ if (event === 'load') {
+ // @ts-expect-error test event only needs to trigger the registered handler
+ handler({});
+ }
+ });
+
+ await uploadService.uploadToServerS3(largeFile, {});
+
+ expect(lambdaClient.upload.createS3PreSignedUrl.mutate).not.toHaveBeenCalled();
+ expect(lambdaClient.upload.createS3MultipartUploadPartUrl.mutate).toHaveBeenCalledTimes(3);
+ expect(slice).toHaveBeenCalledTimes(3);
+ expect(xhr.send).toHaveBeenCalledTimes(3);
+ expect(arrayBuffer).not.toHaveBeenCalled();
+ expect(lambdaClient.upload.completeS3MultipartUpload.mutate).toHaveBeenCalledWith({
+ partCount: 3,
+ parts: [
+ { etag: 'etag-value', partNumber: 1 },
+ { etag: 'etag-value', partNumber: 2 },
+ { etag: 'etag-value', partNumber: 3 },
+ ],
+ pathname: expect.stringContaining('mock-uuid.bin'),
+ uploadId: 'upload-1',
+ });
+ expect(lambdaClient.upload.abortS3MultipartUpload.mutate).not.toHaveBeenCalled();
+ });
+
+ it('should abort the S3 multipart upload when a part cannot be signed', async () => {
+ const largeFile = new File(['small fixture'], 'large.bin');
+ Object.defineProperty(largeFile, 'size', { value: 64 * 1024 * 1024 });
+ vi.mocked(lambdaClient.upload.createS3MultipartUpload.mutate).mockResolvedValue({
+ uploadId: 'upload-1',
+ });
+ vi.mocked(lambdaClient.upload.createS3MultipartUploadPartUrl.mutate).mockRejectedValue(
+ new Error('signing failed'),
+ );
+ vi.mocked(lambdaClient.upload.abortS3MultipartUpload.mutate).mockResolvedValue({
+ success: true,
+ });
+
+ await expect(uploadService.uploadToServerS3(largeFile, {})).rejects.toThrow('signing failed');
+
+ expect(lambdaClient.upload.abortS3MultipartUpload.mutate).toHaveBeenCalledWith({
+ pathname: expect.any(String),
+ uploadId: 'upload-1',
+ });
+ expect(lambdaClient.upload.completeS3MultipartUpload.mutate).not.toHaveBeenCalled();
+ });
+ });
+
+ it('should calculate a SHA-256 hash with a reusable BYOB buffer', async () => {
+ const file = new File(['fixture'], 'fixture.bin');
+ const arrayBuffer = vi.fn();
+ Object.defineProperty(file, 'arrayBuffer', { value: arrayBuffer });
+ Object.defineProperty(file, 'stream', {
+ value: () =>
+ new ReadableStream<Uint8Array>({
+ type: 'bytes',
+ start(controller) {
+ const byteController = controller as ReadableByteStreamController;
+ byteController.enqueue(new Uint8Array([1, 2]));
+ byteController.enqueue(new Uint8Array([3, 4]));
+ byteController.close();
+ },
+ }),
+ });
+
+ await expect(hashFile(file)).resolves.toBe('streamed-hash');
+ expect(mockHashUpdate).toHaveBeenCalledOnce();
+ expect(arrayBuffer).not.toHaveBeenCalled();
});
});
diff --git a/src/services/upload.ts b/src/services/upload.ts
index ae0c51d00f5..83a9963fd02 100644
--- a/src/services/upload.ts
+++ b/src/services/upload.ts
@@ -1,3 +1,4 @@
+import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import { parseDataUri } from '@lobechat/model-runtime/utils/uriParser';
import { uuid } from '@lobechat/utils';
import dayjs from 'dayjs';
@@ -5,11 +6,35 @@ import { sha256 } from 'js-sha256';
import { fileEnv } from '@/envs/file';
import { lambdaClient } from '@/libs/trpc/client';
-import { type FileMetadata, type UploadBase64ToS3Result } from '@/types/files';
-import { type FileUploadState, type FileUploadStatus } from '@/types/files/upload';
+import type { FileMetadata, UploadBase64ToS3Result } from '@/types/files';
+import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';
export const UPLOAD_NETWORK_ERROR = 'NetWorkError';
+const MAX_MULTIPART_PARTS = 10_000;
+const HASH_BUFFER_SIZE = 4 * 1024 * 1024;
+const MULTIPART_PART_SIZE = 32 * 1024 * 1024;
+const MULTIPART_UPLOAD_THRESHOLD = 64 * 1024 * 1024;
+
+export const hashFile = async (file: File, signal?: AbortSignal): Promise<string> => {
+ const hasher = sha256.create();
+ const reader = file.stream().getReader({ mode: 'byob' });
+ let buffer = new ArrayBuffer(HASH_BUFFER_SIZE);
+
+ try {
+ while (true) {
+ if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
+
+ const { done, value } = await reader.read(new Uint8Array(buffer));
+ if (done) return hasher.hex();
+ hasher.update(value);
+ buffer = value.buffer as ArrayBuffer;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+};
+
/**
* Generate file storage path metadata for S3-compatible storage
* @param originalFilename - Original filename
@@ -60,6 +85,8 @@ class UploadService {
file: File,
{ onProgress, directory, pathname, abortController }: UploadFileToS3Options,
): Promise<{ data: FileMetadata; success: boolean }> => {
+ if (file.size > MAX_UPLOAD_FILE_SIZE) throw new Error(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
+
// Server-side upload logic
// if is server mode, upload to server s3,
@@ -112,7 +139,7 @@ class UploadService {
// Use unified upload method
const { data: metadata } = await this.uploadFileToS3(file, options);
- const hash = sha256(await file.arrayBuffer());
+ const hash = await hashFile(file, options.abortController?.signal);
return {
fileType: mimeType,
@@ -142,87 +169,150 @@ class UploadService {
pathname?: string;
},
): Promise<FileMetadata> => {
- const xhr = new XMLHttpRequest();
-
- const { preSignUrl, ...result } = await this.getSignedUploadUrl(file, { directory, pathname });
+ const {
+ date,
+ dirname,
+ filename,
+ pathname: uploadPathname,
+ } = generateFilePathMetadata(file.name, { directory, pathname });
+ const result = { date, dirname, filename, path: uploadPathname };
const startTime = Date.now();
- // Setup abort listener
- if (abortController) {
- abortController.signal.addEventListener('abort', () => {
- xhr.abort();
- });
- }
-
- xhr.upload.addEventListener('progress', (event) => {
- if (event.lengthComputable) {
- const progress = Number(((event.loaded / event.total) * 100).toFixed(1));
-
- const speedInByte = event.loaded / ((Date.now() - startTime) / 1000);
-
- onProgress?.('uploading', {
- // if the progress is 100, it means the file is uploaded
- // but the server is still processing it
- // so make it as 99.9 and let users think it's still uploading
- progress: progress === 100 ? 99.9 : progress,
- restTime: (event.total - event.loaded) / speedInByte,
- speed: speedInByte,
+ try {
+ if (file.size >= MULTIPART_UPLOAD_THRESHOLD) {
+ await this.uploadMultipart(file, uploadPathname, abortController?.signal, (loaded) => {
+ onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
+ });
+ } else {
+ const preSignUrl = await lambdaClient.upload.createS3PreSignedUrl.mutate({
+ pathname: uploadPathname,
+ size: file.size,
});
- }
- });
- xhr.open('PUT', preSignUrl);
- xhr.setRequestHeader('Content-Type', file.type);
- const data = await file.arrayBuffer();
-
- await new Promise((resolve, reject) => {
- xhr.addEventListener('load', () => {
- if (xhr.status >= 200 && xhr.status < 300) {
- onProgress?.('success', {
- progress: 100,
- restTime: 0,
- speed: file.size / ((Date.now() - startTime) / 1000),
- });
- resolve(xhr.response);
- } else {
- reject(xhr.statusText);
- }
- });
- xhr.addEventListener('error', () => {
- if (xhr.status === 0) reject(UPLOAD_NETWORK_ERROR);
- else reject(xhr.statusText);
- });
- xhr.addEventListener('abort', () => {
+ await this.putBlob(
+ preSignUrl,
+ file,
+ abortController?.signal,
+ (loaded) => {
+ onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
+ },
+ file.type,
+ );
+ }
+ } catch (error) {
+ if (abortController?.signal.aborted) {
onProgress?.('cancelled', { progress: 0, restTime: 0, speed: 0 });
- reject(new Error('Upload cancelled by user'));
- });
- xhr.send(data);
+ }
+ throw error;
+ }
+
+ onProgress?.('success', {
+ progress: 100,
+ restTime: 0,
+ speed: file.size / Math.max((Date.now() - startTime) / 1000, 0.001),
});
return result;
};
- private getSignedUploadUrl = async (
- file: File,
- options: { directory?: string; pathname?: string } = {},
- ): Promise<
- FileMetadata & {
- preSignUrl: string;
- }
- > => {
- // Generate file path metadata
- const { date, dirname, filename, pathname } = generateFilePathMetadata(file.name, options);
-
- const preSignUrl = await lambdaClient.upload.createS3PreSignedUrl.mutate({ pathname });
+ private getUploadState = (loaded: number, total: number, startTime: number): FileUploadState => {
+ const elapsed = Math.max((Date.now() - startTime) / 1000, 0.001);
+ const speed = loaded / elapsed;
+ const progress = total > 0 ? Number(((loaded / total) * 100).toFixed(1)) : 0;
return {
- date,
- dirname,
- filename,
- path: pathname,
- preSignUrl,
+ progress: progress === 100 ? 99.9 : progress,
+ restTime: speed > 0 ? (total - loaded) / speed : 0,
+ speed,
};
};
+
+ private putBlob = async (
+ url: string,
+ blob: Blob,
+ signal: AbortSignal | undefined,
+ onProgress: (loaded: number) => void,
+ contentType?: string,
+ ): Promise<string | undefined> => {
+ if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
+
+ const xhr = new XMLHttpRequest();
+ const abort = () => xhr.abort();
+ signal?.addEventListener('abort', abort, { once: true });
+
+ try {
+ return await new Promise<string | undefined>((resolve, reject) => {
+ xhr.upload.addEventListener('progress', (event) => {
+ if (event.lengthComputable) onProgress(event.loaded);
+ });
+ xhr.addEventListener('load', () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ resolve(xhr.getResponseHeader?.('ETag') || undefined);
+ } else reject(xhr.statusText);
+ });
+ xhr.addEventListener('error', () => {
+ if (xhr.status === 0) reject(UPLOAD_NETWORK_ERROR);
+ else reject(xhr.statusText);
+ });
+ xhr.addEventListener('abort', () => reject(new Error('Upload cancelled by user')));
+ xhr.open('PUT', url);
+ if (contentType) xhr.setRequestHeader('Content-Type', contentType);
+ xhr.send(blob);
+ });
+ } finally {
+ signal?.removeEventListener('abort', abort);
+ }
+ };
+
+ private uploadMultipart = async (
+ file: File,
+ pathname: string,
+ signal: AbortSignal | undefined,
+ onProgress: (loaded: number) => void,
+ ): Promise<void> => {
+ const partSize = Math.max(MULTIPART_PART_SIZE, Math.ceil(file.size / MAX_MULTIPART_PARTS));
+ const partCount = Math.ceil(file.size / partSize);
+ const parts: Array<{ etag: string; partNumber: number }> = [];
+ const { uploadId } = await lambdaClient.upload.createS3MultipartUpload.mutate({
+ contentType: file.type || undefined,
+ pathname,
+ size: file.size,
+ });
+
+ try {
+ for (let partNumber = 1; partNumber <= partCount; partNumber++) {
+ if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
+
+ const offset = (partNumber - 1) * partSize;
+ const end = Math.min(offset + partSize, file.size);
+ const url = await lambdaClient.upload.createS3MultipartUploadPartUrl.mutate({
+ partNumber,
+ pathname,
+ uploadId,
+ });
+
+ const etag = await this.putBlob(url, file.slice(offset, end), signal, (loaded) => {
+ onProgress(offset + loaded);
+ });
+ if (etag) parts.push({ etag, partNumber });
+ onProgress(end);
+ }
+
+ await lambdaClient.upload.completeS3MultipartUpload.mutate({
+ partCount,
+ parts: parts.length === partCount ? parts : undefined,
+ pathname,
+ uploadId,
+ });
+ } catch (error) {
+ try {
+ await lambdaClient.upload.abortS3MultipartUpload.mutate({ pathname, uploadId });
+ } catch (abortError) {
+ console.error('Failed to abort S3 multipart upload:', abortError);
+ }
+ throw error;
+ }
+ };
}
export const uploadService = new UploadService();
diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.ts
index 78dc06c8f3c..6978bd9dc01 100644
--- a/src/store/file/slices/upload/action.test.ts
+++ b/src/store/file/slices/upload/action.test.ts
@@ -1,5 +1,6 @@
import { toast } from '@lobehub/ui/base-ui';
import { act, renderHook } from '@testing-library/react';
+import { fileTypeFromBlob } from 'file-type';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { handleFileUploadError } from '@/business/client/handleFileUploadError';
@@ -30,20 +31,32 @@ vi.mock('@/utils/client/imageDimensions', () => ({
// Mock for sha256
vi.mock('js-sha256', () => ({
- sha256: vi.fn(() => 'mock-hash-value'),
+ sha256: {
+ create: vi.fn(() => ({
+ hex: vi.fn(() => 'mock-hash-value'),
+ update: vi.fn(),
+ })),
+ },
}));
// Mock file-type module (dynamic import)
vi.mock('file-type', () => ({
- fileTypeFromBuffer: vi.fn(),
+ fileTypeFromBlob: vi.fn(),
}));
-// Mock File.arrayBuffer method
+// jsdom's File does not expose the browser stream API used by the upload path.
beforeAll(() => {
- Object.defineProperty(File.prototype, 'arrayBuffer', {
+ Object.defineProperty(File.prototype, 'stream', {
configurable: true,
value: function () {
- return Promise.resolve(new ArrayBuffer(8));
+ return new ReadableStream<Uint8Array>({
+ type: 'bytes',
+ start(controller) {
+ const byteController = controller as ReadableByteStreamController;
+ byteController.enqueue(new Uint8Array([1, 2, 3]));
+ byteController.close();
+ },
+ });
},
writable: true,
});
@@ -52,6 +65,7 @@ beforeAll(() => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(handleFileUploadError).mockReturnValue(false);
+ vi.mocked(fileTypeFromBlob).mockResolvedValue(undefined);
vi.mocked(getAudioDuration).mockResolvedValue(undefined);
});
@@ -560,7 +574,7 @@ describe('FileUploadAction', () => {
);
});
- it('should correct image file type from bytes when file.type is wrong', async () => {
+ it('should correct image file type from the Blob when file.type is wrong', async () => {
const { result } = renderHook(() => useStore());
const pngBytes = new Uint8Array([
@@ -581,10 +595,7 @@ describe('FileUploadAction', () => {
id: 'file-id-mislabelled',
url: 'https://example.com/mislabelled.jpg',
};
- const { fileTypeFromBuffer } = await import('file-type');
-
- vi.spyOn(mockFile, 'arrayBuffer').mockResolvedValue(pngBytes.buffer);
- vi.mocked(fileTypeFromBuffer).mockResolvedValue({ ext: 'png', mime: 'image/png' } as any);
+ vi.mocked(fileTypeFromBlob).mockResolvedValue({ ext: 'png', mime: 'image/png' });
vi.mocked(getImageDimensions).mockResolvedValue(undefined);
vi.spyOn(fileService, 'checkFileHash').mockResolvedValue(mockCheckResult);
const uploadSpy = vi
@@ -613,7 +624,7 @@ describe('FileUploadAction', () => {
);
});
- it('should detect file type from buffer when file.type is empty', async () => {
+ it('should detect file type from the Blob when file.type is empty', async () => {
const { result } = renderHook(() => useStore());
const mockFile = new File(['test content'], 'noType.png', { type: '' });
@@ -632,9 +643,7 @@ describe('FileUploadAction', () => {
vi.spyOn(uploadService, 'uploadFileToS3').mockResolvedValue(mockUploadResult);
vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);
- // Mock dynamic import of fileTypeFromBuffer
- const { fileTypeFromBuffer } = await import('file-type');
- vi.mocked(fileTypeFromBuffer).mockResolvedValue({ ext: 'png', mime: 'image/png' } as any);
+ vi.mocked(fileTypeFromBlob).mockResolvedValue({ ext: 'png', mime: 'image/png' });
await act(async () => {
await result.current.uploadWithProgress({
@@ -642,7 +651,7 @@ describe('FileUploadAction', () => {
});
});
- expect(fileTypeFromBuffer).toHaveBeenCalled();
+ expect(fileTypeFromBlob).toHaveBeenCalledWith(mockFile);
expect(fileService.createFile).toHaveBeenCalledWith(
expect.objectContaining({
fileType: 'image/png',
@@ -670,9 +679,7 @@ describe('FileUploadAction', () => {
vi.spyOn(uploadService, 'uploadFileToS3').mockResolvedValue(mockUploadResult);
vi.spyOn(fileService, 'createFile').mockResolvedValue(mockFileResponse);
- // Mock dynamic import to return undefined
- const { fileTypeFromBuffer } = await import('file-type');
- vi.mocked(fileTypeFromBuffer).mockResolvedValue(undefined);
+ vi.mocked(fileTypeFromBlob).mockResolvedValue(undefined);
await act(async () => {
await result.current.uploadWithProgress({
@@ -711,8 +718,7 @@ describe('FileUploadAction', () => {
url: 'https://example.com/voice.m4a',
});
- const { fileTypeFromBuffer } = await import('file-type');
- vi.mocked(fileTypeFromBuffer).mockResolvedValue({ ext: 'mp4', mime: 'video/mp4' } as any);
+ vi.mocked(fileTypeFromBlob).mockResolvedValue({ ext: 'mp4', mime: 'video/mp4' });
await act(async () => {
await result.current.uploadWithProgress({ file: mockFile });
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index 2b635d72565..4b047b19556 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -1,18 +1,16 @@
import { LOBE_CHAT_CLOUD } from '@lobechat/business-const';
-import { inferImageMimeTypeFromBytes } from '@lobechat/utils';
import { toast } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
-import { sha256 } from 'js-sha256';
import { handleFileUploadError } from '@/business/client/handleFileUploadError';
import { fileService } from '@/services/file';
-import { uploadService } from '@/services/upload';
-import { type StoreSetter } from '@/store/types';
-import { type UploadFileItem } from '@/types/files';
+import { hashFile, uploadService } from '@/services/upload';
+import type { StoreSetter } from '@/store/types';
+import type { UploadFileItem } from '@/types/files';
import { getAudioDuration } from '@/utils/client/audioDuration';
import { getImageDimensions } from '@/utils/client/imageDimensions';
-import { type FileStore } from '../../store';
+import type { FileStore } from '../../store';
import { audioMimeFromExtension } from '../chat/uploadGuard';
type OnStatusUpdate = (
@@ -71,18 +69,23 @@ interface UploadWithProgressResult {
url: string;
}
-const normalizeUploadedImageFileType = async (
+const normalizeUploadedFileType = async (
file: File,
- fileArrayBuffer: ArrayBuffer,
-): Promise<File> => {
- const detectedMimeType = await inferImageMimeTypeFromBytes(fileArrayBuffer);
+): Promise<{ detectedMimeType?: string; file: File }> => {
+ const { fileTypeFromBlob } = await import('file-type');
+ const detectedMimeType = (await fileTypeFromBlob(file))?.mime;
- if (!detectedMimeType || detectedMimeType === file.type) return file;
+ if (!detectedMimeType?.startsWith('image/') || detectedMimeType === file.type) {
+ return { detectedMimeType, file };
+ }
- return new File([file], file.name, {
- lastModified: file.lastModified,
- type: detectedMimeType,
- });
+ return {
+ detectedMimeType,
+ file: new File([file], file.name, {
+ lastModified: file.lastModified,
+ type: detectedMimeType,
+ }),
+ };
};
type ExistingFileMetadata = Record<string, unknown> & { path?: string };
@@ -146,8 +149,7 @@ export class FileUploadActionImpl {
const statusId = uploadId ?? file.name;
try {
- const fileArrayBuffer = await file.arrayBuffer();
- const normalizedFile = await normalizeUploadedImageFileType(file, fileArrayBuffer);
+ const { detectedMimeType, file: normalizedFile } = await normalizeUploadedFileType(file);
const extensionAudioMime = audioMimeFromExtension(normalizedFile.name);
const audioDurationPromise =
normalizedFile.type.startsWith('audio/') || extensionAudioMime
@@ -158,7 +160,7 @@ export class FileUploadActionImpl {
const dimensions = await getImageDimensions(normalizedFile);
// 2. check file hash
- const hash = sha256(fileArrayBuffer);
+ const hash = await hashFile(normalizedFile, abortController?.signal);
const checkStatus = await fileService.checkFileHash(hash);
let metadata: ExistingFileMetadata;
@@ -202,14 +204,7 @@ export class FileUploadActionImpl {
}
// 4. use more powerful file type detector to get file type
- let fileType = normalizedFile.type;
-
- if (!normalizedFile.type) {
- const { fileTypeFromBuffer } = await import('file-type');
-
- const type = await fileTypeFromBuffer(fileArrayBuffer);
- fileType = type?.mime || 'text/plain';
- }
+ let fileType = normalizedFile.type || detectedMimeType || 'text/plain';
// Audio containers like .m4a share the ISO-BMFF box with .mp4, so both the browser and
// byte-sniffing may report an empty or `video/*` mime. Trust the extension to keep these
@@ -259,6 +254,15 @@ export class FileUploadActionImpl {
return { ...data, dimensions, filename: normalizedFile.name };
} catch (error) {
+ if (abortController?.signal.aborted) {
+ onStatusUpdate?.({
+ id: statusId,
+ type: 'updateFile',
+ value: { status: 'cancelled', uploadState: { progress: 0, restTime: 0, speed: 0 } },
+ });
+ return;
+ }
+
if (
handleFileUploadError(error, {
onUploadBlocked: ({ code, description }) =>
diff --git a/src/utils/unzipFile.test.ts b/src/utils/unzipFile.test.ts
index 970aa2d17fe..f3aca9a291f 100644
--- a/src/utils/unzipFile.test.ts
+++ b/src/utils/unzipFile.test.ts
@@ -1,5 +1,5 @@
import { zip } from 'fflate';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { unzipFile } from './unzipFile';
@@ -126,6 +126,18 @@ describe('unzipFile', () => {
await expect(unzipFile(invalidFile)).rejects.toThrow();
});
+ it('should reject oversized ZIP files before reading them into memory', async () => {
+ const largeFile = new File([], 'large.zip', { type: 'application/zip' });
+ const arrayBuffer = vi.fn();
+ Object.defineProperties(largeFile, {
+ arrayBuffer: { value: arrayBuffer },
+ size: { value: 64 * 1024 * 1024 + 1 },
+ });
+
+ await expect(unzipFile(largeFile)).rejects.toThrow('too large');
+ expect(arrayBuffer).not.toHaveBeenCalled();
+ });
+
it('should handle various image file types with correct MIME types', async () => {
const testFiles = {
'photo.jpg': new TextEncoder().encode('JPEG'),
diff --git a/src/utils/unzipFile.ts b/src/utils/unzipFile.ts
index c2b1c0d3a8c..0809a39dd4b 100644
--- a/src/utils/unzipFile.ts
+++ b/src/utils/unzipFile.ts
@@ -1,5 +1,7 @@
import { unzip } from 'fflate';
+import { MAX_FILE_PARSE_SIZE } from '@/const/file';
+
/**
* Determines the MIME type based on file extension
*/
@@ -78,42 +80,59 @@ const getFileType = (fileName: string): string => {
* @returns Promise that resolves to an array of extracted Files
*/
export const unzipFile = async (zipFile: File): Promise<File[]> => {
+ if (zipFile.size > MAX_FILE_PARSE_SIZE) {
+ throw new Error('ZIP file is too large to extract in memory');
+ }
+
return new Promise((resolve, reject) => {
zipFile
.arrayBuffer()
.then((arrayBuffer) => {
const uint8Array = new Uint8Array(arrayBuffer);
+ let expandedSize = 0;
+
+ unzip(
+ uint8Array,
+ {
+ filter: ({ originalSize }) => {
+ expandedSize += originalSize;
+ if (expandedSize > MAX_FILE_PARSE_SIZE) {
+ throw new Error('ZIP contents are too large to extract in memory');
+ }
+ return true;
+ },
+ },
+ (error, unzipped) => {
+ if (error) {
+ reject(error);
+ return;
+ }
- unzip(uint8Array, (error, unzipped) => {
- if (error) {
- reject(error);
- return;
- }
-
- const extractedFiles: File[] = [];
+ const extractedFiles: File[] = [];
- for (const [path, data] of Object.entries(unzipped)) {
- // Skip directories and hidden files
- if (path.endsWith('/') || path.includes('__MACOSX') || path.startsWith('.')) {
- continue;
- }
+ for (const [path, data] of Object.entries(unzipped)) {
+ // Skip directories and hidden files
+ if (path.endsWith('/') || path.includes('__MACOSX') || path.startsWith('.')) {
+ continue;
+ }
- // Get the filename from the path
- const fileName = path.split('/').pop() || path;
+ // Get the filename from the path
+ const fileName = path.split('/').pop() || path;
- // Create a File object from the extracted data
- const blob = new Blob([new Uint8Array(data)], {
- type: getFileType(fileName),
- });
- const file = new File([blob], fileName, {
- type: getFileType(fileName),
- });
+ // Create a File object from the extracted data
+ const blob = new Blob([new Uint8Array(data)], {
+ type: getFileType(fileName),
+ });
+ const file = new File([blob], fileName, {
+ type: getFileType(fileName),
+ });
- extractedFiles.push(file);
- }
+ extractedFiles.push(file);
+ }
- resolve(extractedFiles);
- });
+ resolve(extractedFiles);
+ },
+ );
})
.catch(() => {
reject(new Error('Failed to read ZIP file'));