diff --git a/CHANGELOG.md b/CHANGELOG.md index fa17f10e..b484b8b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **upload**: Display a clear diagnostic error toast when remote file uploads fail due to an unconfigured or localhost S3 storage endpoint + ### Changed ## [0.6.2] - 2026-10-29 diff --git a/packages/webui/components/file-browser/file-browser.test.tsx b/packages/webui/components/file-browser/file-browser.test.tsx index 23045c59..c6d1d5b1 100644 --- a/packages/webui/components/file-browser/file-browser.test.tsx +++ b/packages/webui/components/file-browser/file-browser.test.tsx @@ -195,9 +195,12 @@ describe('FileBrowser', () => { }) it('renders empty state when there are no folders and files and not loading', () => { - renderComponent({ folders: [], files: [], isLoading: false }) + const { container } = renderComponent({ folders: [], files: [], isLoading: false }) expect(screen.getByText(/This folder is empty|此文件夹为空/i)).toBeDefined() + const emptyArea = container.querySelector('.empty-area') + expect(emptyArea).not.toBeNull() + expect(emptyArea?.classList.contains('flex-1')).toBe(true) }) it('renders loading skeleton and does not render empty state when isLoading is true (card view)', () => { diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index 7f45fdaf..1cedb77b 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -545,6 +545,9 @@ export function FileBrowser({ onMutate: () => { return { files: [...filesToUpload] } }, + onError: () => { + toast.error(m.failed_upload_file()) + }, onSuccess: async (data, variables, context) => { const currentFiles = context?.files || [] const isCurrentFolderUpload = variables.json.parentId === assetId @@ -1007,6 +1010,27 @@ export function FileBrowser({ > {isLoading && folders.length === 0 && displayedFiles.length === 0 ? ( + ) : !isLoading && + folders.length === 0 && + displayedFiles.length === 0 && + !isFetchingNextFoldersPage && + !isFetchingNextFilesPage ? ( +
+ {isRecents ? ( +
+ +

{m.no_recent_files()}

+

+ {m.no_recent_files_description()} +

+
+ ) : ( + {m.this_folder_is_empty()} + )} +
) : displayStyle === 'list' ? ( {m.loading_more()}

)} - - {!isLoading && - folders.length === 0 && - displayedFiles.length === 0 && - !isFetchingNextFoldersPage && - !isFetchingNextFilesPage && ( -
- {isRecents ? ( -
- -

{m.no_recent_files()}

-

- {m.no_recent_files_description()} -

-
- ) : ( - {m.this_folder_is_empty()} - )} -
- )} {selectedCount > 0 && ( diff --git a/packages/webui/components/file-browser/mobile-file-browser.tsx b/packages/webui/components/file-browser/mobile-file-browser.tsx index 086cfc3b..23727afb 100644 --- a/packages/webui/components/file-browser/mobile-file-browser.tsx +++ b/packages/webui/components/file-browser/mobile-file-browser.tsx @@ -215,6 +215,9 @@ export function MobileFileBrowser({ onMutate: () => { return { files: [...pendingFilesToUpload] } }, + onError: () => { + toast.error(m.failed_upload_file()) + }, onSuccess: async (data, _variables, context) => { const currentFiles = context?.files || [] const filesProgressInfo = currentFiles diff --git a/packages/webui/lib/uploader.test.ts b/packages/webui/lib/uploader.test.ts index ae1154a5..288ac67b 100644 --- a/packages/webui/lib/uploader.test.ts +++ b/packages/webui/lib/uploader.test.ts @@ -1,8 +1,14 @@ // @vitest-environment happy-dom -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { activeUploads, uploadFilesWithUppy, isNetworkIssue } from './uploader' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + activeUploads, + uploadFilesWithUppy, + isNetworkIssue, + isLocalhostStorageMismatch, +} from './uploader' import { acquireWakeLock, releaseWakeLock } from './wake-lock' import { useUploadStore } from '@/ui/stores/upload' +import { m } from '@/ui/paraglide/messages.js' vi.mock('sonner', () => ({ toast: { @@ -37,6 +43,16 @@ import { client } from '@/ui/api/client' import { toast } from 'sonner' describe('Uploader', () => { + const initialLocation = window.location + + afterEach(() => { + Object.defineProperty(window, 'location', { + value: initialLocation, + configurable: true, + writable: true, + }) + }) + beforeEach(() => { vi.clearAllMocks() activeUploads.clear() @@ -206,6 +222,56 @@ describe('Uploader', () => { }) }) + describe('isLocalhostStorageMismatch', () => { + it('detects mismatch when upload URL is localhost and window location is remote', () => { + // In happy-dom window.location defaults to localhost:3000 + Object.defineProperty(window, 'location', { + value: { + hostname: '192.168.1.100', + origin: 'http://192.168.1.100:3000', + }, + configurable: true, + writable: true, + }) + + expect(isLocalhostStorageMismatch('http://localhost:3000/files/shumai/files/1.png')).toBe( + true, + ) + expect(isLocalhostStorageMismatch('http://127.0.0.1:3000/files/shumai/files/1.png')).toBe( + true, + ) + expect(isLocalhostStorageMismatch('http://[::1]:3000/files/shumai/files/1.png')).toBe(true) + expect(isLocalhostStorageMismatch('http://0.0.0.0:3000/files/shumai/files/1.png')).toBe(true) + + // Remote upload URL with remote window -> no mismatch + expect(isLocalhostStorageMismatch('http://192.168.1.100:3000/files/shumai/files/1.png')).toBe( + false, + ) + expect(isLocalhostStorageMismatch('https://s3.amazonaws.com/bucket/files/1.png')).toBe(false) + expect(isLocalhostStorageMismatch('/files/shumai/files/1.png')).toBe(false) + expect(isLocalhostStorageMismatch(undefined)).toBe(false) + expect(isLocalhostStorageMismatch('')).toBe(false) + }) + + it('returns false when window location itself is localhost', () => { + Object.defineProperty(window, 'location', { + value: { + hostname: 'localhost', + origin: 'http://localhost:3000', + }, + configurable: true, + writable: true, + }) + + expect(isLocalhostStorageMismatch('http://localhost:3000/files/shumai/files/1.png')).toBe( + false, + ) + expect(isLocalhostStorageMismatch('http://127.0.0.1:3000/files/shumai/files/1.png')).toBe( + false, + ) + }) + }) + it('pauses on network disconnect, does not report terminal failure, and resumes on back-online', async () => { Object.defineProperty(navigator, 'onLine', { value: true, configurable: true }) useUploadStore @@ -315,9 +381,85 @@ describe('Uploader', () => { param: { teamId: 'team-1', taskId: 'task-1' }, json: { fileId: 'file-1', errorMessage: '403 Forbidden' }, }) + expect(toast.error).toHaveBeenCalledWith(m.failed_upload_file_with_name({ name: 'test.mp4' })) expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('failed') expect(activeUploads.size).toBe(0) addFileSpy.mockRestore() }) + + it('shows S3 endpoint localhost error toast without retrying when remote user encounters localhost upload URL', async () => { + Object.defineProperty(window, 'location', { + value: { + hostname: '192.168.1.100', + origin: 'http://192.168.1.100:3000', + }, + configurable: true, + writable: true, + }) + Object.defineProperty(navigator, 'onLine', { value: true, configurable: true }) + + useUploadStore + .getState() + .startTask('task-1', 'task-1', [{ fileId: 'file-1', name: 'remote.mp4', size: 100 }]) + + const addFileSpy = vi.spyOn(Uppy.prototype, 'addFile').mockReturnValue('f1') + const retryAllSpy = vi.spyOn(Uppy.prototype, 'retryAll') + + const uploadPromise = uploadFilesWithUppy({ + files: [{ id: 'temp-1', file: new File(['content'], 'remote.mp4', { type: 'video/mp4' }) }], + taskId: 'task-1', + teamId: 'team-1', + storageBackend: 'local', + createdAssets: [{ tempId: 'temp-1', assetId: 'file-1', key: 'files/remote.mp4' }], + presignedUrls: [ + { + id: 'temp-1', + fileId: 'file-1', + url: 'http://localhost:3000/files/shumai/files/remote.mp4', + }, + ], + }) + + await new Promise((r) => setTimeout(r, 10)) + const capturedUppy = addFileSpy.mock.contexts[0] as Uppy + expect(capturedUppy).toBeDefined() + + const mockFile = { + id: 'f1', + name: 'remote.mp4', + meta: { + fileId: 'file-1', + url: 'http://localhost:3000/files/shumai/files/remote.mp4', + }, + } as unknown as UppyFile> + + const networkError = new Error('Failed to fetch') + capturedUppy.emit('upload-error', mockFile, networkError) + capturedUppy.emit('complete', { + successful: [], + failed: [{ ...mockFile, error: networkError.message }], + }) + + await uploadPromise + + // Should NOT retry when localhost mismatch is detected + expect(retryAllSpy).not.toHaveBeenCalled() + + // Must show specific AWS_ENDPOINT_URL_S3 toast + expect(toast.error).toHaveBeenCalledWith(m.upload_failed_s3_endpoint_localhost(), { + id: 's3-endpoint-localhost-mismatch', + duration: 10000, + }) + + expect(client.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({ + param: { teamId: 'team-1', taskId: 'task-1' }, + json: { fileId: 'file-1', errorMessage: 'Failed to fetch' }, + }) + expect(useUploadStore.getState().tasks['task-1']?.files['file-1']?.status).toBe('failed') + expect(activeUploads.size).toBe(0) + + addFileSpy.mockRestore() + retryAllSpy.mockRestore() + }) }) diff --git a/packages/webui/lib/uploader.ts b/packages/webui/lib/uploader.ts index 03b9db32..0ec03c97 100644 --- a/packages/webui/lib/uploader.ts +++ b/packages/webui/lib/uploader.ts @@ -5,6 +5,7 @@ import type { PresignedUrl } from '@shumai/dtos' import { client } from '@/ui/api/client' import { useUploadStore } from '@/ui/stores/upload' import { toast } from 'sonner' +import { m } from '@/ui/paraglide/messages.js' import { acquireWakeLock, releaseWakeLock } from './wake-lock' export type FileWithId = { @@ -18,6 +19,7 @@ export interface ActiveUploadFile { fileId: string key?: string uploadId?: string + url?: string } export const activeUploads = new Map() @@ -63,6 +65,21 @@ if (typeof window !== 'undefined') { }) } +const LOCALHOST_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0']) + +export function isLocalhostStorageMismatch(uploadUrlString?: string): boolean { + if (!uploadUrlString || typeof window === 'undefined') return false + try { + const uploadUrl = new URL(uploadUrlString, window.location.origin) + const isUploadLocalhost = LOCALHOST_HOSTS.has(uploadUrl.hostname) + const isWindowLocalhost = LOCALHOST_HOSTS.has(window.location.hostname) + + return isUploadLocalhost && !isWindowLocalhost + } catch { + return false + } +} + export function isNetworkIssue(error?: unknown): boolean { if (typeof navigator !== 'undefined' && !navigator.onLine) { return true @@ -76,7 +93,7 @@ export function isNetworkIssue(error?: unknown): boolean { msg.includes('network error') || msg.includes('failed to fetch') || msg.includes('networkerror') || - msg.includes('load failed') || + (msg.includes('load failed') && !msg.includes('upload failed')) || msg.includes('err_internet_disconnected') ) { return true @@ -171,6 +188,12 @@ export async function uploadFilesWithUppy({ } const data = (await res.json()) as { url: string } + if (fileId) { + const active = activeUploads.get(fileId) + if (active) { + active.url = data.url + } + } return { url: data.url } }, }) @@ -268,7 +291,7 @@ export async function uploadFilesWithUppy({ console.error('Failed to confirm upload:', err) failFile(taskId, fileId) decrement() - toast.error(`Failed to confirm upload: ${file.name}`) + toast.error(m.failed_confirm_upload_with_name({ name: file.name })) await onFileFinished?.(fileId) throw err } @@ -283,11 +306,21 @@ export async function uploadFilesWithUppy({ ) => { const fileId = file.meta.fileId as string if (!activeUploads.has(fileId)) return + const active = activeUploads.get(fileId) + const uploadUrl = (file.meta?.url as string | undefined) || active?.url + activeUploads.delete(fileId) failFile(taskId, fileId) decrement() - toast.error(`Failed to upload file: ${file.name}`) + if (isLocalhostStorageMismatch(uploadUrl)) { + toast.error(m.upload_failed_s3_endpoint_localhost(), { + id: 's3-endpoint-localhost-mismatch', + duration: 10000, + }) + } else { + toast.error(m.failed_upload_file_with_name({ name: file.name })) + } const errorPromise = (async () => { try { @@ -295,7 +328,8 @@ export async function uploadFilesWithUppy({ param: { teamId, taskId }, json: { fileId, - errorMessage: (error as Error)?.message || 'Upload failed', + errorMessage: + (error as Error)?.message || (typeof error === 'string' ? error : 'Upload failed'), }, }) } catch (err) { @@ -311,6 +345,19 @@ export async function uploadFilesWithUppy({ if (!file) return console.error(`[Uploader] upload-error for ${file.name}:`, error) + const fileId = file.meta?.fileId as string | undefined + const uploadUrl = + (file.meta?.url as string | undefined) || + (fileId ? activeUploads.get(fileId)?.url : undefined) + + if (isLocalhostStorageMismatch(uploadUrl)) { + console.warn( + `[Uploader] Localhost storage endpoint mismatch detected for ${file.name}. Failing permanently without retry.`, + ) + handlePermanentError(file, error) + return + } + if (isNetworkIssue(error)) { console.warn( `[Uploader] Network error detected for ${file.name}. Keeping upload active to resume when connection is restored.`, @@ -357,6 +404,7 @@ export async function uploadFilesWithUppy({ taskId, fileId, key, + url, }) increment() @@ -385,7 +433,19 @@ export async function uploadFilesWithUppy({ const failedFiles = result?.failed || [] const isOffline = typeof navigator !== 'undefined' && !navigator.onLine const hasNetworkFailures = - isOffline || failedFiles.some((f) => isNetworkIssue((f as { error?: unknown })?.error)) + isOffline || + failedFiles.some((f) => { + const err = (f as { error?: unknown })?.error + const fileMeta = (f as { meta?: Record })?.meta + const fId = fileMeta?.fileId as string | undefined + const uUrl = + (fileMeta?.url as string | undefined) || + (fId ? activeUploads.get(fId)?.url : undefined) + if (isLocalhostStorageMismatch(uUrl)) { + return false + } + return isNetworkIssue(err) + }) if (hasNetworkFailures) { console.log( diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 50116eb8..4fbeaf55 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -1124,6 +1124,9 @@ "n_folders_singular": "{count} Folder", "n_folders_plural": "{count} Folders", "failed_upload_file": "Failed to upload file", + "failed_upload_file_with_name": "Failed to upload file: {name}", + "failed_confirm_upload_with_name": "Failed to confirm upload: {name}", + "upload_failed_s3_endpoint_localhost": "Upload failed: Server storage endpoint is configured as localhost, but Shumai is being accessed from a remote address. Please set the AWS_ENDPOINT_URL_S3 environment variable on your server to your external URL.", "failed_fetch_share_link": "Failed to fetch share link", "failed_fetch_folders": "Failed to fetch folders", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index 1f83748b..dec8f4b9 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -1124,6 +1124,9 @@ "n_folders_singular": "{count} 个文件夹", "n_folders_plural": "{count} 个文件夹", "failed_upload_file": "上传文件失败", + "failed_upload_file_with_name": "上传文件失败: {name}", + "failed_confirm_upload_with_name": "确认上传失败: {name}", + "upload_failed_s3_endpoint_localhost": "上传失败:服务器存储端点配置为 localhost,但当前通过远程地址访问 Shumai。请在服务器上将 AWS_ENDPOINT_URL_S3 环境变量配置为外部访问地址。", "failed_fetch_share_link": "获取分享链接失败", "failed_fetch_folders": "获取文件夹失败", diff --git a/packages/webui/routes/__root.tsx b/packages/webui/routes/__root.tsx index 0088fd88..c9d3a658 100644 --- a/packages/webui/routes/__root.tsx +++ b/packages/webui/routes/__root.tsx @@ -75,7 +75,12 @@ function RootComponent() { }) if (!showSidebar) { - return + return ( + <> + + + + ) } const unreadCount = me?.unreadNotificationCount ?? 0