From ec42c4e9ffb9c5f70b9bb87f97332411c6f72800 Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 11 Jun 2026 11:44:26 +0800 Subject: [PATCH 1/5] feat(file): add bulk download links API and frontend batch download dialog --- packages/api/src/api/file.test.ts | 81 +++++++++ packages/api/src/api/file.ts | 63 +++++++ packages/core/src/asset/asset.test.ts | 157 ++++++++++++++++++ packages/core/src/asset/asset.ts | 140 ++++++++++++++++ packages/dtos/src/asset.ts | 17 ++ .../components/file-browser/file-browser.tsx | 90 +++++++++- .../file-browser/use-file-actions.ts | 84 +++++++++- packages/webui/components/members-dialog.tsx | 26 +-- 8 files changed, 639 insertions(+), 19 deletions(-) diff --git a/packages/api/src/api/file.test.ts b/packages/api/src/api/file.test.ts index c2f5968b..66ec2efb 100644 --- a/packages/api/src/api/file.test.ts +++ b/packages/api/src/api/file.test.ts @@ -36,6 +36,7 @@ vi.mock('@shumai/core/src/authz/authz', () => ({ ResourceType: { Asset: 'asset', Team: 'team', + Project: 'project', }, })) @@ -452,4 +453,84 @@ describe('file api', () => { beforeIndex: 'index-1', }) }) + + it('POST /files/download-links generates links if assets belong to the same project', async () => { + const mockFindMany = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([ + { + id: 'asset1', + projectId: 'project-id-1', + type: 'file', + targetId: null, + }, + { + id: 'asset2', + projectId: 'project-id-1', + type: 'folder', + targetId: null, + }, + // Mocking only the required subset of Prisma Asset properties for the test + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ] as any) + + const mockGetDownloadLinks = vi.spyOn(assetService, 'getDownloadLinks').mockResolvedValue([ + { id: 'file1', name: 'file1.txt', url: 'http://link1' }, + { id: 'file2', name: 'file2.txt', url: 'http://link2' }, + ]) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/download-links', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset1', 'asset2'] }), + }) + + expect(res.status).toBe(200) + const json = await res.json() + expect(json.files).toHaveLength(2) + expect(json.files[0].name).toBe('file1.txt') + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user1', name: 'Test User' }, + permission: Permission.Read, + type: 'project', + id: 'project-id-1', + }) + + expect(assetService.getDownloadLinks).toHaveBeenCalledWith(['asset1', 'asset2']) + + mockFindMany.mockRestore() + mockGetDownloadLinks.mockRestore() + }) + + it('POST /files/download-links rejects if assets belong to different projects', async () => { + const mockFindMany = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([ + { + id: 'asset1', + projectId: 'project-id-1', + type: 'file', + targetId: null, + }, + { + id: 'asset2', + projectId: 'project-id-2', + type: 'file', + targetId: null, + }, + // Mocking only the required subset of Prisma Asset properties for the test + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ] as any) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/download-links', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset1', 'asset2'] }), + }) + + expect(res.status).toBe(400) + const json = await res.json() + expect(json.error).toBe('All selected items must belong to the same project') + + mockFindMany.mockRestore() + }) }) diff --git a/packages/api/src/api/file.ts b/packages/api/src/api/file.ts index b7c7b00c..63f151ca 100644 --- a/packages/api/src/api/file.ts +++ b/packages/api/src/api/file.ts @@ -15,6 +15,7 @@ import { updateAssetOrderRequestSchema, updateFileRequestSchema, uploadFileRequestSchema, + getDownloadLinksRequestSchema, } from '@shumai/dtos' import { transcodeService } from '@shumai/transcode/src/transcode' import fs from 'fs' @@ -264,5 +265,67 @@ const route = new Hono<{ Variables: { user: User } }>() return c.json({ key }) }) + .post('/files/download-links', zValidator('json', getDownloadLinksRequestSchema), async (c) => { + const user = c.get('user') + const req = c.req.valid('json') + + if (req.ids.length === 0) { + return c.json({ files: [] }) + } + + // 1. Fetch input assets to verify project grouping + const assets = await prisma.asset.findMany({ + where: { id: { in: req.ids }, isDeleted: false }, + select: { + id: true, + projectId: true, + type: true, + targetId: true, + target: { select: { projectId: true } }, + }, + }) + + if (assets.length === 0) { + return c.json({ files: [] }) + } + + const projectIds = new Set() + for (const asset of assets) { + let projId = asset.projectId + if (asset.type === 'symlink' && asset.target?.projectId) { + projId = asset.target.projectId + } + if (projId) { + projectIds.add(projId) + } + } + + // 2. Validate same-project constraint + if (projectIds.size !== 1) { + return c.json({ error: 'All selected items must belong to the same project' }, 400) + } + + const projectId = Array.from(projectIds)[0] + + // 3. Verify user has READ permission on this project + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Project, + id: projectId, + }) + + // 4. Resolve starting IDs (dereference top-level symlinks) + const startingIds = assets.map((asset) => { + if (asset.type === 'symlink' && asset.targetId) { + return asset.targetId + } + return asset.id + }) + + // 5. Generate download links + const files = await assetService.getDownloadLinks(startingIds) + return c.json({ files }) + }) export default route diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 75e977d4..5a820b09 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -1647,4 +1647,161 @@ describe('AssetService — natural sort by name', () => { expect(result.data.map((a) => a.name)).toEqual(['apple', 'apricot', 'banana', 'cherry']) }) + + describe('getDownloadLinks', () => { + it('resolves folders, version stacks, and symlinks to correct latest files and urls', async () => { + const user = await prisma.user.create({ + data: { + name: 'DownloadUser', + email: `download-${Date.now()}@example.com`, + }, + }) + const team = await prisma.team.create({ data: { name: 'DownloadTeam' } }) + const project = await prisma.project.create({ + data: { name: 'DownloadProject', teamId: team.id }, + }) + + // Create folder structure: + // - rootFolder (folder) + // - file1.txt (file) + // - subFolder (folder) + // - file2.txt (file) + // - stack (version_stack) + // - version1.txt (file, sortIndex = 'a1') + // - version2.txt (file, sortIndex = 'a0') -> latest + // - symlinkToFile (symlink -> file1.txt) + // - symlinkToStack (symlink -> stack) + + const rootFolder = await prisma.asset.create({ + data: { + name: 'rootFolder', + type: AssetType.folder, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + const file1 = await prisma.asset.create({ + data: { + name: 'file1.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + storageKey: { create: { key: 'keys/file1' } }, + }, + }) + + const subFolder = await prisma.asset.create({ + data: { + name: 'subFolder', + type: AssetType.folder, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + await prisma.asset.create({ + data: { + name: 'file2.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: subFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + storageKey: { create: { key: 'keys/file2' } }, + }, + }) + + const stack = await prisma.asset.create({ + data: { + name: 'stack', + type: AssetType.version_stack, + project: { connect: { id: project.id } }, + parent: { connect: { id: subFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + await prisma.asset.create({ + data: { + name: 'version1.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: stack.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + sortIndex: 'a1', + storageKey: { create: { key: 'keys/v1' } }, + }, + }) + + await prisma.asset.create({ + data: { + name: 'version2.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: stack.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + sortIndex: 'a0', // smaller sortIndex means latest + storageKey: { create: { key: 'keys/v2' } }, + }, + }) + + await prisma.asset.create({ + data: { + name: 'symlinkToFile', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: file1.id } }, + }, + }) + + await prisma.asset.create({ + data: { + name: 'symlinkToStack', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: stack.id } }, + }, + }) + + // Run download links request on rootFolder + const result = await assetService.getDownloadLinks([rootFolder.id]) + + // We expect: + // 1. file1.txt + // 2. file2.txt + // 3. version2.txt (latest version of the stack) + // 4. file1.txt (from symlinkToFile target resolution, deduplicated) + // 5. version2.txt (from symlinkToStack target resolution, deduplicated) + + const fileNames = result.map((r) => r.name) + expect(fileNames).toHaveLength(3) // 3 unique files + expect(fileNames).toContain('file1.txt') + expect(fileNames).toContain('file2.txt') + expect(fileNames).toContain('version2.txt') + expect(fileNames).not.toContain('version1.txt') // older version should not be downloaded + expect(fileNames).not.toContain('rootFolder') + expect(fileNames).not.toContain('subFolder') + expect(fileNames).not.toContain('stack') + + // Check urls are returned correctly (mock s3 presign resolves to 'http://mock-s3-url') + for (const item of result) { + expect(item.url).toBe('http://mock-s3-url') + } + }) + }) }) diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index b28b50a6..6bf85adf 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -1649,6 +1649,146 @@ export class AssetService { ) } + async getDownloadLinks( + startingIds: string[], + ): Promise> { + if (startingIds.length === 0) return [] + + const descendants = await this.prismaClient.$queryRaw< + Array<{ + id: string + name: string + type: string + parentId: string | null + storageKeyId: string | null + sortIndex: string | null + targetId: string | null + }> + >` + WITH RECURSIVE descendant AS ( + SELECT id, name, type, parent_id, storage_key_id, sort_index, target_id, is_deleted + FROM assets + WHERE id IN (${Prisma.join(startingIds)}) AND is_deleted = false + UNION ALL + SELECT a.id, a.name, a.type, a.parent_id, a.storage_key_id, a.sort_index, a.target_id, a.is_deleted + FROM assets a + INNER JOIN descendant d ON a.parent_id = d.id + WHERE a.is_deleted = false + ) + SELECT id, name, type, parent_id AS "parentId", storage_key_id AS "storageKeyId", sort_index AS "sortIndex", target_id AS "targetId" FROM descendant; + ` + + // Find any symlink in the descendants and resolve its target. + const symlinks = descendants.filter((d) => d.type === 'symlink') + let resolvedTargets: Array<{ + id: string + name: string + type: string + parentId: string | null + storageKeyId: string | null + sortIndex: string | null + targetId: string | null + }> = [] + + if (symlinks.length > 0) { + const targetIds = symlinks.map((s) => s.targetId).filter((id): id is string => !!id) + if (targetIds.length > 0) { + const dbTargets = await this.prismaClient.asset.findMany({ + where: { id: { in: targetIds }, isDeleted: false }, + }) + resolvedTargets = dbTargets.map((t) => ({ + id: t.id, + name: t.name, + type: t.type, + parentId: t.parentId, + storageKeyId: t.storageKeyId, + sortIndex: t.sortIndex, + targetId: t.targetId, + })) + } + } + + const allAssets = [...descendants.filter((d) => d.type !== 'symlink'), ...resolvedTargets] + + const nonFolderAssets = allAssets.filter( + (a) => + a.type !== 'folder' && a.type !== 'root' && a.type !== 'share_root' && a.type !== 'share', + ) + + // Separate version stacks and other files + const versionStackIds = new Set( + nonFolderAssets.filter((a) => a.type === 'version_stack').map((a) => a.id), + ) + + const versionAssetsByStack = new Map() + const otherAssets: typeof nonFolderAssets = [] + + for (const asset of nonFolderAssets) { + if (asset.type === 'version_stack') { + continue + } + if (asset.parentId && versionStackIds.has(asset.parentId)) { + const list = versionAssetsByStack.get(asset.parentId) || [] + list.push(asset) + versionAssetsByStack.set(asset.parentId, list) + } else { + otherAssets.push(asset) + } + } + + // Pick the latest version for each version stack (ascending sortIndex: 'asc' means first version is latest) + const latestVersions: typeof nonFolderAssets = [] + for (const versions of versionAssetsByStack.values()) { + versions.sort((x, y) => { + if (!x.sortIndex || !y.sortIndex) return 0 + return x.sortIndex < y.sortIndex ? -1 : x.sortIndex > y.sortIndex ? 1 : 0 + }) + if (versions.length > 0) { + latestVersions.push(versions[0]) + } + } + + const finalFiles = [...otherAssets, ...latestVersions] + + // Deduplicate files by id + const uniqueFilesMap = new Map() + for (const file of finalFiles) { + uniqueFilesMap.set(file.id, file) + } + const deduplicatedFiles = Array.from(uniqueFilesMap.values()) + + // Fetch storage keys + const storageKeyIds = deduplicatedFiles + .map((f) => f.storageKeyId) + .filter((id): id is string => !!id) + const storageKeys = await this.prismaClient.storageKey.findMany({ + where: { id: { in: storageKeyIds } }, + }) + const storageKeyMap = new Map(storageKeys.map((k) => [k.id, k.key])) + + const downloadLinks = await Promise.all( + deduplicatedFiles.map(async (file) => { + const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null + if (!key) return null + + const url = await s3Service.presign( + process.env.S3_BUCKET || 'shumai', + key, + 'GET', + file.name, + ) + + return { + id: file.id, + name: file.name, + url, + } + }), + ) + + return downloadLinks.filter((link): link is { id: string; name: string; url: string } => !!link) + } + private async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise { if (!asset.media) return null diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 1b81ec2d..4855fbbb 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -294,3 +294,20 @@ export const postAttachmentResponseSchema = z.object({ uploadUrl: z.string(), }) export type PostAttachmentResponse = z.infer + +export const getDownloadLinksRequestSchema = z.object({ + ids: z.array(z.string()), +}) +export type GetDownloadLinksRequest = z.infer + +export const downloadLinkItemSchema = z.object({ + id: z.string(), + name: z.string(), + url: z.string(), +}) +export type DownloadLinkItem = z.infer + +export const getDownloadLinksResponseSchema = z.object({ + files: z.array(downloadLinkItemSchema), +}) +export type GetDownloadLinksResponse = z.infer diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index a11c1fd1..fd5a77ef 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -13,7 +13,7 @@ import { useFieldStore } from '@/ui/stores/fields' import { useUploadStore } from '@/ui/stores/upload' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' -import { Download } from 'lucide-react' +import { Download, AlertTriangle, Loader2 } from 'lucide-react' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { toast } from 'sonner' import type { DragState } from '../dnd-types' @@ -30,6 +30,15 @@ import { AlertDialogHeader, AlertDialogTitle, } from '../ui/alert-dialog' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '../ui/dialog' +import { Progress } from '../ui/progress' import { Button } from '../ui/button' import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu' import { FileCard } from './file-card' @@ -327,6 +336,12 @@ export function FileBrowser({ isDeleteDialogOpen, setIsDeleteDialogOpen, confirmDelete, + isDownloadDialogOpen, + setIsDownloadDialogOpen, + itemsToDownload, + isDownloading, + downloadProgress, + startDownload, } = useFileActions({ teamId, projectId, @@ -1007,6 +1022,79 @@ export function FileBrowser({ + + + + + {isDownloading ? 'Downloading Files' : 'Prepare Download'} + + {isDownloading + ? 'Please wait while we queue your downloads. Do not close this dialog.' + : 'Selected files and folders will be prepared for download.'} + + + + {!isDownloading ? ( +
+
+ You have selected{' '} + {itemsToDownload.length}{' '} + item(s). +
+
+ +
+

No Folder Structure

+

+ Folder hierarchy will be flattened. All nested files will be downloaded directly + into your default download folder. +

+
+
+
+ ) : ( +
+
+ + + {downloadProgress.total === 0 + ? 'Preparing download links...' + : `Downloading file ${downloadProgress.current} of ${downloadProgress.total}...`} + +
+ {downloadProgress.total > 0 && ( +
+ +

+ Current file: {downloadProgress.currentName} +

+
+ )} +
+ )} + + + {!isDownloading ? ( + <> + + + + ) : ( + + )} + +
+
) } diff --git a/packages/webui/components/file-browser/use-file-actions.ts b/packages/webui/components/file-browser/use-file-actions.ts index 24f26dcb..3b45c4c3 100644 --- a/packages/webui/components/file-browser/use-file-actions.ts +++ b/packages/webui/components/file-browser/use-file-actions.ts @@ -5,6 +5,7 @@ import type { AssetInfo } from '@shumai/dtos' import { useMutation, useQueryClient } from '@tanstack/react-query' import type { InferRequestType, InferResponseType } from 'hono/client' import { useState } from 'react' +import { toast } from 'sonner' interface UseFileActionsProps { teamId: string @@ -26,6 +27,14 @@ export function useFileActions({ const [editingItemId, setEditingItemId] = useState(null) const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [itemsToDelete, setItemsToDelete] = useState([]) + const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false) + const [itemsToDownload, setItemsToDownload] = useState([]) + const [isDownloading, setIsDownloading] = useState(false) + const [downloadProgress, setDownloadProgress] = useState<{ + current: number + total: number + currentName: string + }>({ current: 0, total: 0, currentName: '' }) const queryClient = useQueryClient() const $createFolder = client.api.folders.$post @@ -111,6 +120,19 @@ export function useFileActions({ }, }) + const $getDownloadLinks = client.api.files['download-links'].$post + const { mutateAsync: getDownloadLinks } = useMutation< + InferResponseType, + Error, + InferRequestType + >({ + mutationFn: async (request) => { + const res = await $getDownloadLinks(request) + if (!res.ok) throw new Error('Failed to get download links') + return (await res.json()) as unknown as InferResponseType + }, + }) + const handleRename = (item: AssetInfo) => { setEditingItemId(item.id!) } @@ -186,11 +208,57 @@ export function useFileActions({ } const handleDownload = (items: AssetInfo[]) => { - alert( - `Download functionality - Would download ${ - items.length - } item(s): ${items.map((i) => i.name).join(', ')}`, - ) + if (items.length === 0) return + setItemsToDownload(items) + setDownloadProgress({ current: 0, total: 0, currentName: '' }) + setIsDownloadDialogOpen(true) + } + + const startDownload = async () => { + setIsDownloading(true) + try { + const res = await getDownloadLinks({ + json: { ids: itemsToDownload.map((i) => i.id!) }, + }) + const files = res.files + + const chunkSize = 5 + const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + + for (let i = 0; i < files.length; i += chunkSize) { + const chunk = files.slice(i, i + chunkSize) + + // Trigger downloads for this batch in parallel by creating/clicking links + for (const file of chunk) { + const absoluteIndex = i + chunk.indexOf(file) + 1 + setDownloadProgress({ + current: absoluteIndex, + total: files.length, + currentName: file.name, + }) + + const a = document.createElement('a') + a.href = file.url + a.download = file.name + a.target = '_blank' + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + } + + // If we have more chunks to process, wait 1 second before triggering the next batch + if (i + chunkSize < files.length) { + await delay(1000) + } + } + toast.success('Downloads started successfully') + } catch (error) { + toast.error('Download failed') + console.error(error) + } finally { + setIsDownloading(false) + setIsDownloadDialogOpen(false) + } } const handleNewFolder = (name: string) => { @@ -283,5 +351,11 @@ export function useFileActions({ setIsDeleteDialogOpen, itemsToDelete, confirmDelete, + isDownloadDialogOpen, + setIsDownloadDialogOpen, + itemsToDownload, + isDownloading, + downloadProgress, + startDownload, } } diff --git a/packages/webui/components/members-dialog.tsx b/packages/webui/components/members-dialog.tsx index 1c7fffa0..73bbcffa 100644 --- a/packages/webui/components/members-dialog.tsx +++ b/packages/webui/components/members-dialog.tsx @@ -1,22 +1,22 @@ import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar' import { Button } from '@/ui/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog' import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuTrigger, + DropdownMenu, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Input } from '@/ui/components/ui/input' import { ChevronDown, Copy, Loader2, Trash2 } from 'lucide-react' From 5d928ce2b79a6600b01f4ab91b254b2b3350e19f Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 11 Jun 2026 12:08:35 +0800 Subject: [PATCH 2/5] feat(ui): update download dialog flow to instantly resolve links and trigger concurrent downloads --- .../components/file-browser/file-browser.tsx | 61 ++++++-------- .../file-browser/use-file-actions.ts | 80 +++++++------------ 2 files changed, 51 insertions(+), 90 deletions(-) diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index fd5a77ef..a1f74655 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -38,7 +38,6 @@ import { DialogHeader, DialogTitle, } from '../ui/dialog' -import { Progress } from '../ui/progress' import { Button } from '../ui/button' import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu' import { FileCard } from './file-card' @@ -338,9 +337,8 @@ export function FileBrowser({ confirmDelete, isDownloadDialogOpen, setIsDownloadDialogOpen, - itemsToDownload, - isDownloading, - downloadProgress, + isLoadingLinks, + resolvedFiles, startDownload, } = useFileActions({ teamId, @@ -1026,20 +1024,27 @@ export function FileBrowser({ - {isDownloading ? 'Downloading Files' : 'Prepare Download'} + {isLoadingLinks ? 'Preparing Download' : 'Confirm Download'} - {isDownloading - ? 'Please wait while we queue your downloads. Do not close this dialog.' + {isLoadingLinks + ? 'Resolving all files and folders. Please wait...' : 'Selected files and folders will be prepared for download.'} - {!isDownloading ? ( + {isLoadingLinks ? ( +
+ + + Preparing download links... + +
+ ) : (
- You have selected{' '} - {itemsToDownload.length}{' '} - item(s). + This download will include{' '} + {resolvedFiles.length}{' '} + file(s).
@@ -1052,44 +1057,26 @@ export function FileBrowser({
- ) : ( -
-
- - - {downloadProgress.total === 0 - ? 'Preparing download links...' - : `Downloading file ${downloadProgress.current} of ${downloadProgress.total}...`} - -
- {downloadProgress.total > 0 && ( -
- -

- Current file: {downloadProgress.currentName} -

-
- )} -
)} - {!isDownloading ? ( + {!isLoadingLinks ? ( <> - ) : ( - )} diff --git a/packages/webui/components/file-browser/use-file-actions.ts b/packages/webui/components/file-browser/use-file-actions.ts index 3b45c4c3..8e02dfbb 100644 --- a/packages/webui/components/file-browser/use-file-actions.ts +++ b/packages/webui/components/file-browser/use-file-actions.ts @@ -28,13 +28,10 @@ export function useFileActions({ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [itemsToDelete, setItemsToDelete] = useState([]) const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false) - const [itemsToDownload, setItemsToDownload] = useState([]) - const [isDownloading, setIsDownloading] = useState(false) - const [downloadProgress, setDownloadProgress] = useState<{ - current: number - total: number - currentName: string - }>({ current: 0, total: 0, currentName: '' }) + const [isLoadingLinks, setIsLoadingLinks] = useState(false) + const [resolvedFiles, setResolvedFiles] = useState< + Array<{ id: string; name: string; url: string }> + >([]) const queryClient = useQueryClient() const $createFolder = client.api.folders.$post @@ -207,60 +204,38 @@ export function useFileActions({ } } - const handleDownload = (items: AssetInfo[]) => { + const handleDownload = async (items: AssetInfo[]) => { if (items.length === 0) return - setItemsToDownload(items) - setDownloadProgress({ current: 0, total: 0, currentName: '' }) setIsDownloadDialogOpen(true) - } - - const startDownload = async () => { - setIsDownloading(true) + setIsLoadingLinks(true) + setResolvedFiles([]) try { const res = await getDownloadLinks({ - json: { ids: itemsToDownload.map((i) => i.id!) }, + json: { ids: items.map((i) => i.id!) }, }) - const files = res.files - - const chunkSize = 5 - const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) - - for (let i = 0; i < files.length; i += chunkSize) { - const chunk = files.slice(i, i + chunkSize) - - // Trigger downloads for this batch in parallel by creating/clicking links - for (const file of chunk) { - const absoluteIndex = i + chunk.indexOf(file) + 1 - setDownloadProgress({ - current: absoluteIndex, - total: files.length, - currentName: file.name, - }) - - const a = document.createElement('a') - a.href = file.url - a.download = file.name - a.target = '_blank' - document.body.appendChild(a) - a.click() - document.body.removeChild(a) - } - - // If we have more chunks to process, wait 1 second before triggering the next batch - if (i + chunkSize < files.length) { - await delay(1000) - } - } - toast.success('Downloads started successfully') + setResolvedFiles(res.files) } catch (error) { - toast.error('Download failed') + toast.error('Failed to prepare download links') + setIsDownloadDialogOpen(false) console.error(error) } finally { - setIsDownloading(false) - setIsDownloadDialogOpen(false) + setIsLoadingLinks(false) } } + const startDownload = () => { + for (const file of resolvedFiles) { + const a = document.createElement('a') + a.href = file.url + a.download = file.name + a.target = '_blank' + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + } + setIsDownloadDialogOpen(false) + } + const handleNewFolder = (name: string) => { createFolder( { json: { name, parentId: assetId } }, @@ -353,9 +328,8 @@ export function useFileActions({ confirmDelete, isDownloadDialogOpen, setIsDownloadDialogOpen, - itemsToDownload, - isDownloading, - downloadProgress, + isLoadingLinks, + resolvedFiles, startDownload, } } From f30d68c0a2f22edaea9f07173b53b738a2df24ba Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 11 Jun 2026 12:17:00 +0800 Subject: [PATCH 3/5] feat(ui): implement staggered background queue downloader for bulk files --- .../file-browser/use-file-actions.ts | 46 +++++++++++++++---- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/packages/webui/components/file-browser/use-file-actions.ts b/packages/webui/components/file-browser/use-file-actions.ts index 8e02dfbb..53d91261 100644 --- a/packages/webui/components/file-browser/use-file-actions.ts +++ b/packages/webui/components/file-browser/use-file-actions.ts @@ -224,16 +224,44 @@ export function useFileActions({ } const startDownload = () => { - for (const file of resolvedFiles) { - const a = document.createElement('a') - a.href = file.url - a.download = file.name - a.target = '_blank' - document.body.appendChild(a) - a.click() - document.body.removeChild(a) - } + const files = [...resolvedFiles] setIsDownloadDialogOpen(false) + + if (files.length === 0) return + + toast.info( + `Starting download of ${files.length} files. Please allow multiple downloads if prompted by your browser.`, + { + duration: 5000, + }, + ) + + const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + + const runQueue = async () => { + const batchSize = 5 + for (let i = 0; i < files.length; i += batchSize) { + const chunk = files.slice(i, i + batchSize) + for (const file of chunk) { + const a = document.createElement('a') + a.href = file.url + a.download = file.name + a.target = '_blank' + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + } + if (i + batchSize < files.length) { + await delay(600) + } + } + toast.success('All downloads initiated successfully') + } + + runQueue().catch((err) => { + console.error('Background downloads failed:', err) + toast.error('Some downloads could not be started') + }) } const handleNewFolder = (name: string) => { From aed06760321cc8048d0c6e673f885557028b05f9 Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 11 Jun 2026 13:06:01 +0800 Subject: [PATCH 4/5] refactor(api): extract db query from download-links endpoint to service method --- packages/api/src/api/file.test.ts | 48 ++++++++------------------- packages/api/src/api/file.ts | 40 ++++------------------ packages/core/src/asset/asset.test.ts | 47 ++++++++++++++++++++++++++ packages/core/src/asset/asset.ts | 44 ++++++++++++++++++++++++ 4 files changed, 111 insertions(+), 68 deletions(-) diff --git a/packages/api/src/api/file.test.ts b/packages/api/src/api/file.test.ts index 66ec2efb..063ea2bb 100644 --- a/packages/api/src/api/file.test.ts +++ b/packages/api/src/api/file.test.ts @@ -455,22 +455,12 @@ describe('file api', () => { }) it('POST /files/download-links generates links if assets belong to the same project', async () => { - const mockFindMany = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([ - { - id: 'asset1', - projectId: 'project-id-1', - type: 'file', - targetId: null, - }, - { - id: 'asset2', - projectId: 'project-id-1', - type: 'folder', - targetId: null, - }, - // Mocking only the required subset of Prisma Asset properties for the test - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ] as any) + const mockGetProjectIdsAndStartingIds = vi + .spyOn(assetService, 'getProjectIdsAndStartingIds') + .mockResolvedValue({ + projectIds: ['project-id-1'], + startingIds: ['asset1', 'asset2'], + }) const mockGetDownloadLinks = vi.spyOn(assetService, 'getDownloadLinks').mockResolvedValue([ { id: 'file1', name: 'file1.txt', url: 'http://link1' }, @@ -498,27 +488,17 @@ describe('file api', () => { expect(assetService.getDownloadLinks).toHaveBeenCalledWith(['asset1', 'asset2']) - mockFindMany.mockRestore() + mockGetProjectIdsAndStartingIds.mockRestore() mockGetDownloadLinks.mockRestore() }) it('POST /files/download-links rejects if assets belong to different projects', async () => { - const mockFindMany = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([ - { - id: 'asset1', - projectId: 'project-id-1', - type: 'file', - targetId: null, - }, - { - id: 'asset2', - projectId: 'project-id-2', - type: 'file', - targetId: null, - }, - // Mocking only the required subset of Prisma Asset properties for the test - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ] as any) + const mockGetProjectIdsAndStartingIds = vi + .spyOn(assetService, 'getProjectIdsAndStartingIds') + .mockResolvedValue({ + projectIds: ['project-id-1', 'project-id-2'], + startingIds: ['asset1', 'asset2'], + }) const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const res = await app.request('/files/download-links', { @@ -531,6 +511,6 @@ describe('file api', () => { const json = await res.json() expect(json.error).toBe('All selected items must belong to the same project') - mockFindMany.mockRestore() + mockGetProjectIdsAndStartingIds.mockRestore() }) }) diff --git a/packages/api/src/api/file.ts b/packages/api/src/api/file.ts index 63f151ca..2f91201a 100644 --- a/packages/api/src/api/file.ts +++ b/packages/api/src/api/file.ts @@ -273,39 +273,19 @@ const route = new Hono<{ Variables: { user: User } }>() return c.json({ files: [] }) } - // 1. Fetch input assets to verify project grouping - const assets = await prisma.asset.findMany({ - where: { id: { in: req.ids }, isDeleted: false }, - select: { - id: true, - projectId: true, - type: true, - targetId: true, - target: { select: { projectId: true } }, - }, - }) + // 1. Fetch project IDs and starting IDs from the service layer + const { projectIds, startingIds } = await assetService.getProjectIdsAndStartingIds(req.ids) - if (assets.length === 0) { + if (startingIds.length === 0) { return c.json({ files: [] }) } - const projectIds = new Set() - for (const asset of assets) { - let projId = asset.projectId - if (asset.type === 'symlink' && asset.target?.projectId) { - projId = asset.target.projectId - } - if (projId) { - projectIds.add(projId) - } - } - // 2. Validate same-project constraint - if (projectIds.size !== 1) { + if (projectIds.length !== 1) { return c.json({ error: 'All selected items must belong to the same project' }, 400) } - const projectId = Array.from(projectIds)[0] + const projectId = projectIds[0] // 3. Verify user has READ permission on this project await authzService.hasPermission({ @@ -315,15 +295,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: projectId, }) - // 4. Resolve starting IDs (dereference top-level symlinks) - const startingIds = assets.map((asset) => { - if (asset.type === 'symlink' && asset.targetId) { - return asset.targetId - } - return asset.id - }) - - // 5. Generate download links + // 4. Generate download links const files = await assetService.getDownloadLinks(startingIds) return c.json({ files }) }) diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 5a820b09..1dc54e66 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -1804,4 +1804,51 @@ describe('AssetService — natural sort by name', () => { } }) }) + + describe('getProjectIdsAndStartingIds', () => { + it('returns empty lists for empty inputs', async () => { + const result = await assetService.getProjectIdsAndStartingIds([]) + expect(result.projectIds).toEqual([]) + expect(result.startingIds).toEqual([]) + }) + + it('resolves project IDs and starting IDs, including symlinks', async () => { + const team = await prisma.team.create({ data: { name: 'Test Team' } }) + const project = await prisma.project.create({ + data: { name: 'Test Project', teamId: team.id }, + }) + const user = await prisma.user.create({ + data: { name: 'Test User', email: `test-${Date.now()}@example.com` }, + }) + + const file1 = await prisma.asset.create({ + data: { + name: 'file1.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + const symlink = await prisma.asset.create({ + data: { + name: 'symlink', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: file1.id } }, + }, + }) + + const result = await assetService.getProjectIdsAndStartingIds([file1.id, symlink.id]) + expect(result.projectIds).toContain(project.id) + expect(result.projectIds).toHaveLength(1) + expect(result.startingIds).toHaveLength(2) + // Since it's a symlink, its starting ID should be resolved to the target file1.id + expect(result.startingIds[0]).toBe(file1.id) + expect(result.startingIds[1]).toBe(file1.id) + }) + }) }) diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index 6bf85adf..36e930d2 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -1649,6 +1649,50 @@ export class AssetService { ) } + async getProjectIdsAndStartingIds(assetIds: string[]): Promise<{ + projectIds: string[] + startingIds: string[] + }> { + if (assetIds.length === 0) { + return { projectIds: [], startingIds: [] } + } + + const assets = await this.prismaClient.asset.findMany({ + where: { id: { in: assetIds }, isDeleted: false }, + select: { + id: true, + projectId: true, + type: true, + targetId: true, + target: { select: { projectId: true } }, + }, + }) + + const projectIds = new Set() + const startingIds: string[] = [] + + for (const asset of assets) { + let projId = asset.projectId + if (asset.type === 'symlink' && asset.target?.projectId) { + projId = asset.target.projectId + } + if (projId) { + projectIds.add(projId) + } + + if (asset.type === 'symlink' && asset.targetId) { + startingIds.push(asset.targetId) + } else { + startingIds.push(asset.id) + } + } + + return { + projectIds: Array.from(projectIds), + startingIds, + } + } + async getDownloadLinks( startingIds: string[], ): Promise> { From c910f22542606cf488710c33b5b758cdbd0bdff8 Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 11 Jun 2026 13:08:29 +0800 Subject: [PATCH 5/5] refactor(core): move starting symlink resolution to getDownloadLinks and simplify getProjectIds --- packages/api/src/api/file.test.ts | 22 ++++------- packages/api/src/api/file.ts | 8 ++-- packages/core/src/asset/asset.test.ts | 56 +++++++++++++++++++++------ packages/core/src/asset/asset.ts | 45 ++++++++++----------- 4 files changed, 79 insertions(+), 52 deletions(-) diff --git a/packages/api/src/api/file.test.ts b/packages/api/src/api/file.test.ts index 063ea2bb..0251020b 100644 --- a/packages/api/src/api/file.test.ts +++ b/packages/api/src/api/file.test.ts @@ -455,12 +455,9 @@ describe('file api', () => { }) it('POST /files/download-links generates links if assets belong to the same project', async () => { - const mockGetProjectIdsAndStartingIds = vi - .spyOn(assetService, 'getProjectIdsAndStartingIds') - .mockResolvedValue({ - projectIds: ['project-id-1'], - startingIds: ['asset1', 'asset2'], - }) + const mockGetProjectIds = vi + .spyOn(assetService, 'getProjectIds') + .mockResolvedValue(['project-id-1']) const mockGetDownloadLinks = vi.spyOn(assetService, 'getDownloadLinks').mockResolvedValue([ { id: 'file1', name: 'file1.txt', url: 'http://link1' }, @@ -488,17 +485,14 @@ describe('file api', () => { expect(assetService.getDownloadLinks).toHaveBeenCalledWith(['asset1', 'asset2']) - mockGetProjectIdsAndStartingIds.mockRestore() + mockGetProjectIds.mockRestore() mockGetDownloadLinks.mockRestore() }) it('POST /files/download-links rejects if assets belong to different projects', async () => { - const mockGetProjectIdsAndStartingIds = vi - .spyOn(assetService, 'getProjectIdsAndStartingIds') - .mockResolvedValue({ - projectIds: ['project-id-1', 'project-id-2'], - startingIds: ['asset1', 'asset2'], - }) + const mockGetProjectIds = vi + .spyOn(assetService, 'getProjectIds') + .mockResolvedValue(['project-id-1', 'project-id-2']) const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const res = await app.request('/files/download-links', { @@ -511,6 +505,6 @@ describe('file api', () => { const json = await res.json() expect(json.error).toBe('All selected items must belong to the same project') - mockGetProjectIdsAndStartingIds.mockRestore() + mockGetProjectIds.mockRestore() }) }) diff --git a/packages/api/src/api/file.ts b/packages/api/src/api/file.ts index 2f91201a..e73cf8a8 100644 --- a/packages/api/src/api/file.ts +++ b/packages/api/src/api/file.ts @@ -273,10 +273,10 @@ const route = new Hono<{ Variables: { user: User } }>() return c.json({ files: [] }) } - // 1. Fetch project IDs and starting IDs from the service layer - const { projectIds, startingIds } = await assetService.getProjectIdsAndStartingIds(req.ids) + // 1. Fetch project IDs from the service layer + const projectIds = await assetService.getProjectIds(req.ids) - if (startingIds.length === 0) { + if (projectIds.length === 0) { return c.json({ files: [] }) } @@ -296,7 +296,7 @@ const route = new Hono<{ Variables: { user: User } }>() }) // 4. Generate download links - const files = await assetService.getDownloadLinks(startingIds) + const files = await assetService.getDownloadLinks(req.ids) return c.json({ files }) }) diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 1dc54e66..76299020 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -1803,16 +1803,52 @@ describe('AssetService — natural sort by name', () => { expect(item.url).toBe('http://mock-s3-url') } }) + + it('resolves top-level symlinks to their targets when passed as direct starting IDs', async () => { + const team = await prisma.team.create({ data: { name: 'Test Team' } }) + const project = await prisma.project.create({ + data: { name: 'Test Project', teamId: team.id }, + }) + const user = await prisma.user.create({ + data: { name: 'Test User', email: `test-${Date.now()}@example.com` }, + }) + + const file1 = await prisma.asset.create({ + data: { + name: 'file1.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + storageKey: { create: { key: 'keys/file1' } }, + }, + }) + + const symlink = await prisma.asset.create({ + data: { + name: 'symlinkToFile', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: file1.id } }, + }, + }) + + const result = await assetService.getDownloadLinks([symlink.id]) + expect(result).toHaveLength(1) + expect(result[0].name).toBe('file1.txt') + expect(result[0].id).toBe(file1.id) + }) }) - describe('getProjectIdsAndStartingIds', () => { + describe('getProjectIds', () => { it('returns empty lists for empty inputs', async () => { - const result = await assetService.getProjectIdsAndStartingIds([]) - expect(result.projectIds).toEqual([]) - expect(result.startingIds).toEqual([]) + const result = await assetService.getProjectIds([]) + expect(result).toEqual([]) }) - it('resolves project IDs and starting IDs, including symlinks', async () => { + it('resolves project IDs, including symlinks', async () => { const team = await prisma.team.create({ data: { name: 'Test Team' } }) const project = await prisma.project.create({ data: { name: 'Test Project', teamId: team.id }, @@ -1842,13 +1878,9 @@ describe('AssetService — natural sort by name', () => { }, }) - const result = await assetService.getProjectIdsAndStartingIds([file1.id, symlink.id]) - expect(result.projectIds).toContain(project.id) - expect(result.projectIds).toHaveLength(1) - expect(result.startingIds).toHaveLength(2) - // Since it's a symlink, its starting ID should be resolved to the target file1.id - expect(result.startingIds[0]).toBe(file1.id) - expect(result.startingIds[1]).toBe(file1.id) + const result = await assetService.getProjectIds([file1.id, symlink.id]) + expect(result).toContain(project.id) + expect(result).toHaveLength(1) }) }) }) diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index 36e930d2..56e55792 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -1649,28 +1649,21 @@ export class AssetService { ) } - async getProjectIdsAndStartingIds(assetIds: string[]): Promise<{ - projectIds: string[] - startingIds: string[] - }> { + async getProjectIds(assetIds: string[]): Promise { if (assetIds.length === 0) { - return { projectIds: [], startingIds: [] } + return [] } const assets = await this.prismaClient.asset.findMany({ where: { id: { in: assetIds }, isDeleted: false }, select: { - id: true, projectId: true, type: true, - targetId: true, target: { select: { projectId: true } }, }, }) const projectIds = new Set() - const startingIds: string[] = [] - for (const asset of assets) { let projId = asset.projectId if (asset.type === 'symlink' && asset.target?.projectId) { @@ -1679,23 +1672,31 @@ export class AssetService { if (projId) { projectIds.add(projId) } - - if (asset.type === 'symlink' && asset.targetId) { - startingIds.push(asset.targetId) - } else { - startingIds.push(asset.id) - } } - return { - projectIds: Array.from(projectIds), - startingIds, - } + return Array.from(projectIds) } - async getDownloadLinks( - startingIds: string[], - ): Promise> { + async getDownloadLinks(ids: string[]): Promise> { + if (ids.length === 0) return [] + + // Resolve starting IDs (dereference top-level symlinks) + const assets = await this.prismaClient.asset.findMany({ + where: { id: { in: ids }, isDeleted: false }, + select: { + id: true, + type: true, + targetId: true, + }, + }) + + const startingIds = assets.map((asset) => { + if (asset.type === 'symlink' && asset.targetId) { + return asset.targetId + } + return asset.id + }) + if (startingIds.length === 0) return [] const descendants = await this.prismaClient.$queryRaw<