A full-featured download manager.
fix(downloads): normalize windows task output paths (#2395)
Dr_rOotaebe512c5f9f
diff --git a/src/main/ipc/commands/open-task-file.test.ts b/src/main/ipc/commands/open-task-file.test.tsindex 6dce7dcf..4c3ebc5a 100644--- a/src/main/ipc/commands/open-task-file.test.ts+++ b/src/main/ipc/commands/open-task-file.test.ts@@ -10,7 +10,7 @@ const { warn } = vi.hoisted(() => ({ warn: vi.fn() }))vi.mock('@core/logger', () => ({ getLogger: () => ({ warn }) }))vi.mock('node:fs/promises', () => ({ stat: vi.fn() }))-function setup() {+function setup(platform: NodeJS.Platform = 'linux') {const task = makeDownloadTask({id: 'a',status: TaskStatus.Completed,@@ -24,7 +24,7 @@ function setup() {task,shell,getTask,- handler: createOpenTaskFileHandler({ shell, getTask }),+ handler: createOpenTaskFileHandler({ shell, getTask, platform }),}}@@ -38,6 +38,49 @@ beforeEach(() => {})describe('openTaskFile', () => {+ it.each([+ ['//nas/share//模型 文件.bin', '\\\\nas\\share\\模型 文件.bin'],+ ['\\\\nas\\share\\folder//file.bin', '\\\\nas\\share\\folder\\file.bin'],+ ['C:/downloads//file.bin', 'C:\\downloads\\file.bin'],+ ])(+ 'normalizes Windows output before stat and open: %s',+ async (stored, expected) => {+ const { handler, task, shell } = setup('win32')+ task.finalPath = stored+ await handler({ taskId: 'a' })+ expect(stat).toHaveBeenCalledExactlyOnceWith(expected)+ expect(shell.openPath).toHaveBeenCalledExactlyOnceWith(expected)+ expect(task.finalPath).toBe(stored)+ }+ )++ it('still rejects a changed stored path after normalizing Windows output', async () => {+ const { handler, task, shell } = setup('win32')+ task.finalPath = '//nas/share//file.bin'+ vi.mocked(stat).mockImplementationOnce(async () => {+ task.finalPath = '//nas/share/other.bin'+ return { isFile: () => true } as Awaited<ReturnType<typeof stat>>+ })+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({+ code: ErrorCode.TaskOpenFailed,+ })+ expect(shell.openPath).not.toHaveBeenCalled()+ })++ it.each([+ '//?/UNC/nas/share/file.bin',+ '\\\\.\\PhysicalDrive0',+ 'C:file.bin',+ ])('rejects unsafe Windows output: %s', async (output) => {+ const { handler, task, shell } = setup('win32')+ task.finalPath = output+ await expect(handler({ taskId: 'a' })).rejects.toMatchObject({+ code: ErrorCode.IpcInvalidPayload,+ })+ expect(stat).not.toHaveBeenCalled()+ expect(shell.openPath).not.toHaveBeenCalled()+ })+it('opens only the published file owned by the task, ignoring supplied paths', async () => {const { handler, shell } = setup()await handler({ taskId: 'a', path: '/some/other/file' })diff --git a/src/main/ipc/commands/open-task-file.ts b/src/main/ipc/commands/open-task-file.tsindex 801f7834..b0d9a6b3 100644--- a/src/main/ipc/commands/open-task-file.ts+++ b/src/main/ipc/commands/open-task-file.ts@@ -1,14 +1,15 @@import { stat } from 'node:fs/promises'-import path from 'node:path'import { getLogger } from '@core/logger'import { AppError, ErrorCode } from '@shared/errors'import { openTaskFilePayloadSchema } from '@shared/schemas/open-task-file'import type { DownloadTask } from '@shared/types/task'import { canOpenTaskFile } from '@shared/types/task-actions'+import { normalizeTaskOutputPath } from './task-output-path'const log = getLogger('open-task-file')interface OpenTaskFileDeps {+ platform?: NodeJS.Platformshell: { openPath: (path: string) => Promise<string> }getTask: (taskId: string) => DownloadTask | undefined}@@ -24,19 +25,11 @@ export function createOpenTaskFileHandler(deps: OpenTaskFileDeps) {throw new AppError(ErrorCode.InvalidSelection, 'Task output is not ready')// Resolve only the task-owned published path, never a renderer-supplied path.- const outputPath = task.finalPath || task.diskPath- const normalized = outputPath.replaceAll('\\', '/')- if (- outputPath.includes('\0') ||- !path.isAbsolute(outputPath) ||- ['//?/', '//./', '/??/', '//??/'].some((prefix) =>- normalized.startsWith(prefix)- )+ const storedPath = task.finalPath || task.diskPath+ const outputPath = normalizeTaskOutputPath(+ storedPath,+ deps.platform ?? process.platform)- throw new AppError(- ErrorCode.IpcInvalidPayload,- 'Invalid task output path'- )let stage: 'stat' | 'recheck' | 'open' = 'stat'try {if (!(await stat(outputPath)).isFile())@@ -47,7 +40,7 @@ export function createOpenTaskFileHandler(deps: OpenTaskFileDeps) {if (!current ||!canOpenTaskFile(current) ||- (current.finalPath || current.diskPath) !== outputPath+ (current.finalPath || current.diskPath) !== storedPath)throw new Error('Task output changed')stage = 'open'diff --git a/src/main/ipc/commands/reveal-in-folder.test.ts b/src/main/ipc/commands/reveal-in-folder.test.tsindex 3d90dd97..fbdfa047 100644--- a/src/main/ipc/commands/reveal-in-folder.test.ts+++ b/src/main/ipc/commands/reveal-in-folder.test.ts@@ -29,6 +29,7 @@ describe('revealInFolder', () => {it('reveals the current path owned by the requested task', async () => {const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'linux',shell,getTask: (taskId) =>taskId === 'task-1'@@ -49,6 +50,7 @@ describe('revealInFolder', () => {it('hides an indexed BT workspace behind its stable final path', async () => {const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'linux',shell,getTask: () => ({diskPath: '/Users/me/Downloads/.motrix/61282448e78c1fc29ac1/p',@@ -115,6 +117,7 @@ describe('revealInFolder', () => {.mockResolvedValueOnce(directoryStat)const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'win32',shell,getTask: () => ({diskPath: 'C:\\Downloads\\file.iso.motrix',@@ -163,6 +166,7 @@ describe('revealInFolder', () => {openPath: vi.fn(async () => 'OS failed to open /downloads'),}const handler = createRevealInFolderHandler({+ platform: 'linux',shell,getTask: () => ({ diskPath: '', finalPath: '/downloads/file.iso' }),})@@ -179,6 +183,7 @@ describe('revealInFolder', () => {)const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'linux',shell,getTask: () => ({ diskPath: '', finalPath: '/downloads/file.iso' }),})@@ -191,6 +196,7 @@ describe('revealInFolder', () => {it('rejects an unknown task instead of accepting a renderer path', async () => {const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'linux',shell,getTask: () => undefined,})@@ -200,20 +206,64 @@ describe('revealInFolder', () => {})it.each([- '\\\\server\\share\\downloads\\file.iso',- '//server/share/downloads/file.iso',- ])('allows a task-owned UNC path: %s', async (diskPath) => {+ [+ '\\\\server\\share\\downloads\\file.iso',+ '\\\\server\\share\\downloads\\file.iso',+ ],+ [+ '//server/share/downloads/file.iso',+ '\\\\server\\share\\downloads\\file.iso',+ ],+ [+ '//server/share/downloads//模型 文件.iso',+ '\\\\server\\share\\downloads\\模型 文件.iso',+ ],+ [+ '\\\\server\\share\\downloads//file.iso',+ '\\\\server\\share\\downloads\\file.iso',+ ],+ ['C:/downloads//file.iso', 'C:\\downloads\\file.iso'],+ ])('normalizes a task-owned Windows path: %s', async (diskPath, expected) => {const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'win32',shell,getTask: () => ({ diskPath, finalPath: '' }),})await handler({ taskId: 'task-unc' })- expect(shell.showItemInFolder).toHaveBeenCalledWith(diskPath)+ expect(stat).toHaveBeenCalledExactlyOnceWith(expected)+ expect(shell.showItemInFolder).toHaveBeenCalledExactlyOnceWith(expected)+ expect(shell.openPath).not.toHaveBeenCalled()})+ it.each([+ ['//server/share//file.iso', '\\\\server\\share\\'],+ ['//server/share/models//file.iso', '\\\\server\\share\\models'],+ ['C://file.iso', 'C:\\'],+ ])(+ 'opens the native parent of a missing Windows output: %s',+ async (finalPath, parent) => {+ statMock+ .mockRejectedValueOnce(missingPath())+ .mockResolvedValueOnce(directoryStat)+ const shell = {+ showItemInFolder: vi.fn(),+ openPath: vi.fn(async () => ''),+ }+ const handler = createRevealInFolderHandler({+ platform: 'win32',+ shell,+ getTask: () => ({ diskPath: `${finalPath}.motrix`, finalPath }),+ })+ await handler({ taskId: 'task-unc' })+ expect(statMock).toHaveBeenNthCalledWith(2, parent)+ expect(shell.openPath).toHaveBeenCalledExactlyOnceWith(parent)+ expect(shell.showItemInFolder).not.toHaveBeenCalled()+ }+ )+it.each(['\\\\?\\C:\\downloads\\file.iso','\\\\.\\PhysicalDrive0',@@ -222,6 +272,7 @@ describe('revealInFolder', () => {])('rejects a Windows device namespace: %s', async (diskPath) => {const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'win32',shell,getTask: () => ({ diskPath, finalPath: '' }),})@@ -235,6 +286,7 @@ describe('revealInFolder', () => {it('rejects a relative task path', async () => {const shell = { showItemInFolder: vi.fn(), openPath: vi.fn(async () => '') }const handler = createRevealInFolderHandler({+ platform: 'linux',shell,getTask: () => ({diskPath: '../downloads/file.iso',diff --git a/src/main/ipc/commands/reveal-in-folder.ts b/src/main/ipc/commands/reveal-in-folder.tsindex a3d3e2ae..9537f02a 100644--- a/src/main/ipc/commands/reveal-in-folder.ts+++ b/src/main/ipc/commands/reveal-in-folder.ts@@ -2,8 +2,10 @@ import { stat } from 'node:fs/promises'import path from 'node:path'import { AppError, ErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'+import { normalizeTaskOutputPath } from './task-output-path'export interface RevealInFolderDeps {+ platform?: NodeJS.Platformshell: {showItemInFolder: (path: string) => voidopenPath: (path: string) => Promise<string>@@ -15,16 +17,6 @@ export interface RevealInFolderDeps {export type RevealInFolderPayload = { taskId: string }-function isWindowsDeviceNamespace(value: string): boolean {- const normalized = value.replaceAll('\\', '/')- return (- normalized.startsWith('//?/') ||- normalized.startsWith('//./') ||- normalized.startsWith('/??/') ||- normalized.startsWith('//??/')- )-}-function resolveOutputPath(deps: RevealInFolderDeps,payload: RevealInFolderPayload@@ -52,19 +44,11 @@ function resolveOutputPath(export function createRevealInFolderHandler(deps: RevealInFolderDeps) {return async (payload: RevealInFolderPayload): Promise<void> => {- const taskPath = resolveOutputPath(deps, payload)- if (- typeof taskPath !== 'string' ||- taskPath.trim() === '' ||- taskPath.includes('\0') ||- (!path.isAbsolute(taskPath) && !path.win32.isAbsolute(taskPath)) ||- isWindowsDeviceNamespace(taskPath)- ) {- throw new AppError(- ErrorCode.IpcInvalidPayload,- 'revealInFolder: task has an invalid path'- )- }+ const platform = deps.platform ?? process.platform+ const taskPath = normalizeTaskOutputPath(+ resolveOutputPath(deps, payload),+ platform+ )try {const output = await stat(taskPath).catch(@@ -81,7 +65,7 @@ export function createRevealInFolderHandler(deps: RevealInFolderDeps) {// Incomplete outputs can still have a .motrix suffix or live in a BT// workspace. showItemInFolder silently fails for their absent final// path, so open its containing directory until the output is published.- const pathApi = path.posix.isAbsolute(taskPath) ? path.posix : path.win32+ const pathApi = platform === 'win32' ? path.win32 : path.posixconst directory = pathApi.dirname(taskPath)if (!(await stat(directory)).isDirectory()) {throw new Error('task parent is not a directory')diff --git a/src/main/ipc/commands/task-output-path.ts b/src/main/ipc/commands/task-output-path.tsnew file mode 100644index 00000000..94a8e581--- /dev/null+++ b/src/main/ipc/commands/task-output-path.ts@@ -0,0 +1,34 @@+import path from 'node:path'+import { AppError, ErrorCode } from '@shared/errors'++function isWindowsDeviceNamespace(value: string): boolean {+ const normalized = value.replaceAll('\\', '/')+ return ['//?/', '//./', '/??/', '//??/'].some((prefix) =>+ normalized.startsWith(prefix)+ )+}++/** Validate task-owned paths before passing them to the desktop shell. */+export function normalizeTaskOutputPath(+ value: string,+ platform: NodeJS.Platform+): string {+ const pathApi = platform === 'win32' ? path.win32 : path.posix+ if (+ typeof value !== 'string' ||+ value.trim() === '' ||+ value.includes('\0') ||+ !pathApi.isAbsolute(value) ||+ isWindowsDeviceNamespace(value)+ ) {+ throw new AppError(ErrorCode.IpcInvalidPayload, 'Task has an invalid path')+ }++ // aria2 can return //server/share//file when dir has a trailing separator.+ // Electron converts separator direction but keeps the repeated separators.+ const output = platform === 'win32' ? path.win32.normalize(value) : value+ if (isWindowsDeviceNamespace(output)) {+ throw new AppError(ErrorCode.IpcInvalidPayload, 'Task has an invalid path')+ }+ return output+}diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsxindex 0c69e0c5..11b66cab 100644--- a/src/renderer/routes/downloads/task-actions-menu.test.tsx+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx@@ -433,6 +433,25 @@ describe('TaskActionsMenu', () => {expect.objectContaining({ type: 'success' }))})+ it('copies a native Windows UNC path for an existing external task', async () => {+ vi.mocked(transport).platform = 'win32'+ setup(true, [+ makeDownloadTask({+ id: 'unc',+ name: 'Model',+ finalPath: '//nas/share//模型 文件.bin',+ }),+ ])+ fireEvent.contextMenu(screen.getByText('Model'))+ fireEvent.click(+ await screen.findByRole('menuitem', { name: 'Copy file path' })+ )+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledExactlyOnceWith(+ '\\\\nas\\share\\模型 文件.bin'+ )+ )+ })it('opens file selection for a magnet whose metadata is ready', async () => {setup(true, [makeDownloadTask({diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsxindex 68bde00c..32c5522a 100644--- a/src/renderer/routes/downloads/task-actions-menu.tsx+++ b/src/renderer/routes/downloads/task-actions-menu.tsx@@ -28,6 +28,7 @@ import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selectioimport { openTaskFile } from '@renderer/lib/open-task-file'import { transport } from '@renderer/lib/transport'import { CommandIds } from '@shared/commands-catalog'+import { formatNativePath } from '@shared/lib/path-display'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import { TaskStatus } from '@shared/types/task'@@ -139,7 +140,10 @@ export function TaskActionsMenu({() => taskMenuShortcuts(macOS, __MOTRIX_TARGET__ === 'electron'),[macOS])- const taskPath = single?.finalPath || single?.diskPath+ const taskPath = formatNativePath(+ single?.finalPath || single?.diskPath || '',+ transport.platform+ )const runAction = async (action: () => Promise<unknown>,failureTitle: stringdiff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsxindex 719af336..a785ac18 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx@@ -3,6 +3,7 @@ import '@renderer/lib/i18n'import { getInspectorSnapHeights } from '@renderer/components/desktop-kit/inspector-drawer'import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'+import { transport } from '@renderer/lib/transport'import { DownloadErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'@@ -413,6 +414,32 @@ describe('TaskInspectorDrawer', () => {).not.toBeInTheDocument()})+ it('displays and copies a native Windows UNC path without changing the task', async () => {+ const platform = vi+ .spyOn(transport, 'platform', 'get')+ .mockReturnValue('win32')+ try {+ const user = userEvent.setup()+ const clipboard = vi.spyOn(navigator.clipboard, 'writeText')+ const selection = createSelectionStore<DownloadTask>((task) => task.id)+ const storedPath = '//nas/share//模型 文件.bin'+ const nativePath = '\\\\nas\\share\\模型 文件.bin'+ const tasks = [fake({ finalPath: storedPath, diskPath: storedPath })]+ selection.getState().setItems(tasks)+ selection.getState().select('a')+ render(<TestHarness selection={selection} tasks={tasks} />)++ expect(screen.getByTitle(nativePath)).toBeInTheDocument()+ expect(screen.queryByTitle(storedPath)).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Copy file path' }))+ expect(clipboard).toHaveBeenCalledExactlyOnceWith(nativePath)+ expect(tasks[0].finalPath).toBe(storedPath)+ clipboard.mockRestore()+ } finally {+ platform.mockRestore()+ }+ })+it('does not switch inspector content during marquee preview', () => {const selection = createSelectionStore<DownloadTask>((t) => t.id)const tasks = [diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex 750be5e9..bc22ac93 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -28,6 +28,7 @@ import {import { LegacyFreshDownload } from '@renderer/features/legacy-import/legacy-fresh-download'import { createTaskInspectorActivitySnapshotCache } from '@renderer/hooks/use-task-inspector-activity'import { transport } from '@renderer/lib/transport'+import { formatNativePath } from '@shared/lib/path-display'import { Commands } from '@shared/protocol/commands'import type { DownloadTask } from '@shared/types/task'import { TaskType } from '@shared/types/task'@@ -70,6 +71,10 @@ export function TaskInspectorDrawer({const snap = useDownloadsView((s) => s.inspectorSnap)const setSnap = useDownloadsView((s) => s.setInspectorSnap)const single = selected.length === 1 ? selected[0] : null+ const taskPath = formatNativePath(+ single?.finalPath || single?.diskPath || '',+ transport.platform+ )const isBt = single?.type === TaskType.Bt || single?.type === TaskType.Magnetconst showPieces = single !== null && canInspectPieces(single)const subtab = useDownloadsView((s) => s.inspectorTab)@@ -155,15 +160,16 @@ export function TaskInspectorDrawer({><DiskIcon className="me-1 size-3.5 shrink-0 text-muted-foreground" /><MiddleEllipsis- text={single.finalPath || single.diskPath}+ text={taskPath}maxChars={64}className="font-sans!"/></Button><CopyButtonvariant="ghost"+ aria-label={t('panel.downloads.action.copyPath')}className="ms-1 h-4.5 w-4.5 shrink-0 rounded-md p-0 has-[>svg]:px-0 [&_svg:not([class*='size-'])]:size-3"- content={single.finalPath || single.diskPath}+ content={taskPath}/></div>)}diff --git a/src/shared/lib/path-display.test.ts b/src/shared/lib/path-display.test.tsindex 52977b28..9e7482eb 100644--- a/src/shared/lib/path-display.test.ts+++ b/src/shared/lib/path-display.test.ts@@ -1,5 +1,29 @@import { describe, expect, it } from 'vitest'-import { truncatePath } from './path-display'+import { formatNativePath, truncatePath } from './path-display'++describe('formatNativePath', () => {+ it.each([+ ['//nas/share//模型 文件.bin', '\\\\nas\\share\\模型 文件.bin'],+ ['\\\\nas\\share\\folder//file.bin', '\\\\nas\\share\\folder\\file.bin'],+ ['C:/downloads//file.bin', 'C:\\downloads\\file.bin'],+ ['C:/', 'C:\\'],+ ['///downloads//file.bin', '\\downloads\\file.bin'],+ ['', ''],+ ])(+ 'formats Windows separators without losing the root: %s',+ (value, expected) => {+ expect(formatNativePath(value, 'win32')).toBe(expected)+ }+ )++ it.each(['darwin', 'linux', 'web'])(+ 'preserves paths on %s, including literal backslashes',+ (platform) => {+ const value = '/downloads/a\\b//file.bin'+ expect(formatNativePath(value, platform)).toBe(value)+ }+ )+})const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })const length = (value: string) => [...segmenter.segment(value)].lengthdiff --git a/src/shared/lib/path-display.ts b/src/shared/lib/path-display.tsindex 25d2fa59..d53d1043 100644--- a/src/shared/lib/path-display.ts+++ b/src/shared/lib/path-display.ts@@ -3,6 +3,15 @@ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })const isSeparator = (character: string) =>character === '/' || character === '\\'+/** Format local Windows paths for display/copy; never infer the server OS. */+export function formatNativePath(path: string, platform: string): string {+ if (platform !== 'win32') return path+ const windowsPath = path.replaceAll('/', '\\')+ // Keep the UNC prefix while collapsing repeated separators inside the path.+ const prefix = /^\\\\[^\\]/.test(windowsPath) ? '\\' : ''+ return prefix + windowsPath.replace(/\\+/g, '\\')+}+/** Display-only fragments; maxChars includes the single-character ellipsis. */export function getPathDisplayParts(path: string, maxChars: number) {if (!Number.isSafeInteger(maxChars) || maxChars < 0)