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): show why a large chat upload failed, retry transient S3 part failures, cancel on remove (#23427)

Rdmclin23d7aa46974c4
diff --git a/apps/server/src/modules/S3/index.test.ts b/apps/server/src/modules/S3/index.test.ts
index 596f22103fc..42f04ef9fca 100644
--- a/apps/server/src/modules/S3/index.test.ts
+++ b/apps/server/src/modules/S3/index.test.ts
@@ -1,5 +1,4 @@
// @vitest-environment node
-import type { ListPartsCommandOutput } from '@aws-sdk/client-s3';
import {
AbortMultipartUploadCommand,
CompleteMultipartUploadCommand,
@@ -9,7 +8,7 @@ import {
GetObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
- paginateListParts,
+ ListPartsCommand,
PutObjectCommand,
S3Client,
UploadPartCommand,
@@ -588,7 +587,7 @@ describe('FileS3', () => {
{ ETag: 'etag-1', PartNumber: 1 },
]);
- expect(paginateListParts).not.toHaveBeenCalled();
+ expect(ListPartsCommand).not.toHaveBeenCalled();
expect(CompleteMultipartUploadCommand).toHaveBeenCalledWith({
Bucket: 'test-bucket',
Key: 'large.bin',
@@ -604,17 +603,12 @@ describe('FileS3', () => {
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.mockResolvedValueOnce({
+ Parts: [
+ { ETag: 'etag-2', PartNumber: 2 },
+ { ETag: 'etag-1', PartNumber: 1 },
+ ],
+ });
mockS3ClientSend.mockResolvedValue({});
await s3.completeMultipartUpload('large.bin', 'upload-1', 2);
@@ -634,12 +628,7 @@ describe('FileS3', () => {
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;
- })(),
- );
+ mockS3ClientSend.mockResolvedValueOnce({ Parts: [{ ETag: 'etag-1', PartNumber: 1 }] });
await expect(s3.completeMultipartUpload('large.bin', 'upload-1', 2)).rejects.toThrow(
'has 1/2 parts',
@@ -649,17 +638,12 @@ describe('FileS3', () => {
it('validates listed part sizes before completing a reserved upload', async () => {
const s3 = new FileS3();
- vi.mocked(paginateListParts).mockReturnValue(
- (async function* (): AsyncGenerator<ListPartsCommandOutput, undefined> {
- yield {
- Parts: [
- { ETag: 'etag-1', PartNumber: 1, Size: 32 },
- { ETag: 'etag-2', PartNumber: 2, Size: 5 },
- ],
- } as ListPartsCommandOutput;
- return undefined;
- })(),
- );
+ mockS3ClientSend.mockResolvedValueOnce({
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1, Size: 32 },
+ { ETag: 'etag-2', PartNumber: 2, Size: 5 },
+ ],
+ });
mockS3ClientSend.mockResolvedValue({});
await s3.completeMultipartUpload('large.bin', 'upload-1', 2, undefined, {
@@ -672,17 +656,12 @@ describe('FileS3', () => {
it('rejects a reserved multipart upload with an unexpected part size', async () => {
const s3 = new FileS3();
- vi.mocked(paginateListParts).mockReturnValue(
- (async function* (): AsyncGenerator<ListPartsCommandOutput, undefined> {
- yield {
- Parts: [
- { ETag: 'etag-1', PartNumber: 1, Size: 31 },
- { ETag: 'etag-2', PartNumber: 2, Size: 6 },
- ],
- } as ListPartsCommandOutput;
- return undefined;
- })(),
- );
+ mockS3ClientSend.mockResolvedValueOnce({
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1, Size: 31 },
+ { ETag: 'etag-2', PartNumber: 2, Size: 6 },
+ ],
+ });
await expect(
s3.completeMultipartUpload('large.bin', 'upload-1', 2, undefined, {
@@ -693,6 +672,76 @@ describe('FileS3', () => {
expect(CompleteMultipartUploadCommand).not.toHaveBeenCalled();
});
+ it('stops listing parts on the last page even when R2 still returns a next marker', async () => {
+ const s3 = new FileS3();
+ // Cloudflare R2: the last page reports IsTruncated=false but NextPartNumberMarker='2',
+ // and the page after it reports NextPartNumberMarker='0'. The SDK paginator looped on this.
+ mockS3ClientSend
+ .mockResolvedValueOnce({
+ IsTruncated: false,
+ NextPartNumberMarker: '2',
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1, Size: 32 },
+ { ETag: 'etag-2', PartNumber: 2, Size: 5 },
+ ],
+ })
+ .mockResolvedValueOnce({ IsTruncated: false, NextPartNumberMarker: '0' })
+ .mockResolvedValue({});
+
+ await s3.completeMultipartUpload('large.bin', 'upload-1', 2, undefined, {
+ partSize: 32,
+ size: 37,
+ });
+
+ expect(ListPartsCommand).toHaveBeenCalledTimes(1);
+ expect(CompleteMultipartUploadCommand).toHaveBeenCalledWith(
+ expect.objectContaining({
+ MultipartUpload: {
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1 },
+ { ETag: 'etag-2', PartNumber: 2 },
+ ],
+ },
+ }),
+ );
+ });
+
+ it('follows truncated part listings and stops when the marker does not advance', async () => {
+ const s3 = new FileS3();
+ mockS3ClientSend
+ .mockResolvedValueOnce({
+ IsTruncated: true,
+ NextPartNumberMarker: '1',
+ Parts: [{ ETag: 'etag-1', PartNumber: 1 }],
+ })
+ .mockResolvedValueOnce({
+ IsTruncated: true,
+ NextPartNumberMarker: '1',
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1 },
+ { ETag: 'etag-2', PartNumber: 2 },
+ ],
+ })
+ .mockResolvedValue({});
+
+ await s3.completeMultipartUpload('large.bin', 'upload-1', 2);
+
+ expect(ListPartsCommand).toHaveBeenCalledTimes(2);
+ expect(ListPartsCommand).toHaveBeenLastCalledWith(
+ expect.objectContaining({ PartNumberMarker: '1', UploadId: 'upload-1' }),
+ );
+ expect(CompleteMultipartUploadCommand).toHaveBeenCalledWith(
+ expect.objectContaining({
+ MultipartUpload: {
+ Parts: [
+ { ETag: 'etag-1', PartNumber: 1 },
+ { ETag: 'etag-2', PartNumber: 2 },
+ ],
+ },
+ }),
+ );
+ });
+
it('should abort an unfinished upload', async () => {
const s3 = new FileS3();
mockS3ClientSend.mockResolvedValue({});
diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.ts
index 04eede773da..b075f087ade 100644
--- a/apps/server/src/modules/S3/index.ts
+++ b/apps/server/src/modules/S3/index.ts
@@ -7,7 +7,7 @@ import {
GetObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
- paginateListParts,
+ ListPartsCommand,
PutObjectCommand,
S3Client,
UploadPartCommand,
@@ -33,6 +33,8 @@ const DEFAULT_S3_REGION = 'us-east-1';
const PUBLIC_READ_ACL_HEADER = 'public-read';
// S3 DeleteObjects rejects more than 1000 keys per request.
const DELETE_OBJECTS_MAX_KEYS = 1000;
+// A multipart upload has at most 10,000 parts, so the part-number marker advances at most that often.
+const MAX_LIST_PARTS_PAGES = 10_000;
const encodeContentDispositionFilename = (fileName: string) =>
encodeURIComponent(fileName || 'download').replaceAll(
@@ -253,6 +255,51 @@ export class S3 {
return getSignedUrl(this.presignClient, command, { expiresIn: 3600 });
}
+ /**
+ * Lists every uploaded part of a multipart upload.
+ *
+ * Pages by `IsTruncated` instead of the SDK's `paginateListParts`, which only
+ * checks that `NextPartNumberMarker` is present. Cloudflare R2 returns that
+ * marker on the last page too (`IsTruncated: false, NextPartNumberMarker: '2'`)
+ * and `'0'` on the empty page after it, so the SDK paginator re-lists the parts
+ * forever and the request hangs until the gateway times out.
+ */
+ private async listMultipartParts(key: string, uploadId: string) {
+ const parts = new Map<number, { ETag: string; PartNumber: number; Size?: number }>();
+ let marker: string | undefined;
+
+ for (let page = 0; page < MAX_LIST_PARTS_PAGES; page++) {
+ const result = await this.client.send(
+ new ListPartsCommand({
+ Bucket: this.bucket,
+ Key: key,
+ PartNumberMarker: marker,
+ UploadId: uploadId,
+ }),
+ );
+
+ for (const part of result.Parts ?? []) {
+ if (!part.ETag || !part.PartNumber) continue;
+ parts.set(part.PartNumber, {
+ ETag: part.ETag,
+ PartNumber: part.PartNumber,
+ Size: part.Size,
+ });
+ }
+
+ const next = result.NextPartNumberMarker;
+ // Stop on the last page, and on any marker that does not move forward.
+ if (!result.IsTruncated || !next || Number(next) <= Number(marker ?? 0)) {
+ return [...parts.values()];
+ }
+ marker = next;
+ }
+
+ throw new Error(
+ `S3 multipart upload ${uploadId} lists more than ${MAX_LIST_PARTS_PAGES} pages`,
+ );
+ }
+
public async completeMultipartUpload(
key: string,
uploadId: string,
@@ -263,17 +310,8 @@ export class S3 {
const parts: Array<{ ETag: string; PartNumber: number; Size?: number }> =
uploadedParts && !expectedFile ? [...uploadedParts] : [];
- if (!uploadedParts || expectedFile) {
- 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, Size: part.Size });
- }
- }
- }
+ if (!uploadedParts || expectedFile)
+ parts.push(...(await this.listMultipartParts(key, uploadId)));
parts.sort((a, b) => a.PartNumber - b.PartNumber);
const hasAllParts =
diff --git a/locales/en-US/error.json b/locales/en-US/error.json
index e25bbd67ad4..61c9cf9f8c4 100644
--- a/locales/en-US/error.json
+++ b/locales/en-US/error.json
@@ -185,6 +185,7 @@
"unlock.tabs.password": "Password",
"upload.desc": "Details: {{detail}}",
"upload.fileOnlySupportInServerMode": "The current deployment mode does not support uploading non-image files. To upload files in {{ext}} format, please switch to server database deployment or use the {{cloud}} service.",
+ "upload.fileTooLarge": "This file is over the {{max}} upload limit and can’t be uploaded.",
"upload.networkError": "Please check your network connection and ensure that the file storage service's cross-origin configuration is correct.",
"upload.permissionDenied": "You don't have permission to upload files in this workspace.",
"upload.serviceUnavailable": "The upload service is temporarily unavailable. Please try again in a moment.",
@@ -199,6 +200,7 @@
"upload.storageBlock.viewPlans": "View plans",
"upload.storageBlock.viewUsage": "View storage usage",
"upload.storageLimitExceeded": "Your file storage has reached the plan limit. Please upgrade your plan or delete unused files to free up space.",
+ "upload.storageRejected": "The file storage service rejected the upload ({{detail}}). Please try again later.",
"upload.title": "File upload failed. Please check your network connection or try again later",
"upload.unknownError": "Error reason: {{reason}}",
"upload.uploadFailed": "File upload failed.",
diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.json
index ef34b13c2d5..0b9ebef6a8e 100644
--- a/locales/zh-CN/error.json
+++ b/locales/zh-CN/error.json
@@ -185,6 +185,7 @@
"unlock.tabs.password": "密码",
"upload.desc": "详情:{{detail}}",
"upload.fileOnlySupportInServerMode": "当前部署模式不支持上传非图片文件。若需上传 {{ext}},请切换到服务端数据库部署或使用 {{cloud}}",
+ "upload.fileTooLarge": "文件超过 {{max}} 上传上限,无法上传",
"upload.networkError": "网络异常或跨域配置不正确。请检查文件存储服务的 CORS 设置后重试",
"upload.permissionDenied": "您没有权限在此工作区上传文件。",
"upload.serviceUnavailable": "上传服务暂时不可用,请稍后重试",
@@ -199,6 +200,7 @@
"upload.storageBlock.viewPlans": "查看套餐",
"upload.storageBlock.viewUsage": "查看存储用量",
"upload.storageLimitExceeded": "文件存储空间已达到当前套餐上限,请升级套餐或删除不需要的文件以释放空间。",
+ "upload.storageRejected": "文件存储服务拒绝了这次上传({{detail}}),请稍后重试",
"upload.title": "上传未能完成",
"upload.unknownError": "原因:{{reason}}",
"upload.uploadFailed": "上传未能完成",
diff --git a/packages/locales/src/default/error.ts b/packages/locales/src/default/error.ts
index 36f5ddf461d..ce1de1a220a 100644
--- a/packages/locales/src/default/error.ts
+++ b/packages/locales/src/default/error.ts
@@ -318,6 +318,7 @@ export default {
'upload.desc': 'Details: {{detail}}',
'upload.fileOnlySupportInServerMode':
'The current deployment mode does not support uploading non-image files. To upload files in {{ext}} format, please switch to server database deployment or use the {{cloud}} service.',
+ 'upload.fileTooLarge': 'This file is over the {{max}} upload limit and can’t be uploaded.',
'upload.networkError':
"Please check your network connection and ensure that the file storage service's cross-origin configuration is correct.",
'upload.serviceUnavailable':
@@ -340,6 +341,8 @@ export default {
'upload.permissionDenied': "You don't have permission to upload files in this workspace.",
'upload.storageLimitExceeded':
'Your file storage has reached the plan limit. Please upgrade your plan or delete unused files to free up space.',
+ 'upload.storageRejected':
+ 'The file storage service rejected the upload ({{detail}}). Please try again later.',
'upload.title': 'File upload failed. Please check your network connection or try again later',
'upload.unknownError': 'Error reason: {{reason}}',
'upload.uploadFailed': 'File upload failed.',
diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.ts
index 795450be93e..4d700f86877 100644
--- a/packages/types/src/files/upload.ts
+++ b/packages/types/src/files/upload.ts
@@ -87,6 +87,11 @@ export interface UploadFileItem {
* card pulses to show the paste was received.
*/
repastedAt?: number;
+ /**
+ * `false` when the failure would repeat on retry (e.g. the file is over the
+ * upload size limit), so the chip offers only removal.
+ */
+ retryable?: boolean;
/**
* Set when the draft was uploaded as an agent-share VISITOR: the file lives
* under the creator's account, so remove/retry must go through the
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx
index 8c142554ecd..cc3f43c9209 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx
@@ -90,6 +90,7 @@ const ImageCard = memo<UploadFileItem>((item) => {
const removeChatUploadFile = useFileStore((s) => s.removeChatUploadFile);
const retryChatUploadFile = useFileStore((s) => s.retryChatUploadFile);
const { busy, canRetry, indicator } = getUploadChipState(item);
+ const failed = indicator === 'error';
const src = previewUrl || item.fileUrl || item.base64Url;
const cardRef = useRef<HTMLDivElement>(null);
useRepastePulse(cardRef, item.repastedAt);
@@ -105,11 +106,7 @@ const ImageCard = memo<UploadFileItem>((item) => {
});
return (
- <div
- aria-busy={busy}
- ref={cardRef}
- {...stylex.props(styles.card, canRetry && styles.cardError)}
- >
+ <div aria-busy={busy} ref={cardRef} {...stylex.props(styles.card, failed && styles.cardError)}>
{src && <img alt={file.name} draggable={false} src={src} {...stylex.props(styles.image)} />}
<Tooltip title={<UploadTooltipContent {...item} />}>
<button
@@ -120,15 +117,16 @@ const ImageCard = memo<UploadFileItem>((item) => {
{...stylex.props(styles.previewButton)}
/>
</Tooltip>
- {(busy || canRetry) && (
+ {(busy || failed) && (
<div {...stylex.props(styles.overlay)}>
{indicator === 'busy' ? (
<UploadIndicator label={t('upload.preview.status.uploading')} size={24} />
) : (
<>
<Icon
- aria-label={t('upload.preview.status.error')}
+ aria-label={item.error || t('upload.preview.status.error')}
icon={CircleAlertIcon}
+ role={'img'}
size={20}
style={{ color: cssVar.colorError }}
/>
@@ -136,12 +134,14 @@ const ImageCard = memo<UploadFileItem>((item) => {
{errorCode ? (
<FileUploadErrorActions compact code={errorCode} />
) : (
- <ActionIcon
- icon={RotateCwIcon}
- size={'small'}
- title={t('retry', { ns: 'common' })}
- onClick={handleRetry}
- />
+ canRetry && (
+ <ActionIcon
+ icon={RotateCwIcon}
+ size={'small'}
+ title={t('retry', { ns: 'common' })}
+ onClick={handleRetry}
+ />
+ )
)}
</div>
</>
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
index de26700e5de..981c8886b15 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
@@ -51,7 +51,7 @@ const styles = stylex.create({
type FileItemProps = UploadFileItem;
const ContextItem = memo<FileItemProps>((props) => {
- const { errorCode, file, id, status } = props;
+ const { error, errorCode, file, id, status } = props;
const { t } = useTranslation(['chat', 'common']);
const contextKey = useChatInputUploadKey();
const removeChatUploadFile = useFileStore((s) => s.removeChatUploadFile);
@@ -97,7 +97,13 @@ const ContextItem = memo<FileItemProps>((props) => {
) : indicator === 'busy' ? (
<UploadIndicator label={t('upload.preview.status.uploading')} size={12} />
) : (
- <Icon icon={CircleAlertIcon} size={12} style={{ color: cssVar.colorError }} />
+ <Icon
+ aria-label={error || t('upload.preview.status.error')}
+ icon={CircleAlertIcon}
+ role={'img'}
+ size={12}
+ style={{ color: cssVar.colorError }}
+ />
)}
</Flexbox>
)}
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts
index 3484fc2d9b0..9055bee5f83 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.test.ts
@@ -45,6 +45,13 @@ describe('getUploadChipState', () => {
},
);
+ it('shows the failure but offers no retry when retrying would fail the same way', () => {
+ expect(getUploadChipState({ retryable: false, status: 'error' })).toMatchObject({
+ canRetry: false,
+ indicator: 'error',
+ });
+ });
+
it.each([undefined, Number.NaN, Number.POSITIVE_INFINITY])(
'drops unmeasurable progress (%s)',
(progress) => {
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
index b4b9be617bb..b98328c1fbe 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/utils.ts
@@ -38,9 +38,10 @@ export const getHarmoniousSize = (
/** Keep upload feedback and available actions consistent throughout the chip lifecycle. */
export const getUploadChipState = ({
+ retryable,
status,
uploadState,
-}: Pick<UploadFileItem, 'status' | 'uploadState'>) => {
+}: Pick<UploadFileItem, 'retryable' | 'status' | 'uploadState'>) => {
const busy = status === 'pending' || status === 'uploading' || status === 'processing';
const rawProgress = uploadState?.progress;
const progress =
@@ -53,7 +54,8 @@ export const getUploadChipState = ({
return {
busy,
canPreview: status === 'success',
- canRetry: status === 'error' || status === 'cancelled',
+ /** A failure that would only repeat (e.g. over the size limit) offers removal, not retry. */
+ canRetry: (status === 'error' || status === 'cancelled') && retryable !== false,
/** Every busy step shares one `busy` indicator, so users see a single spinner throughout. */
indicator,
progress,
diff --git a/src/services/__tests__/upload.test.ts b/src/services/__tests__/upload.test.ts
index f965603303a..55536bd810a 100644
--- a/src/services/__tests__/upload.test.ts
+++ b/src/services/__tests__/upload.test.ts
@@ -5,7 +5,7 @@ import { fileEnv } from '@/envs/file';
import { lambdaClient } from '@/libs/trpc/client';
import { hashFile } from '../hashFile';
-import { UPLOAD_NETWORK_ERROR, uploadService } from '../upload';
+import { UPLOAD_NETWORK_ERROR, UploadRequestError, uploadService } from '../upload';
const { mockHashHex, mockHashUpdate } = vi.hoisted(() => ({
mockHashHex: vi.fn(() => 'streamed-hash'),
@@ -388,7 +388,32 @@ describe('UploadService', () => {
}
});
- await expect(uploadService.uploadToServerS3(mockFile, {})).rejects.toBe('Bad Request');
+ await expect(uploadService.uploadToServerS3(mockFile, {})).rejects.toMatchObject({
+ name: 'UploadRequestError',
+ status: 400,
+ });
+ });
+
+ it('should keep the status and storage code when HTTP/2 leaves statusText empty', async () => {
+ const xhr = new XMLHttpRequest();
+ vi.spyOn(xhr, 'addEventListener').mockImplementation((event, handler) => {
+ if (event === 'load') {
+ Object.assign(xhr, {
+ responseText:
+ '<?xml version="1.0"?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match</Message></Error>',
+ status: 403,
+ statusText: '',
+ });
+ // @ts-expect-error - mock implementation
+ handler({});
+ }
+ });
+
+ const error = await uploadService.uploadToServerS3(mockFile, {}).catch((e: unknown) => e);
+
+ expect(error).toBeInstanceOf(UploadRequestError);
+ expect(error).toMatchObject({ code: 'SignatureDoesNotMatch', retryable: false, status: 403 });
+ expect((error as Error).message).toContain('HTTP 403 SignatureDoesNotMatch');
});
it('should use custom directory when provided', async () => {
@@ -461,16 +486,105 @@ describe('UploadService', () => {
expect(slice).toHaveBeenCalledTimes(2);
expect(xhr.send).toHaveBeenCalledTimes(2);
expect(arrayBuffer).not.toHaveBeenCalled();
- expect(lambdaClient.upload.completeS3MultipartUpload.mutate).toHaveBeenCalledWith({
- partCount: 2,
- parts: [
- { etag: 'etag-value', partNumber: 1 },
- { etag: 'etag-value', partNumber: 2 },
- ],
- pathname: expect.stringContaining('mock-uuid.bin'),
+ expect(lambdaClient.upload.completeS3MultipartUpload.mutate).toHaveBeenCalledWith(
+ {
+ partCount: 2,
+ parts: [
+ { etag: 'etag-value', partNumber: 1 },
+ { etag: 'etag-value', partNumber: 2 },
+ ],
+ pathname: expect.stringContaining('mock-uuid.bin'),
+ uploadId: 'upload-1',
+ },
+ { signal: undefined },
+ );
+ expect(lambdaClient.upload.abortS3MultipartUpload.mutate).not.toHaveBeenCalled();
+ });
+
+ it('should resend a multipart part that storage failed transiently', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ const largeFile = new File(['small fixture'], 'large.bin');
+ Object.defineProperty(largeFile, 'size', { value: 64 * 1024 * 1024 });
+ Object.defineProperty(largeFile, 'slice', {
+ value: vi.fn(() => new Blob(['part'])),
+ });
+ 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,
+ });
+
+ let attempts = 0;
+ const xhr = new XMLHttpRequest();
+ vi.spyOn(xhr, 'addEventListener').mockImplementation((event, handler) => {
+ if (event !== 'load') return;
+ attempts += 1;
+ // The last part fails once with S3's idle-socket timeout, then succeeds.
+ Object.assign(
+ xhr,
+ attempts === 2
+ ? {
+ responseText: '<Error><Code>RequestTimeout</Code></Error>',
+ status: 400,
+ statusText: '',
+ }
+ : { responseText: '', status: 200, statusText: '' },
+ );
+ // @ts-expect-error - mock implementation
+ handler({});
+ });
+
+ const upload = uploadService.uploadToServerS3(largeFile, {});
+ await vi.runAllTimersAsync();
+ await upload;
+
+ expect(xhr.send).toHaveBeenCalledTimes(3);
+ expect(lambdaClient.upload.createS3MultipartUploadPartUrl.mutate).toHaveBeenCalledTimes(3);
+ expect(lambdaClient.upload.completeS3MultipartUpload.mutate).toHaveBeenCalledOnce();
+ expect(lambdaClient.upload.abortS3MultipartUpload.mutate).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('should not resend a multipart part that storage refused outright', async () => {
+ const largeFile = new File(['small fixture'], 'large.bin');
+ Object.defineProperty(largeFile, 'size', { value: 64 * 1024 * 1024 });
+ Object.defineProperty(largeFile, 'slice', { value: vi.fn(() => new Blob(['part'])) });
+ vi.mocked(lambdaClient.upload.createS3MultipartUpload.mutate).mockResolvedValue({
uploadId: 'upload-1',
});
- expect(lambdaClient.upload.abortS3MultipartUpload.mutate).not.toHaveBeenCalled();
+ vi.mocked(lambdaClient.upload.createS3MultipartUploadPartUrl.mutate).mockResolvedValue(
+ 'https://example.com/part',
+ );
+ vi.mocked(lambdaClient.upload.abortS3MultipartUpload.mutate).mockResolvedValue({
+ success: true,
+ });
+
+ const xhr = new XMLHttpRequest();
+ vi.spyOn(xhr, 'addEventListener').mockImplementation((event, handler) => {
+ if (event !== 'load') return;
+ Object.assign(xhr, {
+ responseText: '<Error><Code>AccessDenied</Code></Error>',
+ status: 403,
+ statusText: '',
+ });
+ // @ts-expect-error - mock implementation
+ handler({});
+ });
+
+ await expect(uploadService.uploadToServerS3(largeFile, {})).rejects.toMatchObject({
+ code: 'AccessDenied',
+ status: 403,
+ });
+ expect(xhr.send).toHaveBeenCalledOnce();
+ expect(lambdaClient.upload.abortS3MultipartUpload.mutate).toHaveBeenCalledOnce();
+ expect(lambdaClient.upload.completeS3MultipartUpload.mutate).not.toHaveBeenCalled();
});
it('should abort the S3 multipart upload when a part cannot be signed', async () => {
diff --git a/src/services/upload.ts b/src/services/upload.ts
index 09657fe49bd..98fd39b5620 100644
--- a/src/services/upload.ts
+++ b/src/services/upload.ts
@@ -15,6 +15,80 @@ export const UPLOAD_NETWORK_ERROR = 'NetWorkError';
const MAX_MULTIPART_PARTS = 10_000;
const MULTIPART_PART_SIZE = 32 * 1024 * 1024;
const MULTIPART_UPLOAD_THRESHOLD = 64 * 1024 * 1024;
+/** One part is sent at most this many times when storage fails it transiently. */
+const MULTIPART_PART_MAX_ATTEMPTS = 3;
+const MULTIPART_PART_RETRY_DELAY_MS = 1000;
+
+/** S3 error codes that only mean "try again", returned with a 4xx status. */
+const RETRYABLE_STORAGE_ERROR_CODES = new Set([
+ 'RequestTimeout',
+ 'RequestTimeTooSkewed',
+ 'SlowDown',
+ 'ServiceUnavailable',
+ 'InternalError',
+]);
+
+/**
+ * Object storage refused a PUT. Browsers leave `statusText` empty over HTTP/2,
+ * so the status and the storage's own error code are kept explicitly: without
+ * them the failure reached the user as an error with no reason at all.
+ */
+export class UploadRequestError extends Error {
+ readonly code?: string;
+ readonly status: number;
+
+ constructor({ code, detail, status }: { code?: string; detail?: string; status: number }) {
+ super(
+ `Storage rejected the upload (HTTP ${status}${code ? ` ${code}` : ''})${detail ? `: ${detail}` : ''}`,
+ );
+ this.name = 'UploadRequestError';
+ this.code = code;
+ this.status = status;
+ }
+
+ /** Whether sending the same bytes again can succeed. */
+ get retryable(): boolean {
+ return (
+ this.status === 408 ||
+ this.status === 429 ||
+ this.status >= 500 ||
+ (!!this.code && RETRYABLE_STORAGE_ERROR_CODES.has(this.code))
+ );
+ }
+}
+
+const readStorageError = (xhr: XMLHttpRequest): UploadRequestError => {
+ let body = '';
+ try {
+ body = typeof xhr.responseText === 'string' ? xhr.responseText : '';
+ } catch {
+ // responseText throws for non-text response types; the status is enough then.
+ }
+ const code = /<Code>([^<]+)<\/Code>/.exec(body)?.[1]?.trim();
+ const detail = /<Message>([^<]+)<\/Message>/.exec(body)?.[1]?.trim() || xhr.statusText || '';
+
+ return new UploadRequestError({ code, detail: detail || undefined, status: xhr.status });
+};
+
+const isRetryableUploadError = (error: unknown) =>
+ error === UPLOAD_NETWORK_ERROR || (error instanceof UploadRequestError && error.retryable);
+
+const waitBeforeRetry = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(signal.reason ?? new Error('Upload cancelled by user'));
+ return;
+ }
+ const onAbort = () => {
+ clearTimeout(timer);
+ reject(signal?.reason ?? new Error('Upload cancelled by user'));
+ };
+ const timer = setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
/**
* Generate file storage path metadata for S3-compatible storage
@@ -284,11 +358,11 @@ class UploadService {
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.getResponseHeader?.('ETag') || undefined);
- } else reject(xhr.statusText);
+ } else reject(readStorageError(xhr));
});
xhr.addEventListener('error', () => {
if (xhr.status === 0) reject(UPLOAD_NETWORK_ERROR);
- else reject(xhr.statusText);
+ else reject(readStorageError(xhr));
});
xhr.addEventListener('abort', () => reject(new Error('Upload cancelled by user')));
xhr.open('PUT', url);
@@ -300,6 +374,49 @@ class UploadService {
}
};
+ /**
+ * Send one multipart part, retrying a transient storage or network failure
+ * with a freshly signed URL so a single dropped part does not fail a large file.
+ */
+ private uploadPart = async ({
+ blob,
+ onProgress,
+ partNumber,
+ pathname,
+ signal,
+ uploadId,
+ }: {
+ blob: Blob;
+ onProgress: (loaded: number) => void;
+ partNumber: number;
+ pathname: string;
+ signal: AbortSignal | undefined;
+ uploadId: string;
+ }): Promise<string | undefined> => {
+ for (let attempt = 1; ; attempt++) {
+ const url = await lambdaClient.upload.createS3MultipartUploadPartUrl.mutate({
+ partNumber,
+ pathname,
+ uploadId,
+ });
+
+ try {
+ return await this.putBlob(url, blob, signal, onProgress);
+ } catch (error) {
+ if (
+ signal?.aborted ||
+ attempt >= MULTIPART_PART_MAX_ATTEMPTS ||
+ !isRetryableUploadError(error)
+ ) {
+ throw error;
+ }
+
+ onProgress(0);
+ await waitBeforeRetry(MULTIPART_PART_RETRY_DELAY_MS * attempt, signal);
+ }
+ }
+ };
+
private uploadMultipart = async (
file: File,
pathname: string,
@@ -323,25 +440,29 @@ class UploadService {
const offset = (partNumber - 1) * partSize;
const end = Math.min(offset + partSize, file.size);
- const url = await lambdaClient.upload.createS3MultipartUploadPartUrl.mutate({
+ const etag = await this.uploadPart({
+ blob: file.slice(offset, end),
+ onProgress: (loaded) => onProgress(offset + loaded),
partNumber,
pathname,
+ signal,
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,
- });
+ if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
+ // Removing the chip while the parts are being merged cancels this request too.
+ await lambdaClient.upload.completeS3MultipartUpload.mutate(
+ {
+ partCount,
+ parts: parts.length === partCount ? parts : undefined,
+ pathname,
+ uploadId,
+ },
+ { signal },
+ );
} catch (error) {
try {
await lambdaClient.upload.abortS3MultipartUpload.mutate({ pathname, uploadId });
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index 517d37014cb..d14de9325f3 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -7,7 +7,9 @@ import { UnreadableServerResponseError } from '@/libs/trpc/client/unreadableServ
import { fileService } from '@/services/file';
import { ragService } from '@/services/rag';
import { shareChatService } from '@/services/shareChat';
+import { UploadRequestError } from '@/services/upload';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import type { UploadFileItem } from '@/types/files/upload';
import { useFileStore as useStore } from '../../store';
@@ -55,8 +57,19 @@ vi.mock('@/services/shareChat', () => ({
vi.mock('i18next', () => ({
t: (
key: string,
- options?: { message?: string; reason?: string; requestId?: string; status?: number },
+ options?: {
+ detail?: string;
+ max?: string;
+ message?: string;
+ reason?: string;
+ requestId?: string;
+ status?: number;
+ },
) => {
+ if (key === 'upload.storageRejected') return `Storage rejected the upload (${options?.detail})`;
+
+ if (key === 'upload.fileTooLarge') return `Over the ${options?.max} limit`;
+
if (key === 'upload.permissionDenied') {
return 'You do not have permission to upload files in this workspace.';
}
@@ -533,6 +546,135 @@ describe('useFileStore:chat', () => {
]);
});
+ // Regression (T-14442): a 117 MB zip's last S3 part was refused over HTTP/2, the
+ // rejection carried the empty `statusText`, and the chip failed with no reason.
+ it('never leaves a failed upload without a reason', async () => {
+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });
+
+ const { result } = renderHook(() => useStore());
+ const file = new File(['zip'], 'readme.zip', { type: 'application/zip' });
+ vi.spyOn(result.current, 'uploadWithProgress').mockRejectedValue('');
+
+ await act(async () => {
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
+ });
+
+ expect(uploadList()).toEqual([
+ expect.objectContaining({ error: 'File upload failed.', status: 'error' }),
+ ]);
+ });
+
+ it('names the storage status and code when storage refuses the upload', async () => {
+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });
+
+ const { result } = renderHook(() => useStore());
+ const file = new File(['zip'], 'readme.zip', { type: 'application/zip' });
+ vi.spyOn(result.current, 'uploadWithProgress').mockRejectedValue(
+ new UploadRequestError({ code: 'RequestTimeout', status: 400 }),
+ );
+
+ await act(async () => {
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
+ });
+
+ expect(uploadList()).toEqual([
+ expect.objectContaining({
+ error: 'Storage rejected the upload (HTTP 400 · RequestTimeout)',
+ status: 'error',
+ }),
+ ]);
+ expect(uploadList()[0].retryable).not.toBe(false);
+ });
+
+ it('states the size limit and offers no retry for a file over it', async () => {
+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });
+
+ const { result } = renderHook(() => useStore());
+ const file = new File(['zip'], 'huge.zip', { type: 'application/zip' });
+ const uploadWithProgress = vi
+ .spyOn(result.current, 'uploadWithProgress')
+ .mockRejectedValue(new Error('Files larger than 2147483647 bytes cannot be uploaded'));
+
+ await act(async () => {
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
+ });
+
+ expect(uploadList()).toEqual([
+ expect.objectContaining({ error: 'Over the 2 GB limit', retryable: false, status: 'error' }),
+ ]);
+
+ await act(async () => {
+ await result.current.retryChatUploadFile(CONTEXT_KEY, uploadList()[0].id);
+ });
+ expect(uploadWithProgress).toHaveBeenCalledOnce();
+ });
+
+ describe('removing a chip while it uploads', () => {
+ it('cancels the transfer and deletes nothing server-side', async () => {
+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });
+ const removeFile = vi.spyOn(fileService, 'removeFile').mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useStore());
+ const file = new File(['zip'], 'readme.zip', { type: 'application/zip' });
+ let signal: AbortSignal | undefined;
+ vi.spyOn(result.current, 'uploadWithProgress').mockImplementation(
+ ({ abortController }) =>
+ new Promise((resolve) => {
+ signal = abortController?.signal;
+ signal?.addEventListener('abort', () => resolve(undefined));
+ }),
+ );
+
+ let upload!: Promise<void>;
+ await act(async () => {
+ upload = result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
+ await vi.waitFor(() => expect(uploadList()).toHaveLength(1));
+ });
+ const pending = uploadList()[0] as UploadFileItem;
+ expect(pending.status).toBe('pending');
+
+ await act(async () => {
+ await result.current.removeChatUploadFile(CONTEXT_KEY, pending.id);
+ await upload;
+ });
+
+ expect(signal?.aborted).toBe(true);
+ expect(uploadList()).toEqual([]);
+ expect(removeFile).not.toHaveBeenCalled();
+ });
+
+ it('deletes a file record that lands after the chip was removed', async () => {
+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });
+ const removeFile = vi.spyOn(fileService, 'removeFile').mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useStore());
+ const file = new File(['zip'], 'readme.zip', { type: 'application/zip' });
+ let finish!: () => void;
+ vi.spyOn(result.current, 'uploadWithProgress').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ // createFile is not cancellable: the record arrives despite the abort.
+ finish = () => resolve({ id: 'file-landed', url: 'https://example.com/f' });
+ }),
+ );
+
+ let upload!: Promise<void>;
+ await act(async () => {
+ upload = result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
+ await vi.waitFor(() => expect(uploadList()).toHaveLength(1));
+ });
+
+ await act(async () => {
+ await result.current.removeChatUploadFile(CONTEXT_KEY, uploadList()[0].id);
+ finish();
+ await upload;
+ });
+
+ expect(removeFile).toHaveBeenCalledWith('file-landed');
+ expect(ragService.parseFileContent).not.toHaveBeenCalled();
+ });
+ });
+
// Regression: a gateway HTML error page answered the upload API and the card
// showed `Error reason: Unexpected token '<', "<!doctype "... is not valid JSON`.
it('shows the upload-unavailable copy with the request id of an HTML error page', async () => {
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index 8ef6df2b4af..88285ae6208 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -1,4 +1,8 @@
-import { SHARE_VISITOR_MAX_FILE_SIZE } from '@lobechat/const';
+import {
+ MAX_UPLOAD_FILE_SIZE,
+ SHARE_VISITOR_MAX_FILE_SIZE,
+ UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE,
+} from '@lobechat/const';
import { type ChatContextContent } from '@lobechat/types';
import { createNanoId } from '@lobechat/utils';
import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';
@@ -12,7 +16,7 @@ import { findUnreadableServerResponseError } from '@/libs/trpc/client/unreadable
import { fileService } from '@/services/file';
import { ragService } from '@/services/rag';
import { shareChatService } from '@/services/shareChat';
-import { UPLOAD_NETWORK_ERROR } from '@/services/upload';
+import { UPLOAD_NETWORK_ERROR, UploadRequestError } from '@/services/upload';
import { getAgentStoreState } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { type UploadFileListDispatch } from '@/store/file/reducers/uploadFileList';
@@ -124,9 +128,32 @@ const withoutDuplicateImages = (
const formatShareUploadLimit = () => `${Math.round(SHARE_VISITOR_MAX_FILE_SIZE / 1024 / 1024)} MB`;
+const formatUploadLimit = () => `${Math.round(MAX_UPLOAD_FILE_SIZE / 1024 ** 3)} GB`;
+
+/**
+ * The file is over the size every upload is held to: the client check in
+ * `uploadFileToS3` and the server's input validation both carry this message.
+ * Sending it again fails the same way, so it is not offered as a retry.
+ */
+const isUploadSizeLimitError = (error: unknown) =>
+ getErrorMessage(error).includes(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
+
const getUploadErrorDescription = (error: unknown): string => {
if (error === UPLOAD_NETWORK_ERROR) return t('upload.networkError', { ns: 'error' });
+ if (isUploadSizeLimitError(error)) {
+ return t('upload.fileTooLarge', { max: formatUploadLimit(), ns: 'error' });
+ }
+
+ // Storage answered the PUT with an error. Its status and code are the only
+ // trace of why (the browser's statusText is empty over HTTP/2).
+ if (error instanceof UploadRequestError) {
+ return t('upload.storageRejected', {
+ detail: [`HTTP ${error.status}`, error.code].filter(Boolean).join(' · '),
+ ns: 'error',
+ });
+ }
+
// A share upload is admitted by the CREATOR's storage quota, so the block
// is theirs to lift — never route the visitor to their own plan/usage page.
if (isShareStorageBlockError(error)) {
@@ -144,13 +171,24 @@ const getUploadErrorDescription = (error: unknown): string => {
return withResponseDetail(t('upload.serviceUnavailable', { ns: 'error' }), unreadable);
}
- return typeof error === 'string'
- ? error
- : t('upload.unknownError', { ns: 'error', reason: getErrorMessage(error) });
+ const reason = getErrorMessage(error).trim();
+ // A failed chip must always say why; an empty reason left only a red icon.
+ if (!reason) return t('upload.uploadFailed', { ns: 'error' });
+
+ return typeof error === 'string' ? reason : t('upload.unknownError', { ns: 'error', reason });
};
const EMPTY_CHAT_UPLOAD_FILE_LIST: UploadFileItem[] = [];
+/** Statuses of a chip whose file has no server row yet (its id is still the pending id). */
+const UNSETTLED_UPLOAD_STATUSES = new Set<UploadFileItem['status']>([
+ 'cancelled',
+ 'error',
+ 'pending',
+ 'processing',
+ 'uploading',
+]);
+
export class FileActionImpl {
readonly #get: () => FileStore;
readonly #set: Setter;
@@ -161,6 +199,8 @@ export class FileActionImpl {
* and a same-named upload may appear under the old key later.
*/
readonly #inFlightUploads = new Set<{ contextKey: string }>();
+ /** Cancels an upload when its chip is removed, keyed by the chip's pending id. */
+ readonly #uploadAbortControllers = new Map<string, AbortController>();
constructor(set: Setter, get: () => FileStore, _api?: unknown) {
void _api;
@@ -345,15 +385,19 @@ export class FileActionImpl {
this.#get().dispatchChatUploadFileList(contextKey, { id, type: 'removeFile' });
+ // Removing a chip mid-upload cancels the transfer rather than letting it
+ // finish in the background into a file nobody sends.
+ this.#uploadAbortControllers.get(id)?.abort();
+
if (item?.skipRemoveFile) return;
+ // Only a settled upload has a server row; until then the id is the pending
+ // client id, and an upload that lands after the abort deletes itself.
+ if (item && UNSETTLED_UPLOAD_STATUSES.has(item.status)) return;
+
// Share uploads are creator-owned rows the visitor's own file API cannot
// see; the share endpoint deletes them only while still unsent.
if (item?.shareId) {
- // Only a settled upload has a server row to drop; a pending or failed
- // draft is client-side only (its id is still the file name) and the
- // share endpoint would just reject it.
- if (item.status !== 'success') return;
await shareChatService.removeFile(item.shareId, id);
return;
}
@@ -363,7 +407,7 @@ export class FileActionImpl {
retryChatUploadFile = async (contextKey: string, id: string): Promise<void> => {
const item = this.#getChatUploadFileList(contextKey).find((file) => file.id === id);
- if (!item?.agentId) return;
+ if (!item?.agentId || item.retryable === false) return;
this.#get().dispatchChatUploadFileList(contextKey, { id, type: 'removeFile' });
await this.uploadChatFiles(contextKey, [item.file], item.agentId, { shareId: item.shareId });
@@ -538,57 +582,98 @@ export class FileActionImpl {
for (const id of repastedIds)
dispatchChatUploadFileList({ id, type: 'updateFile', value: { repastedAt } });
- const files = uploadFiles.map((item) => item.file);
- const uploadIds = new Map(uploadFiles.map((item) => [item.file, item.id]));
-
// upload files and process it
- const pools = files.map(async (file) => {
- const uploadId = uploadIds.get(file)!;
- let fileResult: { id: string; url: string } | undefined;
-
+ const pools = uploadFiles.map(async ({ file, id: uploadId }) => {
+ // Share uploads have no cancellable transfer of their own yet.
+ const abortController = shareId ? undefined : new AbortController();
+ if (abortController) this.#uploadAbortControllers.set(uploadId, abortController);
try {
- fileResult = shareId
- ? await uploadShareVisitorFile({
- file,
- onStatusUpdate: dispatchChatUploadFileList,
- shareId,
- uploadId,
- })
- : await this.#get().uploadWithProgress({
- conversationAgentId: agentId,
- file,
- onStatusUpdate: dispatchChatUploadFileList,
- uploadId,
- });
- } catch (error) {
- if (getErrorMessage(error) === 'UNAUTHORIZED') {
- dispatchChatUploadFileList({ id: uploadId, type: 'removeFile' });
- } else {
- dispatchChatUploadFileList({
- id: uploadId,
- type: 'updateFile',
- value: {
- error: getUploadErrorDescription(error),
- status: 'error',
- uploadState: undefined,
- },
+ await this.#uploadChatFile({
+ abortController,
+ agentId,
+ dispatchChatUploadFileList,
+ file,
+ shareId,
+ uploadId,
+ });
+ } finally {
+ this.#uploadAbortControllers.delete(uploadId);
+ }
+ });
+
+ await Promise.all(pools);
+ };
+
+ #uploadChatFile = async ({
+ abortController,
+ agentId,
+ dispatchChatUploadFileList,
+ file,
+ shareId,
+ uploadId,
+ }: {
+ abortController?: AbortController;
+ agentId: string;
+ dispatchChatUploadFileList: (payload: UploadFileListDispatch) => void;
+ file: File;
+ shareId: string | undefined;
+ uploadId: string;
+ }): Promise<void> => {
+ let fileResult: { id: string; url: string } | undefined;
+
+ try {
+ fileResult = shareId
+ ? await uploadShareVisitorFile({
+ file,
+ onStatusUpdate: dispatchChatUploadFileList,
+ shareId,
+ uploadId,
+ })
+ : await this.#get().uploadWithProgress({
+ abortController,
+ conversationAgentId: agentId,
+ file,
+ onStatusUpdate: dispatchChatUploadFileList,
+ uploadId,
});
- }
+ } catch (error) {
+ if (abortController?.signal.aborted) return;
+
+ if (getErrorMessage(error) === 'UNAUTHORIZED') {
+ dispatchChatUploadFileList({ id: uploadId, type: 'removeFile' });
+ } else {
+ dispatchChatUploadFileList({
+ id: uploadId,
+ type: 'updateFile',
+ value: {
+ error: getUploadErrorDescription(error),
+ retryable: !isUploadSizeLimitError(error),
+ status: 'error',
+ uploadState: undefined,
+ },
+ });
}
+ }
- if (!fileResult) return;
+ if (!fileResult) return;
- // image don't need to be chunked and embedding
- if (isChunkingUnsupported(file.type)) return;
+ // The chip was removed while the file record was being created: drop the
+ // record too, so a cancelled upload leaves nothing behind.
+ if (abortController?.signal.aborted) {
+ await fileService.removeFile(fileResult.id).catch((error: unknown) => {
+ console.error('Failed to remove cancelled upload:', error);
+ });
+ return;
+ }
- // A share file is creator-owned, so the visitor cannot pre-parse it; the
- // run parses it on the creator's account when the turn is set up.
- if (shareId) return;
+ // image don't need to be chunked and embedding
+ if (isChunkingUnsupported(file.type)) return;
- await ragService.parseFileContent(fileResult.id);
- });
+ // A share file is creator-owned, so the visitor cannot pre-parse it; the
+ // run parses it on the creator's account when the turn is set up.
+ if (shareId) return;
- await Promise.all(pools);
+ await ragService.parseFileContent(fileResult.id);
};
}