diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index 515fa602..2793c2c0 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -457,18 +457,45 @@ export function FileBrowser({ const { mutate: createUploadTaskMutation } = useMutation< InferResponseType, Error, - InferRequestType + InferRequestType, + { files: FileWithId[] } >({ mutationFn: async (request) => { const res = await $createUploadTask(request) if (!res.ok) throw new Error('Failed to create upload task') return (await res.json()) as InferResponseType }, - onSuccess: async (data, variables) => { + onMutate: () => { + return { files: [...filesToUpload] } + }, + onSuccess: async (data, variables, context) => { + const currentFiles = context?.files || [] const isCurrentFolderUpload = variables.json.parentId === assetId + // Register task and files in the store for real-time progress tracking + const filesProgressInfo = currentFiles + .map((f) => { + const urlInfo = ( + data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined + )?.find((p) => p.id === f.id) + return { + fileId: urlInfo?.fileId || f.id, + name: f.file.name, + size: f.file.size, + } + }) + .filter((info) => !!info.fileId) + + const visibleFiles = currentFiles.filter((f) => !f.file.name.startsWith('.')) + const taskName = + visibleFiles.length === 1 ? visibleFiles[0].file.name : `${visibleFiles.length} Items` + + if (data.taskId) { + startTask(data.taskId, taskName, filesProgressInfo) + } + if (isCurrentFolderUpload) { - const newLocalFiles: AssetInfo[] = filesToUpload + const newLocalFiles: AssetInfo[] = currentFiles .filter((f) => { const path = (f.file.webkitRelativePath || f.file.name).split('/') return path.length === 1 @@ -500,7 +527,7 @@ export function FileBrowser({ // The RPC client returns an object that we cast to the expected type // eslint-disable-next-line @typescript-eslint/no-explicit-any - await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!) + await uploadFiles(currentFiles, data.presignedUrls as any, data.taskId!) queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId], }) @@ -509,6 +536,10 @@ export function FileBrowser({ const incrementUploading = useUploadStore((state) => state.increment) const decrementUploading = useUploadStore((state) => state.decrement) + const startTask = useUploadStore((state) => state.startTask) + const updateFileProgress = useUploadStore((state) => state.updateFileProgress) + const completeFile = useUploadStore((state) => state.completeFile) + const failFile = useUploadStore((state) => state.failFile) const { fields } = useFieldStore() const displayedFields = useMemo(() => { if (!isShareView) return fields.filter((f) => f.visible) @@ -688,25 +719,53 @@ export function FileBrowser({ incrementUploading() try { try { - const resp = await fetch(uploadInfo.url, { - method: 'PUT', - body: file.file, - headers: { - 'Content-Type': file.file.type, + const xhr = new XMLHttpRequest() + const uploadPromise = new Promise<{ ok: boolean; status: number }>( + (resolve, reject) => { + xhr.open('PUT', uploadInfo.url) + xhr.setRequestHeader('Content-Type', file.file.type) + + xhr.upload.onprogress = (event) => { + if (event.lengthComputable) { + updateFileProgress(taskId, uploadInfo.fileId, event.loaded) + } + } + + xhr.onload = () => { + if (xhr.status >= 200 && xhr.status < 300) { + resolve({ ok: true, status: xhr.status }) + } else { + resolve({ ok: false, status: xhr.status }) + } + } + + xhr.onerror = () => { + reject(new Error('Network error')) + } + + xhr.onabort = () => { + reject(new Error('Upload aborted')) + } + + xhr.send(file.file) }, - }) + ) + + const resp = await uploadPromise if (resp.ok) { + completeFile(taskId, uploadInfo.fileId) await confirmUpload({ - param: { teamId: teamId, taskId: taskId }, + param: { teamId: teamId!, taskId: taskId }, json: { fileId: uploadInfo.fileId, }, }) } else { + failFile(taskId, uploadInfo.fileId) toast.error(`Failed to upload file: ${file.file.name}`) await confirmUpload({ - param: { teamId: teamId, taskId: taskId }, + param: { teamId: teamId!, taskId: taskId }, json: { fileId: uploadInfo.fileId, errorMessage: `upload failed with status: ${resp.status}`, @@ -715,9 +774,10 @@ export function FileBrowser({ return } } catch (error) { + failFile(taskId, uploadInfo.fileId) toast.error(`Failed to upload file: ${file.file.name}`) await confirmUpload({ - param: { teamId: teamId, taskId: taskId }, + param: { teamId: teamId!, taskId: taskId }, json: { fileId: uploadInfo.fileId, errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`, diff --git a/packages/webui/components/file-browser/file-card.tsx b/packages/webui/components/file-browser/file-card.tsx index d31b23bb..63781ca7 100644 --- a/packages/webui/components/file-browser/file-card.tsx +++ b/packages/webui/components/file-browser/file-card.tsx @@ -6,11 +6,11 @@ import { Badge } from '@/ui/components/ui/badge' import { Button } from '@/ui/components/ui/button' import { Checkbox } from '@/ui/components/ui/checkbox' import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuTrigger, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { EditableText } from '@/ui/components/ui/editable-text' import { Skeleton } from '@/ui/components/ui/skeleton' @@ -22,6 +22,8 @@ import React, { useEffect, useMemo, useRef, useState } from 'react' import type { DragState } from '../dnd-types' import FieldRenderer from '../field-renderer' import { FilePreview } from './file-preview' +import { useUploadStore } from '@/ui/stores/upload' +import { ProgressCircle } from '@/ui/components/ui/progress-circle' import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import { FIELD_TYPE_ICONS } from '../fields-manager' @@ -82,6 +84,13 @@ export function FileCard({ const [name, setName] = useState(item.name) const inputRef = useRef(null) + const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || '']) + const uploadPercent = fileUploadState + ? fileUploadState.total > 0 + ? (fileUploadState.loaded / fileUploadState.total) * 100 + : 0 + : 0 + const shouldPoll = (item.type === 'file' || item.type === 'version_stack') && !!teamId && @@ -247,20 +256,24 @@ export function FileCard({ {displayItem.status !== 'error' && ( )} - - {displayItem.status === 'uploaded' - ? 'Processing' - : displayItem.status === 'error' - ? 'Failed to upload' - : displayItem.status} - + {displayItem.status === 'uploading' ? ( + + ) : ( + + {displayItem.status === 'uploaded' + ? 'Processing' + : displayItem.status === 'error' + ? 'Failed to upload' + : displayItem.status} + + )} ) : ( diff --git a/packages/webui/components/file-browser/file-list-item.tsx b/packages/webui/components/file-browser/file-list-item.tsx index 2db23542..7d87b807 100644 --- a/packages/webui/components/file-browser/file-list-item.tsx +++ b/packages/webui/components/file-browser/file-list-item.tsx @@ -11,6 +11,8 @@ import FieldRenderer from '../field-renderer' import { Badge } from '@/ui/components/ui/badge' import { Checkbox } from '@/ui/components/ui/checkbox' import { EditableText } from '@/ui/components/ui/editable-text' +import { useUploadStore } from '@/ui/stores/upload' +import { ProgressCircle } from '@/ui/components/ui/progress-circle' import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' @@ -60,6 +62,13 @@ export function FileListItem({ const [name, setName] = useState(item.name) const inputRef = useRef(null) + const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || '']) + const uploadPercent = fileUploadState + ? fileUploadState.total > 0 + ? (fileUploadState.loaded / fileUploadState.total) * 100 + : 0 + : 0 + const shouldPoll = (item.type === 'file' || item.type === 'version_stack') && !!teamId && @@ -197,7 +206,9 @@ export function FileListItem({ className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary" />
- {displayItem.preview?.thumbnailUrl ? ( + {displayItem.status === 'uploading' ? ( + + ) : displayItem.preview?.thumbnailUrl ? ( = ({ progress, className }) => { const radius = 20 const circumference = 2 * Math.PI * radius - const offset = circumference - (progress / 100) * circumference + const offset = circumference - (Math.min(100, Math.max(0, progress)) / 100) * circumference return ( - + @@ -24,12 +25,11 @@ export const ProgressCircle: React.FC = ({ progress, classN cx="25" cy="25" r={radius} - className="stroke-current text-blue-600" + className="stroke-primary transition-all duration-300 ease-out" strokeWidth="4" fill="transparent" strokeDasharray={circumference} strokeDashoffset={offset} - style={{ transition: 'stroke-dashoffset 0.3s' }} transform="rotate(-90 25 25)" /> = ({ progress, classN y="50%" textAnchor="middle" dy=".3em" - className="text-xs font-semibold text-gray-700" + className="fill-foreground text-[10px] font-bold" > {`${Math.round(progress)}%`} diff --git a/packages/webui/components/upload-tasks.tsx b/packages/webui/components/upload-tasks.tsx index 427008ec..c8cb3da9 100644 --- a/packages/webui/components/upload-tasks.tsx +++ b/packages/webui/components/upload-tasks.tsx @@ -4,7 +4,7 @@ import { useTeamId } from '@/ui/hooks/use-team-id' import { useInfiniteQuery } from '@tanstack/react-query' import { useUploadStore } from '@/ui/stores/upload' import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react' -import { useEffect } from 'react' +import { useEffect, useMemo } from 'react' import { useInView } from 'react-intersection-observer' import { format, parseISO, isToday, isYesterday } from 'date-fns' import { Progress } from '@/ui/components/ui/progress' @@ -24,9 +24,28 @@ function formatDayHeader(dateString: string): string { return format(date, 'MMMM d, yyyy') } +function formatBytes(bytes: number): string { + if (bytes === 0) return '0 B' + const k = 1024 + const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] + const i = Math.floor(Math.log(bytes) / Math.log(k)) + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i] +} + function UploadTaskItem({ task }: { task: TaskInfo }) { - const isCompleted = task.uploaded === task.total - const percent = task.total > 0 ? (task.uploaded / task.total) * 100 : 0 + const clientProgress = useUploadStore((state) => state.tasks[task.id]) + + const isCompleted = clientProgress + ? clientProgress.loaded === clientProgress.total && task.uploaded === task.total + : task.uploaded === task.total + + const percent = clientProgress + ? clientProgress.total > 0 + ? (clientProgress.loaded / clientProgress.total) * 100 + : 0 + : task.total > 0 + ? (task.uploaded / task.total) * 100 + : 0 let formattedTime: string try { @@ -72,7 +91,9 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
- {task.uploaded} / {task.total} {task.total === 1 ? 'file' : 'files'} + {clientProgress + ? `${formatBytes(clientProgress.loaded)} / ${formatBytes(clientProgress.total)} (${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'})` + : `${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'}`} {!isCompleted && ( {Math.round(percent)}% @@ -92,6 +113,7 @@ interface TaskGroup { export function UploadTasks() { const teamId = useTeamId() const uploading = useUploadStore((state) => state.uploading) + const clientActiveTasks = useUploadStore((state) => state.tasks) const { data: tasksData, fetchNextPage, @@ -126,6 +148,27 @@ export function UploadTasks() { const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? [] + const combinedTasks = useMemo(() => { + const serverTaskIds = new Set(tasks.map((t) => t.id)) + const clientOnlyTasks: TaskInfo[] = Object.values(clientActiveTasks) + .filter((ct) => !serverTaskIds.has(ct.taskId)) + .map((ct) => { + const completedCount = Object.values(ct.files).filter( + (f) => f.status === 'completed' || f.status === 'failed', + ).length + + return { + id: ct.taskId, + name: ct.name, + total: Object.keys(ct.files).length, + uploaded: completedCount, + createdAt: new Date().toISOString(), + } + }) + + return [...clientOnlyTasks, ...tasks].sort((a, b) => b.id.localeCompare(a.id)) + }, [tasks, clientActiveTasks]) + if (isLoading) { return (
@@ -134,7 +177,7 @@ export function UploadTasks() { ) } - if (tasks.length === 0) { + if (combinedTasks.length === 0) { return (
@@ -148,7 +191,7 @@ export function UploadTasks() { // Group tasks by day (maintaining desc ordering) const taskGroups: TaskGroup[] = [] - tasks.forEach((task) => { + combinedTasks.forEach((task) => { const day = formatDayHeader(task.createdAt) let group = taskGroups.find((g) => g.day === day) if (!group) { diff --git a/packages/webui/stores/upload.ts b/packages/webui/stores/upload.ts index 0d274622..26db600f 100644 --- a/packages/webui/stores/upload.ts +++ b/packages/webui/stores/upload.ts @@ -1,13 +1,166 @@ import { create } from 'zustand' +export interface FileUploadState { + fileId: string + name: string + loaded: number + total: number + status: 'uploading' | 'completed' | 'failed' +} + +export interface TaskUploadState { + taskId: string + name: string + loaded: number + total: number + files: Record +} + type UploadStore = { uploading: number + tasks: Record + fileProgress: Record increment: () => void decrement: () => void + startTask: ( + taskId: string, + taskName: string, + files: Array<{ fileId: string; name: string; size: number }>, + ) => void + updateFileProgress: (taskId: string, fileId: string, loaded: number) => void + completeFile: (taskId: string, fileId: string) => void + failFile: (taskId: string, fileId: string) => void } export const useUploadStore = create((set) => ({ uploading: 0, + tasks: {}, + fileProgress: {}, increment: () => set((state) => ({ uploading: state.uploading + 1 })), decrement: () => set((state) => ({ uploading: state.uploading - 1 })), + + startTask: (taskId, taskName, files) => + set((state) => { + const taskFiles: Record = {} + let totalBytes = 0 + + files.forEach((f) => { + taskFiles[f.fileId] = { + fileId: f.fileId, + name: f.name, + loaded: 0, + total: f.size, + status: 'uploading', + } + totalBytes += f.size + }) + + const newTasks = { + ...state.tasks, + [taskId]: { + taskId, + name: taskName, + loaded: 0, + total: totalBytes, + files: taskFiles, + }, + } + + const newFileProgress = { ...state.fileProgress } + files.forEach((f) => { + newFileProgress[f.fileId] = taskFiles[f.fileId] + }) + + return { + tasks: newTasks, + fileProgress: newFileProgress, + } + }), + + updateFileProgress: (taskId, fileId, loaded) => + set((state) => { + const task = state.tasks[taskId] + if (!task) return {} + + const file = task.files[fileId] + if (!file) return {} + + const updatedFile = { ...file, loaded } + const updatedFiles = { ...task.files, [fileId]: updatedFile } + + const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0) + + return { + tasks: { + ...state.tasks, + [taskId]: { + ...task, + loaded: loadedBytes, + files: updatedFiles, + }, + }, + fileProgress: { + ...state.fileProgress, + [fileId]: updatedFile, + }, + } + }), + + completeFile: (taskId, fileId) => + set((state) => { + const task = state.tasks[taskId] + if (!task) return {} + + const file = task.files[fileId] + if (!file) return {} + + const updatedFile: FileUploadState = { ...file, status: 'completed', loaded: file.total } + const updatedFiles = { ...task.files, [fileId]: updatedFile } + + const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0) + + return { + tasks: { + ...state.tasks, + [taskId]: { + ...task, + loaded: loadedBytes, + files: updatedFiles, + }, + }, + fileProgress: { + ...state.fileProgress, + [fileId]: updatedFile, + }, + } + }), + + failFile: (taskId, fileId) => + set((state) => { + const task = state.tasks[taskId] + if (!task) return {} + + const file = task.files[fileId] + if (!file) return {} + + const updatedFile: FileUploadState = { ...file, status: 'failed' } + const updatedFiles = { ...task.files, [fileId]: updatedFile } + + const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0) + + return { + tasks: { + ...state.tasks, + [taskId]: { + ...task, + loaded: loadedBytes, + files: updatedFiles, + }, + }, + fileProgress: { + ...state.fileProgress, + [fileId]: updatedFile, + }, + } + }), }))