Skip to content

A full-featured download manager.

feat(downloads): add task re-download (#2363)

Dr_rOotf9098cd82b0d
diff --git a/.github/pr-assets/task-redownload-worker-fallback.png b/.github/pr-assets/task-redownload-worker-fallback.png
new file mode 100644
index 00000000..9861d69f
Binary files /dev/null and b/.github/pr-assets/task-redownload-worker-fallback.png differ
diff --git a/docs/plugin-hook-runtime.md b/docs/plugin-hook-runtime.md
index 580a19da..cc9743cb 100644
--- a/docs/plugin-hook-runtime.md
+++ b/docs/plugin-hook-runtime.md
@@ -144,6 +144,14 @@ context or an uncommitted effect from a failed plugin.
`enrich` and `audit` failures are isolated and the chain continues. An `audit`
plugin cannot produce mutating effects.
+Activation failures use the same isolation policy as Hook invocation failures,
+and an open circuit breaker skips activation entirely. The built-in filename
+template's `beforeFinalize` Hook is optional: its `pre-resolve` role controls
+ordering, but a worker startup failure, crash, timeout, or Hook error discards
+its effects and preserves the previously accepted target name. Finalization
+continues with the ordinary path validation and collision handling. Required
+resolver and post-processing Hooks retain their abort-on-failure policy.
+
### 5.3 Terminal task and post-Hook sequence
```text
diff --git a/docs/plugin-hook-runtime.zh-CN.md b/docs/plugin-hook-runtime.zh-CN.md
index 827ec87a..f2b92edd 100644
--- a/docs/plugin-hook-runtime.zh-CN.md
+++ b/docs/plugin-hook-runtime.zh-CN.md
@@ -133,6 +133,12 @@ Inactive -> Activating -> Active -> Quiescing -> Inactive
`pre-resolve`、`resolve` 和 `post-process` 失败会中止链;`enrich` 与
`audit` 失败会被隔离,链继续执行。`audit` 插件不能产生变更效果。
+激活失败与 Hook 调用失败遵循相同的隔离策略;熔断器打开时直接跳过激活。
+内置文件名模板的 `beforeFinalize` Hook 是可选步骤:`pre-resolve` 角色用于
+控制执行顺序,Worker 启动失败、崩溃、超时或 Hook 报错时,会丢弃该插件的
+效果并保留此前接受的目标文件名。收尾继续执行原有的路径校验和重名处理。
+必要的解析与后处理 Hook 仍在失败时中止链。
+
### 5.3 任务终态与 post-Hook 顺序
```text
diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts
index cc4ba92c..b7718085 100644
--- a/e2e/global-setup.ts
+++ b/e2e/global-setup.ts
@@ -11,6 +11,7 @@ const ROOT = process.cwd()
const REQUIRED_ARTIFACTS = [
'dist/main/index.cjs',
'dist/preload/preload.cjs',
+ 'dist/core/plugin/host/quick-js-worker.cjs',
'dist/renderer/index.html',
]
diff --git a/scripts/dev.mjs b/scripts/dev.mjs
index 015e305f..88b31c31 100644
--- a/scripts/dev.mjs
+++ b/scripts/dev.mjs
@@ -3,11 +3,11 @@
//
// Responsibilities:
// 1. Start Vite's dev server for the renderer at a fixed port.
-// 2. Run `vite build --watch` for the main and preload configs.
-// 3. Once BOTH main and preload have produced their initial bundle,
+// 2. Run `vite build --watch` for the main, preload, and plugin worker configs.
+// 3. Once all three have produced their initial bundle,
// spawn Electron with VITE_DEV_SERVER_URL pointing at the dev
// server so the main process routes the main window to Vite.
-// 4. On subsequent main/preload rebuilds, relaunch Electron so the
+// 4. On subsequent main/preload/worker rebuilds, relaunch Electron so the
// new bundle takes effect. Renderer-side hot reloads are handled
// by Vite's built-in HMR — no restart needed.
//
@@ -33,6 +33,7 @@ const ELECTRON_SHUTDOWN_TIMEOUT_MS = 45_000
const DEV_SHUTDOWN_MESSAGE = 'motrix:dev-shutdown'
let electronProcess = null
+let initialBuildComplete = false
let shuttingDown = false
let intentionalKill = false
let restartTimer = null
@@ -103,7 +104,7 @@ function watchBuild(configName, name, onFirst, onRebuild) {
}
function startElectron() {
- if (electronProcess || shuttingDown) return
+ if (electronProcess || shuttingDown || !initialBuildComplete) return
electronProcess = spawn(electronBinary, ['.'], {
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
cwd: projectRoot,
@@ -215,7 +216,17 @@ async function main() {
).catch(reject)
})
- await Promise.all([mainReady, preloadReady])
+ const workerReady = new Promise((resolve, reject) => {
+ watchBuild(
+ 'vite.worker.config.ts',
+ 'worker',
+ resolve,
+ scheduleRestart
+ ).catch(reject)
+ })
+
+ await Promise.all([mainReady, preloadReady, workerReady])
+ initialBuildComplete = true
log('initial build complete — launching electron')
startElectron()
}
diff --git a/src/core/plugin/hooks/hook-orchestrator.test.ts b/src/core/plugin/hooks/hook-orchestrator.test.ts
index b13d6f18..e29e9a5f 100644
--- a/src/core/plugin/hooks/hook-orchestrator.test.ts
+++ b/src/core/plugin/hooks/hook-orchestrator.test.ts
@@ -330,6 +330,116 @@ describe('HookOrchestrator', () => {
expect(invokeHook).toHaveBeenCalledOnce()
})
+ describe('demand activation failure isolation', () => {
+ it.each([
+ ['beforeCreate', 'enrich', 'optional.enrich', false],
+ ['beforeCreate', 'audit', 'optional.audit', false],
+ ['beforeCreate', 'resolve', 'required.resolve', true],
+ ['beforeCreate', 'pre-resolve', 'motrix.filename-template', true],
+ ['beforeFinalize', 'enrich', 'optional.enrich', false],
+ ['beforeFinalize', 'pre-resolve', 'motrix.filename-template', false],
+ ['beforeFinalize', 'pre-resolve', 'required.prepare', true],
+ ['beforeFinalize', 'post-process', 'required.merge', true],
+ ] as const)(
+ '%s handles %s activation failure for %s (abort=%s)',
+ async (hook, role, id, aborts) => {
+ const plugins: FixturePlugin[] = [
+ { id, role, hooks: [hook] },
+ { id: 'z.healthy', role: 'audit', hooks: [hook] },
+ ]
+ const { host, extras } = makeMockHost(plugins)
+ const healthy = host.allActive().filter((entry) => entry.id !== id)
+ vi.spyOn(host, 'allActive').mockReturnValue(healthy)
+ const activateForHook = vi.fn(async (pluginId: string) => {
+ if (pluginId === id) throw new Error('worker unavailable')
+ })
+ const breaker: CircuitBreaker = {
+ success: vi.fn(),
+ failure: vi.fn(),
+ isOpen: vi.fn(() => false),
+ }
+ const orch = new HookOrchestrator({
+ host,
+ activationDispatcher: {
+ candidatesForHook: () =>
+ plugins.map((plugin) => ({
+ id: plugin.id,
+ role: plugin.role,
+ manifest: makeManifest(plugin),
+ generation: 1,
+ executableDigest: 'a'.repeat(64),
+ })),
+ activateForHook,
+ },
+ breaker,
+ hookTimeoutMs: TIMEOUTS,
+ ...ORCH_OPTS_BASE,
+ })
+
+ const result =
+ hook === 'beforeCreate'
+ ? await orch.runBeforeCreateHttp(makeBeforeCreateDto(), 'task-1')
+ : await orch.runBeforeFinalize(makeBeforeFinalizeDto(), 'task-1')
+
+ expect(Boolean(result.aborted)).toBe(aborts)
+ expect(breaker.failure).toHaveBeenCalledWith(id, hook)
+ expect(extras.invocations).toEqual(
+ aborts ? [] : [{ pluginId: 'z.healthy', hook }]
+ )
+ if (!result.aborted && hook === 'beforeFinalize') {
+ expect(result.final).toMatchObject(makeBeforeFinalizeDto())
+ expect(result.staged.allMetadataOps()).toEqual([])
+ expect(result.staged.hasPolicyChecks).toBe(false)
+ }
+
+ vi.mocked(breaker.isOpen).mockImplementation(
+ (pluginId) => pluginId === id
+ )
+ activateForHook.mockClear()
+ if (hook === 'beforeCreate') {
+ await orch.runBeforeCreateHttp(makeBeforeCreateDto(), 'task-2')
+ } else {
+ await orch.runBeforeFinalize(makeBeforeFinalizeDto(), 'task-2')
+ }
+ expect(activateForHook).not.toHaveBeenCalledWith(id, hook)
+ }
+ )
+
+ it.each(['afterComplete', 'onError'] as const)(
+ '%s continues other plugins when one worker cannot start',
+ async (hook) => {
+ const plugins: FixturePlugin[] = [
+ { id: 'broken', role: 'audit', hooks: [hook] },
+ { id: 'healthy', role: 'audit', hooks: [hook] },
+ ]
+ const { host, extras } = makeMockHost(plugins)
+ const orch = new HookOrchestrator({
+ host,
+ activationDispatcher: {
+ candidatesForHook: () =>
+ plugins.map((plugin) => ({
+ id: plugin.id,
+ role: plugin.role,
+ manifest: makeManifest(plugin),
+ generation: 1,
+ executableDigest: 'a'.repeat(64),
+ })),
+ activateForHook: async (id) => {
+ if (id === 'broken') throw new Error('worker unavailable')
+ },
+ },
+ hookTimeoutMs: TIMEOUTS,
+ ...ORCH_OPTS_BASE,
+ })
+
+ await expect(
+ orch.runParallel(hook, {} as never, 'task-1')
+ ).resolves.toBeUndefined()
+ expect(extras.invocations).toEqual([{ pluginId: 'healthy', hook }])
+ }
+ )
+ })
+
describe('runBeforeCreateHttp — happy path', () => {
let host: PluginHost
let bridges: Map<string, MockBridge>
@@ -813,6 +923,66 @@ describe('HookOrchestrator', () => {
expect(result.reason).toContain('resolve crash')
})
+ it.each(['crash', 'timeout'])(
+ 'discards filename template effects after %s and keeps the original target',
+ async (failure) => {
+ let laterPayload: Record<string, unknown> | undefined
+ const { host } = makeMockHost([
+ {
+ id: 'motrix.filename-template',
+ role: 'pre-resolve',
+ hooks: ['beforeFinalize'],
+ handler: async ({ bridge, signal }) => {
+ const ctx = bridge.setHookContext.mock.calls[0]?.[0]
+ ctx.staged.setFinalizePath('/downloads/partial.zip')
+ ctx.staged.appendMeta({
+ pluginId: 'motrix.filename-template',
+ op: 'set',
+ key: 'partial',
+ value: true,
+ })
+ if (failure === 'crash') throw new Error('worker crashed')
+ await new Promise<void>((_resolve, reject) => {
+ signal.addEventListener(
+ 'abort',
+ () => reject(new Error('hook timed out')),
+ { once: true }
+ )
+ })
+ },
+ },
+ {
+ id: 'healthy',
+ role: 'audit',
+ hooks: ['beforeFinalize'],
+ handler: ({ ctxPayload }) => {
+ laterPayload = ctxPayload
+ },
+ },
+ ])
+ const policyCheck = vi.fn()
+ host.capturePolicyCheck = () => policyCheck
+ const orch = new HookOrchestrator({
+ host,
+ hookTimeoutMs: TIMEOUTS,
+ ...ORCH_OPTS_BASE,
+ })
+ const initial = makeBeforeFinalizeDto()
+
+ const result = await orch.runBeforeFinalize(initial, 'task-1')
+
+ expect(result.aborted).toBeFalsy()
+ if (result.aborted) throw new Error(result.reason)
+ expect(result.final).toMatchObject(initial)
+ expect(result.finalFilePath).toBeUndefined()
+ expect(result.replacement).toBeUndefined()
+ expect(result.staged.allMetadataOps()).toEqual([])
+ expect(laterPayload).toMatchObject(initial)
+ // Only the successful audit plugin retains a commit-boundary policy check.
+ expect(policyCheck).toHaveBeenCalledOnce()
+ }
+ )
+
it('does not recursively discard unjournaled bytes during abort', async () => {
const discardSpy = vi
.spyOn(FfmpegStaging.prototype, 'discard')
diff --git a/src/core/plugin/hooks/hook-orchestrator.ts b/src/core/plugin/hooks/hook-orchestrator.ts
index 685c94b1..e749698a 100644
--- a/src/core/plugin/hooks/hook-orchestrator.ts
+++ b/src/core/plugin/hooks/hook-orchestrator.ts
@@ -18,6 +18,9 @@ import {
// - enrich / audit throwing -> chain continues (fail-open with isolation).
// The throwing plugin's staged effects are dropped via removeFromPlugin so
// they cannot poison the merged result.
+// - Filename templating beforeFinalize is optional despite its pre-resolve
+// ordering: failure preserves the previously accepted target path.
+// Activation failures follow the same policy as invocation failures.
//
// Architecture contract:
// - MUST NOT import from electron, @main/, @server/, @renderer/.
@@ -124,7 +127,15 @@ export interface ChainAborted {
interface ChainEntry {
id: string
role: RoleBand
- info: ActivePluginInfo
+}
+
+function abortsChainOnFailure(hook: SeriesHook, entry: ChainEntry): boolean {
+ // This builtin chooses a display name, not the file contents. Its early
+ // ordering must not make a downloaded artifact depend on a healthy worker.
+ if (hook === 'beforeFinalize' && entry.id === 'motrix.filename-template') {
+ return false
+ }
+ return isMostCritical(entry.role)
}
function roleFromManifest(
@@ -184,7 +195,7 @@ export class HookOrchestrator {
initial: BeforeCreateHttpContextDTO,
taskId: string
): Promise<BeforeCreateHttpResult | ChainAborted> {
- const chain = await this.eligiblePlugins(
+ const chain = this.eligiblePlugins(
'beforeCreate',
initial.uris[0],
initial.type
@@ -226,7 +237,7 @@ export class HookOrchestrator {
continue
}
- const abort = newHookAbort(timeout)
+ let abort: ReturnType<typeof newHookAbort> | undefined
diagnosticPluginIds.push(entry.id)
this.recordHttpDiagnostic(entry.id, taskId, 'beforeCreate.input', {
sourceUrl: working.sourceUrl,
@@ -236,6 +247,8 @@ export class HookOrchestrator {
})
try {
+ await this.activateForHook(entry, 'beforeCreate')
+ abort = newHookAbort(timeout)
const check = this.opts.host.capturePolicyCheck?.(entry.id)
if (check) staged.bindPolicyCheck(entry.id, check)
const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)
@@ -282,7 +295,7 @@ export class HookOrchestrator {
error: message,
})
- if (isMostCritical(entry.role)) {
+ if (abortsChainOnFailure('beforeCreate', entry)) {
await this.opts.auditLog?.log({
type: 'chain.abort',
hook: 'beforeCreate',
@@ -298,7 +311,7 @@ export class HookOrchestrator {
staged.removeFromPlugin(entry.id)
working = mergeBeforeCreateWorking(initial, staged)
} finally {
- abort.dispose()
+ abort?.dispose()
}
}
@@ -358,7 +371,7 @@ export class HookOrchestrator {
initial: BeforeFinalizeContextDTO,
taskId: string
): Promise<BeforeFinalizeResult | ChainAborted> {
- const chain = await this.eligiblePlugins(
+ const chain = this.eligiblePlugins(
'beforeFinalize',
undefined,
initial.task.type
@@ -407,8 +420,10 @@ export class HookOrchestrator {
staged.appendStaging(entry.id, staging)
const previousFinalizePath = staged.pendingFinalizePath
- const abort = newHookAbort(timeout)
+ let abort: ReturnType<typeof newHookAbort> | undefined
try {
+ await this.activateForHook(entry, 'beforeFinalize')
+ abort = newHookAbort(timeout)
const check = this.opts.host.capturePolicyCheck?.(entry.id)
if (check) staged.bindPolicyCheck(entry.id, check)
const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)
@@ -454,7 +469,7 @@ export class HookOrchestrator {
error: message,
})
- if (isMostCritical(entry.role)) {
+ if (abortsChainOnFailure('beforeFinalize', entry)) {
await this.opts.auditLog?.log({
type: 'chain.abort',
hook: 'beforeFinalize',
@@ -465,6 +480,10 @@ export class HookOrchestrator {
})
return { aborted: true, reason: `${entry.id}: ${message}` }
}
+ log.warn(
+ { taskId, pluginId: entry.id, error: message },
+ 'optional beforeFinalize plugin failed; keeping the accepted target'
+ )
staged.removeFromPlugin(entry.id)
staged.restoreFinalizePath(previousFinalizePath)
working = {
@@ -473,7 +492,7 @@ export class HookOrchestrator {
targetFilePath: previousFinalizePath ?? initial.targetFilePath,
}
} finally {
- abort.dispose()
+ abort?.dispose()
}
}
@@ -521,7 +540,7 @@ export class HookOrchestrator {
ctxDto: AfterCompleteContextDTO | OnErrorContextDTO,
taskId: string
): Promise<void> {
- const chain = await this.eligiblePlugins(hook)
+ const chain = this.eligiblePlugins(hook)
if (chain.length === 0) return
const timeout = this.opts.hookTimeoutMs.parallel
@@ -538,9 +557,11 @@ export class HookOrchestrator {
return
}
- const abort = newHookAbort(timeout)
+ let abort: ReturnType<typeof newHookAbort> | undefined
try {
+ await this.activateForHook(entry, hook)
+ abort = newHookAbort(timeout)
const metadataSnapshot = await this.metadataSnapshot(taskId, entry.id)
await this.opts.host.invokeHook(entry.id, hook, {
taskId,
@@ -569,7 +590,7 @@ export class HookOrchestrator {
error: (e as Error).message,
})
} finally {
- abort.dispose()
+ abort?.dispose()
}
})
@@ -581,16 +602,14 @@ export class HookOrchestrator {
// -------------------------------------------------------------------------
/**
- * Internal — collect every active plugin whose manifest declares the hook
- * and (for before* hooks) whose hostPermissions accept the task URL. Result
- * is sorted by role band ascending so the chain runs resolve before enrich
- * before audit.
+ * Discover candidates without starting workers. Each entry activates inside
+ * its own failure boundary after the circuit-breaker check.
*/
- private async eligiblePlugins(
+ private eligiblePlugins(
hook: AnyHook,
url?: string,
taskType?: 'http' | 'bt' | 'magnet' | 'ftp' | 'metalink'
- ): Promise<ChainEntry[]> {
+ ): ChainEntry[] {
const out: ChainEntry[] = []
const descriptors = this.opts.activationDispatcher?.candidatesForHook(
hook,
@@ -600,32 +619,14 @@ export class HookOrchestrator {
}
)
if (descriptors) {
- for (const descriptor of descriptors) {
- await this.opts.activationDispatcher?.activateForHook(
- descriptor.id,
- hook
- )
- const info = this.opts.host
- .allActive()
- .find((active) => active.id === descriptor.id)
- if (!info) {
- throw new Error(
- `hook demand activation completed without active plugin ${descriptor.id}`
- )
- }
- const role = roleFromManifest(info, hook)
- if (role) out.push({ id: info.id, role, info })
- }
return sortByBand(
- out.map((entry) => ({
- pluginId: entry.id,
- role: entry.role,
- info: entry.info,
+ descriptors.map((descriptor) => ({
+ pluginId: descriptor.id,
+ role: descriptor.role,
}))
).map((entry) => ({
id: entry.pluginId,
role: entry.role,
- info: entry.info,
}))
}
@@ -660,11 +661,31 @@ export class HookOrchestrator {
)
if (!eligible) continue
if (!role) continue
- out.push({ id: info.id, role, info })
+ out.push({ id: info.id, role })
+ }
+ return sortByBand(out.map((e) => ({ pluginId: e.id, role: e.role }))).map(
+ (e) => ({ id: e.pluginId, role: e.role })
+ )
+ }
+
+ private async activateForHook(
+ entry: ChainEntry,
+ hook: AnyHook
+ ): Promise<void> {
+ if (!this.opts.activationDispatcher) return
+ await this.opts.activationDispatcher.activateForHook(entry.id, hook)
+ const active = this.opts.host
+ .allActive()
+ .find((plugin) => plugin.id === entry.id)
+ if (!active) {
+ throw new Error(
+ `hook demand activation completed without active plugin ${entry.id}`
+ )
}
- return sortByBand(
- out.map((e) => ({ pluginId: e.id, role: e.role, info: e.info }))
- ).map((e) => ({ id: e.pluginId, role: e.role, info: e.info }))
+ const role = roleFromManifest(active, hook)
+ if (!role)
+ throw new Error(`active plugin ${entry.id} no longer declares ${hook}`)
+ entry.role = role
}
/**
diff --git a/src/core/plugin/hooks/staged-effects.ts b/src/core/plugin/hooks/staged-effects.ts
index 8e5c5e47..45ad0f63 100644
--- a/src/core/plugin/hooks/staged-effects.ts
+++ b/src/core/plugin/hooks/staged-effects.ts
@@ -170,12 +170,10 @@ export class StagedEffectStore {
/**
* Plan C fail-open isolation — drop every staged contribution from the named
- * plugin. Called by the HookOrchestrator when an enrich/audit plugin throws
- * mid-chain so its partial effects are not committed alongside the
- * succeeding plugins'. The finalize path is intentionally NOT cleared here:
- * it is only ever set by resolve/post-process plugins (audit/enrich cannot
- * touch it per the matrix), so removing one of their meta/http stages should
- * not roll back a separate plugin's finalize decision.
+ * plugin. Called by the HookOrchestrator when an optional plugin fails so
+ * its partial effects are not committed alongside succeeding plugins'.
+ * The caller separately restores the previous finalize path, preserving
+ * any target accepted before this plugin ran.
*/
removeFromPlugin(pluginId: string): void {
this.httpPatches = this.httpPatches.filter((e) => e.pluginId !== pluginId)
diff --git a/src/core/plugin/host/orchestrator.e2e.test.ts b/src/core/plugin/host/orchestrator.e2e.test.ts
index bd820135..a640045f 100644
--- a/src/core/plugin/host/orchestrator.e2e.test.ts
+++ b/src/core/plugin/host/orchestrator.e2e.test.ts
@@ -94,6 +94,7 @@ async function makeHarness(
input: {
dispatcher?: Dispatcher
config?: Record<string, Record<string, unknown>>
+ workerScriptPath?: string
} = {}
): Promise<Harness> {
const root = await realpath(
@@ -157,7 +158,7 @@ async function makeHarness(
registry,
stateStore,
capabilityHost,
- workerScriptPath: WORKER_SCRIPT_PATH,
+ workerScriptPath: input.workerScriptPath ?? WORKER_SCRIPT_PATH,
idleDisposeMs: 1,
appVersion: '2.5.0',
runtime: 'server',
@@ -565,6 +566,50 @@ describe('locked builtin bundles through PluginHost + QuickJS Hooks', () => {
})
}, 30_000)
+ it('filename-template preserves the download target when the worker bundle is missing', async () => {
+ const harness = await makeHarness({
+ workerScriptPath: path.join(
+ os.tmpdir(),
+ randomUUID(),
+ 'missing-worker.cjs'
+ ),
+ })
+ enableOnly(harness, 'motrix.filename-template')
+ const taskId = 'missing-filename-worker'
+ const saveDir = path.join(harness.root, 'downloads')
+ await mkdir(saveDir)
+ const filePath = path.join(saveDir, 'original.zip')
+ const dto = beforeFinalize({
+ task: taskSnapshot({
+ id: taskId,
+ filePath,
+ saveDir,
+ type: 'http',
+ kind: 'direct',
+ }),
+ sourceUrl: 'https://example.com/original.zip',
+ })
+ dto.inputFilePath = `${filePath}.motrix`
+ await writeFile(dto.inputFilePath, 'downloaded bytes')
+
+ const result = await harness.orchestrator.runBeforeFinalize(dto, taskId)
+
+ expect(result.aborted).toBeFalsy()
+ if (result.aborted) throw new Error(result.reason)
+ expect(result.final.filePath).toBe(filePath)
+ expect(result.final.targetFilePath).toBe(filePath)
+ expect(result.finalFilePath).toBeUndefined()
+ expect(result.replacement).toBeUndefined()
+ expect(result.staged.allMetadataOps()).toEqual([])
+ expect(result.staged.hasPolicyChecks).toBe(false)
+ expect(await readFile(dto.inputFilePath, 'utf8')).toBe('downloaded bytes')
+ expect(
+ harness.stateStore.get('motrix.filename-template')?.lastError
+ ).toContain('Cannot find module')
+ await harness.host.deactivate('motrix.filename-template')
+ expect(harness.host.isQuiescent('motrix.filename-template')).toBe(true)
+ })
+
it('filename-template applies an updated date template to a completed browser download', async () => {
const config = { 'motrix.filename-template': { template: '{{title}}' } }
const harness = await makeHarness({ config })
diff --git a/src/core/plugin/host/plugin-host.test.ts b/src/core/plugin/host/plugin-host.test.ts
index f000b4c5..f2cb099a 100644
--- a/src/core/plugin/host/plugin-host.test.ts
+++ b/src/core/plugin/host/plugin-host.test.ts
@@ -534,6 +534,58 @@ describe('PluginHost', () => {
await host.shutdown()
})
+ it.each(['missing worker', 'worker crash', 'worker fatal'])(
+ 'preserves the activation failure for coalesced callers: %s',
+ async (failure) => {
+ const failedWorkerPath = path.join(root, 'FailedWorker.cjs')
+ const message =
+ failure === 'missing worker'
+ ? `Cannot find module '${failedWorkerPath}'`
+ : 'plugin activation failed'
+ if (failure === 'worker crash') {
+ writeFileSync(failedWorkerPath, `throw new Error('${message}')`)
+ } else if (failure === 'worker fatal') {
+ writeFileSync(
+ failedWorkerPath,
+ `const { parentPort } = require('node:worker_threads')
+parentPort.on('message', (msg) => {
+ if (msg.type === 'init') {
+ parentPort.postMessage({ type: 'fatal', code: 'plugin.bundle.parse_error', message: '${message}' })
+ }
+})`
+ )
+ }
+ const host = new PluginHost({
+ registry,
+ stateStore,
+ capabilityHost: capHost,
+ workerScriptPath: failedWorkerPath,
+ deactivateBudgetMs: 20,
+ appVersion: '2.5.0',
+ runtime: 'server',
+ hostLanguage: 'en-US',
+ })
+
+ try {
+ await Promise.all([
+ expect(host.activate('alice.demo')).rejects.toMatchObject({
+ code: ErrorCode.PluginRuntimeFault,
+ message,
+ }),
+ expect(host.activate('alice.demo')).rejects.toMatchObject({
+ code: ErrorCode.PluginRuntimeFault,
+ message,
+ }),
+ ])
+ await host.deactivate('alice.demo')
+ expect(host.isQuiescent('alice.demo')).toBe(true)
+ expect(host.workerFor('alice.demo')).toBeUndefined()
+ } finally {
+ await host.shutdown()
+ }
+ }
+ )
+
it('cancels activation blocked on bundle read without a late worker', async () => {
let markReadStarted!: () => void
const readStarted = new Promise<void>((resolve) => {
diff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.ts
index a4523fd7..79eb0cb2 100644
--- a/src/core/plugin/host/plugin-host.ts
+++ b/src/core/plugin/host/plugin-host.ts
@@ -143,7 +143,7 @@ interface ActivationAttempt {
epoch: number
cancelled: boolean
cancellation: Promise<never>
- cancel(): void
+ cancel(reason?: Error): void
promise: Promise<void>
}
@@ -367,10 +367,10 @@ export class PluginHost {
epoch,
cancelled: false,
cancellation,
- cancel: () => {
+ cancel: (reason = this.activationSupersededError(pluginId)) => {
if (attempt.cancelled) return
attempt.cancelled = true
- rejectCancellation(this.activationSupersededError(pluginId))
+ rejectCancellation(reason)
},
promise: Promise.resolve(),
}
@@ -656,7 +656,11 @@ export class PluginHost {
}
this.opts.stateStore.recordError(pluginId, `${code}: ${message}`)
this.opts.registry.refreshState(pluginId)
- rejectReady(new AppError(ErrorCode.PluginRuntimeFault, message))
+ const error = new AppError(ErrorCode.PluginRuntimeFault, message)
+ rejectReady(error)
+ // Teardown cancels activation synchronously. Preserve the worker
+ // failure even if cancellation wins the nested readiness race.
+ attempt.cancel(error)
void this.deactivate(pluginId).catch(() => undefined)
},
}
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index 47677046..f50423c3 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -834,3 +834,50 @@ describe('plugin diagnostic state query', () => {
expect(getLogState).not.toHaveBeenCalled()
})
})
+
+describe('CheckTaskFileExists query', () => {
+ it('checks output file existence through taskManager', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-check-file-test-'))
+ const existingFile = path.join(root, 'exists.txt')
+ await writeFile(existingFile, 'hello')
+ const missingFile = path.join(root, 'missing.txt')
+
+ const taskManager = {
+ getById: vi.fn((id: string) => {
+ if (id === 't-exists') {
+ return makeDownloadTask({ id: 't-exists', finalPath: existingFile })
+ }
+ if (id === 't-missing') {
+ return makeDownloadTask({ id: 't-missing', finalPath: missingFile })
+ }
+ return undefined
+ }),
+ }
+
+ const handlers = buildQueryHandlers({
+ taskManager,
+ } as unknown as QueryContext)
+
+ // The output file still exists.
+ await expect(
+ handlers[Queries.CheckTaskFileExists]?.({ taskId: 't-exists' })
+ ).resolves.toEqual({ exists: true })
+
+ // The output file has been deleted.
+ await expect(
+ handlers[Queries.CheckTaskFileExists]?.({ taskId: 't-missing' })
+ ).resolves.toEqual({ exists: false })
+
+ // The task does not exist.
+ await expect(
+ handlers[Queries.CheckTaskFileExists]?.({ taskId: 't-unknown' })
+ ).resolves.toEqual({ exists: false })
+
+ // The request payload is invalid.
+ await expect(
+ handlers[Queries.CheckTaskFileExists]?.({ taskId: '' })
+ ).rejects.toThrow()
+
+ await rm(root, { recursive: true, force: true })
+ })
+})
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 8e176409..4fcfd6e7 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -4,6 +4,7 @@ import type { EngineAdapter } from '@core/engine/engine-adapter'
import type { EngineSupervisor } from '@core/engine/engine-supervisor'
import { getTuningRecommendation } from '@core/engine/get-tuning-recommendation'
import { getFfmpegInstallStatus } from '@core/ffmpeg/verified-install'
+import { pathExists } from '@core/fs/path-exists'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { createGetGeoIPStatusHandler } from '@core/geoip/get-geo-ip-status'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
@@ -45,6 +46,7 @@ import {
} from '@shared/protocol/errors'
import type { QueryHandlerMap } from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import { checkTaskFileExistsPayloadSchema } from '@shared/schemas/check-task-file'
import { PluginLogRequestSchema } from '@shared/schemas/plugin-logs'
import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspector-activity'
import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'
@@ -346,6 +348,16 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
params.pluginId,
params.hook
),
+
+ [Queries.CheckTaskFileExists]: async (payload: unknown) => {
+ const { taskId } = checkTaskFileExistsPayloadSchema.parse(payload)
+ const task = taskManager.getById(taskId)
+ if (!task) return { exists: false }
+ const outputPath = task.finalPath || task.diskPath
+ if (!outputPath || typeof outputPath !== 'string')
+ return { exists: false }
+ return { exists: await pathExists(outputPath) }
+ },
}
}
diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsx
index e6179ad0..5094a481 100644
--- a/src/renderer/layouts/app-layout.tsx
+++ b/src/renderer/layouts/app-layout.tsx
@@ -26,6 +26,7 @@ import { electronServices } from '@renderer/platform/electron-services'
import { PlatformServicesProvider } from '@renderer/platform/services'
import { webServices } from '@renderer/platform/web-services'
import type { RouteHandle } from '@renderer/router-types'
+import { RedownloadOverwriteDialogHost } from '@renderer/routes/downloads/inspector/redownload-overwrite-dialog-host'
import { RemoveTasksDialogHost } from '@renderer/routes/downloads/inspector/remove-tasks-dialog-host'
import { useDownloadsSelection } from '@renderer/routes/downloads/store'
import { useDownloadsView } from '@renderer/routes/downloads/view-preferences'
@@ -144,6 +145,7 @@ export function AppLayout() {
{__MOTRIX_TARGET__ === 'electron' && <DesktopMenuContext />}
<MenuNavigationFocus />
<RemoveTasksDialogHost />
+ <RedownloadOverwriteDialogHost />
<OperationDialogHost />
<EngineDiagnosticsDialogHost />
{__MOTRIX_TARGET__ === 'web' && <AddTaskDialogHost />}
diff --git a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog-host.tsx b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog-host.tsx
new file mode 100644
index 00000000..ebd7b0da
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog-host.tsx
@@ -0,0 +1,24 @@
+import { RedownloadOverwriteDialog } from './redownload-overwrite-dialog'
+import { useRedownloadOverwriteStore } from './redownload-overwrite-store'
+import { useTaskActions } from './use-task-actions'
+
+const EMPTY = [] as const
+
+/**
+ * Global host for the re-download confirmation dialog.
+ */
+export function RedownloadOverwriteDialogHost() {
+ const state = useRedownloadOverwriteStore()
+ const actions = useTaskActions(EMPTY)
+ return (
+ <RedownloadOverwriteDialog
+ open={state.open}
+ busy={state.busy}
+ target={state.target}
+ onOpenChange={(open) => {
+ if (!open) actions.closeRedownloadOverwriteDialog()
+ }}
+ onConfirm={() => void actions.confirmRedownloadOverwrite()}
+ />
+ )
+}
diff --git a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx
new file mode 100644
index 00000000..0fdc196c
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx
@@ -0,0 +1,73 @@
+import '@renderer/lib/i18n'
+import { makeDownloadTask } from '@test-utils/task'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+import { RedownloadOverwriteDialog } from './redownload-overwrite-dialog'
+
+describe('RedownloadOverwriteDialog', () => {
+ it('does not render when target is null', () => {
+ const { container } = render(
+ <RedownloadOverwriteDialog
+ open={true}
+ target={null}
+ onOpenChange={vi.fn()}
+ onConfirm={vi.fn()}
+ />
+ )
+ expect(container.firstChild).toBeNull()
+ })
+
+ it('renders title and description with task name when open', () => {
+ const task = makeDownloadTask({ id: 't1', name: 'sample.mp4' })
+ render(
+ <RedownloadOverwriteDialog
+ open={true}
+ target={task}
+ onOpenChange={vi.fn()}
+ onConfirm={vi.fn()}
+ />
+ )
+
+ expect(screen.getByText('File Already Exists')).toBeDefined()
+ expect(
+ screen.getByText(
+ /“sample\.mp4” already exists in the download directory\./
+ )
+ ).toBeDefined()
+ })
+
+ it('calls onConfirm when confirm button clicked', () => {
+ const task = makeDownloadTask({ id: 't1', name: 'sample.mp4' })
+ const onConfirm = vi.fn()
+ render(
+ <RedownloadOverwriteDialog
+ open={true}
+ target={task}
+ onOpenChange={vi.fn()}
+ onConfirm={onConfirm}
+ />
+ )
+
+ const confirmBtn = screen.getByRole('button', { name: 'Re-download' })
+ fireEvent.click(confirmBtn)
+ expect(onConfirm).toHaveBeenCalledTimes(1)
+ })
+
+ it('disables buttons when busy is true', () => {
+ const task = makeDownloadTask({ id: 't1', name: 'sample.mp4' })
+ render(
+ <RedownloadOverwriteDialog
+ open={true}
+ busy={true}
+ target={task}
+ onOpenChange={vi.fn()}
+ onConfirm={vi.fn()}
+ />
+ )
+
+ const cancelBtn = screen.getByRole('button', { name: 'Cancel' })
+ const confirmBtn = screen.getByRole('button', { name: 'Re-download' })
+ expect(cancelBtn).toHaveProperty('disabled', true)
+ expect(confirmBtn).toHaveProperty('disabled', true)
+ })
+})
diff --git a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx
new file mode 100644
index 00000000..d6254582
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx
@@ -0,0 +1,70 @@
+import { WarningIcon } from '@renderer/components/icons'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@renderer/components/ui/alert-dialog'
+import type { DownloadTask } from '@shared/types/task'
+import { useTranslation } from 'react-i18next'
+
+export interface RedownloadOverwriteDialogProps {
+ open: boolean
+ busy?: boolean
+ target: DownloadTask | null
+ onOpenChange: (open: boolean) => void
+ onConfirm: () => void
+}
+
+/**
+ * Confirm re-downloading when the destination file already exists.
+ */
+export function RedownloadOverwriteDialog({
+ open,
+ busy,
+ target,
+ onOpenChange,
+ onConfirm,
+}: RedownloadOverwriteDialogProps) {
+ const { t } = useTranslation()
+
+ if (!target) return null
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <div className="flex items-center gap-2">
+ <WarningIcon className="size-5 shrink-0 text-amber-500" />
+ <AlertDialogTitle>
+ {t('panel.downloads.action.redownloadOverwriteTitle')}
+ </AlertDialogTitle>
+ </div>
+ <AlertDialogDescription>
+ {t('panel.downloads.action.redownloadOverwriteDescription', {
+ name: target.name,
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={busy}>
+ {t('common.cancel')}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ disabled={busy}
+ onClick={(event) => {
+ event.preventDefault()
+ onConfirm()
+ }}
+ >
+ {t('panel.downloads.action.redownload')}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/src/renderer/routes/downloads/inspector/redownload-overwrite-store.ts b/src/renderer/routes/downloads/inspector/redownload-overwrite-store.ts
new file mode 100644
index 00000000..ba9ccfc1
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/redownload-overwrite-store.ts
@@ -0,0 +1,24 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
+import type { DownloadTask } from '@shared/types/task'
+import { create } from 'zustand'
+
+/**
+ * Shared state for the re-download confirmation dialog.
+ */
+export const useRedownloadOverwriteStore = create<{
+ open: boolean
+ target: DownloadTask | null
+ busy: boolean
+}>(() => ({
+ open: false,
+ target: null,
+ busy: false,
+}))
+
+onOperatorSessionLost(() =>
+ useRedownloadOverwriteStore.setState({
+ open: false,
+ target: null,
+ busy: false,
+ })
+)
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
index b6d02b4d..83ef9010 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
@@ -504,5 +504,36 @@ describe('TaskInspectorActionBar', () => {
expect(copyButton.querySelector('[data-icon="copy"]')).not.toBeNull()
expect(copyButton.querySelector('[data-icon="check"]')).toBeNull()
})
+
+ it('renders Re-download button for completed task and triggers re-download on click', async () => {
+ const task = makeTask({
+ id: 'completed-1',
+ status: TaskStatus.Completed,
+ })
+ ;(transport.invoke as ReturnType<typeof vi.fn>).mockImplementation(
+ async (channel) => {
+ if (channel === Queries.CheckTaskFileExists) {
+ return { exists: false }
+ }
+ return { ok: true }
+ }
+ )
+
+ render(<TaskInspectorActionBar selected={[task]} onClose={vi.fn()} />)
+
+ const redownloadButton = screen.getByRole('button', {
+ name: /Re-download/,
+ })
+ expect(redownloadButton).toBeDefined()
+
+ fireEvent.click(redownloadButton)
+
+ await waitFor(() => {
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Queries.CheckTaskFileExists,
+ { taskId: 'completed-1' }
+ )
+ })
+ })
})
})
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
index e2e23f23..220501a5 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
@@ -4,6 +4,7 @@ import {
OpenFileIcon,
PauseIcon,
RemoveIcon,
+ RestartIcon,
ResumeIcon,
RetryIcon,
RevealFolderIcon,
@@ -260,6 +261,24 @@ export function TaskInspectorActionBar({
onClick={(e) => void actions.onRetry({ alt: e.altKey })}
/>
)}
+ {actions.redownloadCount > 0 && (
+ <CountedButton
+ label={t('panel.downloads.action.redownload')}
+ total={actions.total}
+ count={actions.redownloadCount}
+ tooltipSingle={
+ alt && actions.total === 1
+ ? t('panel.downloads.action.redownloadWithDialog')
+ : t('panel.downloads.action.redownload')
+ }
+ tooltipBatch={t('panel.downloads.action.redownloadTooltipBatch', {
+ n: actions.redownloadCount,
+ total: actions.total,
+ })}
+ icon={<RestartIcon />}
+ onClick={(e) => void actions.onRedownload({ alt: e.altKey })}
+ />
+ )}
{actions.reseedCount > 0 && (
<CountedButton
label={t('panel.downloads.action.reseed')}
diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.test.ts b/src/renderer/routes/downloads/inspector/use-task-actions.test.ts
index 7b87e8a5..10f963d7 100644
--- a/src/renderer/routes/downloads/inspector/use-task-actions.test.ts
+++ b/src/renderer/routes/downloads/inspector/use-task-actions.test.ts
@@ -26,6 +26,7 @@ import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
+import { useRedownloadOverwriteStore } from './redownload-overwrite-store'
import { useTaskActions } from './use-task-actions'
// Kept overrides: id:'t1' (≠ 'task-1'), name:'sample' (≠ 'task'),
@@ -243,4 +244,189 @@ describe('useTaskActions', () => {
result.current.onRemove({ shift: false })
expect(transport.invoke).not.toHaveBeenCalled()
})
+
+ it('correctly counts redownload-eligible completed tasks', () => {
+ const tasks = [
+ makeTask({ id: 'a', status: TaskStatus.Completed }),
+ makeTask({ id: 'b', status: TaskStatus.Downloading }),
+ makeTask({ id: 'c', status: TaskStatus.Error }),
+ makeTask({ id: 'd', status: TaskStatus.Completed, kind: TaskKind.Mux }),
+ ]
+ const { result } = renderHook(() => useTaskActions(tasks))
+ expect(result.current.redownloadCount).toBe(1) // Only task a is eligible.
+ })
+
+ it('onRedownload({ alt: true }) opens dialog with prefilled parameters', async () => {
+ const task = makeTask({ id: 'comp', status: TaskStatus.Completed })
+ ;(transport.invoke as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
+ dir: '/downloads',
+ header: ['Cookie: session=123'],
+ })
+ const { result } = renderHook(() => useTaskActions([task]))
+ await result.current.onRedownload({ alt: true })
+
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Queries.GetEngineTaskOptions,
+ 'gid-1'
+ )
+ expect(openAddTaskDialog).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tab: 'links',
+ cookie: 'session=123',
+ saveDir: '/downloads',
+ })
+ )
+ })
+
+ it('onRedownload opens overwrite confirm dialog when output file exists', async () => {
+ const task = makeTask({ id: 'comp', status: TaskStatus.Completed })
+ ;(transport.invoke as ReturnType<typeof vi.fn>).mockImplementation(
+ async (channel) => {
+ if (channel === Queries.CheckTaskFileExists) {
+ return { exists: true }
+ }
+ return { ok: true }
+ }
+ )
+ const { result } = renderHook(() => useTaskActions([task]))
+ await result.current.onRedownload({ alt: false })
+
+ expect(transport.invoke).toHaveBeenCalledWith(Queries.CheckTaskFileExists, {
+ taskId: 'comp',
+ })
+ expect(useRedownloadOverwriteStore.getState().open).toBe(true)
+ expect(useRedownloadOverwriteStore.getState().target?.id).toBe('comp')
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.anything()
+ )
+
+ // The user confirms re-downloading in the dialog.
+ await result.current.confirmRedownloadOverwrite()
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.objectContaining({
+ uris: ['http://example.com/x'],
+ })
+ )
+ expect(useRedownloadOverwriteStore.getState().open).toBe(false)
+ })
+
+ it.each(['direct', 'confirm', 'edit'])(
+ 'uses the saved directory when engine options are unavailable: %s',
+ async (mode) => {
+ const task = makeTask({ status: TaskStatus.Completed })
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.CheckTaskFileExists) {
+ return { exists: mode === 'confirm' }
+ }
+ if (channel === Queries.GetEngineTaskOptions) return null
+ return { ok: true }
+ })
+ const { result } = renderHook(() => useTaskActions([task]))
+
+ await result.current.onRedownload({ alt: mode === 'edit' })
+ if (mode === 'confirm') {
+ await result.current.confirmRedownloadOverwrite()
+ }
+
+ const expected = expect.objectContaining({
+ saveDir: '/tmp',
+ filename: 'sample',
+ })
+ if (mode === 'edit') {
+ expect(openAddTaskDialog).toHaveBeenCalledWith(expected)
+ } else {
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expected
+ )
+ }
+ }
+ )
+
+ it('onRedownload directly creates task when output file does not exist', async () => {
+ const task = makeTask({ id: 'comp', status: TaskStatus.Completed })
+ ;(transport.invoke as ReturnType<typeof vi.fn>).mockImplementation(
+ async (channel) => {
+ if (channel === Queries.CheckTaskFileExists) {
+ return { exists: false }
+ }
+ return { ok: true }
+ }
+ )
+ const { result } = renderHook(() => useTaskActions([task]))
+ await result.current.onRedownload({ alt: false })
+
+ expect(transport.invoke).toHaveBeenCalledWith(Queries.CheckTaskFileExists, {
+ taskId: 'comp',
+ })
+ expect(useRedownloadOverwriteStore.getState().open).toBe(false)
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.objectContaining({
+ uris: ['http://example.com/x'],
+ })
+ )
+ })
+
+ it('onRedownload warns and falls back to dialog if original credentials expired', async () => {
+ // This task requires credentials and cannot be replayed from its URI alone.
+ const task = makeTask({
+ id: 'comp-cred',
+ status: TaskStatus.Completed,
+ instances: [
+ {
+ instanceId: 'inst-1',
+ motrixId: 'comp-cred',
+ gid: 'gid-cred',
+ phase: TaskInstancePhase.HttpDownload,
+ status: TaskStatus.Completed,
+ progress: 100,
+ totalBytes: 1000,
+ downloadedBytes: 1000,
+ uploadedBytes: 0,
+ diskPath: '/tmp/sample',
+ transitionPhase: TransitionPhase.Idle,
+ uris: ['http://example.com/file'],
+ uriHash: null,
+ payload: {
+ directReplay: {
+ version: 1,
+ requestModifiers: ['cookies'],
+ replayability: 'requires-credentials',
+ },
+ },
+ createdAt: 1,
+ updatedAt: 2,
+ },
+ ],
+ })
+
+ ;(transport.invoke as ReturnType<typeof vi.fn>).mockImplementation(
+ async (channel) => {
+ if (channel === Queries.CheckTaskFileExists) {
+ return { exists: false }
+ }
+ if (channel === Queries.GetEngineTaskOptions) {
+ return null // Simulate an engine restart or expired credentials.
+ }
+ return { ok: true }
+ }
+ )
+
+ const { result } = renderHook(() => useTaskActions([task]))
+ await result.current.onRedownload({ alt: false })
+
+ expect(toastAddMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'warning',
+ })
+ )
+ expect(openAddTaskDialog).toHaveBeenCalled()
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.CreateTask,
+ expect.anything()
+ )
+ })
})
diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.ts b/src/renderer/routes/downloads/inspector/use-task-actions.ts
index 73b3cac6..458af27e 100644
--- a/src/renderer/routes/downloads/inspector/use-task-actions.ts
+++ b/src/renderer/routes/downloads/inspector/use-task-actions.ts
@@ -1,21 +1,30 @@
import { toast } from '@renderer/components/ui/toast'
import { taskWritesAvailable } from '@renderer/features/application-menu/task-context'
-import { getTaskListSnapshot } from '@renderer/hooks/use-task-list'
+import {
+ getTaskListSnapshot,
+ invalidateTaskList,
+} from '@renderer/hooks/use-task-list'
import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { transport } from '@renderer/lib/transport'
import { type CommandChannel, Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
+import {
+ type AddTaskFormValues,
+ formValuesToTaskCreateRequests,
+} from '@shared/schemas/add-task'
+import { isUriOnlyDirectReplay } from '@shared/schemas/direct-replay-recipe'
import {
type MoveTasksPayload,
moveTasksResultSchema,
} from '@shared/schemas/move-tasks'
import type { EngineTaskOptions } from '@shared/types/engine-task-options'
-import type { DownloadTask } from '@shared/types/task'
+import { type DownloadTask, TaskInstancePhase } from '@shared/types/task'
import type { BulkTaskCommandResult } from '@shared/types/task-actions'
import {
canAttemptRetry,
canMoveInQueue,
canPause,
+ canRedownload,
canRemove,
canReseed,
canResume,
@@ -24,6 +33,7 @@ import {
} from '@shared/types/task-actions'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useRedownloadOverwriteStore } from './redownload-overwrite-store'
import { useRemoveTasksStore } from './remove-tasks-store'
export interface RemoveDialogState {
@@ -97,7 +107,7 @@ function buildPrefillFromTask(
return {
tab: 'links' as const,
urls: task.uris.join('\n'),
- saveDir: (opts?.dir as string | undefined) || task.diskPath,
+ saveDir: (opts?.dir as string | undefined) || task.saveDir,
filename: task.finalName,
split:
opts?.split && typeof opts.split === 'string'
@@ -144,6 +154,7 @@ export interface TaskActionsState {
stopSeedingCount: number
reseedCount: number
retryCount: number
+ redownloadCount: number
removeCount: number
total: number
@@ -155,6 +166,9 @@ export interface TaskActionsState {
onStopSeeding: () => Promise<void>
onReseed: (modifier?: { alt: boolean }) => Promise<void>
onRetry: (modifier?: { alt: boolean }) => Promise<void>
+ onRedownload: (modifier?: { alt: boolean }) => Promise<void>
+ closeRedownloadOverwriteDialog: () => void
+ confirmRedownloadOverwrite: () => Promise<void>
onRemove: (modifier?: { shift: boolean }) => void
closeRemoveDialog: () => void
confirmRemove: (deleteFiles: boolean) => Promise<void>
@@ -181,6 +195,7 @@ export function useTaskActions(
let stopSeedingCount = 0
let reseedCount = 0
let retryCount = 0
+ let redownloadCount = 0
let removeCount = 0
for (const task of selected) {
if (canPause(task)) pauseCount++
@@ -188,6 +203,7 @@ export function useTaskActions(
if (canStopSeeding(task)) stopSeedingCount++
if (canReseed(task)) reseedCount++
if (canAttemptRetry(task)) retryCount++
+ if (canRedownload(task)) redownloadCount++
if (canRemove(task)) removeCount++
}
return {
@@ -197,6 +213,7 @@ export function useTaskActions(
stopSeedingCount,
reseedCount,
retryCount,
+ redownloadCount,
removeCount,
total: selected.length,
}
@@ -350,10 +367,11 @@ export function useTaskActions(
const onRetry = useCallback(
async (modifier?: { alt: boolean }) => {
+ const retryKind = selected[0] ? getTaskRetryKind(selected[0]) : null
if (
modifier?.alt &&
selected.length === 1 &&
- getTaskRetryKind(selected[0]) === 'torrent-readd'
+ (retryKind === 'torrent-readd' || retryKind === 'direct-readd')
) {
await altReAddSingle(selected[0])
return
@@ -363,6 +381,129 @@ export function useTaskActions(
[selected, altReAddSingle, dispatchSubset]
)
+ const checkFileExists = useCallback(
+ async (task: DownloadTask): Promise<boolean> => {
+ try {
+ const res = (await transport.invoke(Queries.CheckTaskFileExists, {
+ taskId: task.id,
+ })) as { exists: boolean }
+ return Boolean(res?.exists)
+ } catch {
+ return false
+ }
+ },
+ []
+ )
+
+ const executeRedownload = useCallback(
+ async (task: DownloadTask) => {
+ // Check whether the original task can be replayed from its URI alone.
+ const primary = task.instances.find(
+ (instance) => instance.phase === TaskInstancePhase.HttpDownload
+ )
+ const isUriOnly = primary ? isUriOnlyDirectReplay(primary.payload) : true
+
+ let opts: EngineTaskOptions | null = null
+ try {
+ opts = (await transport.invoke(
+ Queries.GetEngineTaskOptions,
+ task.engineTaskId
+ )) as EngineTaskOptions | null
+ } catch {
+ opts = null
+ }
+
+ // Let the user restore credentials when the engine no longer has them.
+ if (!isUriOnly && !opts) {
+ toast.add({
+ title: t('panel.downloads.action.redownloadCredentialsExpired'),
+ type: 'warning',
+ })
+ await altReAddSingle(task)
+ return
+ }
+
+ try {
+ const prefill = buildPrefillFromTask(task, opts)
+ const requests = formValuesToTaskCreateRequests(
+ prefill as AddTaskFormValues
+ )
+ for (const req of requests) {
+ await transport.invoke(Commands.CreateTask, req)
+ }
+ invalidateTaskList()
+ toast.add({
+ title: t('panel.downloads.action.redownloadStarted'),
+ type: 'success',
+ })
+ } catch (err) {
+ toast.add({
+ title: t('panel.downloads.action.singleTaskFailed', {
+ name: task.name,
+ reason: errMsg(err),
+ }),
+ type: 'error',
+ })
+ }
+ },
+ [altReAddSingle, t]
+ )
+
+ const onRedownload = useCallback(
+ async (modifier?: { alt: boolean }) => {
+ if (!readyToWrite()) return
+ const targets = resolveLatest(selected).filter(canRedownload)
+ if (!targets.length) return
+ const task = targets[0]
+
+ // Alt-click opens the task dialog for editing before re-downloading.
+ if (modifier?.alt) {
+ await altReAddSingle(task)
+ return
+ }
+
+ // A regular click first checks whether the destination still exists.
+ const exists = await checkFileExists(task)
+ if (exists) {
+ useRedownloadOverwriteStore.setState({
+ open: true,
+ target: task,
+ busy: false,
+ })
+ return
+ }
+
+ // Start immediately when the output file is missing.
+ await executeRedownload(task)
+ },
+ [selected, readyToWrite, altReAddSingle, checkFileExists, executeRedownload]
+ )
+
+ const confirmRedownloadOverwrite = useCallback(async () => {
+ const target = useRedownloadOverwriteStore.getState().target
+ if (!target) return
+ useRedownloadOverwriteStore.setState({ busy: true })
+ try {
+ await executeRedownload(target)
+ } finally {
+ useRedownloadOverwriteStore.setState({
+ open: false,
+ target: null,
+ busy: false,
+ })
+ }
+ }, [executeRedownload])
+
+ const closeRedownloadOverwriteDialog = useCallback(() => {
+ if (!useRedownloadOverwriteStore.getState().busy) {
+ useRedownloadOverwriteStore.setState({
+ open: false,
+ target: null,
+ busy: false,
+ })
+ }
+ }, [])
+
const onRemove = useCallback(
(modifier?: { shift: boolean }) => {
if (useRemoveTasksStore.getState().busy || !readyToWrite()) return
@@ -420,6 +561,9 @@ export function useTaskActions(
onStopSeeding,
onReseed,
onRetry,
+ onRedownload,
+ closeRedownloadOverwriteDialog,
+ confirmRedownloadOverwrite,
onRemove,
closeRemoveDialog,
confirmRemove,
diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsx
index bf665948..9facf175 100644
--- a/src/renderer/routes/downloads/task-actions-menu.test.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx
@@ -611,6 +611,7 @@ describe('organized task menu and keyboard actions', () => {
)
expect(groups).toEqual([
['Open file', 'Open folder', 'Show Inspector'],
+ ['Re-download'],
['Copy URL', 'Copy file path'],
['New Task…'],
['Remove'],
diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsx
index 05990ede..12ab45bc 100644
--- a/src/renderer/routes/downloads/task-actions-menu.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.tsx
@@ -124,6 +124,7 @@ export function TaskActionsMenu({
actions.resumeCount +
actions.retryCount +
actions.reseedCount +
+ actions.redownloadCount +
actions.stopSeedingCount >
0 ||
single?.status === TaskStatus.MetadataReady ||
@@ -328,10 +329,21 @@ export function TaskActionsMenu({
</DropdownMenuItem>
)}
{actions.retryCount > 0 && (
- <DropdownMenuItem onClick={() => void actions.onRetry()}>
+ <DropdownMenuItem
+ onClick={(event) => void actions.onRetry({ alt: event.altKey })}
+ >
{t('panel.downloads.action.retry')}
</DropdownMenuItem>
)}
+ {actions.redownloadCount > 0 && (
+ <DropdownMenuItem
+ onClick={(event) =>
+ void actions.onRedownload({ alt: event.altKey })
+ }
+ >
+ {t('panel.downloads.action.redownload')}
+ </DropdownMenuItem>
+ )}
{actions.reseedCount > 0 && (
<DropdownMenuItem onClick={() => void actions.onReseed()}>
{t('panel.downloads.action.reseed')}
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index 8815e68a..74a7e481 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -4,6 +4,7 @@ import type { EngineAdapter } from '@core/engine/engine-adapter'
import type { EngineSupervisor } from '@core/engine/engine-supervisor'
import { createGetEngineTaskOptionsHandler } from '@core/engine/get-engine-task-options'
import { getTuningRecommendation } from '@core/engine/get-tuning-recommendation'
+import { pathExists } from '@core/fs/path-exists'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { createGetGeoIPStatusHandler } from '@core/geoip/get-geo-ip-status'
import type { NotificationCenter } from '@core/notifications/notification-center'
@@ -41,6 +42,7 @@ import type { TrackerManager } from '@core/tracker'
import type { SupportedLocale } from '@shared/constants/locales'
import type { QueryHandlerMap } from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import { checkTaskFileExistsPayloadSchema } from '@shared/schemas/check-task-file'
import { PluginLogRequestSchema } from '@shared/schemas/plugin-logs'
import { ListServerDirectoryLocationsRequestSchema } from '@shared/schemas/server-directory'
import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'
@@ -402,6 +404,16 @@ export function buildServerQueryHandlers(
[Queries.GetUnreadNotificationCount]: async () =>
notificationCenter.unreadCount(),
+ [Queries.CheckTaskFileExists]: async (payload: unknown) => {
+ const { taskId } = checkTaskFileExistsPayloadSchema.parse(payload)
+ const task = taskManager.getById(taskId)
+ if (!task) return { exists: false }
+ const outputPath = task.finalPath || task.diskPath
+ if (!outputPath || typeof outputPath !== 'string')
+ return { exists: false }
+ return { exists: await pathExists(outputPath) }
+ },
+
// NAT, tuning, and history queries are intentionally omitted in server
// mode — those subsystems are Electron-only or not wired here yet.
}
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 4c4a4bc8..2eabb051 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -891,7 +891,14 @@
"selectFilesFailed": "تعذّر فتح اختيار الملفات.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "إيقاف التوزيع",
- "stopSeedingTooltipBatch": "إيقاف التوزيع: {{n}} من المهام المحددة ({{total}})"
+ "stopSeedingTooltipBatch": "إيقاف التوزيع: {{n}} من المهام المحددة ({{total}})",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "الأقران",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 30b4bf7c..217ec40a 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -879,7 +879,14 @@
"selectFilesFailed": "Изборът на файлове не можа да бъде отворен.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Спиране на сийдването",
- "stopSeedingTooltipBatch": "Спиране на сийдването на {{n}} от {{total}} избрани задачи"
+ "stopSeedingTooltipBatch": "Спиране на сийдването на {{n}} от {{total}} избрани задачи",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Участници",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 28030a2a..382a8614 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -882,7 +882,14 @@
"selectFilesFailed": "No s'ha pogut obrir la selecció de fitxers.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Aturar la distribució",
- "stopSeedingTooltipBatch": "Aturar la distribució de {{n}} de {{total}} tasques seleccionades"
+ "stopSeedingTooltipBatch": "Aturar la distribució de {{n}} de {{total}} tasques seleccionades",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Parells",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index b333d28d..32f23cd8 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -908,7 +908,14 @@
"moveQueueTop": "An den Anfang",
"moveQueueBottom": "Ans Ende",
"copyError": "Fehlerinformationen kopieren",
- "errorReport": "{{name}}\nAufgaben-ID: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nAufgaben-ID: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}} angezeigt · {{total}} insgesamt",
"type": {
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 9fdf44f3..bb072db1 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -879,7 +879,14 @@
"selectFilesFailed": "Δεν ήταν δυνατό το άνοιγμα της επιλογής αρχείων.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Διακοπή διαμοιρασμού",
- "stopSeedingTooltipBatch": "Διακοπή διαμοιρασμού — επιλεγμένες εργασίες: {{n}} / {{total}}"
+ "stopSeedingTooltipBatch": "Διακοπή διαμοιρασμού — επιλεγμένες εργασίες: {{n}} / {{total}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Ομότιμοι",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index bdb900bb..02f82bc4 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -908,7 +908,14 @@
"moveQueueTop": "Move to Front",
"moveQueueBottom": "Move to Back",
"copyError": "Copy error information",
- "errorReport": "{{name}}\nTask ID: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nTask ID: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}} shown · {{total}} total",
"type": {
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 6d283c12..7a97f3d6 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -920,7 +920,14 @@
"moveQueueTop": "Mover al principio",
"moveQueueBottom": "Mover al final",
"copyError": "Copiar información del error",
- "errorReport": "{{name}}\nID de tarea: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID de tarea: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "Mostradas: {{shown}} · total: {{total}}",
"type": {
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index e8731b2d..5bc2123f 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -879,7 +879,14 @@
"selectFilesFailed": "باز کردن انتخاب فایل ممکن نشد.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "توقف توزیع",
- "stopSeedingTooltipBatch": "توقف توزیع {{n}} مورد از {{total}} مورد انتخاب‌شده"
+ "stopSeedingTooltipBatch": "توقف توزیع {{n}} مورد از {{total}} مورد انتخاب‌شده",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "همتاها",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 3f5e71e6..67bab6a9 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -882,7 +882,14 @@
"selectFilesFailed": "Impossible d’ouvrir la sélection des fichiers.",
"singleTaskFailed": "{{name}} : {{reason}}",
"stopSeeding": "Arrêter le partage",
- "stopSeedingTooltipBatch": "Arrêter le partage de {{n}} des {{total}} tâches sélectionnées"
+ "stopSeedingTooltipBatch": "Arrêter le partage de {{n}} des {{total}} tâches sélectionnées",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Pairs",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 637eb898..289dab50 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -908,7 +908,14 @@
"moveQueueTop": "A sor elejére",
"moveQueueBottom": "A sor végére",
"copyError": "Hibainformáció másolása",
- "errorReport": "{{name}}\nFeladatazonosító: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nFeladatazonosító: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}} megjelenítve · összesen {{total}}",
"type": {
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index 94e332b4..d9c43abe 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -896,7 +896,14 @@
"moveQueueTop": "Pindahkan ke depan",
"moveQueueBottom": "Pindahkan ke belakang",
"copyError": "Salin informasi kesalahan",
- "errorReport": "{{name}}\nID tugas: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID tugas: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}} ditampilkan · {{total}} total",
"type": {
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index 779ffb57..13e4f34e 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -920,7 +920,14 @@
"moveQueueTop": "Sposta all’inizio",
"moveQueueBottom": "Sposta alla fine",
"copyError": "Copia informazioni sull’errore",
- "errorReport": "{{name}}\nID attività: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID attività: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "Visualizzati: {{shown}} · Totale: {{total}}",
"type": {
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 6f47e1be..9af2b29d 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -896,7 +896,14 @@
"moveQueueTop": "先頭に移動",
"moveQueueBottom": "末尾に移動",
"copyError": "エラー情報をコピー",
- "errorReport": "{{name}}\nタスク ID:{{id}}\n{{details}}"
+ "errorReport": "{{name}}\nタスク ID:{{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}} 件表示 · 全 {{total}} 件",
"type": {
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index c5f990cc..ca3148ce 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -896,7 +896,14 @@
"moveQueueTop": "맨 앞으로 이동",
"moveQueueBottom": "맨 뒤로 이동",
"copyError": "오류 정보 복사",
- "errorReport": "{{name}}\n작업 ID: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\n작업 ID: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}}개 표시 · 전체 {{total}}개",
"type": {
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 4a38c3c1..80a7e507 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -879,7 +879,14 @@
"selectFilesFailed": "Kunne ikke åpne filvalget.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Stopp deling",
- "stopSeedingTooltipBatch": "Stopp deling: {{n}} / {{total}} i utvalget"
+ "stopSeedingTooltipBatch": "Stopp deling: {{n}} / {{total}} i utvalget",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Noder",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index fab03e71..9019d5e5 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -879,7 +879,14 @@
"selectFilesFailed": "De bestandsselectie kon niet worden geopend.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Seeden stoppen",
- "stopSeedingTooltipBatch": "Seeden stoppen voor {{n}} van de {{total}} geselecteerde taken"
+ "stopSeedingTooltipBatch": "Seeden stoppen voor {{n}} van de {{total}} geselecteerde taken",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Peers",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index b3215483..d97f092e 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -932,7 +932,14 @@
"moveQueueTop": "Przesuń na początek",
"moveQueueBottom": "Przesuń na koniec",
"copyError": "Kopiuj informacje o błędzie",
- "errorReport": "{{name}}\nID zadania: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID zadania: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "Wyświetlane: {{shown}} · Łącznie: {{total}}",
"type": {
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 5bf728db..1313dbd3 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -920,7 +920,14 @@
"moveQueueTop": "Mover para o início",
"moveQueueBottom": "Mover para o fim",
"copyError": "Copiar informações do erro",
- "errorReport": "{{name}}\nID da tarefa: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID da tarefa: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "Exibidos: {{shown}} · total: {{total}}",
"type": {
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 8008978d..4f8fa679 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -882,7 +882,14 @@
"selectFilesFailed": "Selecția fișierelor nu a putut fi deschisă.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Oprește distribuirea",
- "stopSeedingTooltipBatch": "Oprește distribuirea: {{n}} din selecția totală de {{total}}"
+ "stopSeedingTooltipBatch": "Oprește distribuirea: {{n}} din selecția totală de {{total}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Parteneri",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 81a09c71..dfb85ec6 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -932,7 +932,14 @@
"moveQueueTop": "В начало очереди",
"moveQueueBottom": "В конец очереди",
"copyError": "Копировать сведения об ошибке",
- "errorReport": "{{name}}\nID задачи: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID задачи: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "Показано: {{shown}} · Всего: {{total}}",
"type": {
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 57cb11eb..982e005d 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -876,7 +876,14 @@
"selectFilesFailed": "เปิดหน้าต่างเลือกไฟล์ไม่ได้",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "หยุดปล่อยไฟล์",
- "stopSeedingTooltipBatch": "หยุดปล่อยไฟล์ {{n}} จาก {{total}} งานที่เลือก"
+ "stopSeedingTooltipBatch": "หยุดปล่อยไฟล์ {{n}} จาก {{total}} งานที่เลือก",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "เพียร์",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 5e5f6c4d..0555e634 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -908,7 +908,14 @@
"moveQueueTop": "Başa Taşı",
"moveQueueBottom": "Sona Taşı",
"copyError": "Hata bilgilerini kopyala",
- "errorReport": "{{name}}\nGörev kimliği: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nGörev kimliği: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "{{shown}} gösteriliyor · toplam {{total}}",
"type": {
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 555299ea..c191503d 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -885,7 +885,14 @@
"selectFilesFailed": "Не вдалося відкрити вибір файлів.",
"singleTaskFailed": "{{name}}: {{reason}}",
"stopSeeding": "Зупинити роздавання",
- "stopSeedingTooltipBatch": "Зупинити роздавання для {{n}} з {{total}} вибраних"
+ "stopSeedingTooltipBatch": "Зупинити роздавання для {{n}} з {{total}} вибраних",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"column": {
"connections": "Піри",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 80698632..d2f370fa 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -896,7 +896,14 @@
"moveQueueTop": "Chuyển lên đầu",
"moveQueueBottom": "Chuyển xuống cuối",
"copyError": "Sao chép thông tin lỗi",
- "errorReport": "{{name}}\nID tác vụ: {{id}}\n{{details}}"
+ "errorReport": "{{name}}\nID tác vụ: {{id}}\n{{details}}",
+ "redownload": "Re-download",
+ "redownloadWithDialog": "Re-download with options... (Alt+Click)",
+ "redownloadTooltipBatch": "Re-download {{n}} of {{total}} selected",
+ "redownloadOverwriteTitle": "File Already Exists",
+ "redownloadOverwriteDescription": "“{{name}}” already exists in the download directory. Re-downloading will overwrite or rename it. Do you want to continue?",
+ "redownloadCredentialsExpired": "Original request options have expired. Please review and submit.",
+ "redownloadStarted": "Re-download started"
},
"titleCount": "Đang hiện {{shown}} · Tổng cộng {{total}}",
"type": {
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index cd4addd3..822d9e82 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -896,7 +896,14 @@
"moveQueueTop": "移至队列最前",
"moveQueueBottom": "移至队列最后",
"copyError": "复制错误信息",
- "errorReport": "{{name}}\n任务 ID:{{id}}\n{{details}}"
+ "errorReport": "{{name}}\n任务 ID:{{id}}\n{{details}}",
+ "redownload": "重新下载",
+ "redownloadWithDialog": "编辑参数后重新下载…(Alt+Click)",
+ "redownloadTooltipBatch": "重新下载所选中的 {{n}} / {{total}}",
+ "redownloadOverwriteTitle": "文件已存在",
+ "redownloadOverwriteDescription": "文件“{{name}}”已存在于下载路径中。重新下载将覆盖或重命名该文件,是否继续?",
+ "redownloadCredentialsExpired": "原始下载参数已失效,请确认后提交",
+ "redownloadStarted": "已重新发起下载"
},
"titleCount": "{{shown}} 项 · 共 {{total}}",
"type": {
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 2fe22cba..4052d06a 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -896,7 +896,14 @@
"moveQueueTop": "移至佇列最前",
"moveQueueBottom": "移至佇列最後",
"copyError": "複製錯誤資訊",
- "errorReport": "{{name}}\n任務 ID:{{id}}\n{{details}}"
+ "errorReport": "{{name}}\n任務 ID:{{id}}\n{{details}}",
+ "redownload": "重新下載",
+ "redownloadWithDialog": "編輯參數後重新下載…(Alt+Click)",
+ "redownloadTooltipBatch": "重新下載所選中的 {{n}} / {{total}}",
+ "redownloadOverwriteTitle": "檔案已存在",
+ "redownloadOverwriteDescription": "檔案「{{name}}」已存在於下載路徑中。重新下載將覆蓋或重命名該檔案,是否繼續?",
+ "redownloadCredentialsExpired": "原始下載參數已失效,請確認後提交",
+ "redownloadStarted": "已重新發起下載"
},
"titleCount": "顯示 {{shown}} 項 · 共 {{total}} 項",
"type": {
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index b27b4bb9..f5d079e6 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -98,6 +98,7 @@ export const Queries = {
GetLinuxDefaultAssociations: 'query:getLinuxDefaultAssociations',
GetWindowsDefaultAssociations: 'query:getWindowsDefaultAssociations',
GetApplicationMenu: 'query:getApplicationMenu',
+ CheckTaskFileExists: 'query:checkTaskFileExists',
} as const
export type QueryChannel = (typeof Queries)[keyof typeof Queries]
diff --git a/src/shared/schemas/check-task-file.ts b/src/shared/schemas/check-task-file.ts
new file mode 100644
index 00000000..1455ad53
--- /dev/null
+++ b/src/shared/schemas/check-task-file.ts
@@ -0,0 +1,19 @@
+import { z } from 'zod'
+
+/** Request to check whether a task's output file exists. */
+export const checkTaskFileExistsPayloadSchema = z.object({
+ taskId: z.string().trim().min(1),
+})
+
+export type CheckTaskFileExistsPayload = z.infer<
+ typeof checkTaskFileExistsPayloadSchema
+>
+
+/** Result of checking whether a task's output file exists. */
+export const checkTaskFileExistsResultSchema = z.object({
+ exists: z.boolean(),
+})
+
+export type CheckTaskFileExistsResult = z.infer<
+ typeof checkTaskFileExistsResultSchema
+>
diff --git a/src/shared/types/task-actions.test.ts b/src/shared/types/task-actions.test.ts
index 3f90a440..670b39eb 100644
--- a/src/shared/types/task-actions.test.ts
+++ b/src/shared/types/task-actions.test.ts
@@ -14,6 +14,7 @@ import {
canInspectPieces,
canPause,
canRebuildTaskInputs,
+ canRedownload,
canRemove,
canReseed,
canResume,
@@ -589,4 +590,45 @@ describe('canAttemptRetry', () => {
expect(canRetryMagnetMetadata(task)).toBe(false)
expect(getTaskRetryKind(task)).toBeNull()
})
+
+ describe('canRedownload', () => {
+ it('returns true for completed direct and torrent-like tasks', () => {
+ const httpTask = makeTask({
+ kind: TaskKind.Direct,
+ type: TaskType.Http,
+ status: TaskStatus.Completed,
+ })
+ const btTask = makeTask({
+ kind: TaskKind.Bt,
+ type: TaskType.Bt,
+ status: TaskStatus.Completed,
+ })
+ expect(canRedownload(httpTask)).toBe(true)
+ expect(canRedownload(btTask)).toBe(true)
+ })
+
+ it('returns false for non-completed statuses', () => {
+ expect(canRedownload(makeTask({ status: TaskStatus.Downloading }))).toBe(
+ false
+ )
+ expect(canRedownload(makeTask({ status: TaskStatus.Paused }))).toBe(false)
+ expect(canRedownload(makeTask({ status: TaskStatus.Error }))).toBe(false)
+ expect(canRedownload(makeTask({ status: TaskStatus.Finalizing }))).toBe(
+ false
+ )
+ })
+
+ it('returns false for coordinator media tasks', () => {
+ const muxTask = makeTask({
+ kind: TaskKind.Mux,
+ status: TaskStatus.Completed,
+ })
+ const hlsTask = makeTask({
+ kind: TaskKind.Hls,
+ status: TaskStatus.Completed,
+ })
+ expect(canRedownload(muxTask)).toBe(false)
+ expect(canRedownload(hlsTask)).toBe(false)
+ })
+ })
})
diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.ts
index 18aa9c81..5632990e 100644
--- a/src/shared/types/task-actions.ts
+++ b/src/shared/types/task-actions.ts
@@ -122,6 +122,15 @@ export function canReseed(t: DownloadTask): boolean {
)
}
+/** Completed regular downloads can be downloaded again. */
+export function canRedownload(t: DownloadTask): boolean {
+ return (
+ !hasLegacyImport(t) &&
+ !isMediaKind(t.kind) &&
+ t.status === TaskStatus.Completed
+ )
+}
+
export function canRetry(t: DownloadTask): boolean {
return (
!hasLegacyImport(t) &&
diff --git a/tests/scripts/dev-runner.test.ts b/tests/scripts/dev-runner.test.ts
new file mode 100644
index 00000000..4e924436
--- /dev/null
+++ b/tests/scripts/dev-runner.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment node
+import { EventEmitter } from 'node:events'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ build: vi.fn(),
+ createServer: vi.fn(),
+ process: { env: {}, on: vi.fn(), exit: vi.fn() },
+}))
+
+vi.mock('cross-spawn', () => ({ default: mocks.spawn }))
+vi.mock('vite', () => ({
+ build: mocks.build,
+ createServer: mocks.createServer,
+}))
+vi.mock('node:process', () => ({ default: mocks.process }))
+vi.mock('node:module', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('node:module')>()),
+ createRequire: () => () => '/test/electron',
+}))
+
+const builds = new Map<string, () => void>()
+let builtinProcess: EventEmitter
+let electronProcess: EventEmitter & {
+ connected: boolean
+ send: ReturnType<typeof vi.fn>
+}
+
+beforeEach(() => {
+ vi.resetModules()
+ vi.resetAllMocks()
+ vi.useFakeTimers()
+ builds.clear()
+ builtinProcess = new EventEmitter()
+ electronProcess = Object.assign(new EventEmitter(), {
+ connected: true,
+ send: vi.fn(),
+ })
+ mocks.spawn.mockImplementation((_command, args) =>
+ args.includes('build:builtin') ? builtinProcess : electronProcess
+ )
+ mocks.createServer.mockResolvedValue({ listen: vi.fn() })
+ mocks.build.mockImplementation(async (options) => {
+ builds.set(
+ path.basename(options.configFile),
+ options.plugins[0].writeBundle
+ )
+ })
+})
+
+afterEach(() => {
+ vi.clearAllTimers()
+ vi.useRealTimers()
+})
+
+describe('Electron development runner', () => {
+ it('waits for the plugin worker build and restarts Electron when it changes', async () => {
+ // @ts-expect-error — .mjs without types
+ await import('../../scripts/dev.mjs')
+ expect(mocks.spawn).toHaveBeenCalledTimes(1)
+ builtinProcess.emit('exit', 0)
+ await vi.waitFor(() => expect(mocks.build).toHaveBeenCalledTimes(3))
+
+ builds.get('vite.main.config.ts')!()
+ builds.get('vite.preload.config.ts')!()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(mocks.spawn).toHaveBeenCalledTimes(1)
+
+ // A rebuild of an already-ready bundle cannot bypass the startup gate.
+ builds.get('vite.main.config.ts')!()
+ await vi.advanceTimersByTimeAsync(200)
+ expect(mocks.spawn).toHaveBeenCalledTimes(1)
+
+ builds.get('vite.worker.config.ts')!()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(mocks.spawn).toHaveBeenCalledTimes(2)
+ expect(mocks.spawn).toHaveBeenLastCalledWith(
+ '/test/electron',
+ ['.'],
+ expect.any(Object)
+ )
+
+ builds.get('vite.worker.config.ts')!()
+ await vi.advanceTimersByTimeAsync(200)
+ expect(electronProcess.send).toHaveBeenCalledWith(
+ 'motrix:dev-shutdown',
+ expect.any(Function)
+ )
+ electronProcess.emit('exit', 0)
+ expect(mocks.spawn).toHaveBeenCalledTimes(3)
+ })
+})
diff --git a/tests/scripts/e2e-global-setup.test.ts b/tests/scripts/e2e-global-setup.test.ts
index ccf5f3f2..479c5857 100644
--- a/tests/scripts/e2e-global-setup.test.ts
+++ b/tests/scripts/e2e-global-setup.test.ts
@@ -20,6 +20,7 @@ const exists = vi.mocked(existsSync)
const artifacts = [
'dist/main/index.cjs',
'dist/preload/preload.cjs',
+ 'dist/core/plugin/host/quick-js-worker.cjs',
'dist/renderer/index.html',
].map((artifact) => path.join(process.cwd(), artifact))