feat(upload): allow canceling in-progress upload tasks from sidebar (#511)

* feat(upload): allow canceling in-progress upload tasks from sidebar

* fix(upload): resolve concurrent confirmation race and store counter issues on cancellation

* fix(webui): immediately remove cancelled upload files from file list view
This commit is contained in:
Yiling-J
2026-10-31 16:39:54 +08:00
committed by GitHub
parent ff3d71ed3d
commit c2348b0e68
15 changed files with 926 additions and 93 deletions
@@ -250,12 +250,15 @@ export function FileBrowser({
}
const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([])
const fileProgress = useUploadStore((state) => state.fileProgress)
const displayedFiles = useMemo(() => {
const existingIds = new Set(files.map((f) => f.id))
const filteredLocal = localUploadingFiles.filter((f) => !existingIds.has(f.id))
const filteredLocal = localUploadingFiles
.filter((f) => !existingIds.has(f.id))
.filter((f) => fileProgress[f.id!]?.status !== 'failed')
return [...filteredLocal, ...files]
}, [files, localUploadingFiles])
}, [files, localUploadingFiles, fileProgress])
const activePreviewItem = useMemo(() => {
if (selectedIds.size === 0) return null
@@ -575,6 +578,7 @@ export function FileBrowser({
startTask(data.taskId, taskName, filesProgressInfo)
}
let batchIds: Set<string> | null = null
if (isCurrentFolderUpload) {
const newLocalFiles: AssetInfo[] = currentFiles
.filter((f) => {
@@ -615,6 +619,7 @@ export function FileBrowser({
updatedAt: new Date().toISOString(),
}
})
batchIds = new Set(newLocalFiles.map((f) => f.id!))
setLocalUploadingFiles((prev) => [...newLocalFiles, ...prev])
}
@@ -626,26 +631,32 @@ export function FileBrowser({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
await uploadFilesWithUppy({
files: currentFiles,
taskId: data.taskId!,
teamId: teamId!,
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
createdAssets: data.createdAssets,
presignedUrls: data.presignedUrls,
onFileFinished: async (fileId) => {
await queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
setLocalUploadingFiles((prev) => prev.filter((f) => f.id !== fileId))
},
})
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
try {
await uploadFilesWithUppy({
files: currentFiles,
taskId: data.taskId!,
teamId: teamId!,
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
createdAssets: data.createdAssets,
presignedUrls: data.presignedUrls,
onFileFinished: async (fileId) => {
await queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
setLocalUploadingFiles((prev) => prev.filter((f) => f.id !== fileId))
},
})
} finally {
if (batchIds) {
setLocalUploadingFiles((prev) => prev.filter((f) => !batchIds!.has(f.id!)))
}
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
}
},
})
@@ -0,0 +1,172 @@
// @vitest-environment happy-dom
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { UploadTasks } from './upload-tasks'
import { useUploadStore } from '@/ui/stores/upload'
import * as uploaderLib from '@/ui/lib/uploader'
import { toast } from 'sonner'
const mockGetTasks = vi.fn()
const mockCancelTask = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
upload: {
tasks: Object.assign(
{
$get: () => mockGetTasks(),
},
{
':taskId': {
cancel: {
$post: (args: unknown) => mockCancelTask(args),
},
},
},
),
},
},
},
},
},
}))
vi.mock('@/ui/hooks/use-team-id', () => ({
useTeamId: () => 'team-1',
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
describe('UploadTasks', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.clearAllMocks()
queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
useUploadStore.setState({
uploading: 0,
tasks: {},
fileProgress: {},
})
})
afterEach(() => {
cleanup()
})
it('renders completed and failed tasks without a cancel button', async () => {
mockGetTasks.mockResolvedValue({
ok: true,
json: async () => ({
data: [
{
id: 'task-done',
name: 'Completed Task',
total: 2,
uploaded: 2,
status: 'completed',
createdAt: new Date().toISOString(),
},
{
id: 'task-failed',
name: 'Failed Task',
total: 2,
uploaded: 1,
status: 'failed',
createdAt: new Date().toISOString(),
},
],
pageInfo: {},
}),
})
render(
<QueryClientProvider client={queryClient}>
<UploadTasks />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('Completed Task')).toBeDefined()
expect(screen.getByText('Failed Task')).toBeDefined()
})
// No cancel button should be rendered for completed or failed tasks
expect(screen.queryByRole('button', { name: /cancel/i })).toBeNull()
})
it('renders cancel button for running tasks and executes cancel flow on confirmation', async () => {
const cancelActiveSpy = vi.spyOn(uploaderLib, 'cancelActiveUploadTask')
mockGetTasks.mockResolvedValue({
ok: true,
json: async () => ({
data: [
{
id: 'task-running',
name: 'Running Task',
total: 3,
uploaded: 1,
status: 'uploading',
createdAt: new Date().toISOString(),
},
],
pageInfo: {},
}),
})
mockCancelTask.mockResolvedValue({
ok: true,
json: async () => ({ success: true }),
})
render(
<QueryClientProvider client={queryClient}>
<UploadTasks />
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('Running Task')).toBeDefined()
})
// Cancel button should be present
const cancelButton = screen.getByRole('button', { name: /cancel/i })
expect(cancelButton).toBeDefined()
// Click Cancel to open confirmation dialog
fireEvent.click(cancelButton)
await waitFor(() => {
expect(screen.getByText(/cancel upload task\?/i)).toBeDefined()
})
// Click confirm in the dialog
const confirmButtons = screen.getAllByRole('button', { name: /cancel upload/i })
fireEvent.click(confirmButtons[confirmButtons.length - 1])
await waitFor(() => {
expect(cancelActiveSpy).toHaveBeenCalledWith('task-running')
expect(mockCancelTask).toHaveBeenCalledWith(
expect.objectContaining({
param: { teamId: 'team-1', taskId: 'task-running' },
}),
)
expect(toast.success).toHaveBeenCalled()
})
})
})
+119 -17
View File
@@ -1,13 +1,26 @@
import { client } from '@/ui/api/client'
import type { TaskInfo } from '@shumai/dtos'
import { useTeamId } from '@/ui/hooks/use-team-id'
import { useInfiniteQuery } from '@tanstack/react-query'
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useUploadStore } from '@/ui/stores/upload'
import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react'
import { useEffect, useMemo } from 'react'
import { cancelActiveUploadTask } from '@/ui/lib/uploader'
import { Loader2, CheckCircle2, Clock, UploadCloud, AlertCircle } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { format, parseISO, isToday, isYesterday } from 'date-fns'
import { Progress } from '@/ui/components/ui/progress'
import { Button } from '@/ui/components/ui/button'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { toast } from 'sonner'
import { formatTimeAgo } from '@/ui/lib/time'
import { m } from '@/ui/paraglide/messages.js'
@@ -33,20 +46,29 @@ function formatBytes(bytes: number): string {
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}
function UploadTaskItem({ task }: { task: TaskInfo }) {
function UploadTaskItem({ task, teamId }: { task: TaskInfo; teamId?: string }) {
const [isCancelConfirmOpen, setIsCancelConfirmOpen] = useState(false)
const clientProgress = useUploadStore((state) => state.tasks[task.id])
const cancelTaskInStore = useUploadStore((state) => state.cancelTask)
const queryClient = useQueryClient()
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
const isFailed = task.status === 'failed'
const isDone = task.status === 'completed' || isCompleted
const isRunning = !isDone && !isFailed
const percent = isDone
? 100
: clientProgress
? clientProgress.total > 0
? (clientProgress.loaded / clientProgress.total) * 100
: 0
: task.total > 0
? (task.uploaded / task.total) * 100
: 0
let formattedTime: string
try {
@@ -55,6 +77,37 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
formattedTime = m.unknown()
}
const { mutate: cancelMutation, isPending: isCanceling } = useMutation({
mutationFn: async () => {
cancelActiveUploadTask(task.id)
cancelTaskInStore(task.id)
if (teamId) {
const res = await client.api.teams[':teamId'].upload.tasks[':taskId'].cancel.$post({
param: { teamId, taskId: task.id },
})
if (!res.ok) {
throw new Error('Failed to cancel upload task')
}
return await res.json()
}
},
onSuccess: () => {
setIsCancelConfirmOpen(false)
toast.success(m.upload_task_canceled())
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'upload', 'tasks'],
})
queryClient.invalidateQueries({
queryKey: ['search', teamId],
})
},
onError: (err) => {
console.error('Failed to cancel upload task:', err)
toast.error(m.failed_to_cancel_upload_task())
},
})
return (
<div className="group relative flex flex-col p-4 rounded-xl border border-sidebar-border bg-sidebar-accent/30 text-sidebar-foreground shadow-xs transition-all duration-200 hover:shadow-md hover:border-sidebar-foreground/20 hover:bg-sidebar-accent/50">
{/* Top row: Name & Status Badge */}
@@ -68,11 +121,16 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
</span>
</div>
<div className="flex-shrink-0">
{isCompleted ? (
{isDone ? (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-muted-foreground bg-muted px-2 py-0.5 rounded-full transition-colors">
<CheckCircle2 className="w-3.5 h-3.5" />
{m.done()}
</span>
) : isFailed ? (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-destructive bg-destructive/10 px-2 py-0.5 rounded-full">
<AlertCircle className="w-3.5 h-3.5" />
{m.status_failed()}
</span>
) : (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-sidebar-primary bg-sidebar-primary/10 px-2 py-0.5 rounded-full animate-pulse">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
@@ -88,7 +146,7 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
<span>{formattedTime}</span>
</div>
{/* Bottom row: Progress Bar and Fraction */}
{/* Bottom row: Progress Bar, Fraction & Cancel Button */}
<div className="space-y-1.5 mt-auto">
<div className="flex items-center justify-between text-xs font-semibold">
<span className="text-muted-foreground/80">
@@ -96,12 +154,56 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
? `${formatBytes(clientProgress.loaded)} / ${formatBytes(clientProgress.total)} (${m.files_progress({ uploaded: task.uploaded, total: task.total })})`
: m.files_progress({ uploaded: task.uploaded, total: task.total })}
</span>
{!isCompleted && (
<span className="text-sidebar-primary font-mono font-bold">{Math.round(percent)}%</span>
)}
<div className="flex items-center gap-2">
{!isDone && !isFailed && (
<span className="text-sidebar-primary font-mono font-bold">
{Math.round(percent)}%
</span>
)}
{isRunning && (
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs font-medium text-muted-foreground hover:text-destructive hover:bg-destructive/10"
disabled={isCanceling}
onClick={(e) => {
e.stopPropagation()
setIsCancelConfirmOpen(true)
}}
>
{isCanceling ? <Loader2 className="w-3 h-3 animate-spin mr-1" /> : null}
{m.cancel()}
</Button>
)}
</div>
</div>
<Progress value={percent} className="h-1.5 w-full bg-muted" />
</div>
<AlertDialog open={isCancelConfirmOpen} onOpenChange={setIsCancelConfirmOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{m.cancel_upload_task_confirm_title()}</AlertDialogTitle>
<AlertDialogDescription>
{m.cancel_upload_task_confirm_description()}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isCanceling}>{m.cancel()}</AlertDialogCancel>
<AlertDialogAction
disabled={isCanceling}
onClick={(e) => {
e.preventDefault()
cancelMutation()
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isCanceling ? <Loader2 className="w-4 h-4 animate-spin mr-1" /> : null}
{m.cancel_upload_task()}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
@@ -218,7 +320,7 @@ export function UploadTasks() {
{/* Tasks in Day */}
<div className="mt-3 space-y-3">
{group.tasks.map((task) => (
<UploadTaskItem key={task.id} task={task} />
<UploadTaskItem key={task.id} task={task} teamId={teamId} />
))}
</div>
</div>