From 07f73e8b845743aa72f5c53ce6a81d3e67049ff2 Mon Sep 17 00:00:00 2001 From: Jin Zy <2956232209@qq.com> Date: Tue, 20 Oct 2026 19:25:07 +0800 Subject: [PATCH] =?UTF-8?q?fix(task):=20=E6=96=87=E4=BB=B6=E5=A4=8D?= =?UTF-8?q?=E5=88=B6/=E7=A7=BB=E5=8A=A8=E8=BF=9B=E5=BA=A6=E6=8C=89?= =?UTF-8?q?=E5=A2=9E=E9=87=8F=E7=B4=AF=E5=8A=A0=EF=BC=8C=E9=81=BF=E5=85=8D?= =?UTF-8?q?=E8=BF=9B=E5=BA=A6=E6=9D=A1=E5=80=92=E9=80=80=E4=B8=8E=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=95=B0=E5=B0=91=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象:复制含多个同级子目录的目录,或一次粘贴多个项目时,任务进度会 往回跳,完成消息里的文件数远少于实际值。用真实 taskManager 端到端跑: 复制 1 个含 5 个子目录、共 200 个文件的目录,完成消息为「处理了 40 个 文件」,进度在涨到 20% 后又回退到 1%;多选 1 个文件 + 2 个目录 (共 7 个文件)时消息为「处理了 3 个文件」。目标目录里的文件是完整的, 出错的只是上报的进度与文件数(测试中已断言目标目录文件数正确)。 根因:updateProgress(addedSize, addedFiles) 按增量累加,文件分支传的 确实是增量(updateProgress(stats.size, 1));但目录分支把 copyDirectoryWithProgress 上报的「当前目录内累计量」减去全局 processedSize,而该累计量在每个子目录、每个源路径都会从 0 重新计数, 相减得到负数,已处理量被退回到最后一个子目录的数值。只有单个扁平 目录时两者恰好对齐,所以此前没有暴露。 修复:copyDirectoryWithProgress 改为每复制一个文件上报 (stats.size, 1),与文件分支的既有约定一致;moveDirectoryWithProgress 的重命名分支本就一次性上报该目录总量,作为增量同样成立(EXDEV 分支 复用前者)。目录分支直接把 updateProgress 传入,删除两处减法。 影响范围:仅任务进度百分比、N/M 计数与完成消息中的文件数;复制/移动 结果、冲突策略与失败处理均未改动,统计口径也未改变。 测试:新增 server/src/__tests__/file-operation-progress.test.ts, 用临时目录构造真实文件树端到端跑任务,断言进度单调不减、完成消息 文件数正确、目标目录文件数正确;覆盖同级子目录、文件+目录混合、 多目录移动与扁平目录回归。修复前 3/4 失败,修复后 4/4 通过;server 全量 17 suites / 130 tests 通过,npm run build 通过。 --- .../__tests__/file-operation-progress.test.ts | 186 ++++++++++++++++++ .../src/modules/task/fileOperationWorker.ts | 16 +- 2 files changed, 193 insertions(+), 9 deletions(-) create mode 100644 server/src/__tests__/file-operation-progress.test.ts diff --git a/server/src/__tests__/file-operation-progress.test.ts b/server/src/__tests__/file-operation-progress.test.ts new file mode 100644 index 00000000..b956bac5 --- /dev/null +++ b/server/src/__tests__/file-operation-progress.test.ts @@ -0,0 +1,186 @@ +import fs from 'fs' +import os from 'os' +import path from 'path' + +// taskManager 依赖 uuid v14(纯 ESM),Jest 的 CJS 运行时无法直接加载,这里用轻量假实现替换 +jest.mock('../modules/task/taskManager.js', () => { + const tasks = new Map() + const taskManager = { + __updates: [] as any[], + createTask: (type: string, data: any) => { + const id = 'test-task' + tasks.set(id, { id, type, status: 'pending', progress: 0, message: '任务已创建', data }) + return id + }, + updateTask: (id: string, updates: any) => { + const task = tasks.get(id) + if (!task) return + Object.assign(task, updates) + taskManager.__updates.push({ progress: task.progress, message: task.message, status: task.status }) + }, + getTask: (id: string) => tasks.get(id) + } + return { taskManager } +}) + +import { taskManager } from '../modules/task/taskManager.js' +import { executeFileOperation } from '../modules/task/fileOperationWorker.js' + +interface TaskUpdate { + progress: number + message: string + status: string +} + +function getUpdates(): TaskUpdate[] { + return (taskManager as any).__updates +} + +function resetUpdates() { + ;(taskManager as any).__updates.length = 0 +} + +function getFinishedUpdate(): TaskUpdate { + const updates = getUpdates() + return updates[updates.length - 1] +} + +// 进度条只应前进:任一时刻的百分比都不得小于上一次上报值 +function expectMonotonicProgress() { + const percentages = getUpdates().map((item) => item.progress) + for (let i = 1; i < percentages.length; i++) { + expect(percentages[i]).toBeGreaterThanOrEqual(percentages[i - 1]) + } +} + +function writeFileWithSize(filePath: string, size: number) { + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + fs.writeFileSync(filePath, Buffer.alloc(size, 'a')) +} + +// 递归统计目录下的文件数,用于确认「复制结果本身正确,只是上报数字错误」 +function countFiles(dirPath: string): number { + let count = 0 + for (const item of fs.readdirSync(dirPath, { withFileTypes: true })) { + const itemPath = path.join(dirPath, item.name) + if (item.isDirectory()) { + count += countFiles(itemPath) + } else { + count++ + } + } + return count +} + +describe('文件复制/移动任务的进度统计', () => { + let workDir: string + + beforeEach(() => { + resetUpdates() + workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsm-file-op-')) + }) + + afterEach(() => { + fs.rmSync(workDir, { recursive: true, force: true }) + }) + + it('复制含多个同级子目录的目录:进度不倒退,完成消息文件数正确', async () => { + const sourceDir = path.join(workDir, 'source') + const targetDir = path.join(workDir, 'target') + // 两个同级子目录,各 2 个 10 字节文件(合计 4 个文件 / 40 字节) + writeFileWithSize(path.join(sourceDir, 'alpha', 'a1.txt'), 10) + writeFileWithSize(path.join(sourceDir, 'alpha', 'a2.txt'), 10) + writeFileWithSize(path.join(sourceDir, 'beta', 'b1.txt'), 10) + writeFileWithSize(path.join(sourceDir, 'beta', 'b2.txt'), 10) + fs.mkdirSync(targetDir, { recursive: true }) + + const taskId = taskManager.createTask('copy', { + sourcePaths: [sourceDir], + targetPath: targetDir, + operation: 'copy', + conflictStrategy: 'replace' + }) + await executeFileOperation(taskId) + + // 复制结果本身完全正确(4 个文件都在目标目录),出错的只是上报的进度与文件数 + expect(countFiles(path.join(targetDir, 'source'))).toBe(4) + expectMonotonicProgress() + + const finished = getFinishedUpdate() + expect(finished.status).toBe('completed') + expect(finished.progress).toBe(100) + expect(finished.message).toContain('4 个文件') + }) + + it('同时复制一个文件和一个目录:进度不倒退,完成消息文件数正确', async () => { + const looseFile = path.join(workDir, 'loose.txt') + const sourceDir = path.join(workDir, 'source') + const targetDir = path.join(workDir, 'target') + writeFileWithSize(looseFile, 100) + writeFileWithSize(path.join(sourceDir, 'c1.txt'), 10) + writeFileWithSize(path.join(sourceDir, 'c2.txt'), 10) + fs.mkdirSync(targetDir, { recursive: true }) + + const taskId = taskManager.createTask('copy', { + sourcePaths: [looseFile, sourceDir], + targetPath: targetDir, + operation: 'copy', + conflictStrategy: 'replace' + }) + await executeFileOperation(taskId) + + expectMonotonicProgress() + + const finished = getFinishedUpdate() + expect(finished.status).toBe('completed') + expect(finished.progress).toBe(100) + expect(finished.message).toContain('3 个文件') + }) + + it('同时移动多个目录:进度不倒退,完成消息文件数正确', async () => { + const firstDir = path.join(workDir, 'first') + const secondDir = path.join(workDir, 'second') + const targetDir = path.join(workDir, 'target') + writeFileWithSize(path.join(firstDir, 'f1.txt'), 10) + writeFileWithSize(path.join(secondDir, 's1.txt'), 10) + fs.mkdirSync(targetDir, { recursive: true }) + + const taskId = taskManager.createTask('move', { + sourcePaths: [firstDir, secondDir], + targetPath: targetDir, + operation: 'move', + conflictStrategy: 'replace' + }) + await executeFileOperation(taskId) + + expectMonotonicProgress() + + const finished = getFinishedUpdate() + expect(finished.status).toBe('completed') + expect(finished.message).toContain('2 个文件') + }) + + it('复制不含子目录的目录:进度与文件数保持正确', async () => { + const sourceDir = path.join(workDir, 'source') + const targetDir = path.join(workDir, 'target') + writeFileWithSize(path.join(sourceDir, 'a.txt'), 10) + writeFileWithSize(path.join(sourceDir, 'b.txt'), 10) + writeFileWithSize(path.join(sourceDir, 'c.txt'), 10) + fs.mkdirSync(targetDir, { recursive: true }) + + const taskId = taskManager.createTask('copy', { + sourcePaths: [sourceDir], + targetPath: targetDir, + operation: 'copy', + conflictStrategy: 'replace' + }) + await executeFileOperation(taskId) + + expectMonotonicProgress() + + const finished = getFinishedUpdate() + expect(finished.status).toBe('completed') + expect(finished.progress).toBe(100) + expect(finished.message).toContain('3 个文件') + }) +}) diff --git a/server/src/modules/task/fileOperationWorker.ts b/server/src/modules/task/fileOperationWorker.ts index b8265065..b5610e59 100644 --- a/server/src/modules/task/fileOperationWorker.ts +++ b/server/src/modules/task/fileOperationWorker.ts @@ -43,11 +43,12 @@ async function calculateDirectoryStats(dirPath: string): Promise<{ totalSize: nu } // 递归复制目录 +// onProgress 上报的是「本次新增」的处理量,由调用方累加 async function copyDirectoryWithProgress( src: string, dest: string, taskId: string, - onProgress: (copiedSize: number, copiedFiles: number) => void + onProgress: (addedSize: number, addedFiles: number) => void ): Promise<{ copiedSize: number; copiedFiles: number }> { let copiedSize = 0 let copiedFiles = 0 @@ -70,7 +71,7 @@ async function copyDirectoryWithProgress( await fs.copyFile(srcPath, destPath) copiedSize += stats.size copiedFiles++ - onProgress(copiedSize, copiedFiles) + onProgress(stats.size, 1) } } catch (error) { console.error(`复制文件失败: ${srcPath}`, error) @@ -82,11 +83,12 @@ async function copyDirectoryWithProgress( } // 递归移动目录 +// onProgress 上报的是「本次新增」的处理量,由调用方累加 async function moveDirectoryWithProgress( src: string, dest: string, taskId: string, - onProgress: (movedSize: number, movedFiles: number) => void + onProgress: (addedSize: number, addedFiles: number) => void ): Promise<{ movedSize: number; movedFiles: number }> { // 先尝试直接重命名 try { @@ -225,13 +227,9 @@ export async function executeFileOperation(taskId: string) { updateProgress(stats.size, 1) } else if (stats.isDirectory()) { if (operation === 'copy') { - await copyDirectoryWithProgress(sourcePath, targetFilePath, taskId, (size, files) => { - updateProgress(size - processedSize, files - processedFiles) - }) + await copyDirectoryWithProgress(sourcePath, targetFilePath, taskId, updateProgress) } else { - await moveDirectoryWithProgress(sourcePath, targetFilePath, taskId, (size, files) => { - updateProgress(size - processedSize, files - processedFiles) - }) + await moveDirectoryWithProgress(sourcePath, targetFilePath, taskId, updateProgress) } } } catch (error) {