Skip to content

A full-featured download manager.

fix(downloads): harden interrupted task recovery (#1959)

Dr_rOot48fdc3b9fa4b
diff --git a/e2e/fixtures/http-server.ts b/e2e/fixtures/http-server.ts
index 6618716f..92a9acaa 100644
--- a/e2e/fixtures/http-server.ts
+++ b/e2e/fixtures/http-server.ts
@@ -1,19 +1,49 @@
import crypto from 'node:crypto'
+import { readFile } from 'node:fs/promises'
import http from 'node:http'
import type { AddressInfo } from 'node:net'
+export interface HttpRequestRecord {
+ sequence: number
+ pathname: string
+ method: string
+ range: string | null
+ ifRange: string | null
+ status: number
+ etag: string
+ resourceVersion: number
+}
+
+export interface HttpResourceSnapshot {
+ etag: string
+ sha256: string
+ version: number
+}
+
export interface HttpFixture {
baseUrl: string
fileUrl: string
fileSize: number
+ /** SHA-256 of the resource currently served by `fileUrl`. */
+ readonly payloadSha256: string
+ requests: () => readonly HttpRequestRecord[]
+ resetRequests: () => void
+ setRangeSupport: (supported: boolean) => void
+ /** Swap in a different same-size resource, simulating a changed origin. */
+ changeResource: (etag?: string) => HttpResourceSnapshot
+ verifyFile: (filePath: string) => Promise<boolean>
close: () => Promise<void>
}
-interface StartOptions {
+export interface HttpFixtureOptions {
/** Size of the served test file in bytes. Defaults to 1MB. */
size?: number
/** Path the file is served at. Defaults to /test.bin. */
pathname?: string
+ /** Fixed ETag for the initial resource. Quotes are added when omitted. */
+ etag?: string
+ /** Whether byte ranges are honored. Defaults to true. */
+ rangeSupport?: boolean
/**
* Optional throttle. When set, the response body is streamed in
* ~100ms slices at the target rate. Useful for lifecycle tests
@@ -24,62 +54,150 @@ interface StartOptions {
throttleBytesPerSecond?: number
}
+function quoteEtag(value: string): string {
+ const trimmed = value.trim()
+ if (/^(?:W\/)?".*"$/.test(trimmed)) return trimmed
+ return `"${trimmed}"`
+}
+
+function sha256(value: Uint8Array): string {
+ return crypto.createHash('sha256').update(value).digest('hex')
+}
+
+function firstHeader(value: string | string[] | undefined): string | null {
+ if (Array.isArray(value)) return value[0] ?? null
+ return value ?? null
+}
+
/**
* Starts a hermetic HTTP server on a random localhost port that serves
- * a deterministic byte buffer. Lets add-download e2e specs avoid
- * hitting the public internet (and the flake / privacy concerns that
- * come with it).
+ * a deterministic-size byte buffer. Besides serving Range requests, the
+ * fixture records the protocol decisions made for every request so recovery
+ * specs can distinguish a real resume from a fresh download.
*
* The buffer is generated fresh per call so no two fixtures hash to
* the same file — useful when an aria2 cache or BT swarm test would
* otherwise dedupe.
*/
export async function startHttpFixture(
- opts: StartOptions = {}
+ opts: HttpFixtureOptions = {}
): Promise<HttpFixture> {
const size = opts.size ?? 1024 * 1024
const pathname = opts.pathname ?? '/test.bin'
- const payload = crypto.randomBytes(size)
+ let payload = crypto.randomBytes(size)
+ let etag = quoteEtag(opts.etag ?? `motrix-e2e-${crypto.randomUUID()}`)
+ let resourceVersion = 1
+ let rangeSupport = opts.rangeSupport ?? true
+ let sequence = 0
+ const requests: HttpRequestRecord[] = []
+
+ const record = (
+ req: http.IncomingMessage,
+ status: number,
+ responseEtag = etag,
+ responseVersion = resourceVersion
+ ): void => {
+ requests.push({
+ sequence: ++sequence,
+ pathname: req.url ?? '',
+ method: req.method ?? 'GET',
+ range: req.headers.range ?? null,
+ ifRange: firstHeader(req.headers['if-range']),
+ status,
+ etag: responseEtag,
+ resourceVersion: responseVersion,
+ })
+ }
+
+ const commonHeaders = (
+ contentLength: number,
+ responseEtag: string,
+ supportsRanges: boolean
+ ): Record<string, string> => ({
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Length': String(contentLength),
+ 'Accept-Ranges': supportsRanges ? 'bytes' : 'none',
+ ETag: responseEtag,
+ })
const throttle = opts.throttleBytesPerSecond
const server = http.createServer(async (req, res) => {
+ // Capture an immutable response snapshot: changeResource() may be called
+ // while a throttled response is still draining.
+ const responsePayload = payload
+ const responseEtag = etag
+ const responseVersion = resourceVersion
+ const supportsRanges = rangeSupport
+
if (req.url !== pathname) {
+ record(req, 404, responseEtag, responseVersion)
res.writeHead(404).end()
return
}
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ record(req, 405, responseEtag, responseVersion)
+ res.writeHead(405, { Allow: 'GET, HEAD' }).end()
+ return
+ }
+
+ const rangeHeader = req.headers.range
+ const rangeMatch = rangeHeader?.match(/^bytes=(\d+)-(\d*)$/)
+ const ifRange = firstHeader(req.headers['if-range'])
+ const ifRangeMatches = ifRange === null || ifRange === responseEtag
+ const honorRange = supportsRanges && Boolean(rangeMatch) && ifRangeMatches
+
+ if (supportsRanges && rangeHeader && !rangeMatch) {
+ record(req, 416, responseEtag, responseVersion)
+ res.writeHead(416, {
+ 'Content-Range': `bytes */${responsePayload.length}`,
+ 'Accept-Ranges': 'bytes',
+ ETag: responseEtag,
+ })
+ res.end()
+ return
+ }
- const rangeMatch = req.headers.range?.match(/^bytes=(\d+)-(\d*)$/)
- const rangeStart = rangeMatch ? Number(rangeMatch[1]) : 0
+ const rangeStart = honorRange && rangeMatch ? Number(rangeMatch[1]) : 0
const requestedEnd =
- rangeMatch?.[2] === undefined || rangeMatch[2] === ''
- ? payload.length - 1
- : Number(rangeMatch[2])
+ honorRange && rangeMatch && rangeMatch[2] !== ''
+ ? Number(rangeMatch[2])
+ : responsePayload.length - 1
if (
- !Number.isSafeInteger(rangeStart) ||
- !Number.isSafeInteger(requestedEnd) ||
- rangeStart < 0 ||
- rangeStart >= payload.length ||
- requestedEnd < rangeStart
+ honorRange &&
+ (!Number.isSafeInteger(rangeStart) ||
+ !Number.isSafeInteger(requestedEnd) ||
+ rangeStart < 0 ||
+ rangeStart >= responsePayload.length ||
+ requestedEnd < rangeStart)
) {
+ record(req, 416, responseEtag, responseVersion)
res.writeHead(416, {
- 'Content-Range': `bytes */${payload.length}`,
+ 'Content-Range': `bytes */${responsePayload.length}`,
+ 'Accept-Ranges': 'bytes',
+ ETag: responseEtag,
})
res.end()
return
}
- const rangeEnd = Math.min(requestedEnd, payload.length - 1)
- const body = payload.subarray(rangeStart, rangeEnd + 1)
- res.writeHead(rangeMatch ? 206 : 200, {
- 'Content-Type': 'application/octet-stream',
- 'Content-Length': String(body.length),
- 'Accept-Ranges': 'bytes',
- ...(rangeMatch
+ const rangeEnd = honorRange
+ ? Math.min(requestedEnd, responsePayload.length - 1)
+ : responsePayload.length - 1
+ const body = responsePayload.subarray(rangeStart, rangeEnd + 1)
+ const status = honorRange ? 206 : 200
+ record(req, status, responseEtag, responseVersion)
+ res.writeHead(status, {
+ ...commonHeaders(body.length, responseEtag, supportsRanges),
+ ...(honorRange
? {
- 'Content-Range': `bytes ${rangeStart}-${rangeEnd}/${payload.length}`,
+ 'Content-Range': `bytes ${rangeStart}-${rangeEnd}/${responsePayload.length}`,
}
: {}),
})
+ if (req.method === 'HEAD') {
+ res.end()
+ return
+ }
if (!throttle || throttle <= 0) {
res.end(body)
return
@@ -106,7 +224,7 @@ export async function startHttpFixture(
}
offset = end
if (offset < body.length && !res.destroyed) {
- await new Promise((r) => setTimeout(r, sliceMs))
+ await new Promise((resolve) => setTimeout(resolve, sliceMs))
}
}
if (!res.destroyed) res.end()
@@ -116,13 +234,37 @@ export async function startHttpFixture(
const addr = server.address() as AddressInfo
const baseUrl = `http://127.0.0.1:${addr.port}`
- return {
+ const fixture: HttpFixture = {
baseUrl,
fileUrl: `${baseUrl}${pathname}`,
fileSize: size,
+ get payloadSha256() {
+ return sha256(payload)
+ },
+ requests: () => requests.map((entry) => ({ ...entry })),
+ resetRequests: () => {
+ requests.length = 0
+ },
+ setRangeSupport: (supported) => {
+ rangeSupport = supported
+ },
+ changeResource: (nextEtag) => {
+ payload = crypto.randomBytes(size)
+ resourceVersion++
+ etag = quoteEtag(nextEtag ?? `motrix-e2e-${crypto.randomUUID()}`)
+ return { etag, sha256: sha256(payload), version: resourceVersion }
+ },
+ verifyFile: async (filePath) => {
+ const contents = await readFile(filePath)
+ return contents.length === size && sha256(contents) === sha256(payload)
+ },
close: () =>
new Promise<void>((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()))
+ // A killed aria2 can leave a throttled HTTP socket open until its
+ // kernel close is observed. Tear it down so fixture cleanup is bounded.
+ server.closeAllConnections()
}),
}
+ return fixture
}
diff --git a/e2e/task-recovery-no-pause.spec.ts b/e2e/task-recovery-no-pause.spec.ts
index fba5acdb..5ffed1fc 100644
--- a/e2e/task-recovery-no-pause.spec.ts
+++ b/e2e/task-recovery-no-pause.spec.ts
@@ -1,4 +1,7 @@
+import { readFile } from 'node:fs/promises'
+import path from 'node:path'
import type { ElectronApplication, Page } from '@playwright/test'
+import { Aria2ProcessInspector } from '../src/core/engine/aria2/aria2-process-inspector'
import {
expect,
findAddTaskWindow,
@@ -13,6 +16,109 @@ interface Task {
id: string
status: string
uris: string[]
+ downloadedBytes: number
+ finalPath?: string
+}
+
+interface Aria2OwnerRecord {
+ version: 1
+ pid: number
+ binaryPath: string
+ rpcPort: number
+ argumentMarkers: string[]
+ startedAt: number
+}
+
+function isOwnerRecord(value: unknown): value is Aria2OwnerRecord {
+ if (!value || typeof value !== 'object') return false
+ const record = value as Record<string, unknown>
+ return (
+ record.version === 1 &&
+ Number.isSafeInteger(record.pid) &&
+ Number(record.pid) > 0 &&
+ typeof record.binaryPath === 'string' &&
+ record.binaryPath.length > 0 &&
+ Number.isSafeInteger(record.rpcPort) &&
+ Number(record.rpcPort) > 0 &&
+ Array.isArray(record.argumentMarkers) &&
+ record.argumentMarkers.length >= 2 &&
+ record.argumentMarkers.every(
+ (marker) => typeof marker === 'string' && marker.startsWith('--')
+ ) &&
+ Number.isSafeInteger(record.startedAt) &&
+ Number(record.startedAt) > 0
+ )
+}
+
+async function readManagedAria2(
+ userDataDir: string,
+ rpcPort: number
+): Promise<Aria2OwnerRecord> {
+ const raw = await readFile(path.join(userDataDir, 'aria2-owner.json'), 'utf8')
+ const parsed: unknown = JSON.parse(raw)
+ if (!isOwnerRecord(parsed)) {
+ throw new Error('aria2-owner.json did not contain a valid owner record')
+ }
+ expect(parsed.rpcPort).toBe(rpcPort)
+ expect(path.basename(parsed.binaryPath)).toMatch(/^aria2c(?:\.exe)?$/i)
+ expect(parsed.pid).not.toBe(process.pid)
+ expect(
+ parsed.argumentMarkers.some((marker) => marker.startsWith('--conf-path='))
+ ).toBe(true)
+ expect(
+ parsed.argumentMarkers.some((marker) =>
+ marker.startsWith('--save-session=')
+ )
+ ).toBe(true)
+ return parsed
+}
+
+function samePath(left: string, right: string): boolean {
+ const normalize = (value: string) => {
+ const normalized = path.normalize(value)
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized
+ }
+ return normalize(left) === normalize(right)
+}
+
+async function assertManagedAria2(
+ inspector: Aria2ProcessInspector,
+ owner: Aria2OwnerRecord
+): Promise<void> {
+ const inspected = await inspector.inspectListeningPort(owner.rpcPort)
+ expect(inspected?.pid).toBe(owner.pid)
+ expect(inspected?.name).toMatch(/^aria2c(?:\.exe)?$/i)
+ if (inspected?.executablePath) {
+ expect(samePath(inspected.executablePath, owner.binaryPath)).toBe(true)
+ }
+ expect(inspected?.commandLine).toBeTruthy()
+ for (const marker of owner.argumentMarkers) {
+ expect(inspected?.commandLine).toContain(marker)
+ }
+}
+
+async function terminateManagedAria2(
+ inspector: Aria2ProcessInspector,
+ owner: Aria2OwnerRecord
+): Promise<void> {
+ // Re-inspect immediately before signaling. The trusted test-owned record,
+ // listening port, executable and launch markers must still identify the
+ // same process, preventing a stale PID from terminating an unrelated task.
+ await assertManagedAria2(inspector, owner)
+ // Preserve aria2's own recovery checkpoint while still terminating the
+ // separately managed process. Electron itself was hard-killed above, so no
+ // Motrix shutdown/pause hook participates in this path.
+ process.kill(owner.pid, 'SIGTERM')
+ await expect
+ .poll(() => inspector.isAlive(owner.pid), { timeout: 10_000 })
+ .toBe(false)
+ await expect
+ .poll(
+ async () =>
+ (await inspector.inspectListeningPort(owner.rpcPort))?.pid ?? null,
+ { timeout: 10_000 }
+ )
+ .toBeNull()
}
async function readFirstTask(page: Page): Promise<Task | undefined> {
@@ -31,30 +137,25 @@ async function readFirstTask(page: Page): Promise<Task | undefined> {
}
test.describe('task recovery — no pause', () => {
- // Validates the contract added by createAndPersist's
- // `await sessionManager.requestSave()`: when the IPC handler
- // returns, the task identity row is durable. A SIGKILL right
- // after must NOT cause the relaunch to mint a fresh motrix id
- // for the same gid via the "discovered from engine" path.
- test('task identity survives an immediate hard kill', async ({
+ test('active bytes resume after Electron is hard-killed and managed aria2 terminates', async ({
userDataDir,
- }) => {
- const port1 = await getFreePort()
+ }, testInfo) => {
+ const rpcPort = await getFreePort()
+ const inspector = new Aria2ProcessInspector()
let fx: HttpFixture | undefined
let app: ElectronApplication | undefined
try {
- // 256 KB / 128 KB/s ≈ 2s — small + slow enough that the
- // download is still in-flight when we SIGKILL (the create-time
- // durability guarantee is what we want to exercise), but fast
- // enough that the orphan aria2 from launch 1 doesn't keep the
- // throttled connection alive long after launch 2's relaunch.
+ // Below aria2's default split threshold this remains a single response;
+ // 2 MB at 256 KB/s gives polling time to persist non-zero progress while
+ // keeping both launch legs within the E2E timeout.
fx = await startHttpFixture({
- size: 256 * 1024,
- throttleBytesPerSecond: 128 * 1024,
+ size: 2 * 1024 * 1024,
+ etag: 'motrix-recovery-v1',
+ throttleBytesPerSecond: 256 * 1024,
})
- app = await launchMotrix({ userDataDir, rpcPort: port1 })
+ app = await launchMotrix({ userDataDir, rpcPort })
let main = await app.firstWindow()
await main.waitForLoadState('domcontentloaded')
await waitForEngineReady(main)
@@ -62,46 +163,95 @@ test.describe('task recovery — no pause', () => {
await main.getByRole('button', { name: 'New task' }).click()
const addTaskPage = await findAddTaskWindow(app)
await addTaskPage.getByRole('textbox', { name: 'URLs' }).fill(fx.fileUrl)
- // Click submit. The renderer awaits Commands.CreateDownload,
- // which on the main side awaits requestSave. By the time the
- // form's promise resolves, motrix.db has the row.
await addTaskPage.getByRole('button', { name: 'Download' }).click()
-
- // Wait for the AddTaskWindow to auto-close (its own signal that
- // CreateDownload returned successfully → durability guaranteed).
await addTaskPage.waitForEvent('close', { timeout: 5_000 })
await main.getByRole('link', { name: 'Downloads' }).click()
+ await expect
+ .poll(async () => (await readFirstTask(main))?.downloadedBytes ?? 0, {
+ timeout: 15_000,
+ })
+ // Cross at least one aria2 piece boundary. Killing inside the first
+ // piece legitimately causes a resumed request to begin at byte zero,
+ // which would not prove that the checkpoint retained any body bytes.
+ .toBeGreaterThanOrEqual(1024 * 1024 + 128 * 1024)
+
const taskBefore = await readFirstTask(main)
expect(taskBefore?.id).toBeTruthy()
+ expect(taskBefore?.status).toBe('downloading')
+ expect(taskBefore?.downloadedBytes).toBeGreaterThan(0)
+
+ const owner = await readManagedAria2(userDataDir, rpcPort)
+ await assertManagedAria2(inspector, owner)
- // SIGKILL immediately — no pause, no extra wait. This is the
- // "user clicked Add then pulled the plug" scenario.
+ // Kill Electron without its shutdown hooks, then explicitly terminate the
+ // exact managed aria2 child. Relaunching on the same RPC port is the key
+ // regression guard: a surviving orphan can no longer masquerade as a
+ // successful recovery.
app.process().kill('SIGKILL')
await app.waitForEvent('close', { timeout: 5_000 }).catch(() => {})
app = undefined
+ await terminateManagedAria2(inspector, owner)
- const port2 = await getFreePort()
- app = await launchMotrix({ userDataDir, rpcPort: port2 })
+ // Only requests received after both processes died count as recovery
+ // traffic; the original throttled socket may close asynchronously.
+ fx.resetRequests()
+
+ app = await launchMotrix({ userDataDir, rpcPort })
main = await app.firstWindow()
await main.waitForLoadState('domcontentloaded')
await waitForEngineReady(main)
-
await main.getByRole('link', { name: 'Downloads' }).click()
- // Critical assertion: SAME task id. If create-time save raced
- // the SIGKILL, polling would resurrect the gid as a fresh task
- // with a different motrix id and this would fail.
+
await expect
.poll(async () => (await readFirstTask(main))?.id, { timeout: 15_000 })
.toBe(taskBefore?.id)
+ await expect
+ .poll(async () => (await readFirstTask(main))?.downloadedBytes ?? 0, {
+ timeout: 20_000,
+ })
+ .toBeGreaterThan(taskBefore?.downloadedBytes ?? 0)
+
+ // Range semantics after relaunch are required even when aria2 has to
+ // re-fetch the interrupted leading piece from its boundary at byte zero.
+ // The byte-growth and final digest assertions below cover the rest of
+ // the resume contract without depending on aria2's internal piece size.
+ await expect
+ .poll(
+ () =>
+ fx?.requests().filter((request) => request.method === 'GET')
+ .length ?? 0,
+ { timeout: 15_000 }
+ )
+ .toBeGreaterThan(0)
+ const recoveryRequests = fx.requests()
+ expect(
+ recoveryRequests.some(
+ (request) => request.status === 206 && request.range !== null
+ ),
+ `expected Range recovery traffic, received:\n${JSON.stringify(recoveryRequests, null, 2)}`
+ ).toBe(true)
+
+ await expect
+ .poll(async () => (await readFirstTask(main))?.status, {
+ timeout: 30_000,
+ })
+ .toBe('completed')
const taskAfter = await readFirstTask(main)
expect(taskAfter?.uris).toEqual(taskBefore?.uris)
- expect(taskAfter?.status).not.toBe('error')
- expect(taskAfter?.status).not.toBe('removed')
+ expect(taskAfter?.downloadedBytes).toBe(fx.fileSize)
+ expect(taskAfter?.finalPath).toBeTruthy()
+ expect(await fx.verifyFile(taskAfter?.finalPath ?? '')).toBe(true)
} finally {
if (app) await app.close().catch(() => {})
- if (fx) await fx.close()
+ if (fx) {
+ await testInfo.attach('recovery-http-requests', {
+ body: Buffer.from(JSON.stringify(fx.requests(), null, 2)),
+ contentType: 'application/json',
+ })
+ await fx.close().catch(() => {})
+ }
}
})
})
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.ts
index 8050662b..0b5b87ca 100644
--- a/src/core/engine/aria2/aria2-adapter.test.ts
+++ b/src/core/engine/aria2/aria2-adapter.test.ts
@@ -398,6 +398,86 @@ describe('Aria2Adapter', () => {
})
})
+ it('maps checkpoint recovery to native checkpoint-only aria2 options', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockResolvedValue('checkpoint-gid')
+ const adapter = new Aria2Adapter(rpc)
+
+ await adapter.createDownload({
+ uris: ['http://example.com/f.zip'],
+ saveDir: '/tmp',
+ resumePolicy: 'checkpoint',
+ })
+
+ expect(rpc.addUri).toHaveBeenCalledWith(
+ ['http://example.com/f.zip'],
+ expect.objectContaining({
+ 'always-resume': 'true',
+ continue: 'false',
+ })
+ )
+ })
+
+ it('maps sequential-prefix recovery to aria2 continue options', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockResolvedValue('prefix-gid')
+ const adapter = new Aria2Adapter(rpc)
+
+ await adapter.createDownload({
+ uris: ['http://example.com/f.zip'],
+ saveDir: '/tmp',
+ resumePolicy: 'sequential-prefix',
+ })
+
+ expect(rpc.addUri).toHaveBeenCalledWith(
+ ['http://example.com/f.zip'],
+ expect.objectContaining({
+ 'always-resume': 'true',
+ continue: 'true',
+ })
+ )
+ })
+
+ it('applies recovery safety options after extra engine options', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockResolvedValue('safe-gid')
+ const adapter = new Aria2Adapter(rpc)
+
+ await adapter.createDownload({
+ uris: ['http://example.com/f.zip'],
+ saveDir: '/tmp',
+ resumePolicy: 'sequential-prefix',
+ extraEngineOptions: {
+ 'always-resume': 'false',
+ continue: 'false',
+ },
+ })
+
+ expect(rpc.addUri).toHaveBeenCalledWith(
+ ['http://example.com/f.zip'],
+ expect.objectContaining({
+ 'always-resume': 'true',
+ continue: 'true',
+ })
+ )
+ })
+
+ it('does not inject resume options for ordinary new downloads', async () => {
+ const rpc = createMockRpc()
+ vi.mocked(rpc.addUri).mockResolvedValue('new-gid')
+ const adapter = new Aria2Adapter(rpc)
+
+ await adapter.createDownload({
+ uris: ['http://example.com/f.zip'],
+ saveDir: '/tmp',
+ resumePolicy: 'none',
+ })
+
+ const options = vi.mocked(rpc.addUri).mock.calls[0][1]
+ expect(options).not.toHaveProperty('always-resume')
+ expect(options).not.toHaveProperty('continue')
+ })
+
it('forwards pause:true as aria2 pause option', async () => {
const rpc = createMockRpc()
vi.mocked(rpc.addUri).mockResolvedValue('gid789')
diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.ts
index 1a1acc65..b9707bc2 100644
--- a/src/core/engine/aria2/aria2-adapter.ts
+++ b/src/core/engine/aria2/aria2-adapter.ts
@@ -300,6 +300,18 @@ export class Aria2Adapter implements EngineAdapter {
options.gid = requestedGid
}
+ // Resume controls are product safety invariants, not passthrough options.
+ // Apply them last so a replay recipe cannot silently weaken or broaden
+ // the recovery policy selected by SessionManager.
+ const resumePolicy = params.resumePolicy ?? 'none'
+ if (resumePolicy === 'checkpoint') {
+ options['always-resume'] = 'true'
+ options.continue = 'false'
+ } else if (resumePolicy === 'sequential-prefix') {
+ options['always-resume'] = 'true'
+ options.continue = 'true'
+ }
+
const actualGid = await this.addUriWithConnectionFallback(
params.uris,
options
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.ts
index f8c7ad07..5398b381 100644
--- a/src/core/engine/aria2/aria2-config-builder.test.ts
+++ b/src/core/engine/aria2/aria2-config-builder.test.ts
@@ -2,10 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// ─── Mock node:fs/promises ───────────────────────────────────
-const { mockAccess, mockCopyFile, mockMkdir } = vi.hoisted(() => ({
+const { mockAccess, mockCopyFile, mockMkdir, mockRename } = vi.hoisted(() => ({
mockAccess: vi.fn(),
mockCopyFile: vi.fn(),
mockMkdir: vi.fn(),
+ mockRename: vi.fn(),
}))
vi.mock('node:fs/promises', () => ({
@@ -13,10 +14,12 @@ vi.mock('node:fs/promises', () => ({
access: mockAccess,
copyFile: mockCopyFile,
mkdir: mockMkdir,
+ rename: mockRename,
},
access: mockAccess,
copyFile: mockCopyFile,
mkdir: mockMkdir,
+ rename: mockRename,
}))
import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'
@@ -80,6 +83,68 @@ describe('Aria2ConfigBuilder', () => {
})
})
+ describe('hasSavedSession', () => {
+ it('returns true when the text session exists', async () => {
+ mockAccess.mockResolvedValue(undefined)
+
+ await expect(builder.hasSavedSession()).resolves.toBe(true)
+ expect(mockAccess).toHaveBeenCalledWith(
+ '/home/user/.config/motrix/aria2.session'
+ )
+ })
+
+ it('returns false instead of throwing when the text session is unavailable', async () => {
+ mockAccess.mockRejectedValue(new Error('ENOENT: no such file'))
+
+ await expect(builder.hasSavedSession()).resolves.toBe(false)
+ })
+ })
+
+ describe('SQLite recovery paths', () => {
+ it('resolves the configured database path or the user-data default', () => {
+ expect(builder.resolveSqliteDbPath({ sqlite3DbPath: '' })).toBe(
+ '/home/user/.config/motrix/aria2.db'
+ )
+ expect(
+ builder.resolveSqliteDbPath({ sqlite3DbPath: '/custom/tasks.db' })
+ ).toBe('/custom/tasks.db')
+ })
+
+ it('quarantines the database and existing WAL companions without deleting them', async () => {
+ mockRename
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(
+ Object.assign(new Error('missing'), { code: 'ENOENT' })
+ )
+ .mockRejectedValueOnce(
+ Object.assign(new Error('missing'), { code: 'ENOENT' })
+ )
+
+ await expect(
+ builder.quarantineSqliteDatabase({ sqlite3DbPath: '' }, 'incident-1')
+ ).resolves.toEqual({
+ databasePath: '/home/user/.config/motrix/aria2.db',
+ quarantineBasePath:
+ '/home/user/.config/motrix/aria2.db.corrupt-incident-1',
+ moved: [
+ '/home/user/.config/motrix/aria2.db.corrupt-incident-1',
+ '/home/user/.config/motrix/aria2.db.corrupt-incident-1-wal',
+ ],
+ })
+ expect(mockRename).toHaveBeenNthCalledWith(
+ 1,
+ '/home/user/.config/motrix/aria2.db',
+ '/home/user/.config/motrix/aria2.db.corrupt-incident-1'
+ )
+ expect(mockRename).toHaveBeenNthCalledWith(
+ 2,
+ '/home/user/.config/motrix/aria2.db-wal',
+ '/home/user/.config/motrix/aria2.db.corrupt-incident-1-wal'
+ )
+ })
+ })
+
describe('buildArgs', () => {
it('builds args array with default settings', () => {
const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {
@@ -123,6 +188,44 @@ describe('Aria2ConfigBuilder', () => {
)
})
+ it('loads the text session only when requested by the supervisor', () => {
+ const withoutInput = builder.buildArgs(
+ DEFAULT_ENGINE_SETTINGS,
+ false,
+ null,
+ { download: 0, upload: 0 }
+ )
+ const withInput = builder.buildArgs(
+ DEFAULT_ENGINE_SETTINGS,
+ false,
+ null,
+ { download: 0, upload: 0 },
+ true
+ )
+
+ expect(withoutInput).not.toContain(
+ '--input-file=/home/user/.config/motrix/aria2.session'
+ )
+ expect(withInput).toContain(
+ '--input-file=/home/user/.config/motrix/aria2.session'
+ )
+ })
+
+ it('never combines text-session loading with active SQLite persistence', () => {
+ const args = builder.buildArgs(
+ makeEngineSettings({ sqlite3Persistence: true }),
+ true,
+ null,
+ { download: 0, upload: 0 },
+ true
+ )
+
+ expect(args).toContain('--enable-sqlite3-persistence=true')
+ expect(args).not.toContain(
+ '--input-file=/home/user/.config/motrix/aria2.session'
+ )
+ })
+
it('keeps DHT state inside the writable user config directory', () => {
const args = builder.buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {
download: 0,
diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.ts
index 6a3c7dfa..2ee65242 100644
--- a/src/core/engine/aria2/aria2-config-builder.ts
+++ b/src/core/engine/aria2/aria2-config-builder.ts
@@ -1,4 +1,5 @@
-import { access, copyFile, mkdir } from 'node:fs/promises'
+import { randomUUID } from 'node:crypto'
+import { access, copyFile, mkdir, rename } from 'node:fs/promises'
import path from 'node:path'
import { proxyToAria2Options } from '@core/proxy/serializers'
import type { EngineSettings, ProxySettings } from '@shared/types/settings'
@@ -34,6 +35,60 @@ export class Aria2ConfigBuilder {
}
}
+ /**
+ * Return whether the standard aria2 text session is available for startup.
+ * Any access failure is treated as unavailable so a missing or unreadable
+ * fallback file never prevents the engine from launching.
+ */
+ async hasSavedSession(): Promise<boolean> {
+ try {
+ await access(this.saveSessionPath)
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ resolveSqliteDbPath(settings: Pick<EngineSettings, 'sqlite3DbPath'>): string {
+ return settings.sqlite3DbPath?.trim() || this.defaultDbPath
+ }
+
+ /**
+ * Move a corrupt aria2 persistence database and its SQLite companions aside.
+ * The files remain recoverable for diagnostics and are never overwritten.
+ */
+ async quarantineSqliteDatabase(
+ settings: Pick<EngineSettings, 'sqlite3DbPath'>,
+ token = `${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID()}`
+ ): Promise<{
+ databasePath: string
+ quarantineBasePath: string
+ moved: string[]
+ }> {
+ const databasePath = this.resolveSqliteDbPath(settings)
+ const quarantineBasePath = `${databasePath}.corrupt-${token}`
+ const moved: string[] = []
+ for (const suffix of ['', '-wal', '-shm', '-journal']) {
+ const source = `${databasePath}${suffix}`
+ const destination = `${quarantineBasePath}${suffix}`
+ try {
+ await rename(source, destination)
+ moved.push(destination)
+ } catch (error) {
+ if (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'ENOENT'
+ ) {
+ continue
+ }
+ throw error
+ }
+ }
+ return { databasePath, quarantineBasePath, moved }
+ }
+
/**
* @param settings — current engine settings (read for L2/L3 values).
* @param hasSqlitePersistence — whether the binary supports
@@ -48,12 +103,16 @@ export class Aria2ConfigBuilder {
* @param effective — effective speed limits from SpeedLimitController
* (bytes/sec; 0 = unlimited). On cold start the EngineSupervisor passes
* the controller's computed value, or { 0, 0 } if no provider is wired.
+ * @param loadTextSession — load the standard aria2.session fallback. The
+ * supervisor enables this only when SQLite persistence is inactive and
+ * the file was verified to exist.
*/
buildArgs(
settings: EngineSettings,
hasSqlitePersistence = true,
proxy: ProxySettings | null | undefined,
- effective: { download: number; upload: number }
+ effective: { download: number; upload: number },
+ loadTextSession = false
): string[] {
// Layer order in the produced argv:
// L4 conf-path → L2 engine bindings → L3 user-tunable → L1 invariants
@@ -83,6 +142,11 @@ export class Aria2ConfigBuilder {
`--dht-file-path6=${this.dht6FilePath}`,
`--save-session=${this.saveSessionPath}`
)
+ const sqliteActive =
+ hasSqlitePersistence && settings.sqlite3Persistence === true
+ if (loadTextSession && !sqliteActive) {
+ args.push(`--input-file=${this.saveSessionPath}`)
+ }
if (hasSqlitePersistence) {
const dbPath = settings.sqlite3DbPath?.trim() || this.defaultDbPath
args.push(
diff --git a/src/core/engine/aria2/aria2-process-manager.test.ts b/src/core/engine/aria2/aria2-process-manager.test.ts
index 27f05aa3..5dd03f4c 100644
--- a/src/core/engine/aria2/aria2-process-manager.test.ts
+++ b/src/core/engine/aria2/aria2-process-manager.test.ts
@@ -314,6 +314,24 @@ describe('Aria2ProcessManager', () => {
expect(onError).toHaveBeenCalledWith(err)
})
+
+ it('retains a bounded stderr tail for startup diagnosis and resets it on spawn', async () => {
+ const firstChild = createMockChildProcess()
+ const secondChild = createMockChildProcess()
+ mockSpawnFn
+ .mockReturnValueOnce(firstChild)
+ .mockReturnValueOnce(secondChild)
+
+ await manager.spawn('/usr/bin/aria2c', [])
+ const firstStderrHandler = firstChild.stderr.on.mock.calls[0]?.[1]
+ firstStderrHandler?.(Buffer.from('database disk image is malformed'))
+ expect(manager.getRecentStderr()).toContain(
+ 'database disk image is malformed'
+ )
+
+ await manager.spawn('/usr/bin/aria2c', [])
+ expect(manager.getRecentStderr()).toBe('')
+ })
})
describe('gracefulStop', () => {
diff --git a/src/core/engine/aria2/aria2-process-manager.ts b/src/core/engine/aria2/aria2-process-manager.ts
index 0bb6d7ee..0406ca2a 100644
--- a/src/core/engine/aria2/aria2-process-manager.ts
+++ b/src/core/engine/aria2/aria2-process-manager.ts
@@ -20,6 +20,7 @@ import { buildFeatureReport } from './feature-report'
const log = getLogger('aria2')
const OWNER_RECORD_VERSION = 1
+const STDERR_TAIL_LIMIT = 32 * 1024
const OWNER_MARKER_PREFIXES = [
'--conf-path=',
'--save-session=',
@@ -58,6 +59,7 @@ export class Aria2ProcessManager {
private running = false
private readonly ownershipFilePath: string | null
private readonly inspector: Aria2ProcessInspector
+ private recentStderr = ''
onExit: ((code: number | null, signal: string | null) => void) | null = null
onError: ((err: Error) => void) | null = null
@@ -102,6 +104,7 @@ export class Aria2ProcessManager {
args: string[],
env?: NodeJS.ProcessEnv
): Promise<void> {
+ this.recentStderr = ''
const options: SpawnOptions = {
stdio: ['ignore', 'pipe', 'pipe'],
}
@@ -129,7 +132,11 @@ export class Aria2ProcessManager {
})
child.stderr?.on('data', (data: Buffer) => {
- log.warn({ data: data.toString().trim() }, 'aria2 stderr')
+ const text = data.toString()
+ this.recentStderr = `${this.recentStderr}${text}`.slice(
+ -STDERR_TAIL_LIMIT
+ )
+ log.warn({ data: text.trim() }, 'aria2 stderr')
})
child.on('exit', (code, signal) => {
@@ -186,6 +193,11 @@ export class Aria2ProcessManager {
return this.process?.pid ?? null
}
+ /** Last bounded stderr tail from the current or most recent spawn attempt. */
+ getRecentStderr(): string {
+ return this.recentStderr
+ }
+
async inspectPort(
port: number,
expected: ExpectedAria2Process
diff --git a/src/core/engine/aria2/aria2-sqlite-recovery.test.ts b/src/core/engine/aria2/aria2-sqlite-recovery.test.ts
new file mode 100644
index 00000000..877615d3
--- /dev/null
+++ b/src/core/engine/aria2/aria2-sqlite-recovery.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest'
+import { isSqliteCorruptionDiagnostic } from './aria2-sqlite-recovery'
+
+describe('isSqliteCorruptionDiagnostic', () => {
+ it.each([
+ 'database disk image is malformed',
+ 'sqlite error SQLITE_CORRUPT while reading task table',
+ 'SQLITE_NOTADB: file is encrypted or is not a database',
+ 'malformed database schema (task)',
+ ])('accepts a proven corruption diagnostic: %s', (diagnostic) => {
+ expect(isSqliteCorruptionDiagnostic(diagnostic)).toBe(true)
+ })
+
+ it.each([
+ 'database is locked',
+ 'attempt to write a readonly database',
+ 'disk I/O error',
+ 'database or disk is full',
+ 'connection refused',
+ ])('rejects a non-corruption failure: %s', (diagnostic) => {
+ expect(isSqliteCorruptionDiagnostic(diagnostic)).toBe(false)
+ })
+})
diff --git a/src/core/engine/aria2/aria2-sqlite-recovery.ts b/src/core/engine/aria2/aria2-sqlite-recovery.ts
new file mode 100644
index 00000000..f63ebaba
--- /dev/null
+++ b/src/core/engine/aria2/aria2-sqlite-recovery.ts
@@ -0,0 +1,17 @@
+/** SQLite diagnostics that prove the persistence file itself is malformed. */
+const SQLITE_CORRUPTION_PATTERNS = [
+ /SQLITE_CORRUPT/i,
+ /SQLITE_NOTADB/i,
+ /database disk image is malformed/i,
+ /file is not a database/i,
+ /malformed database schema/i,
+ /database corruption/i,
+] as const
+
+/**
+ * Keep fallback deliberately narrow. Permission, lock, disk-full and generic
+ * I/O failures must remain visible instead of being misreported as corruption.
+ */
+export function isSqliteCorruptionDiagnostic(diagnostic: string): boolean {
+ return SQLITE_CORRUPTION_PATTERNS.some((pattern) => pattern.test(diagnostic))
+}
diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.ts
index 9fb11765..db6afd51 100644
--- a/src/core/engine/engine-adapter.ts
+++ b/src/core/engine/engine-adapter.ts
@@ -22,6 +22,16 @@ export interface OutputFilePath {
relativePath: string
}
+/**
+ * Engine-neutral policy for re-attaching an existing direct-download output.
+ *
+ * - `none`: create a new download without resume-specific engine options.
+ * - `checkpoint`: resume only through the engine's native control/checkpoint
+ * metadata.
+ * - `sequential-prefix`: resume an already-verified contiguous file prefix.
+ */
+export type DownloadResumePolicy = 'none' | 'checkpoint' | 'sequential-prefix'
+
export interface AddTorrentParams {
metadata: Uint8Array
saveDir: string
@@ -76,6 +86,8 @@ export interface CreateDownloadParams {
dlLimit?: number
ulLimit?: number
pause?: boolean
+ /** Defaults to `none`. Callers must select a recovery policy explicitly. */
+ resumePolicy?: DownloadResumePolicy
// Tuning hints
performanceProfile?: EnginePerformanceProfile
diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.ts
index 5053e25c..86d8043d 100644
--- a/src/core/engine/engine-supervisor.test.ts
+++ b/src/core/engine/engine-supervisor.test.ts
@@ -69,6 +69,9 @@ function createMockSettingsManager(): SettingsManager {
sessionSaveInterval: 60,
fileAllocation: 'none',
diskCache: 33554432,
+ sqlite3Persistence: true,
+ sqlite3DbPath: '',
+ sqlite3HistoryLimit: -1,
})),
getApp: vi.fn(() => ({
defaultSaveDir: '/Users/test/Downloads',
@@ -95,6 +98,7 @@ function createMockProcessManager(): Aria2ProcessManager {
kill: vi.fn(),
isRunning: vi.fn(() => true),
getPid: vi.fn(() => 12345),
+ getRecentStderr: vi.fn(() => ''),
inspectPort: vi.fn().mockResolvedValue(null),
forceTerminateVerified: vi.fn().mockResolvedValue(undefined),
onExit: null,
@@ -105,6 +109,12 @@ function createMockProcessManager(): Aria2ProcessManager {
function createMockConfigBuilder(): Aria2ConfigBuilder {
return {
ensureUserConfig: vi.fn().mockResolvedValue('/tmp/aria2.conf'),
+ hasSavedSession: vi.fn().mockResolvedValue(false),
+ quarantineSqliteDatabase: vi.fn().mockResolvedValue({
+ databasePath: '/tmp/aria2.db',
+ quarantineBasePath: '/tmp/aria2.db.corrupt-test',
+ moved: ['/tmp/aria2.db.corrupt-test'],
+ }),
buildArgs: vi.fn(() => ['--conf-path=/tmp/aria2.conf']),
} as unknown as Aria2ConfigBuilder
}
@@ -250,6 +260,80 @@ describe('EngineSupervisor', () => {
expect(adapter.setFeatureReport).toHaveBeenCalledWith(FEATURE_REPORT)
})
+ it('does not probe or load the text session while SQLite persistence is active', async () => {
+ vi.mocked(configBuilder.hasSavedSession).mockResolvedValue(true)
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(configBuilder.hasSavedSession).not.toHaveBeenCalled()
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.anything(),
+ true,
+ expect.anything(),
+ expect.anything()
+ )
+ })
+
+ it('loads an existing text session when SQLite is disabled in settings', async () => {
+ const configured = settings.getEngine()
+ vi.mocked(settings.getEngine).mockReturnValue({
+ ...configured,
+ sqlite3Persistence: false,
+ })
+ vi.mocked(configBuilder.hasSavedSession).mockResolvedValue(true)
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(configBuilder.hasSavedSession).toHaveBeenCalledOnce()
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.objectContaining({ sqlite3Persistence: false }),
+ true,
+ expect.anything(),
+ expect.anything(),
+ true
+ )
+ })
+
+ it('loads an existing text session when the binary lacks SQLite support', async () => {
+ vi.mocked(processManager.probe).mockResolvedValue({
+ ...FEATURE_REPORT,
+ version: '1.37.0',
+ features: ['Async DNS', 'BitTorrent'],
+ hasSqlitePersistence: false,
+ })
+ vi.mocked(configBuilder.hasSavedSession).mockResolvedValue(true)
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(configBuilder.hasSavedSession).toHaveBeenCalledOnce()
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.anything(),
+ false,
+ expect.anything(),
+ expect.anything(),
+ true
+ )
+ })
+
+ it('starts without input-file when the text session is missing', async () => {
+ const configured = settings.getEngine()
+ vi.mocked(settings.getEngine).mockReturnValue({
+ ...configured,
+ sqlite3Persistence: false,
+ })
+ vi.mocked(configBuilder.hasSavedSession).mockResolvedValue(false)
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(configBuilder.hasSavedSession).toHaveBeenCalledOnce()
+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(
+ expect.objectContaining({ sqlite3Persistence: false }),
+ true,
+ expect.anything(),
+ expect.anything()
+ )
+ })
+
it('detects an official binary before spawn and starts with compatibility limits', async () => {
const officialReport: EngineFeatureReport = {
...FEATURE_REPORT,
@@ -437,6 +521,52 @@ describe('EngineSupervisor', () => {
expect(processManager.gracefulStop).toHaveBeenCalledWith(5_000)
expect(rpcClient.disconnect).toHaveBeenCalled()
})
+
+ it('quarantines proven aria2 SQLite corruption and retries once with text persistence', async () => {
+ vi.mocked(configBuilder.hasSavedSession).mockResolvedValue(true)
+ vi.mocked(processManager.getRecentStderr).mockReturnValue(
+ 'SQLite error: database disk image is malformed'
+ )
+ vi.mocked(rpcClient.connect)
+ .mockRejectedValueOnce(new Error('Connection refused'))
+ .mockResolvedValueOnce(undefined)
+
+ const failures: EngineFailurePayload[] = []
+ eventBus.on(Events.EngineFailureOccurred, (payload) => {
+ failures.push(payload as EngineFailurePayload)
+ })
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(supervisor.getState()).toBe(EngineState.Ready)
+ expect(configBuilder.quarantineSqliteDatabase).toHaveBeenCalledOnce()
+ expect(settings.update).toHaveBeenCalledWith({
+ engine: { sqlite3Persistence: false },
+ })
+ expect(processManager.spawn).toHaveBeenCalledTimes(2)
+ expect(configBuilder.buildArgs).toHaveBeenLastCalledWith(
+ expect.objectContaining({ sqlite3Persistence: false }),
+ true,
+ expect.anything(),
+ expect.anything(),
+ true
+ )
+ expect(failures).toHaveLength(0)
+ })
+
+ it('does not downgrade SQLite for lock or disk failures', async () => {
+ vi.mocked(processManager.getRecentStderr).mockReturnValue(
+ 'SQLite error: database is locked'
+ )
+ vi.mocked(rpcClient.connect).mockRejectedValue(
+ new Error('Connection refused')
+ )
+
+ await supervisor.start('/usr/bin/aria2c')
+
+ expect(supervisor.getState()).toBe(EngineState.Failed)
+ expect(configBuilder.quarantineSqliteDatabase).not.toHaveBeenCalled()
+ expect(settings.update).not.toHaveBeenCalled()
+ })
})
describe('stop', () => {
diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.ts
index 49a8d083..878c6e94 100644
--- a/src/core/engine/engine-supervisor.ts
+++ b/src/core/engine/engine-supervisor.ts
@@ -26,6 +26,7 @@ import type { Aria2Adapter } from './aria2/aria2-adapter'
import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'
import type { Aria2ProcessManager } from './aria2/aria2-process-manager'
import type { Aria2RpcClient } from './aria2/aria2-rpc-client'
+import { isSqliteCorruptionDiagnostic } from './aria2/aria2-sqlite-recovery'
import type { Aria2TrustStore } from './aria2/aria2-trust-store'
import { recommend } from './aria2/aria2-tuning'
import {
@@ -90,6 +91,8 @@ export class EngineSupervisor {
// Resets to 0 on every new EngineSupervisor (i.e. every boot) — it is
// deliberately NOT persisted or derived from anything durable.
private failureSeq = 0
+ private sqliteFallbackActive = false
+ private sqliteFallbackAttempted = false
constructor(
private eventBus: EventBus,
@@ -103,10 +106,7 @@ export class EngineSupervisor {
// Wire up process exit handler
this.processManager.onExit = (code, _signal) => {
if (this.stopping || this.suppressExitHandling) return
- if (
- this.state === EngineState.Ready ||
- this.state === EngineState.Starting
- ) {
+ if (this.state === EngineState.Ready) {
this.handleUnexpectedExit(code)
}
}
@@ -139,6 +139,8 @@ export class EngineSupervisor {
this.stopping = false
this.binaryPath = binaryPath
this.restartAttempts = 0
+ this.sqliteFallbackActive = false
+ this.sqliteFallbackAttempted = false
await this.doStart()
}
@@ -346,6 +348,7 @@ export class EngineSupervisor {
this.failure = null
let phase: 'probe' | 'config' | 'spawn' | 'rpc' = 'probe'
+ let engineSettings: EngineSettings | null = null
try {
const featureReport = await this.processManager.probe(this.binaryPath)
@@ -372,11 +375,14 @@ export class EngineSupervisor {
if (this.stopping) return
const configuredEngineSettings = this.settingsManager.getEngine()
- const engineSettings = this.applyCompatibilityLimits(
+ const resolvedEngineSettings = this.applyCompatibilityLimits(
await this.resolveRuntimeEngineSettings(
await this.persistCompatibilityLimits(configuredEngineSettings)
)
)
+ engineSettings = this.sqliteFallbackActive
+ ? { ...resolvedEngineSettings, sqlite3Persistence: false }
+ : resolvedEngineSettings
const proxy = this.settingsManager.getProxy()
// Provider is wired by the shell (Task 8) before start() in production;
// the { 0, 0 } (unlimited) fallback only fires in tests or if start()
@@ -385,12 +391,26 @@ export class EngineSupervisor {
download: 0,
upload: 0,
}
- const args = this.configBuilder.buildArgs(
- engineSettings,
- featureReport.hasSqlitePersistence,
- proxy,
- effective
- )
+ const sqliteActive =
+ featureReport.hasSqlitePersistence &&
+ engineSettings.sqlite3Persistence === true
+ const loadTextSession =
+ !sqliteActive && (await this.configBuilder.hasSavedSession())
+ if (this.stopping) return
+ const args = loadTextSession
+ ? this.configBuilder.buildArgs(
+ engineSettings,
+ featureReport.hasSqlitePersistence,
+ proxy,
+ effective,
+ true
+ )
+ : this.configBuilder.buildArgs(
+ engineSettings,
+ featureReport.hasSqlitePersistence,
+ proxy,
+ effective
+ )
this.lastStartArgs = args
// Step 3: Port check
@@ -439,16 +459,7 @@ export class EngineSupervisor {
this.startHealthCheck()
} catch (err) {
this.lastError = err instanceof Error ? err.message : String(err)
- const reason =
- phase === 'probe'
- ? EngineFailureReason.BinaryUnavailable
- : phase === 'spawn'
- ? EngineFailureReason.SpawnFailed
- : phase === 'rpc'
- ? EngineFailureReason.RpcUnavailable
- : EngineFailureReason.Unknown
- this.recordFailure(reason, this.lastError)
- log.error({ err: this.lastError }, 'start failed')
+ const stderr = this.processManager.getRecentStderr?.() ?? ''
// A process can be alive even though RPC connection failed. Always
// tear down a process spawned by this supervisor before entering Failed;
@@ -464,10 +475,81 @@ export class EngineSupervisor {
}
}
this.rpcClient.disconnect()
+
+ if (
+ engineSettings &&
+ (await this.tryActivateSqliteFallback(
+ engineSettings,
+ `${this.lastError}\n${stderr}`
+ ))
+ ) {
+ this.setState(EngineState.Restarting)
+ await this.doStart()
+ return
+ }
+
+ const reason =
+ phase === 'probe'
+ ? EngineFailureReason.BinaryUnavailable
+ : phase === 'spawn'
+ ? EngineFailureReason.SpawnFailed
+ : phase === 'rpc'
+ ? EngineFailureReason.RpcUnavailable
+ : EngineFailureReason.Unknown
+ this.recordFailure(reason, this.lastError)
+ log.error({ err: this.lastError }, 'start failed')
this.setState(EngineState.Failed)
}
}
+ private async tryActivateSqliteFallback(
+ settings: EngineSettings,
+ diagnostic: string
+ ): Promise<boolean> {
+ if (
+ this.sqliteFallbackAttempted ||
+ this.sqliteFallbackActive ||
+ !this.featureReport?.hasSqlitePersistence ||
+ !settings.sqlite3Persistence ||
+ !isSqliteCorruptionDiagnostic(diagnostic)
+ ) {
+ return false
+ }
+
+ this.sqliteFallbackAttempted = true
+ let quarantine: Awaited<
+ ReturnType<Aria2ConfigBuilder['quarantineSqliteDatabase']>
+ > | null = null
+ try {
+ quarantine = await this.configBuilder.quarantineSqliteDatabase(settings)
+ } catch (error) {
+ // Disabling the backend still gives the text session a chance to start.
+ // Keep the original database untouched if the recoverable move failed.
+ log.warn({ err: error }, 'failed to quarantine corrupt aria2 database')
+ }
+
+ this.sqliteFallbackActive = true
+ try {
+ await this.settingsManager.update({
+ engine: { sqlite3Persistence: false },
+ })
+ } catch (error) {
+ log.warn(
+ { err: error },
+ 'failed to persist aria2 SQLite fallback setting; using runtime fallback'
+ )
+ }
+ log.warn(
+ {
+ databasePath: quarantine?.databasePath,
+ quarantinePaths: quarantine?.moved,
+ textSessionAvailable: await this.configBuilder.hasSavedSession(),
+ },
+ 'corrupt aria2 SQLite persistence quarantined; retrying with text session'
+ )
+ return true
+ }
+
private handleUnexpectedExit(code: number | null): void {
this.stopHealthCheck()
this.recordFailure(
diff --git a/src/core/session/direct-recovery-planner.test.ts b/src/core/session/direct-recovery-planner.test.ts
new file mode 100644
index 00000000..04674e1e
--- /dev/null
+++ b/src/core/session/direct-recovery-planner.test.ts
@@ -0,0 +1,265 @@
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+import {
+ type DirectRecoveryFileStat,
+ DirectRecoveryPlanner,
+} from './direct-recovery-planner'
+
+function makeFileSystem(
+ entries: Readonly<Record<string, DirectRecoveryFileStat | undefined>>,
+ rejectedPaths: readonly string[] = []
+) {
+ return {
+ async stat(filePath: string) {
+ if (rejectedPaths.includes(filePath)) throw new Error('probe failed')
+ return entries[filePath] ?? null
+ },
+ }
+}
+
+const file = (size: number): DirectRecoveryFileStat => ({
+ size,
+ isFile: true,
+})
+
+const directory: DirectRecoveryFileStat = { size: 0, isFile: false }
+
+describe('DirectRecoveryPlanner', () => {
+ it('derives a POSIX output directory and keeps the incomplete filename', async () => {
+ const diskPath = '/downloads/linux.iso.motrix'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({
+ [diskPath]: file(8192),
+ [`${diskPath}.aria2`]: file(128),
+ }),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({
+ primary: { diskPath },
+ finalPath: '/downloads/linux.iso',
+ })
+ ).resolves.toMatchObject({
+ kind: 'checkpoint',
+ reason: 'checkpoint-present',
+ diskPath,
+ saveDir: '/downloads',
+ filename: 'linux.iso.motrix',
+ checkpointPath: '/downloads/linux.iso.motrix.aria2',
+ bytesBefore: 8192,
+ diskPathSource: 'primary',
+ })
+ })
+
+ it('derives a Windows output directory with win32 path semantics', async () => {
+ const diskPath = 'C:\\Downloads\\linux.iso.motrix'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({
+ [diskPath]: file(4096),
+ [`${diskPath}.aria2`]: file(64),
+ }),
+ path.win32
+ )
+
+ await expect(
+ planner.plan({ primary: { diskPath } })
+ ).resolves.toMatchObject({
+ kind: 'checkpoint',
+ diskPath,
+ saveDir: 'C:\\Downloads',
+ filename: 'linux.iso.motrix',
+ bytesBefore: 4096,
+ })
+ })
+
+ it('conservatively derives the incomplete path from finalPath', async () => {
+ const diskPath = '/downloads/archive.zip.motrix'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({ [diskPath]: file(0) }),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({ finalPath: '/downloads/archive.zip' })
+ ).resolves.toMatchObject({
+ kind: 'fresh',
+ reason: 'temp-file-empty',
+ diskPath,
+ saveDir: '/downloads',
+ filename: 'archive.zip.motrix',
+ diskPathSource: 'final-path',
+ })
+ })
+
+ it('marks a missing temporary file as fresh', async () => {
+ const planner = new DirectRecoveryPlanner(makeFileSystem({}), path.posix)
+
+ await expect(
+ planner.plan({ primary: { diskPath: '/downloads/file.motrix' } })
+ ).resolves.toMatchObject({
+ kind: 'fresh',
+ reason: 'temp-file-missing',
+ bytesBefore: 0,
+ })
+ })
+
+ it('marks an empty temporary file as fresh even if a stale checkpoint exists', async () => {
+ const diskPath = '/downloads/file.motrix'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({
+ [diskPath]: file(0),
+ [`${diskPath}.aria2`]: file(128),
+ }),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({ primary: { diskPath } })
+ ).resolves.toMatchObject({
+ kind: 'fresh',
+ reason: 'temp-file-empty',
+ bytesBefore: 0,
+ })
+ })
+
+ it('blocks a non-empty partial file without an aria2 checkpoint', async () => {
+ const diskPath = '/downloads/file.motrix'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({ [diskPath]: file(1024) }),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({ primary: { diskPath } })
+ ).resolves.toMatchObject({
+ kind: 'blocked',
+ reason: 'checkpoint-missing',
+ bytesBefore: 1024,
+ })
+ })
+
+ it('detects a completed final file when the temporary file is gone', async () => {
+ const finalPath = '/downloads/file.bin'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({ [finalPath]: file(2048) }),
+ path.posix
+ )
+
+ await expect(planner.plan({ finalPath })).resolves.toMatchObject({
+ kind: 'finalization-candidate',
+ reason: 'final-file-present',
+ diskPath: '/downloads/file.bin.motrix',
+ bytesBefore: 2048,
+ })
+ })
+
+ it('blocks rather than overwriting when final and temporary files coexist', async () => {
+ const diskPath = '/downloads/file.bin.motrix'
+ const finalPath = '/downloads/file.bin'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({
+ [diskPath]: file(1024),
+ [finalPath]: file(2048),
+ }),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({ primary: { diskPath }, finalPath })
+ ).resolves.toMatchObject({
+ kind: 'blocked',
+ reason: 'final-path-conflict',
+ bytesBefore: 1024,
+ })
+ })
+
+ it.each([
+ {
+ name: 'missing metadata',
+ input: {},
+ reason: 'path-missing',
+ },
+ {
+ name: 'relative path',
+ input: { primary: { diskPath: 'downloads/file.motrix' } },
+ reason: 'path-not-absolute',
+ },
+ {
+ name: 'NUL in path',
+ input: { primary: { diskPath: '/downloads/file\0.motrix' } },
+ reason: 'path-contains-nul',
+ },
+ {
+ name: 'root path with empty basename',
+ input: { primary: { diskPath: '/' } },
+ reason: 'filename-empty',
+ },
+ ])('rejects $name', async ({ input, reason }) => {
+ const planner = new DirectRecoveryPlanner(makeFileSystem({}), path.posix)
+
+ await expect(planner.plan(input)).resolves.toMatchObject({
+ kind: 'invalid',
+ reason,
+ diskPath: null,
+ saveDir: null,
+ filename: null,
+ bytesBefore: 0,
+ })
+ })
+
+ it('rejects a relative finalPath even when diskPath is absolute', async () => {
+ const planner = new DirectRecoveryPlanner(makeFileSystem({}), path.posix)
+
+ await expect(
+ planner.plan({
+ primary: { diskPath: '/downloads/file.motrix' },
+ finalPath: 'downloads/file',
+ })
+ ).resolves.toMatchObject({
+ kind: 'invalid',
+ reason: 'final-path-not-absolute',
+ })
+ })
+
+ it.each([
+ {
+ entries: { '/downloads/file.motrix': directory },
+ reason: 'temp-path-not-file',
+ },
+ {
+ entries: {
+ '/downloads/file.motrix': file(10),
+ '/downloads/file.motrix.aria2': directory,
+ },
+ reason: 'checkpoint-path-not-file',
+ },
+ ])('rejects non-file recovery artifacts', async ({ entries, reason }) => {
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem(entries),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({ primary: { diskPath: '/downloads/file.motrix' } })
+ ).resolves.toMatchObject({
+ kind: 'invalid',
+ reason,
+ })
+ })
+
+ it('turns unexpected probe errors into an invalid plan', async () => {
+ const diskPath = '/downloads/file.motrix'
+ const planner = new DirectRecoveryPlanner(
+ makeFileSystem({}, [diskPath]),
+ path.posix
+ )
+
+ await expect(
+ planner.plan({ primary: { diskPath } })
+ ).resolves.toMatchObject({
+ kind: 'invalid',
+ reason: 'file-probe-failed',
+ })
+ })
+})
diff --git a/src/core/session/direct-recovery-planner.ts b/src/core/session/direct-recovery-planner.ts
new file mode 100644
index 00000000..17e5fa17
--- /dev/null
+++ b/src/core/session/direct-recovery-planner.ts
@@ -0,0 +1,231 @@
+import fs from 'node:fs/promises'
+import path from 'node:path'
+import { INCOMPLETE_SUFFIX } from '@shared/constants/incomplete'
+
+export type DirectRecoveryKind =
+ | 'finalization-candidate'
+ | 'fresh'
+ | 'checkpoint'
+ | 'blocked'
+ | 'invalid'
+
+export type DirectRecoveryReason =
+ | 'final-file-present'
+ | 'temp-file-missing'
+ | 'temp-file-empty'
+ | 'checkpoint-present'
+ | 'checkpoint-missing'
+ | 'final-path-conflict'
+ | 'path-missing'
+ | 'path-contains-nul'
+ | 'path-not-absolute'
+ | 'filename-empty'
+ | 'final-path-contains-nul'
+ | 'final-path-not-absolute'
+ | 'temp-path-not-file'
+ | 'final-path-not-file'
+ | 'checkpoint-path-not-file'
+ | 'file-probe-failed'
+
+export interface DirectRecoveryPrimary {
+ diskPath?: string | null
+}
+
+export interface DirectRecoveryInput {
+ primary?: DirectRecoveryPrimary | null
+ finalPath?: string | null
+}
+
+export interface DirectRecoveryPlan {
+ kind: DirectRecoveryKind
+ reason: DirectRecoveryReason
+ diskPath: string | null
+ saveDir: string | null
+ filename: string | null
+ checkpointPath: string | null
+ bytesBefore: number
+ diskPathSource: 'primary' | 'final-path' | null
+}
+
+export interface DirectRecoveryFileStat {
+ size: number
+ isFile: boolean
+}
+
+export interface DirectRecoveryFileSystem {
+ stat(filePath: string): Promise<DirectRecoveryFileStat | null>
+}
+
+export interface DirectRecoveryPath {
+ isAbsolute(filePath: string): boolean
+ dirname(filePath: string): string
+ basename(filePath: string): string
+}
+
+const nodeFileSystem: DirectRecoveryFileSystem = {
+ async stat(filePath) {
+ try {
+ const stat = await fs.stat(filePath)
+ return { size: stat.size, isFile: stat.isFile() }
+ } catch (error) {
+ if (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'ENOENT'
+ ) {
+ return null
+ }
+ throw error
+ }
+ },
+}
+
+interface ResolvedOutput {
+ diskPath: string
+ saveDir: string
+ filename: string
+ checkpointPath: string
+ diskPathSource: 'primary' | 'final-path'
+}
+
+export class DirectRecoveryPlanner {
+ constructor(
+ private readonly fileSystem: DirectRecoveryFileSystem = nodeFileSystem,
+ private readonly pathApi: DirectRecoveryPath = path
+ ) {}
+
+ async plan(input: DirectRecoveryInput): Promise<DirectRecoveryPlan> {
+ const resolved = this.resolveOutput(input)
+ if ('invalid' in resolved) {
+ return this.invalid(resolved.invalid)
+ }
+
+ const finalPath = input.finalPath || null
+
+ try {
+ const [tempStat, finalStat] = await Promise.all([
+ this.fileSystem.stat(resolved.diskPath),
+ finalPath ? this.fileSystem.stat(finalPath) : Promise.resolve(null),
+ ])
+
+ if (tempStat && !tempStat.isFile) {
+ return this.result(resolved, 'invalid', 'temp-path-not-file', 0)
+ }
+ if (finalStat && !finalStat.isFile) {
+ return this.result(resolved, 'invalid', 'final-path-not-file', 0)
+ }
+
+ if (!tempStat && finalStat) {
+ return this.result(
+ resolved,
+ 'finalization-candidate',
+ 'final-file-present',
+ finalStat.size
+ )
+ }
+
+ if (tempStat && finalStat) {
+ return this.result(
+ resolved,
+ 'blocked',
+ 'final-path-conflict',
+ tempStat.size
+ )
+ }
+
+ if (!tempStat) {
+ return this.result(resolved, 'fresh', 'temp-file-missing', 0)
+ }
+
+ if (tempStat.size === 0) {
+ return this.result(resolved, 'fresh', 'temp-file-empty', 0)
+ }
+
+ const checkpointStat = await this.fileSystem.stat(resolved.checkpointPath)
+ if (checkpointStat && !checkpointStat.isFile) {
+ return this.result(
+ resolved,
+ 'invalid',
+ 'checkpoint-path-not-file',
+ tempStat.size
+ )
+ }
+ if (checkpointStat) {
+ return this.result(
+ resolved,
+ 'checkpoint',
+ 'checkpoint-present',
+ tempStat.size
+ )
+ }
+ return this.result(
+ resolved,
+ 'blocked',
+ 'checkpoint-missing',
+ tempStat.size
+ )
+ } catch {
+ return this.result(resolved, 'invalid', 'file-probe-failed', 0)
+ }
+ }
+
+ private resolveOutput(
+ input: DirectRecoveryInput
+ ): ResolvedOutput | { invalid: DirectRecoveryReason } {
+ const primaryDiskPath = input.primary?.diskPath || null
+ const finalPath = input.finalPath || null
+ const diskPath =
+ primaryDiskPath ?? (finalPath ? `${finalPath}${INCOMPLETE_SUFFIX}` : null)
+
+ if (!diskPath) return { invalid: 'path-missing' }
+ if (diskPath.includes('\0')) return { invalid: 'path-contains-nul' }
+ if (!this.pathApi.isAbsolute(diskPath)) {
+ return { invalid: 'path-not-absolute' }
+ }
+ if (finalPath?.includes('\0')) {
+ return { invalid: 'final-path-contains-nul' }
+ }
+ if (finalPath && !this.pathApi.isAbsolute(finalPath)) {
+ return { invalid: 'final-path-not-absolute' }
+ }
+
+ const filename = this.pathApi.basename(diskPath)
+ if (!filename) return { invalid: 'filename-empty' }
+
+ return {
+ diskPath,
+ saveDir: this.pathApi.dirname(diskPath),
+ filename,
+ checkpointPath: `${diskPath}.aria2`,
+ diskPathSource: primaryDiskPath ? 'primary' : 'final-path',
+ }
+ }
+
+ private result(
+ resolved: ResolvedOutput,
+ kind: DirectRecoveryKind,
+ reason: DirectRecoveryReason,
+ bytesBefore: number
+ ): DirectRecoveryPlan {
+ return {
+ kind,
+ reason,
+ ...resolved,
+ bytesBefore,
+ }
+ }
+
+ private invalid(reason: DirectRecoveryReason): DirectRecoveryPlan {
+ return {
+ kind: 'invalid',
+ reason,
+ diskPath: null,
+ saveDir: null,
+ filename: null,
+ checkpointPath: null,
+ bytesBefore: 0,
+ diskPathSource: null,
+ }
+ }
+}
diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.ts
index f4a1d2f7..563d69a6 100644
--- a/src/core/session/session-manager.test.ts
+++ b/src/core/session/session-manager.test.ts
@@ -251,6 +251,7 @@ function seedAsPair(
finishedAt?: number | null
errorMessage?: string | null
errorCode?: DownloadErrorCode | null
+ payload?: Record<string, unknown>
}
): void {
const isBtLike =
@@ -312,7 +313,7 @@ function seedAsPair(
transitionPhase: opts.transitionPhase ?? TransitionPhase.Idle,
uris: opts.uris ?? [],
uriHash: opts.uriHash ?? null,
- payload: {},
+ payload: opts.payload ?? {},
createdAt: opts.createdAt ?? 0,
updatedAt: opts.updatedAt ?? 0,
},
@@ -326,7 +327,7 @@ function createMockAdapter(): EngineAdapter {
disconnect: vi.fn(),
getCapabilities: vi.fn(),
getFeatureReport: vi.fn(),
- createDownload: vi.fn(async () => 'gid-mock'),
+ createDownload: vi.fn(async ({ gid }) => gid ?? 'gid-mock'),
pauseTask: vi.fn(),
resumeTask: vi.fn(),
removeTask: vi.fn(),
@@ -338,7 +339,7 @@ function createMockAdapter(): EngineAdapter {
getTaskFiles: vi.fn(),
getTaskPieces: vi.fn(),
getGlobalStats: vi.fn(),
- addTorrent: vi.fn(async () => 'gid-mock'),
+ addTorrent: vi.fn(async ({ gid }) => gid ?? 'gid-mock'),
removeDownloadResult: vi.fn(),
getUploadLength: vi.fn(),
listActiveAndWaiting: vi.fn(async () => []),
@@ -1304,8 +1305,8 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'fresh-gid-002'
+ ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
@@ -1319,7 +1320,8 @@ describe('SessionManager', () => {
expect.objectContaining({ checkIntegrity: true })
)
const restored = taskManager.getAll().find((t) => t.id === 'm-bt-002')
- expect(restored?.engineTaskId).toBe('fresh-gid-002')
+ expect(restored?.engineTaskId).toMatch(/^[0-9a-f]{16}$/)
+ expect(restored?.engineTaskId).not.toBe('lost-gid')
expect(restored?.status).not.toBe(TaskStatus.Error)
fs.rmSync(tmpDir, { recursive: true, force: true })
@@ -1367,8 +1369,8 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'fresh-gid-progress'
+ ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
@@ -1855,15 +1857,289 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'fresh-gid-004'
+ ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
expect(adapter.createDownload).toHaveBeenCalledTimes(1)
+ expect(adapter.createDownload).toHaveBeenCalledWith({
+ uris: ['http://example.com/file.zip'],
+ gid: expect.stringMatching(/^[0-9a-f]{16}$/),
+ saveDir: '/tmp',
+ filename: 'file.zip.motrix',
+ connections: undefined,
+ pause: false,
+ resumePolicy: 'none',
+ })
const restored = taskManager.getAll().find((t) => t.id === 'm-http-004')
- expect(restored?.engineTaskId).toBe('fresh-gid-004')
+ expect(restored?.engineTaskId).toMatch(/^[0-9a-f]{16}$/)
+ expect(restored?.engineTaskId).not.toBe('lost-http')
+ })
+
+ it('re-adds HTTP at the exact .motrix path when an aria2 checkpoint exists', async () => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-http-checkpoint-')
+ )
+ const diskPath = path.join(tempDir, 'archive.zip.motrix')
+ try {
+ fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))
+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.alloc(16, 0x62))
+ seedAsPair(db, {
+ motrixId: 'm-http-checkpoint',
+ gid: 'lost-http-checkpoint',
+ name: 'archive.zip',
+ diskPath,
+ finalPath: path.join(tempDir, 'archive.zip'),
+ finalName: 'archive.zip',
+ uris: ['https://example.com/archive.zip'],
+ status: TaskStatus.Downloading,
+ payload: {
+ directReplay: {
+ version: 1,
+ connections: 4,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ },
+ },
+ })
+ ;(
+ adapter.createDownload as ReturnType<typeof vi.fn>
+ ).mockImplementation(async ({ gid }: { gid?: string }) => gid ?? '')
+
+ await sessionManager.restore()
+
+ expect(adapter.createDownload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ saveDir: tempDir,
+ filename: 'archive.zip.motrix',
+ connections: 4,
+ resumePolicy: 'checkpoint',
+ })
+ )
+ expect(taskManager.getById('m-http-checkpoint')?.status).toBe(
+ TaskStatus.Downloading
+ )
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ })
+
+ it('validates a checkpoint source and dispatches it with If-Range', async () => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-http-validator-')
+ )
+ const diskPath = path.join(tempDir, 'archive.zip.motrix')
+ const resourceValidator = {
+ kind: 'strong-etag' as const,
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 7,
+ }
+ const verify = vi.fn().mockResolvedValue({
+ outcome: 'unchanged' as const,
+ ifRange: resourceValidator.value,
+ })
+ try {
+ fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))
+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.alloc(16, 0x62))
+ seedAsPair(db, {
+ motrixId: 'm-http-validator',
+ gid: 'lost-http-validator',
+ name: 'archive.zip',
+ diskPath,
+ finalPath: path.join(tempDir, 'archive.zip'),
+ finalName: 'archive.zip',
+ uris: ['https://example.com/archive.zip'],
+ status: TaskStatus.Downloading,
+ payload: {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ resourceValidator,
+ },
+ },
+ })
+ sessionManager = new SessionManager(
+ taskManager,
+ rpc,
+ db,
+ adapter,
+ undefined,
+ undefined,
+ { verify }
+ )
+
+ await sessionManager.restore()
+
+ expect(verify).toHaveBeenCalledWith(
+ 'https://example.com/archive.zip',
+ resourceValidator
+ )
+ expect(adapter.createDownload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ headers: { 'If-Range': '"release-v1"' },
+ resumePolicy: 'checkpoint',
+ })
+ )
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ })
+
+ it.each([
+ ['source-changed', 'task.recovery.startup.resumeSourceChanged'] as const,
+ [
+ 'range-unsupported',
+ 'task.recovery.startup.resumeRangeUnsupported',
+ ] as const,
+ ['unverifiable', 'task.recovery.startup.resumeValidationFailed'] as const,
+ ])(
+ 'blocks checkpoint recovery when source validation is %s',
+ async (outcome, errorDetailKey) => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-http-validator-blocked-')
+ )
+ const diskPath = path.join(tempDir, 'archive.zip.motrix')
+ const partial = Buffer.from('preserve-partial')
+ const checkpoint = Buffer.from('preserve-checkpoint')
+ const resourceValidator = {
+ kind: 'strong-etag' as const,
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 7,
+ }
+ const verify = vi.fn().mockResolvedValue({ outcome, ifRange: null })
+ try {
+ fs.writeFileSync(diskPath, partial)
+ fs.writeFileSync(`${diskPath}.aria2`, checkpoint)
+ seedAsPair(db, {
+ motrixId: `m-http-validator-${outcome}`,
+ gid: `lost-http-validator-${outcome}`,
+ name: 'archive.zip',
+ diskPath,
+ finalPath: path.join(tempDir, 'archive.zip'),
+ finalName: 'archive.zip',
+ uris: ['https://example.com/archive.zip'],
+ status: TaskStatus.Downloading,
+ payload: {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ resourceValidator,
+ },
+ },
+ })
+ sessionManager = new SessionManager(
+ taskManager,
+ rpc,
+ db,
+ adapter,
+ undefined,
+ undefined,
+ { verify }
+ )
+
+ await sessionManager.restore()
+
+ expect(adapter.createDownload).not.toHaveBeenCalled()
+ expect(
+ taskManager.getById(`m-http-validator-${outcome}`)
+ ).toMatchObject({ status: TaskStatus.Error, errorDetailKey })
+ expect(fs.readFileSync(diskPath)).toEqual(partial)
+ expect(fs.readFileSync(`${diskPath}.aria2`)).toEqual(checkpoint)
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ }
+ )
+
+ it('preserves a non-empty HTTP partial when its checkpoint is missing', async () => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-http-no-checkpoint-')
+ )
+ const diskPath = path.join(tempDir, 'partial.bin.motrix')
+ const bytes = Buffer.from('do-not-overwrite')
+ try {
+ fs.writeFileSync(diskPath, bytes)
+ seedAsPair(db, {
+ motrixId: 'm-http-no-checkpoint',
+ gid: 'lost-http-no-checkpoint',
+ name: 'partial.bin',
+ diskPath,
+ finalPath: path.join(tempDir, 'partial.bin'),
+ finalName: 'partial.bin',
+ uris: ['https://example.com/partial.bin'],
+ status: TaskStatus.Downloading,
+ })
+
+ await sessionManager.restore()
+
+ expect(adapter.createDownload).not.toHaveBeenCalled()
+ expect(taskManager.getById('m-http-no-checkpoint')).toMatchObject({
+ status: TaskStatus.Error,
+ errorDetailKey: 'task.recovery.startup.resumeCheckpointMissing',
+ })
+ expect(fs.readFileSync(diskPath)).toEqual(bytes)
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ })
+
+ it('does not replay a direct task whose request credentials were not persisted', async () => {
+ seedAsPair(db, {
+ motrixId: 'm-http-credentials',
+ gid: 'lost-http-credentials',
+ name: 'private.zip',
+ diskPath: '/tmp/private.zip.motrix',
+ finalPath: '/tmp/private.zip',
+ finalName: 'private.zip',
+ uris: ['https://example.com/private.zip'],
+ status: TaskStatus.Downloading,
+ payload: {
+ directReplay: {
+ version: 1,
+ requestModifiers: ['headers'],
+ replayability: 'requires-credentials',
+ },
+ },
+ })
+
+ await sessionManager.restore()
+
+ expect(adapter.createDownload).not.toHaveBeenCalled()
+ expect(taskManager.getById('m-http-credentials')).toMatchObject({
+ status: TaskStatus.Error,
+ errorDetailKey: 'task.recovery.startup.resumeCredentialsRequired',
+ })
+ })
+
+ it('persists the reserved recovery gid before dispatching HTTP', async () => {
+ seedAsPair(db, {
+ motrixId: 'm-http-durable-gid',
+ gid: 'lost-http-durable-gid',
+ name: 'durable.bin',
+ diskPath: '/tmp/durable.bin.motrix',
+ finalPath: '/tmp/durable.bin',
+ finalName: 'durable.bin',
+ uris: ['https://example.com/durable.bin'],
+ status: TaskStatus.Downloading,
+ })
+ ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => {
+ expect(db.getTask('m-http-durable-gid')?.instances[0]?.gid).toBe(gid)
+ return gid ?? ''
+ }
+ )
+
+ await sessionManager.restore()
+
+ expect(taskManager.getById('m-http-durable-gid')?.engineTaskId).toMatch(
+ /^[0-9a-f]{16}$/
+ )
})
it('preserves a no-live-gid HTTP rename intent for startup recovery instead of re-adding', async () => {
@@ -2153,8 +2429,8 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'fresh-http-gid'
+ ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
@@ -2166,7 +2442,7 @@ describe('SessionManager', () => {
.getAll()
.find((t) => t.id === 'm-http-paused')
expect(restored?.status).toBe(TaskStatus.Paused)
- expect(restored?.engineTaskId).toBe('fresh-http-gid')
+ expect(restored?.engineTaskId).toMatch(/^[0-9a-f]{16}$/)
})
it('does not pause Downloading HTTP task on re-add', async () => {
@@ -2192,8 +2468,8 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'fresh-http-dl-gid'
+ ;(adapter.createDownload as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
@@ -2233,8 +2509,8 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'new-paused-gid'
+ ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
@@ -2280,8 +2556,8 @@ describe('SessionManager', () => {
rpc.tellActive = vi.fn(async () => [])
rpc.tellWaiting = vi.fn(async () => [])
rpc.tellStopped = vi.fn(async () => [])
- ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'new-downloading-gid'
+ ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await sessionManager.restore()
@@ -2750,8 +3026,8 @@ describe('SessionManager', () => {
})
taskManager.add(errored)
- ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockResolvedValue(
- 'fresh-legacy-gid'
+ ;(adapter.addTorrent as ReturnType<typeof vi.fn>).mockImplementation(
+ async ({ gid }: { gid?: string }) => gid ?? ''
)
await session.recoverLegacyTaskLost()
@@ -2759,7 +3035,8 @@ describe('SessionManager', () => {
expect(adapter.addTorrent).toHaveBeenCalledTimes(1)
const recovered = taskManager.getAll().find((t) => t.id === 'm-legacy')
expect(recovered?.status).not.toBe(TaskStatus.Error)
- expect(recovered?.engineTaskId).toBe('fresh-legacy-gid')
+ expect(recovered?.engineTaskId).toMatch(/^[0-9a-f]{16}$/)
+ expect(recovered?.engineTaskId).not.toBe('legacy-gid')
fs.rmSync(torrentDir, { recursive: true, force: true })
})
@@ -3055,7 +3332,11 @@ describe('restore() with task_instances (Plan A Task 7)', () => {
const sm = new SessionManager(taskManager, rpc, db, adapter)
db.saveTaskWithInstances({
- task: makeTaskRow('m-orphan', TaskKind.Direct),
+ task: {
+ ...makeTaskRow('m-orphan', TaskKind.Direct),
+ finalPath: '/tmp/m-orphan.mp4',
+ finalName: 'm-orphan.mp4',
+ },
instances: [
{
...makeInstanceRow(
@@ -3064,6 +3345,7 @@ describe('restore() with task_instances (Plan A Task 7)', () => {
'g-orphan',
TaskInstancePhase.HttpDownload
),
+ diskPath: '/tmp/m-orphan.mp4.motrix',
uris: ['https://example.com/lost.mp4'],
status: TaskStatus.Paused,
},
diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.ts
index 1e038aef..684eea06 100644
--- a/src/core/session/session-manager.ts
+++ b/src/core/session/session-manager.ts
@@ -1,6 +1,7 @@
import fs from 'node:fs'
-import { newTaskId } from '@core/lib/ids'
+import { newEngineTaskId, newTaskId } from '@core/lib/ids'
import { getLogger } from '@core/logger'
+import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'
import type { DownloadTask } from '@shared/types/task'
import {
makeDefaultBtExtension,
@@ -35,12 +36,14 @@ import {
applyTerminalTransition,
terminalFieldsFromRow,
} from '../task/apply-terminal-transition'
+import { DirectResourceValidatorService } from '../task/direct-resource-validator'
import { isTempPath } from '../task/paths'
import { setTaskTransitionPhase } from '../task/task-instance'
import type { TaskManager } from '../task/task-manager'
import { taskRowToDownloadTask } from '../task/task-row-to-download-task'
import { isMagnetCleanupTombstoneHidden } from '../torrent/magnet-cleanup-quarantine'
import { computeUriHash, deriveInfoHash } from './content-key'
+import { DirectRecoveryPlanner } from './direct-recovery-planner'
import type {
MotrixDatabase,
TaskInstanceRow,
@@ -226,7 +229,15 @@ export class SessionManager {
* them so they are not adopted as phantom standalone tasks. Optional so test
* and non-media callers can omit it.
*/
- private mediaTmpRoot?: string
+ private mediaTmpRoot?: string,
+ private directRecoveryPlanner: Pick<
+ DirectRecoveryPlanner,
+ 'plan'
+ > = new DirectRecoveryPlanner(),
+ private directResourceValidator: Pick<
+ DirectResourceValidatorService,
+ 'verify'
+ > = new DirectResourceValidatorService()
) {}
runExclusivePersistence<T>(operation: () => T | Promise<T>): Promise<T> {
@@ -1132,16 +1143,14 @@ export class SessionManager {
}
try {
const bytes = fs.readFileSync(taskPart.torrentMetaPath)
- const newGid = await this.adapter.addTorrent({
- metadata: bytes,
- saveDir: primary?.diskPath || taskPart.finalPath || '/',
- pause: taskPart.aggStatus === TaskStatus.Paused,
- checkIntegrity: true,
- })
- return this.adoptByPair(
- pair,
- newGid,
- this.statusAfterSuccessfulReAdd(pair)
+ return this.dispatchRecoveryCandidate(pair, (gid) =>
+ this.adapter.addTorrent({
+ metadata: bytes,
+ gid,
+ saveDir: primary?.diskPath || taskPart.finalPath || '/',
+ pause: taskPart.aggStatus === TaskStatus.Paused,
+ checkIntegrity: true,
+ })
)
} catch (err) {
log.warn(
@@ -1156,28 +1165,82 @@ export class SessionManager {
}
if (primary && primary.uris.length > 0) {
- try {
- const newGid = await this.adapter.createDownload({
- uris: primary.uris,
- saveDir: primary.diskPath || taskPart.finalPath || '/',
- filename: taskPart.finalName,
- pause: taskPart.aggStatus === TaskStatus.Paused,
- })
- return this.adoptByPair(
+ const recipe = parseDirectReplayRecipe(primary.payload)
+ if (recipe?.replayability === 'requires-credentials') {
+ return this.markRecoverErrorFromPair(
pair,
- newGid,
- this.statusAfterSuccessfulReAdd(pair)
+ 'task.recovery.startup.resumeCredentialsRequired'
)
- } catch (err) {
- log.warn(
- { err, motrixId: taskPart.motrixId },
- 'HTTP re-add failed during restore'
+ }
+
+ const plan = await this.directRecoveryPlanner.plan({
+ primary,
+ finalPath: taskPart.finalPath,
+ })
+ if (plan.kind === 'finalization-candidate') {
+ return this.promoteDirectFinalizationCandidate(pair)
+ }
+ if (plan.kind === 'blocked') {
+ return this.markRecoverErrorFromPair(
+ pair,
+ plan.reason === 'checkpoint-missing'
+ ? 'task.recovery.startup.resumeCheckpointMissing'
+ : 'task.recovery.startup.resumePathInvalid'
)
+ }
+ if (
+ plan.kind === 'invalid' ||
+ !plan.diskPath ||
+ !plan.saveDir ||
+ !plan.filename
+ ) {
return this.markRecoverErrorFromPair(
pair,
- 'task.recovery.startup.reAddFailed'
+ 'task.recovery.startup.resumePathInvalid'
+ )
+ }
+
+ const resumePolicy =
+ plan.kind === 'checkpoint'
+ ? 'checkpoint'
+ : plan.reason === 'temp-file-empty'
+ ? 'sequential-prefix'
+ : 'none'
+ let ifRange: string | null = null
+ if (plan.kind === 'checkpoint' && recipe?.resourceValidator) {
+ if (primary.uris.length !== 1) {
+ return this.markRecoverErrorFromPair(
+ pair,
+ 'task.recovery.startup.resumeValidationFailed'
+ )
+ }
+ const validation = await this.directResourceValidator.verify(
+ primary.uris[0] as string,
+ recipe.resourceValidator
)
+ if (validation.outcome !== 'unchanged') {
+ const errorDetailKey =
+ validation.outcome === 'source-changed'
+ ? 'task.recovery.startup.resumeSourceChanged'
+ : validation.outcome === 'range-unsupported'
+ ? 'task.recovery.startup.resumeRangeUnsupported'
+ : 'task.recovery.startup.resumeValidationFailed'
+ return this.markRecoverErrorFromPair(pair, errorDetailKey)
+ }
+ ifRange = validation.ifRange
}
+ return this.dispatchRecoveryCandidate(pair, (gid) =>
+ this.adapter.createDownload({
+ uris: primary.uris,
+ gid,
+ saveDir: plan.saveDir as string,
+ filename: plan.filename as string,
+ connections: recipe?.connections,
+ ...(ifRange ? { headers: { 'If-Range': ifRange } } : {}),
+ pause: taskPart.aggStatus === TaskStatus.Paused,
+ resumePolicy,
+ })
+ )
}
return this.markRecoverErrorFromPair(
@@ -1186,6 +1249,88 @@ export class SessionManager {
)
}
+ /**
+ * A final output with no remaining temporary file means the prior process
+ * crossed the filesystem boundary but crashed before persisting completion.
+ * Recreate the durable rename intent so TaskRecoveryService can reconcile
+ * it instead of dispatching a second download.
+ */
+ private async promoteDirectFinalizationCandidate(
+ pair: TaskWithInstances
+ ): Promise<DownloadTask> {
+ const now = Date.now()
+ const task = taskRowToDownloadTask(pair.task, pair.instances)
+ task.status = TaskStatus.Finalizing
+ task.updatedAt = now
+ for (const instance of task.instances) {
+ instance.status = TaskStatus.Finalizing
+ instance.updatedAt = now
+ }
+ setTaskTransitionPhase(task, TransitionPhase.Renaming)
+ await this.persistTask(task)
+ return task
+ }
+
+ /**
+ * Persist the replacement GID before dispatching it. If the app crashes
+ * after aria2 accepts the task (or the RPC response is lost), the next
+ * restore pass owns that exact GID and cannot mint a duplicate public task.
+ */
+ private async dispatchRecoveryCandidate(
+ pair: TaskWithInstances,
+ dispatch: (gid: string) => Promise<string>
+ ): Promise<DownloadTask> {
+ const gid = newEngineTaskId(undefined, 'SessionManager recovery')
+ const nextStatus = this.statusAfterSuccessfulReAdd(pair)
+ const candidate = this.adoptByPair(pair, gid, nextStatus)
+ await this.persistTask(candidate)
+
+ try {
+ const actualGid = await dispatch(gid)
+ if (actualGid.toLowerCase() !== gid.toLowerCase()) {
+ throw new Error(
+ `Engine returned gid ${actualGid} instead of reserved gid ${gid}`
+ )
+ }
+ return candidate
+ } catch (err) {
+ log.warn(
+ { err, motrixId: pair.task.motrixId, gid },
+ 'engine re-add failed during restore'
+ )
+
+ let cleanupComplete = false
+ try {
+ await this.adapter.forceRemoveTask(gid)
+ } catch (cleanupError) {
+ log.debug(
+ { err: cleanupError, motrixId: pair.task.motrixId, gid },
+ 'restore re-add force-remove did not settle'
+ )
+ }
+ try {
+ await this.adapter.removeDownloadResult(gid)
+ cleanupComplete = true
+ } catch (cleanupError) {
+ log.warn(
+ { err: cleanupError, motrixId: pair.task.motrixId, gid },
+ 'restore re-add result cleanup failed'
+ )
+ }
+
+ return cleanupComplete
+ ? this.markRecoverErrorFromPair(
+ pair,
+ 'task.recovery.startup.reAddFailed'
+ )
+ : this.markRecoverErrorTask(
+ candidate,
+ pair.task.aggStatus,
+ 'task.recovery.startup.reAddFailed'
+ )
+ }
+ }
+
/**
* Land a restored task in Error with a specific, localized detail key —
* used by every startup-recovery site that gives up on resuming a task
@@ -1203,10 +1348,18 @@ export class SessionManager {
pair: TaskWithInstances,
errorDetailKey: string
): Promise<DownloadTask> {
- const now = Date.now()
const previousStatus = pair.task.aggStatus
const primary = pair.instances[0]
const task = this.adoptByPair(pair, primary?.gid ?? '')
+ return this.markRecoverErrorTask(task, previousStatus, errorDetailKey)
+ }
+
+ private async markRecoverErrorTask(
+ task: DownloadTask,
+ previousStatus: TaskStatus,
+ errorDetailKey: string
+ ): Promise<DownloadTask> {
+ const now = Date.now()
const errored: DownloadTask = {
...task,
...applyTerminalTransition(
diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.ts
index 8a3070f8..6211bdb6 100644
--- a/src/core/task/actions/re-add-task.test.ts
+++ b/src/core/task/actions/re-add-task.test.ts
@@ -1,3 +1,6 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
import { ErrorCode } from '@shared/errors'
import { Events } from '@shared/protocol/events'
import type { DownloadTask } from '@shared/types/task'
@@ -319,22 +322,24 @@ function makeBtErrorTask(overrides: Partial<DownloadTask> = {}): DownloadTask {
}
function makeHttpTask(overrides: Partial<DownloadTask> = {}): DownloadTask {
- return makeDownloadTask({
- id: 't2',
- engineTaskId: 'old-http-gid',
- name: 'file.zip',
- status: TaskStatus.Error,
- saveDir: '/tmp',
- errorMessage: 'connection reset',
- finishedAt: 1234,
- uris: ['https://example.com/file.zip'],
- fileCount: 1,
- filename: 'file.zip',
- diskPath: '/tmp',
- finalPath: '/tmp/file.zip',
- finalName: 'file.zip',
- ...overrides,
- })
+ return withPrimaryInstance(
+ makeDownloadTask({
+ id: 't2',
+ engineTaskId: 'old-http-gid',
+ name: 'file.zip',
+ status: TaskStatus.Error,
+ saveDir: '/tmp',
+ errorMessage: 'connection reset',
+ finishedAt: 1234,
+ uris: ['https://example.com/file.zip'],
+ fileCount: 1,
+ filename: 'file.zip',
+ diskPath: '/tmp/file.zip.motrix',
+ finalPath: '/tmp/file.zip',
+ finalName: 'file.zip',
+ ...overrides,
+ })
+ )
}
function withPrimaryInstance(task: DownloadTask): DownloadTask {
@@ -367,10 +372,177 @@ function withPrimaryInstance(task: DownloadTask): DownloadTask {
}
describe('reAddTask (HTTP path)', () => {
- it('rejects an HTTP retry up front: the replay inputs are not persisted', async () => {
- // uris survive, but headers/cookies/referer/proxy/out do not — a
- // uris-only re-add would issue a different request than the one that
- // failed, so canRebuildTaskInputs refuses before any engine call.
+ it('retries a URI-only HTTP task at its exact .motrix output path', async () => {
+ const task = makeHttpTask()
+ task.instances[0].payload = {
+ directReplay: {
+ version: 1,
+ connections: 6,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ },
+ }
+ const deps = makeDeps(task)
+
+ await reAddTask('t2', deps)
+
+ expect(deps.adapter.createDownload).toHaveBeenCalledWith({
+ uris: ['https://example.com/file.zip'],
+ gid: RESERVED_GID,
+ saveDir: '/tmp',
+ filename: 'file.zip.motrix',
+ connections: 6,
+ pause: false,
+ resumePolicy: 'none',
+ })
+ expect(deps.adapter.addTorrent).not.toHaveBeenCalled()
+ expect(deps.taskManager.set).toHaveBeenCalledWith(
+ 't2',
+ expect.objectContaining({
+ engineTaskId: RESERVED_GID,
+ status: TaskStatus.Downloading,
+ })
+ )
+ })
+
+ it('uses checkpoint resume for a non-empty HTTP partial with .aria2 state', async () => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-direct-readd-')
+ )
+ const diskPath = path.join(tempDir, 'file.zip.motrix')
+ try {
+ fs.writeFileSync(diskPath, Buffer.alloc(32, 0x61))
+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.alloc(16, 0x62))
+ const task = makeHttpTask({
+ diskPath,
+ finalPath: path.join(tempDir, 'file.zip'),
+ })
+ task.instances[0].diskPath = diskPath
+ task.instances[0].payload = {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ resourceValidator: {
+ kind: 'strong-etag',
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 7,
+ },
+ },
+ }
+ const deps = makeDeps(task)
+ const verify = vi.fn().mockResolvedValue({
+ outcome: 'unchanged' as const,
+ ifRange: '"release-v1"',
+ })
+
+ await reAddTask('t2', {
+ ...deps,
+ directResourceValidator: { verify },
+ })
+
+ expect(verify).toHaveBeenCalledWith(
+ 'https://example.com/file.zip',
+ expect.objectContaining({ value: '"release-v1"' })
+ )
+ expect(deps.adapter.createDownload).toHaveBeenCalledWith(
+ expect.objectContaining({
+ saveDir: tempDir,
+ filename: 'file.zip.motrix',
+ headers: { 'If-Range': '"release-v1"' },
+ resumePolicy: 'checkpoint',
+ })
+ )
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a changed checkpoint source before touching the engine', async () => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-direct-changed-')
+ )
+ const diskPath = path.join(tempDir, 'file.zip.motrix')
+ try {
+ fs.writeFileSync(diskPath, Buffer.from('partial'))
+ fs.writeFileSync(`${diskPath}.aria2`, Buffer.from('checkpoint'))
+ const task = makeHttpTask({
+ diskPath,
+ finalPath: path.join(tempDir, 'file.zip'),
+ })
+ task.instances[0].diskPath = diskPath
+ task.instances[0].payload = {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ resourceValidator: {
+ kind: 'strong-etag',
+ value: '"release-v1"',
+ capturedAt: 7,
+ },
+ },
+ }
+ const deps = makeDeps(task)
+ const directResourceValidator = {
+ verify: vi.fn().mockResolvedValue({
+ outcome: 'source-changed',
+ ifRange: null,
+ }),
+ }
+
+ await expect(
+ reAddTask('t2', { ...deps, directResourceValidator })
+ ).rejects.toMatchObject({ code: ErrorCode.TaskNotRetryable })
+
+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()
+ expect(deps.adapter.createDownload).not.toHaveBeenCalled()
+ expect(deps.persistTask).not.toHaveBeenCalled()
+ expect(fs.readFileSync(diskPath)).toEqual(Buffer.from('partial'))
+ expect(fs.readFileSync(`${diskPath}.aria2`)).toEqual(
+ Buffer.from('checkpoint')
+ )
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects HTTP retry before engine mutation when a partial has no checkpoint', async () => {
+ const tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'motrix-direct-blocked-')
+ )
+ const diskPath = path.join(tempDir, 'file.zip.motrix')
+ try {
+ fs.writeFileSync(diskPath, Buffer.from('partial'))
+ const task = makeHttpTask({
+ diskPath,
+ finalPath: path.join(tempDir, 'file.zip'),
+ })
+ task.instances[0].diskPath = diskPath
+ task.instances[0].payload = {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ },
+ }
+ const deps = makeDeps(task)
+
+ await expect(reAddTask('t2', deps)).rejects.toMatchObject({
+ code: ErrorCode.TaskNotRetryable,
+ })
+
+ expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()
+ expect(deps.adapter.createDownload).not.toHaveBeenCalled()
+ expect(deps.persistTask).not.toHaveBeenCalled()
+ expect(fs.readFileSync(diskPath)).toEqual(Buffer.from('partial'))
+ } finally {
+ fs.rmSync(tempDir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects legacy HTTP retry up front when no replay recipe exists', async () => {
const task = makeHttpTask()
const deps = makeDeps(task)
@@ -379,8 +551,6 @@ describe('reAddTask (HTTP path)', () => {
})
expect(deps.adapter.createDownload).not.toHaveBeenCalled()
- expect(deps.adapter.addTorrent).not.toHaveBeenCalled()
- expect(deps.adapter.getEngineTaskOptions).not.toHaveBeenCalled()
expect(deps.adapter.forceRemoveTask).not.toHaveBeenCalled()
})
})
diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.ts
index 0a54c569..657678fd 100644
--- a/src/core/task/actions/re-add-task.ts
+++ b/src/core/task/actions/re-add-task.ts
@@ -1,16 +1,22 @@
import path from 'node:path'
import { newEngineTaskId } from '@core/lib/ids'
import { AppError, ErrorCode } from '@shared/errors'
+import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'
import type { EngineTaskOptions } from '@shared/types/engine-task-options'
import type { DownloadTask } from '@shared/types/task'
-import { TaskStatus } from '@shared/types/task'
+import { TaskInstancePhase, TaskStatus } from '@shared/types/task'
import {
canRebuildTaskInputs,
canReseed,
canRetry,
+ isTorrentLike,
} from '@shared/types/task-actions'
-import type { EngineAdapter } from '../../engine/engine-adapter'
+import type {
+ CreateDownloadParams,
+ EngineAdapter,
+} from '../../engine/engine-adapter'
import type { Logger } from '../../logger'
+import { DirectRecoveryPlanner } from '../../session/direct-recovery-planner'
import { applyTerminalTransition } from '../apply-terminal-transition'
import {
buildFinalOutputFilePaths,
@@ -18,6 +24,7 @@ import {
getBtStorageLayout,
parseBtFileLayout,
} from '../bt-storage-layout'
+import { DirectResourceValidatorService } from '../direct-resource-validator'
import type { TorrentMetaStore } from '../torrent-meta-store'
import { commitTaskUpdate, getTaskOrWarn, type TaskActionDeps } from './shared'
@@ -26,6 +33,7 @@ export interface ReAddTaskDeps extends TaskActionDeps {
persistTask: NonNullable<TaskActionDeps['persistTask']>
torrentMetaStore: TorrentMetaStore
createEngineTaskId?: () => string
+ directResourceValidator?: Pick<DirectResourceValidatorService, 'verify'>
}
async function bestEffortRemove(
@@ -149,6 +157,78 @@ async function reAddBt(
})
}
+const directRecoveryPlanner = new DirectRecoveryPlanner()
+const directResourceValidator = new DirectResourceValidatorService()
+
+async function buildDirectReAddParams(
+ task: DownloadTask,
+ resourceValidator: Pick<DirectResourceValidatorService, 'verify'>
+): Promise<Omit<CreateDownloadParams, 'gid'>> {
+ const primary = task.instances.find(
+ (instance) => instance.phase === TaskInstancePhase.HttpDownload
+ )
+ const recipe = parseDirectReplayRecipe(primary?.payload)
+ if (!primary || !recipe || recipe.replayability !== 'uri-only') {
+ throw new AppError(
+ ErrorCode.TaskNotRetryable,
+ `Task ${task.id} cannot be retried: its direct replay recipe is unavailable`
+ )
+ }
+
+ const plan = await directRecoveryPlanner.plan({
+ primary,
+ finalPath: task.finalPath,
+ })
+ if (
+ plan.kind === 'blocked' ||
+ plan.kind === 'invalid' ||
+ plan.kind === 'finalization-candidate' ||
+ !plan.saveDir ||
+ !plan.filename
+ ) {
+ throw new AppError(
+ ErrorCode.TaskNotRetryable,
+ `Task ${task.id} cannot be retried safely: ${plan.reason}`
+ )
+ }
+
+ let ifRange: string | null = null
+ if (plan.kind === 'checkpoint' && recipe.resourceValidator) {
+ if (primary.uris.length !== 1) {
+ throw new AppError(
+ ErrorCode.TaskNotRetryable,
+ `Task ${task.id} cannot be retried safely: ambiguous-validator-source`
+ )
+ }
+ const validation = await resourceValidator.verify(
+ primary.uris[0] as string,
+ recipe.resourceValidator
+ )
+ if (validation.outcome !== 'unchanged') {
+ throw new AppError(
+ ErrorCode.TaskNotRetryable,
+ `Task ${task.id} cannot be retried safely: ${validation.outcome}`
+ )
+ }
+ ifRange = validation.ifRange
+ }
+
+ return {
+ uris: primary.uris,
+ saveDir: plan.saveDir,
+ filename: plan.filename,
+ connections: recipe.connections,
+ ...(ifRange ? { headers: { 'If-Range': ifRange } } : {}),
+ pause: false,
+ resumePolicy:
+ plan.kind === 'checkpoint'
+ ? 'checkpoint'
+ : plan.reason === 'temp-file-empty'
+ ? 'sequential-prefix'
+ : 'none',
+ }
+}
+
/**
* Rebuild the task with a new reserved engine gid stamped on the aggregate
* and its primary instance (the one whose gid matches the outgoing
@@ -339,7 +419,14 @@ async function reAddTaskUnderMutation(
// Resolve local prerequisites before touching the old engine GID or
// installing a durable reservation. From the reservation onward, the only
// fallible operation before publication is the engine dispatch itself.
- const torrentMetadata = await readBtMetadata(task, deps)
+ const torrentLike = isTorrentLike(task)
+ const torrentMetadata = torrentLike ? await readBtMetadata(task, deps) : null
+ const directParams = torrentLike
+ ? null
+ : await buildDirectReAddParams(
+ task,
+ deps.directResourceValidator ?? directResourceValidator
+ )
let opts: EngineTaskOptions | null = null
try {
opts = await deps.adapter.getEngineTaskOptions(task.engineTaskId)
@@ -352,11 +439,7 @@ async function reAddTaskUnderMutation(
await bestEffortRemove(deps.adapter, task.engineTaskId, deps.log)
const now = Date.now()
- // Both entry gates force torrent-like (canRebuildTaskInputs and canReseed
- // each require it) and reAddBt re-adds as a checkIntegrity-verified
- // torrent, so even a retried Error/Removed task publishes Seeding — the
- // integrity pass decides whether aria2 actually downloads anything more.
- const status = TaskStatus.Seeding
+ const status = torrentLike ? TaskStatus.Seeding : TaskStatus.Downloading
const reservedGid = newEngineTaskId(deps.createEngineTaskId, 'reAddTask')
const reservedOwner = withReservedGid(task, reservedGid, now)
const candidate = withReservedGid(task, reservedGid, now, status)
@@ -383,10 +466,11 @@ async function reAddTaskUnderMutation(
)
try {
- // HTTP/FTP retry is disabled until the persisted replay recipe lands (see
- // plan Follow-ups); reconstruct the HTTP re-add path from git history when
- // it does.
- await reAddBt(task, opts, deps, reservedGid, torrentMetadata)
+ if (torrentLike && torrentMetadata) {
+ await reAddBt(task, opts, deps, reservedGid, torrentMetadata)
+ } else if (directParams) {
+ await deps.adapter.createDownload({ ...directParams, gid: reservedGid })
+ }
} catch (error) {
await handleFailedEngineAdd(
error,
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index c4425021..06226482 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -363,6 +363,7 @@ describe('handleCreateTask', () => {
unknownOption: 'UNKNOWN_OPTION_SECRET_159',
}
+ const deps = makeDeps()
await handleCreateTask(
{
type: 'http',
@@ -382,7 +383,7 @@ describe('handleCreateTask', () => {
],
proxy: `http://user:${secrets.proxy}@proxy.example:8080`,
},
- makeDeps(),
+ deps,
{
extraEngineOptions: {
referer: `https://origin.example/watch?token=${secrets.referer}`,
@@ -421,6 +422,20 @@ describe('handleCreateTask', () => {
| { params: { gid: string } }
| undefined
expect(dispatchFields?.params.gid).toMatch(/^[0-9a-f]{16}$/)
+
+ const taskPayload = lastAddedTask(deps).instances[0]?.payload
+ expect(taskPayload).toEqual({
+ directReplay: {
+ version: 1,
+ connections: 8,
+ requestModifiers: ['headers', 'proxy', 'extraEngineOptions'],
+ replayability: 'requires-credentials',
+ },
+ })
+ const serializedPayload = JSON.stringify(taskPayload)
+ for (const secret of Object.values(secrets)) {
+ expect(serializedPayload).not.toContain(secret)
+ }
})
it('redacts plugin-rewritten URIs without reducing the result to a count', async () => {
@@ -447,6 +462,7 @@ describe('handleCreateTask', () => {
staged: { commitMetadata: vi.fn() },
}),
} as unknown as Deps['orchestrator']
+ const deps = makeDeps()
await handleCreateTask(
{
@@ -456,7 +472,7 @@ describe('handleCreateTask', () => {
filename: 'file.zip',
headers: [],
},
- { ...makeDeps(), orchestrator }
+ { ...deps, orchestrator }
)
const resultLog = logInfo.mock.calls.find(
@@ -466,6 +482,18 @@ describe('handleCreateTask', () => {
rewrittenUris: ['https://cdn.example/file.zip'],
contributors: { uris: 'plugin-rewriter' },
})
+ const task = lastAddedTask(deps)
+ expect(task.uris).toEqual([
+ `https://cdn.example/file.zip?signature=${rewrittenSecret}`,
+ ])
+ expect(task.instances[0]?.uris).toEqual(task.uris)
+ expect(task.instances[0]?.payload).toEqual({
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ },
+ })
expect(JSON.stringify(logInfo.mock.calls)).not.toContain(rewrittenSecret)
})
@@ -487,6 +515,82 @@ describe('handleCreateTask', () => {
['https://a/b'],
expect.objectContaining({ dir: '/d' })
)
+ expect(lastAddedTask(deps).instances[0]?.payload).toEqual({
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ },
+ })
+ })
+
+ it('persists a captured validator for a public direct download', async () => {
+ const deps = makeDeps()
+ const resourceValidator = {
+ kind: 'strong-etag' as const,
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 7,
+ }
+ const capture = vi.fn().mockResolvedValue(resourceValidator)
+ deps.directResourceValidator = { capture }
+
+ await handleCreateTask(httpRequest(), deps)
+
+ expect(capture).toHaveBeenCalledWith('https://a/b')
+ expect(lastAddedTask(deps).instances[0]?.payload).toEqual({
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ resourceValidator,
+ },
+ })
+ })
+
+ it('does not probe a direct request that depends on credentials', async () => {
+ const deps = makeDeps()
+ const capture = vi.fn()
+ deps.directResourceValidator = { capture }
+
+ await handleCreateTask(
+ {
+ ...httpRequest(),
+ headers: [{ name: 'Authorization', value: 'Bearer secret' }],
+ },
+ deps
+ )
+
+ expect(capture).not.toHaveBeenCalled()
+ expect(lastAddedTask(deps).instances[0]?.payload).toEqual({
+ directReplay: {
+ version: 1,
+ requestModifiers: ['headers'],
+ replayability: 'requires-credentials',
+ },
+ })
+ })
+
+ it('does not attach one validator to an ambiguous mirror set', async () => {
+ const deps = makeDeps()
+ const capture = vi.fn()
+ deps.directResourceValidator = { capture }
+
+ await handleCreateTask(
+ {
+ ...httpRequest(),
+ uris: [
+ 'https://mirror-a.example/file',
+ 'https://mirror-b.example/file',
+ ],
+ },
+ deps
+ )
+
+ expect(capture).not.toHaveBeenCalled()
+ expect(
+ lastAddedTask(deps).instances[0]?.payload.directReplay
+ ).not.toHaveProperty('resourceValidator')
})
it('uses the host-prepared save directory for task and aria2 paths', async () => {
@@ -1107,6 +1211,14 @@ describe('handleCreateTask CreateTaskOptions', () => {
expect(options.header).toEqual(['X-A: 1', 'X-B: 2'])
expect(options['load-cookies']).toBe('/tmp/jar.txt')
expect(options.referer).toBe('http://page')
+ expect(lastAddedTask(deps).instances[0]?.payload).toEqual({
+ directReplay: {
+ version: 1,
+ connections: 1,
+ requestModifiers: ['extraEngineOptions'],
+ replayability: 'requires-credentials',
+ },
+ })
})
})
diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.ts
index 42cb70b5..2c5fa150 100644
--- a/src/core/task/create-task-handler.ts
+++ b/src/core/task/create-task-handler.ts
@@ -58,6 +58,11 @@ import {
parseBtFileLayout,
UnsafeTorrentPathError,
} from './bt-storage-layout'
+import {
+ buildDirectReplayRecipe,
+ type DirectReplayRecipe,
+} from './direct-replay-recipe'
+import type { DirectResourceValidatorService } from './direct-resource-validator'
import type { FinalNamePicker } from './final-name-picker'
import { toTempPath } from './paths'
import type { TaskManager } from './task-manager'
@@ -73,6 +78,8 @@ export interface CreateTaskDeps {
taskManager: TaskManager
activityRecorder: TaskActivityRecorder
eventBus: { emit(event: string, payload: unknown): void }
+ /** Optional best-effort capture of a non-secret HTTP resource validator. */
+ directResourceValidator?: Pick<DirectResourceValidatorService, 'capture'>
/**
* Coalesced TaskUpdated publication (TaskUpdatePublisher.publish). Both
* create-side broadcasts are non-terminal (announce a new owned task /
@@ -397,6 +404,8 @@ async function handleCreateTaskUnderAdmission(
// is responsible for the aria2 wire shape.
let pluginStaged: { commit: (cb: () => void) => void } | undefined
let dispatchEngine: (reservedGid: string) => Promise<string>
+ let directReplay: DirectReplayRecipe | null = null
+ let canonicalUris = deriveUris(req)
// Shared by the HTTP and magnet branches — both dispatch through
// createDownload with an identical log line; only their params differ.
const dispatchCreateDownload =
@@ -589,6 +598,33 @@ async function handleCreateTaskUnderAdmission(
}
}
+ // Persist only the request-shape capability needed to decide whether a
+ // future retry can be reconstructed from TaskInstance. Paths and URIs are
+ // already canonical fields on the instance; modifier VALUES remain
+ // engine-call-only so credentials never enter motrix.db.
+ directReplay = buildDirectReplayRecipe(params)
+ if (
+ directReplay.replayability === 'uri-only' &&
+ deps.directResourceValidator &&
+ params.uris.length === 1
+ ) {
+ try {
+ const resourceValidator = await deps.directResourceValidator.capture(
+ params.uris[0] as string
+ )
+ if (resourceValidator) {
+ directReplay = { ...directReplay, resourceValidator }
+ }
+ } catch (error) {
+ // Validator capture is an optional safety enhancement. A HEAD failure
+ // must not make an otherwise valid download impossible to create.
+ log.debug(
+ { err: error, taskId },
+ 'direct resource validator capture skipped'
+ )
+ }
+ }
+ canonicalUris = [...params.uris]
dispatchEngine = dispatchCreateDownload(params)
} else if (req.payload.kind === 'torrent-base64') {
// Torrent bytes were decoded earlier for name/private extraction; they
@@ -683,9 +719,13 @@ async function handleCreateTaskUnderAdmission(
uploadedBytes: 0,
diskPath,
transitionPhase: TransitionPhase.Idle,
- uris: deriveUris(req),
+ uris: canonicalUris,
uriHash: null,
- payload: btStoragePlan ? btStoragePayload(btStoragePlan.layout) : {},
+ payload: btStoragePlan
+ ? btStoragePayload(btStoragePlan.layout)
+ : directReplay
+ ? { directReplay }
+ : {},
createdAt: now,
updatedAt: now,
}
@@ -699,7 +739,7 @@ async function handleCreateTaskUnderAdmission(
saveDir: effectiveSaveDir,
createdAt: now,
updatedAt: now,
- uris: deriveUris(req),
+ uris: canonicalUris,
dlLimit: req.type === 'bt' ? (req.dlLimit ?? 0) : 0,
ulLimit: req.type === 'bt' ? (req.ulLimit ?? 0) : 0,
filename: finalName,
diff --git a/src/core/task/direct-replay-recipe.test.ts b/src/core/task/direct-replay-recipe.test.ts
new file mode 100644
index 00000000..843954ba
--- /dev/null
+++ b/src/core/task/direct-replay-recipe.test.ts
@@ -0,0 +1,109 @@
+import { parseDirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'
+import { describe, expect, it } from 'vitest'
+import { buildDirectReplayRecipe } from './direct-replay-recipe'
+
+describe('direct replay recipe', () => {
+ it('builds a uri-only v1 recipe for a public direct download', () => {
+ const recipe = buildDirectReplayRecipe({ connections: 8 })
+
+ expect(recipe).toEqual({
+ version: 1,
+ connections: 8,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ })
+ expect(parseDirectReplayRecipe({ directReplay: recipe })).toEqual(recipe)
+ })
+
+ it('records only modifier categories and never their sensitive values', () => {
+ const secrets = [
+ 'Bearer AUTH_SECRET',
+ 'session=COOKIE_SECRET',
+ 'http://user:[email protected]',
+ '/tmp/COOKIE_JAR_SECRET.txt',
+ ]
+ const recipe = buildDirectReplayRecipe({
+ headers: {
+ Authorization: secrets[0] ?? '',
+ Cookie: secrets[1] ?? '',
+ },
+ proxy: secrets[2],
+ extraEngineOptions: { 'load-cookies': secrets[3] ?? '' },
+ })
+
+ expect(recipe).toEqual({
+ version: 1,
+ requestModifiers: ['headers', 'proxy', 'extraEngineOptions'],
+ replayability: 'requires-credentials',
+ })
+ const serialized = JSON.stringify(recipe)
+ for (const secret of secrets) expect(serialized).not.toContain(secret)
+ })
+
+ it('accepts a bounded non-secret resource validator on a uri-only recipe', () => {
+ const recipe = {
+ ...buildDirectReplayRecipe({ connections: 4 }),
+ resourceValidator: {
+ kind: 'strong-etag' as const,
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 7,
+ },
+ }
+
+ expect(parseDirectReplayRecipe({ directReplay: recipe })).toEqual(recipe)
+ })
+
+ it.each([
+ ['missing recipe', {}],
+ ['unknown version', { directReplay: { version: 2 } }],
+ [
+ 'unknown field',
+ {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ authorization: 'secret',
+ },
+ },
+ ],
+ [
+ 'inconsistent replayability',
+ {
+ directReplay: {
+ version: 1,
+ requestModifiers: ['headers'],
+ replayability: 'uri-only',
+ },
+ },
+ ],
+ [
+ 'duplicate modifiers',
+ {
+ directReplay: {
+ version: 1,
+ requestModifiers: ['proxy', 'proxy'],
+ replayability: 'requires-credentials',
+ },
+ },
+ ],
+ [
+ 'weak ETag validator',
+ {
+ directReplay: {
+ version: 1,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ resourceValidator: {
+ kind: 'strong-etag',
+ value: 'W/"release-v1"',
+ capturedAt: 7,
+ },
+ },
+ },
+ ],
+ ])('treats %s as non-replayable', (_label, payload) => {
+ expect(parseDirectReplayRecipe(payload)).toBeNull()
+ })
+})
diff --git a/src/core/task/direct-replay-recipe.ts b/src/core/task/direct-replay-recipe.ts
new file mode 100644
index 00000000..525db773
--- /dev/null
+++ b/src/core/task/direct-replay-recipe.ts
@@ -0,0 +1,45 @@
+import type { CreateDownloadParams } from '@core/engine/engine-adapter'
+import type {
+ DirectReplayRecipe,
+ DirectReplayRequestModifier,
+} from '@shared/schemas/direct-replay-recipe'
+
+export type { DirectReplayRecipe } from '@shared/schemas/direct-replay-recipe'
+
+/**
+ * Build the durable, non-sensitive replay capability record for a direct
+ * download. The output intentionally contains neither paths/URIs (already
+ * canonical on TaskInstance) nor any request-modifier values.
+ */
+export function buildDirectReplayRecipe(
+ params: Pick<
+ CreateDownloadParams,
+ 'connections' | 'headers' | 'proxy' | 'extraEngineOptions'
+ >
+): DirectReplayRecipe {
+ const requestModifiers: DirectReplayRequestModifier[] = []
+
+ if (hasEntries(params.headers)) requestModifiers.push('headers')
+ if (hasText(params.proxy)) requestModifiers.push('proxy')
+ if (hasEntries(params.extraEngineOptions)) {
+ requestModifiers.push('extraEngineOptions')
+ }
+
+ return {
+ version: 1,
+ ...(params.connections === undefined
+ ? {}
+ : { connections: params.connections }),
+ requestModifiers,
+ replayability:
+ requestModifiers.length === 0 ? 'uri-only' : 'requires-credentials',
+ }
+}
+
+function hasEntries(value: object | undefined): boolean {
+ return value !== undefined && Object.keys(value).length > 0
+}
+
+function hasText(value: string | undefined): boolean {
+ return value !== undefined && value.length > 0
+}
diff --git a/src/core/task/direct-resource-validator.test.ts b/src/core/task/direct-resource-validator.test.ts
new file mode 100644
index 00000000..cd3b2b54
--- /dev/null
+++ b/src/core/task/direct-resource-validator.test.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it, vi } from 'vitest'
+import { DirectResourceValidatorService } from './direct-resource-validator'
+
+function fetchSequence(...responses: Response[]) {
+ return vi.fn(async () => responses.shift() as Response)
+}
+
+describe('DirectResourceValidatorService', () => {
+ it('captures a strong ETag and content length with HEAD', async () => {
+ const fetchImpl = fetchSequence(
+ new Response(null, {
+ status: 200,
+ headers: { ETag: '"release-v1"', 'Content-Length': '4096' },
+ })
+ )
+ const service = new DirectResourceValidatorService(fetchImpl, 100, () => 7)
+
+ await expect(service.capture('https://example.com/file')).resolves.toEqual({
+ kind: 'strong-etag',
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 7,
+ })
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://example.com/file',
+ expect.objectContaining({
+ method: 'HEAD',
+ headers: { 'Accept-Encoding': 'identity' },
+ redirect: 'follow',
+ })
+ )
+ })
+
+ it('falls back to Last-Modified only when content length is known', async () => {
+ const fetchImpl = fetchSequence(
+ new Response(null, {
+ status: 200,
+ headers: {
+ 'Last-Modified': 'Tue, 25 Aug 2026 08:00:00 GMT',
+ 'Content-Length': '12',
+ },
+ })
+ )
+ const service = new DirectResourceValidatorService(fetchImpl, 100, () => 8)
+
+ await expect(service.capture('https://example.com/file')).resolves.toEqual({
+ kind: 'last-modified',
+ value: 'Tue, 25 Aug 2026 08:00:00 GMT',
+ contentLength: 12,
+ capturedAt: 8,
+ })
+ })
+
+ it('accepts a matching validator only with a 206 range response', async () => {
+ const fetchImpl = fetchSequence(
+ new Response(Uint8Array.of(1), {
+ status: 206,
+ headers: {
+ ETag: '"release-v1"',
+ 'Content-Length': '1',
+ 'Content-Range': 'bytes 0-0/4096',
+ },
+ })
+ )
+ const service = new DirectResourceValidatorService(fetchImpl)
+
+ await expect(
+ service.verify('https://example.com/file', {
+ kind: 'strong-etag',
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 1,
+ })
+ ).resolves.toEqual({ outcome: 'unchanged', ifRange: '"release-v1"' })
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://example.com/file',
+ expect.objectContaining({
+ method: 'GET',
+ headers: {
+ 'Accept-Encoding': 'identity',
+ Range: 'bytes=0-0',
+ 'If-Range': '"release-v1"',
+ },
+ })
+ )
+ })
+
+ it('classifies changed ETag or total length as source-changed', async () => {
+ const changedTag = new DirectResourceValidatorService(
+ fetchSequence(
+ new Response(null, {
+ status: 200,
+ headers: { ETag: '"release-v2"', 'Content-Length': '4096' },
+ })
+ )
+ )
+ const changedLength = new DirectResourceValidatorService(
+ fetchSequence(
+ new Response(Uint8Array.of(1), {
+ status: 206,
+ headers: {
+ ETag: '"release-v1"',
+ 'Content-Range': 'bytes 0-0/8192',
+ },
+ })
+ )
+ )
+ const expected = {
+ kind: 'strong-etag' as const,
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 1,
+ }
+
+ await expect(
+ changedTag.verify('https://example.com/file', expected)
+ ).resolves.toEqual({
+ outcome: 'source-changed',
+ ifRange: null,
+ })
+ await expect(
+ changedLength.verify('https://example.com/file', expected)
+ ).resolves.toEqual({
+ outcome: 'source-changed',
+ ifRange: null,
+ })
+ })
+
+ it('distinguishes ignored Range from an unverifiable response', async () => {
+ const ignoredRange = new DirectResourceValidatorService(
+ fetchSequence(
+ new Response(null, {
+ status: 200,
+ headers: { ETag: '"release-v1"', 'Content-Length': '4096' },
+ })
+ )
+ )
+ const noValidator = new DirectResourceValidatorService(
+ fetchSequence(new Response(null, { status: 200 }))
+ )
+ const expected = {
+ kind: 'strong-etag' as const,
+ value: '"release-v1"',
+ contentLength: 4096,
+ capturedAt: 1,
+ }
+
+ await expect(
+ ignoredRange.verify('https://example.com/file', expected)
+ ).resolves.toEqual({
+ outcome: 'range-unsupported',
+ ifRange: null,
+ })
+ await expect(
+ noValidator.verify('https://example.com/file', expected)
+ ).resolves.toEqual({
+ outcome: 'unverifiable',
+ ifRange: null,
+ })
+ })
+
+ it('does not classify an HTTP error as Range support', async () => {
+ const service = new DirectResourceValidatorService(
+ fetchSequence(
+ new Response(null, {
+ status: 503,
+ headers: { ETag: '"release-v1"' },
+ })
+ )
+ )
+
+ await expect(
+ service.verify('https://example.com/file', {
+ kind: 'strong-etag',
+ value: '"release-v1"',
+ capturedAt: 1,
+ })
+ ).resolves.toEqual({ outcome: 'unverifiable', ifRange: null })
+ })
+})
diff --git a/src/core/task/direct-resource-validator.ts b/src/core/task/direct-resource-validator.ts
new file mode 100644
index 00000000..8be36f21
--- /dev/null
+++ b/src/core/task/direct-resource-validator.ts
@@ -0,0 +1,173 @@
+import type { DirectResourceValidator } from '@shared/schemas/direct-replay-recipe'
+
+const DEFAULT_TIMEOUT_MS = 3_000
+
+type FetchLike = (
+ input: string | URL | Request,
+ init?: RequestInit
+) => Promise<Response>
+
+export type DirectResourceValidationOutcome =
+ | 'unchanged'
+ | 'source-changed'
+ | 'range-unsupported'
+ | 'unverifiable'
+
+export interface DirectResourceValidationResult {
+ outcome: DirectResourceValidationOutcome
+ ifRange: string | null
+}
+
+/**
+ * Captures and verifies non-secret HTTP validators for URI-only direct tasks.
+ * A verifier never downloads a response body: capture uses HEAD, while resume
+ * verification cancels a one-byte Range response immediately after headers.
+ */
+export class DirectResourceValidatorService {
+ constructor(
+ private readonly fetchImpl: FetchLike = (input, init) =>
+ globalThis.fetch(input, init),
+ private readonly timeoutMs = DEFAULT_TIMEOUT_MS,
+ private readonly now: () => number = Date.now
+ ) {}
+
+ async capture(uri: string): Promise<DirectResourceValidator | null> {
+ const response = await this.request(uri, {
+ method: 'HEAD',
+ headers: { 'Accept-Encoding': 'identity' },
+ })
+ if (!response?.ok) return null
+ return readValidator(response.headers, this.now())
+ }
+
+ async verify(
+ uri: string,
+ expected: DirectResourceValidator
+ ): Promise<DirectResourceValidationResult> {
+ const response = await this.request(uri, {
+ method: 'GET',
+ headers: {
+ 'Accept-Encoding': 'identity',
+ Range: 'bytes=0-0',
+ 'If-Range': expected.value,
+ },
+ })
+ if (!response) return { outcome: 'unverifiable', ifRange: null }
+ if (response.status !== 200 && response.status !== 206) {
+ await cancelBody(response)
+ return { outcome: 'unverifiable', ifRange: null }
+ }
+
+ const current = readValidator(response.headers, this.now())
+ const currentValue = validatorValueForKind(current, expected.kind)
+ if (!currentValue) {
+ await cancelBody(response)
+ return { outcome: 'unverifiable', ifRange: null }
+ }
+ if (currentValue !== expected.value) {
+ await cancelBody(response)
+ return { outcome: 'source-changed', ifRange: null }
+ }
+
+ const currentLength = totalResponseLength(response)
+ if (
+ expected.contentLength !== undefined &&
+ currentLength !== null &&
+ currentLength !== expected.contentLength
+ ) {
+ await cancelBody(response)
+ return { outcome: 'source-changed', ifRange: null }
+ }
+
+ const rangeSatisfied = response.status === 206
+ await cancelBody(response)
+ return rangeSatisfied
+ ? { outcome: 'unchanged', ifRange: expected.value }
+ : { outcome: 'range-unsupported', ifRange: null }
+ }
+
+ private async request(
+ uri: string,
+ init: RequestInit
+ ): Promise<Response | null> {
+ const controller = new AbortController()
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs)
+ try {
+ return await this.fetchImpl(uri, {
+ ...init,
+ redirect: 'follow',
+ signal: controller.signal,
+ })
+ } catch {
+ return null
+ } finally {
+ clearTimeout(timeout)
+ }
+ }
+}
+
+function readValidator(
+ headers: Headers,
+ capturedAt: number
+): DirectResourceValidator | null {
+ const contentLength = parseContentLength(headers.get('content-length'))
+ const etag = headers.get('etag')?.trim()
+ if (
+ etag &&
+ !etag.startsWith('W/') &&
+ etag.startsWith('"') &&
+ etag.endsWith('"') &&
+ !/[\r\n]/.test(etag) &&
+ etag.length <= 512
+ ) {
+ return {
+ kind: 'strong-etag',
+ value: etag,
+ ...(contentLength === null ? {} : { contentLength }),
+ capturedAt,
+ }
+ }
+
+ const lastModified = headers.get('last-modified')?.trim()
+ if (
+ lastModified &&
+ contentLength !== null &&
+ Number.isFinite(Date.parse(lastModified)) &&
+ !/[\r\n]/.test(lastModified) &&
+ lastModified.length <= 512
+ ) {
+ return {
+ kind: 'last-modified',
+ value: lastModified,
+ contentLength,
+ capturedAt,
+ }
+ }
+ return null
+}
+
+function validatorValueForKind(
+ current: DirectResourceValidator | null,
+ expectedKind: DirectResourceValidator['kind']
+): string | null {
+ return current?.kind === expectedKind ? current.value : null
+}
+
+function parseContentLength(value: string | null): number | null {
+ if (!value || !/^\d+$/.test(value)) return null
+ const parsed = Number(value)
+ return Number.isSafeInteger(parsed) ? parsed : null
+}
+
+function totalResponseLength(response: Response): number | null {
+ const contentRange = response.headers.get('content-range')
+ const match = contentRange?.match(/\/([0-9]+)$/)
+ if (match?.[1]) return parseContentLength(match[1])
+ return response.status === 200
+ ? parseContentLength(response.headers.get('content-length'))
+ : null
+}
+
+async function cancelBody(response: Response): Promise<void> {
+ await response.body?.cancel().catch(() => {})
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 0074639a..afbb2500 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -70,6 +70,7 @@ import { removeTask } from '@core/task/actions/remove-task'
import { commitPolledTerminalTransition } from '@core/task/actions/shared'
import { countActiveDownloads } from '@core/task/active-downloads'
import { handleCreateTask } from '@core/task/create-task-handler'
+import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'
import { FileCleanupServiceImpl } from '@core/task/file-cleanup-service'
import { FinalNamePickerImpl } from '@core/task/final-name-picker'
import {
@@ -2038,6 +2039,7 @@ async function initializeMainProcess(): Promise<void> {
}
const createTaskDeps = {
adapter,
+ directResourceValidator: new DirectResourceValidatorService(),
settingsManager,
finalNamePicker,
torrentMetaStore,
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index fe6de08d..a1ba1bbc 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -59,6 +59,7 @@ import {
type CreateTaskDeps,
handleCreateTask,
} from '@core/task/create-task-handler'
+import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'
import type { FileCleanupService } from '@core/task/file-cleanup-service'
import type { FinalNamePicker } from '@core/task/final-name-picker'
import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'
@@ -292,6 +293,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
const createDeps: CreateTaskDeps = {
adapter,
+ directResourceValidator: new DirectResourceValidatorService(),
settingsManager,
finalNamePicker,
torrentMetaStore,
diff --git a/src/server/index.ts b/src/server/index.ts
index d8bc7cc2..56e27665 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -70,6 +70,7 @@ import { finalizeTask } from '@core/task/actions/finalize-task'
import { removeTask } from '@core/task/actions/remove-task'
import { commitPolledTerminalTransition } from '@core/task/actions/shared'
import { handleCreateTask } from '@core/task/create-task-handler'
+import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'
import { FileCleanupServiceImpl } from '@core/task/file-cleanup-service'
import { FinalNamePickerImpl } from '@core/task/final-name-picker'
import {
@@ -1398,6 +1399,7 @@ async function main() {
}
const createTaskDeps = {
adapter,
+ directResourceValidator: new DirectResourceValidatorService(),
settingsManager,
finalNamePicker,
torrentMetaStore,
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 7c429624..3e53af3e 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -45,6 +45,7 @@ import {
type CreateTaskDeps,
handleCreateTask,
} from '@core/task/create-task-handler'
+import { DirectResourceValidatorService } from '@core/task/direct-resource-validator'
import type { FileCleanupService } from '@core/task/file-cleanup-service'
import type { FinalNamePicker } from '@core/task/final-name-picker'
import type { OccurrenceDispatcher } from '@core/task/occurrences/occurrence-dispatcher'
@@ -214,6 +215,7 @@ export function buildServerCommandHandlers(
const createDeps: CreateTaskDeps = {
adapter,
+ directResourceValidator: new DirectResourceValidatorService(),
settingsManager,
finalNamePicker,
torrentMetaStore,
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 5af8358a..f78fc41a 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -866,6 +866,12 @@
"torrentMetaMissing": "Cannot recover this BitTorrent task: the .torrent metadata file is missing. Please remove and re-add the task.",
"reAddFailed": "Cannot recover this task: the engine rejected the re-add request. Please remove and re-add manually.",
"dirtyMetadata": "Cannot recover this task: it is missing the identifying information needed to resume.",
+ "resumeCheckpointMissing": "The partial file was preserved, but its resume checkpoint is missing. Restart safely or re-add the task.",
+ "resumeCredentialsRequired": "The partial file was preserved, but this download needs request credentials that cannot be replayed automatically.",
+ "resumePathInvalid": "The partial file was preserved because its stored output path is invalid.",
+ "resumeSourceChanged": "The partial file was preserved because the remote file changed since the download started.",
+ "resumeRangeUnsupported": "The partial file was preserved because the server does not support safe range resume.",
+ "resumeValidationFailed": "The partial file was preserved because Motrix could not verify that the remote file is unchanged.",
"mediaInterrupted": "This media download was interrupted by an app restart and can't be resumed. Re-add it to retry."
}
},
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 379565da..7e4a40cb 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -853,6 +853,12 @@
"torrentMetaMissing": "无法恢复此 BT 任务:.torrent 元数据文件丢失。请删除任务并重新添加。",
"reAddFailed": "无法恢复此任务:引擎拒绝重新添加请求。请删除任务并手动重新添加。",
"dirtyMetadata": "无法恢复此任务:缺少恢复所需的标识信息。",
+ "resumeCheckpointMissing": "已保留部分文件,但续传检查点已丢失。请安全地重新下载或重新添加任务。",
+ "resumeCredentialsRequired": "已保留部分文件,但此下载需要无法自动重放的请求凭据。",
+ "resumePathInvalid": "由于保存的输出路径无效,已保留部分文件且未自动恢复。",
+ "resumeSourceChanged": "远端文件在下载开始后发生变化,已保留部分文件且未继续写入。",
+ "resumeRangeUnsupported": "服务器不支持安全的范围续传,已保留部分文件且未继续写入。",
+ "resumeValidationFailed": "Motrix 无法确认远端文件是否未发生变化,已保留部分文件且未继续写入。",
"mediaInterrupted": "媒体下载因应用重启而中断,无法恢复。请重新添加以重试。"
}
},
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 68645e4d..dc848349 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -853,6 +853,12 @@
"torrentMetaMissing": "無法復原此 BitTorrent 任務: 缺少 .torrent 中繼資料檔案。請移除後重新新增任務。",
"reAddFailed": "無法復原此任務: 引擎拒絕重新新增要求。請移除後手動重新新增。",
"dirtyMetadata": "無法復原此任務: 缺少繼續下載所需的識別資訊。",
+ "resumeCheckpointMissing": "已保留部分檔案,但續傳檢查點已遺失。請安全地重新下載或重新新增任務。",
+ "resumeCredentialsRequired": "已保留部分檔案,但此下載需要無法自動重播的請求憑證。",
+ "resumePathInvalid": "由於儲存的輸出路徑無效,已保留部分檔案且未自動復原。",
+ "resumeSourceChanged": "遠端檔案在下載開始後發生變更,已保留部分檔案且未繼續寫入。",
+ "resumeRangeUnsupported": "伺服器不支援安全的範圍續傳,已保留部分檔案且未繼續寫入。",
+ "resumeValidationFailed": "Motrix 無法確認遠端檔案是否未發生變更,已保留部分檔案且未繼續寫入。",
"mediaInterrupted": "此媒體下載因應用程式重新啟動而中斷,無法繼續。請重新新增後再試。"
}
},
diff --git a/src/shared/schemas/direct-replay-recipe.ts b/src/shared/schemas/direct-replay-recipe.ts
new file mode 100644
index 00000000..7734b179
--- /dev/null
+++ b/src/shared/schemas/direct-replay-recipe.ts
@@ -0,0 +1,106 @@
+import { z } from 'zod'
+
+/**
+ * Request-shape facts that explain why a direct download cannot be replayed
+ * from its persisted URI alone. Values are deliberately never part of this
+ * schema: credentials and per-task engine options stay out of motrix.db.
+ */
+export const directReplayRequestModifierSchema = z.enum([
+ 'headers',
+ 'proxy',
+ 'extraEngineOptions',
+])
+
+const validatorValueSchema = z
+ .string()
+ .min(1)
+ .max(512)
+ .refine((value) => !/[\r\n]/.test(value), 'validator contains CR/LF')
+
+export const directResourceValidatorSchema = z.discriminatedUnion('kind', [
+ z
+ .object({
+ kind: z.literal('strong-etag'),
+ value: validatorValueSchema.refine(
+ (value) =>
+ !value.startsWith('W/') &&
+ value.startsWith('"') &&
+ value.endsWith('"'),
+ 'strong ETag must be quoted and must not use W/'
+ ),
+ contentLength: z.number().int().nonnegative().optional(),
+ capturedAt: z.number().int().nonnegative(),
+ })
+ .strict(),
+ z
+ .object({
+ kind: z.literal('last-modified'),
+ value: validatorValueSchema.refine(
+ (value) => Number.isFinite(Date.parse(value)),
+ 'Last-Modified must be a valid HTTP date'
+ ),
+ contentLength: z.number().int().nonnegative(),
+ capturedAt: z.number().int().nonnegative(),
+ })
+ .strict(),
+])
+
+const directReplayV1Schema = z
+ .object({
+ version: z.literal(1),
+ connections: z.number().int().min(1).max(128).optional(),
+ requestModifiers: z.array(directReplayRequestModifierSchema).max(3),
+ replayability: z.enum(['uri-only', 'requires-credentials']),
+ resourceValidator: directResourceValidatorSchema.optional(),
+ })
+ .strict()
+ .superRefine((recipe, ctx) => {
+ const uniqueModifiers = new Set(recipe.requestModifiers)
+ if (uniqueModifiers.size !== recipe.requestModifiers.length) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'requestModifiers must not contain duplicates',
+ path: ['requestModifiers'],
+ })
+ }
+
+ const expectedReplayability =
+ recipe.requestModifiers.length === 0 ? 'uri-only' : 'requires-credentials'
+ if (recipe.replayability !== expectedReplayability) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'replayability does not match requestModifiers',
+ path: ['replayability'],
+ })
+ }
+ })
+
+export const directReplayRecipeSchema = directReplayV1Schema
+
+export type DirectReplayRequestModifier = z.infer<
+ typeof directReplayRequestModifierSchema
+>
+export type DirectResourceValidator = z.infer<
+ typeof directResourceValidatorSchema
+>
+export type DirectReplayRecipe = z.infer<typeof directReplayRecipeSchema>
+
+/**
+ * Read a versioned recipe from a task-instance payload. Unknown versions,
+ * malformed objects, and internally inconsistent claims are all treated as
+ * non-replayable rather than being partially coerced.
+ */
+export function parseDirectReplayRecipe(
+ payload: Record<string, unknown> | null | undefined
+): DirectReplayRecipe | null {
+ if (!payload) return null
+ const parsed = directReplayRecipeSchema.safeParse(payload.directReplay)
+ return parsed.success ? parsed.data : null
+}
+
+/** True only when the persisted recipe proves URI-only replay is equivalent. */
+export function isUriOnlyDirectReplay(
+ payload: Record<string, unknown> | null | undefined
+): boolean {
+ return parseDirectReplayRecipe(payload)?.replayability === 'uri-only'
+}
diff --git a/src/shared/types/task-actions.test.ts b/src/shared/types/task-actions.test.ts
index 3118e136..9eb9e9c3 100644
--- a/src/shared/types/task-actions.test.ts
+++ b/src/shared/types/task-actions.test.ts
@@ -55,6 +55,27 @@ function magnetMetadataInstance(uri = 'magnet:?xt=urn:btih:abc'): TaskInstance {
}
}
+function directInstance(
+ replayability: 'uri-only' | 'requires-credentials'
+): TaskInstance {
+ const requestModifiers =
+ replayability === 'uri-only' ? [] : (['headers'] as const)
+ return {
+ ...muxInstance(TaskStatus.Error),
+ instanceId: 'primary:t1',
+ gid: 'direct-gid',
+ phase: TaskInstancePhase.HttpDownload,
+ uris: ['https://example.com/x'],
+ payload: {
+ directReplay: {
+ version: 1,
+ requestModifiers,
+ replayability,
+ },
+ },
+ }
+}
+
function makeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {
return makeDownloadTask({
id: 't1',
@@ -330,16 +351,59 @@ describe('canRebuildTaskInputs', () => {
).toBe(true)
})
- // HTTP/FTP is false even WITH uris: headers, cookies, referer, per-task
- // proxy and `out` are not persisted anywhere, so a uris-only re-add is a
- // different request than the one that failed.
- it('returns false for HTTP even with uris', () => {
+ it('returns true for public HTTP with a valid uri-only recipe', () => {
+ expect(
+ canRebuildTaskInputs(
+ makeTask({
+ kind: TaskKind.Direct,
+ type: TaskType.Http,
+ uris: ['http://example.com/x'],
+ instances: [directInstance('uri-only')],
+ })
+ )
+ ).toBe(true)
+ })
+
+ it('returns false for legacy HTTP without a recipe', () => {
+ expect(
+ canRebuildTaskInputs(
+ makeTask({
+ kind: TaskKind.Direct,
+ type: TaskType.Http,
+ uris: ['http://example.com/x'],
+ })
+ )
+ ).toBe(false)
+ })
+
+ it('returns false for HTTP whose request modifiers require credentials', () => {
expect(
canRebuildTaskInputs(
makeTask({
kind: TaskKind.Direct,
type: TaskType.Http,
uris: ['http://example.com/x'],
+ instances: [directInstance('requires-credentials')],
+ })
+ )
+ ).toBe(false)
+ })
+
+ it('returns false for a malformed or unknown recipe version', () => {
+ const instance = directInstance('uri-only')
+ instance.payload = {
+ directReplay: {
+ version: 2,
+ requestModifiers: [],
+ replayability: 'uri-only',
+ },
+ }
+ expect(
+ canRebuildTaskInputs(
+ makeTask({
+ kind: TaskKind.Direct,
+ type: TaskType.Http,
+ instances: [instance],
})
)
).toBe(false)
@@ -452,6 +516,44 @@ describe('canAttemptRetry', () => {
expect(canAttemptRetry(task)).toBe(true)
})
+ it('offers direct-readd only for an errored uri-only direct task', () => {
+ const errorTask = makeTask({
+ kind: TaskKind.Direct,
+ type: TaskType.Http,
+ status: TaskStatus.Error,
+ instances: [directInstance('uri-only')],
+ })
+ const removedTask = makeTask({
+ ...errorTask,
+ status: TaskStatus.Removed,
+ })
+
+ expect(canRebuildTaskInputs(errorTask)).toBe(true)
+ expect(getTaskRetryKind(errorTask)).toBe('direct-readd')
+ expect(canAttemptRetry(errorTask)).toBe(true)
+ expect(canRebuildTaskInputs(removedTask)).toBe(true)
+ expect(getTaskRetryKind(removedTask)).toBeNull()
+ expect(canAttemptRetry(removedTask)).toBe(false)
+ })
+
+ it.each([
+ 'task.recovery.startup.resumeCheckpointMissing',
+ 'task.recovery.startup.resumeCredentialsRequired',
+ 'task.recovery.startup.resumePathInvalid',
+ ])('does not offer a doomed direct retry for %s', (errorDetailKey) => {
+ const task = makeTask({
+ kind: TaskKind.Direct,
+ type: TaskType.Http,
+ status: TaskStatus.Error,
+ errorDetailKey,
+ instances: [directInstance('uri-only')],
+ })
+
+ expect(canRebuildTaskInputs(task)).toBe(true)
+ expect(getTaskRetryKind(task)).toBeNull()
+ expect(canAttemptRetry(task)).toBe(false)
+ })
+
it('does not offer metadata retry without a persisted magnet URI', () => {
const task = makeTask({
kind: TaskKind.Bt,
diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.ts
index daa5c667..393654a6 100644
--- a/src/shared/types/task-actions.ts
+++ b/src/shared/types/task-actions.ts
@@ -1,3 +1,4 @@
+import { isUriOnlyDirectReplay } from '@shared/schemas/direct-replay-recipe'
import {
type DownloadTask,
TaskInstancePhase,
@@ -117,20 +118,23 @@ export function isTorrentLike(t: DownloadTask): boolean {
* the persisted .torrent sidecar: with it, `addTorrent` reproduces the
* original add exactly.
*
- * Everything else (HTTP/FTP/metalink) is FALSE, even though the uris
- * survive. The rest of the add — request headers, cookies, referer,
- * per-task proxy, the `out` filename — is never persisted; `reAddTask`
- * recovers it only from aria2's still-resident stopped result, which is
- * gone after a restart or once aria2 purges the row. A retry built from
- * the uris alone silently re-downloads with different request semantics:
- * an authenticated download becomes an unauthenticated one, a
- * referer-gated URL 403s. Re-enabling this needs a persisted replay
- * recipe — tracked in the plan's Follow-ups.
+ * A direct task is rebuildable only when its versioned instance recipe proves
+ * that the original request had URI-only semantics. Legacy tasks and tasks
+ * created with headers, cookies, referer, proxy, or any other per-task engine
+ * option remain conservatively blocked: those values are intentionally not
+ * persisted because they may contain credentials.
*/
export function canRebuildTaskInputs(t: DownloadTask): boolean {
if (isMediaKind(t.kind)) return false
if (isTorrentLike(t)) return t.torrentMetaPath != null
- return false
+ if (t.kind !== TaskKind.Direct) return false
+
+ const primary = t.instances.find(
+ (instance) => instance.phase === TaskInstancePhase.HttpDownload
+ )
+ return (
+ Boolean(primary?.uris.length) && isUriOnlyDirectReplay(primary?.payload)
+ )
}
/**
@@ -152,12 +156,39 @@ export function canRetryMagnetMetadata(t: DownloadTask): boolean {
)
}
-export type TaskRetryKind = 'torrent-readd' | 'magnet-metadata'
+export type TaskRetryKind = 'torrent-readd' | 'direct-readd' | 'magnet-metadata'
+
+const NON_RETRYABLE_DIRECT_RECOVERY_ERRORS = new Set([
+ 'task.recovery.startup.resumeCheckpointMissing',
+ 'task.recovery.startup.resumeCredentialsRequired',
+ 'task.recovery.startup.resumePathInvalid',
+ 'task.recovery.startup.resumeSourceChanged',
+ 'task.recovery.startup.resumeRangeUnsupported',
+ 'task.recovery.startup.resumeValidationFailed',
+])
/** Resolve the concrete replay operation behind the generic Retry UI. */
export function getTaskRetryKind(t: DownloadTask): TaskRetryKind | null {
if (!canRetry(t)) return null
- if (canRebuildTaskInputs(t)) return 'torrent-readd'
+ if (canRebuildTaskInputs(t)) {
+ if (isTorrentLike(t)) return 'torrent-readd'
+ // Removed direct tasks are user-retired occurrences. Only an Error is an
+ // eligible direct retry; this also prevents the generic retry surface from
+ // silently resurrecting a task the user explicitly removed.
+ // Recovery errors that need new credentials or an explicit safe restart
+ // are also excluded: replaying the same recipe/path would deterministically
+ // fail again and must not be presented as a usable Retry action.
+ if (
+ t.kind === TaskKind.Direct &&
+ t.status === TaskStatus.Error &&
+ !(
+ t.errorDetailKey &&
+ NON_RETRYABLE_DIRECT_RECOVERY_ERRORS.has(t.errorDetailKey)
+ )
+ ) {
+ return 'direct-readd'
+ }
+ }
if (canRetryMagnetMetadata(t)) return 'magnet-metadata'
return null
}