Skip to content

A full-featured download manager.

fix: use uuid v7 for browser-safe request and task ids (#2446)

Dr_rOot27a48681749f
diff --git a/e2e/fixtures/http-server.ts b/e2e/fixtures/http-server.ts
index 92a9acaa..8acca9fb 100644
--- a/e2e/fixtures/http-server.ts
+++ b/e2e/fixtures/http-server.ts
@@ -2,6 +2,7 @@ import crypto from 'node:crypto'
import { readFile } from 'node:fs/promises'
import http from 'node:http'
import type { AddressInfo } from 'node:net'
+import { v7 as uuidv7 } from 'uuid'
export interface HttpRequestRecord {
sequence: number
@@ -85,7 +86,7 @@ export async function startHttpFixture(
const size = opts.size ?? 1024 * 1024
const pathname = opts.pathname ?? '/test.bin'
let payload = crypto.randomBytes(size)
- let etag = quoteEtag(opts.etag ?? `motrix-e2e-${crypto.randomUUID()}`)
+ let etag = quoteEtag(opts.etag ?? `motrix-e2e-${uuidv7()}`)
let resourceVersion = 1
let rangeSupport = opts.rangeSupport ?? true
let sequence = 0
@@ -251,7 +252,7 @@ export async function startHttpFixture(
changeResource: (nextEtag) => {
payload = crypto.randomBytes(size)
resourceVersion++
- etag = quoteEtag(nextEtag ?? `motrix-e2e-${crypto.randomUUID()}`)
+ etag = quoteEtag(nextEtag ?? `motrix-e2e-${uuidv7()}`)
return { etag, sha256: sha256(payload), version: resourceVersion }
},
verifyFile: async (filePath) => {
diff --git a/e2e/renderer-recovery.spec.ts b/e2e/renderer-recovery.spec.ts
index 19e1dc91..8c47d8cf 100644
--- a/e2e/renderer-recovery.spec.ts
+++ b/e2e/renderer-recovery.spec.ts
@@ -1,6 +1,7 @@
import { writeFile } from 'node:fs/promises'
import path from 'node:path'
import type { ElectronApplication, Page } from '@playwright/test'
+import { v7 as uuidv7 } from 'uuid'
import { Commands } from '../src/shared/protocol/commands'
import { Queries } from '../src/shared/protocol/queries'
import {
@@ -468,12 +469,12 @@ test('an accepted submission survives renderer replacement without creating a du
const page = await findAddTaskWindow(electronApp)
await expect(page.getByRole('textbox', { name: 'URLs' })).toBeVisible()
await page.evaluate(
- async ({ query, command, create, uri, saveDir }) => {
+ async ({ query, command, create, uri, saveDir, submissionId }) => {
const session = (await window.motrix?.invoke(query)) as {
generation: string
}
await window.motrix?.invoke(command, {
- id: crypto.randomUUID(),
+ id: submissionId,
generation: session.generation,
channel: create,
args: [{ type: 'http', uris: [uri], saveDir, connections: 1 }],
@@ -485,6 +486,7 @@ test('an accepted submission survives renderer replacement without creating a du
create: Commands.CreateTask,
uri: fixture.fileUrl,
saveDir: path.join(userDataDir, 'downloads'),
+ submissionId: uuidv7(),
}
)
const restored = await recover(electronApp, page)
diff --git a/e2e/web-directory-picker/fixture-transport.ts b/e2e/web-directory-picker/fixture-transport.ts
index dddf3c81..b4c196cd 100644
--- a/e2e/web-directory-picker/fixture-transport.ts
+++ b/e2e/web-directory-picker/fixture-transport.ts
@@ -26,6 +26,7 @@ import {
ValidateServerDirectoryRequestSchema,
} from '@shared/schemas/server-directory'
import { createDefaultSpeedLimitSettings } from '@shared/schemas/speed-limit'
+import { v7 as uuidv7 } from 'uuid'
const folders = new Map<string, string[]>([
['/', ['archive', 'downloads', 'home']],
@@ -69,7 +70,7 @@ const canVisit = (path: string) =>
['/downloads', '/archive'].some(
(root) => path === root || path.startsWith(`${root}/`)
))
-let generalRevision = crypto.randomUUID()
+let generalRevision = uuidv7()
const generalSnapshot = () => ({
revision: generalRevision,
app: GeneralSettingsAppSchema.parse(settings.app),
@@ -85,7 +86,7 @@ function setPreferences(value: DirectoryPreferences) {
const next = DirectoryPreferencesSchema.parse(value)
if (JSON.stringify(next) === JSON.stringify(preferences())) return
settings.app.directoryPreferences = next
- generalRevision = crypto.randomUUID()
+ generalRevision = uuidv7()
for (const listener of listeners.get(Events.DirectoryPreferencesChanged) ??
[])
listener(preferences())
@@ -273,7 +274,7 @@ export const transport: Transport = {
settings.app = { ...settings.app, ...app, directoryPreferences: next }
if (JSON.stringify(current) !== JSON.stringify(next))
setPreferences(next)
- generalRevision = crypto.randomUUID()
+ generalRevision = uuidv7()
return { ok: true, value: generalSnapshot() }
}
case Commands.SaveDownloadsSettings: {
@@ -308,7 +309,7 @@ export const transport: Transport = {
if (JSON.stringify(current) !== JSON.stringify(next))
setPreferences(next)
// Even an empty committed draft fences a timed-out predecessor.
- generalRevision = crypto.randomUUID()
+ generalRevision = uuidv7()
return {
ok: true,
value: downloadsSnapshot(),
diff --git a/e2e/web-directory-picker/preferences.browser.ts b/e2e/web-directory-picker/preferences.browser.ts
index 57f84acf..29bd550d 100644
--- a/e2e/web-directory-picker/preferences.browser.ts
+++ b/e2e/web-directory-picker/preferences.browser.ts
@@ -1,6 +1,8 @@
import { expect, type Locator, type Page, test } from '@playwright/test'
+import { version as uuidVersion } from 'uuid'
import { Commands } from '../../src/shared/protocol/commands'
import { Queries } from '../../src/shared/protocol/queries'
+import { taskCreateRequestSchema } from '../../src/shared/schemas/add-task'
async function seed(page: Page, query = '') {
await page.goto(`/${query}`)
@@ -936,6 +938,41 @@ test('unrestricted common places, root breadcrumb and Mac jumps stay available w
})
})
+test('Web downloads use UUID v7 without native randomUUID and preserve the ID on retry', async ({
+ page,
+}) => {
+ await page.addInitScript(() => {
+ Object.defineProperty(crypto, 'randomUUID', {
+ configurable: true,
+ value: undefined,
+ })
+ })
+ await seed(page)
+ const parent = await openDownload(page)
+ await page.evaluate(() => {
+ window.directoryPickerFixture.taskCreateFailure = true
+ })
+ await parent.getByRole('button', { name: 'Download', exact: true }).click()
+ await expect(
+ parent.getByText('The fixture rejected this download.', { exact: false })
+ ).toBeVisible()
+ const firstCalls = await parentSubmissions(page)
+ expect(firstCalls).toHaveLength(1)
+ const first = taskCreateRequestSchema.parse(firstCalls[0].args[0])
+ if (first.type !== 'http') throw new Error('Expected an HTTP download')
+ expect(uuidVersion(first.requestId ?? '')).toBe(7)
+ await page.evaluate(() => {
+ window.directoryPickerFixture.taskCreateFailure = false
+ })
+ await parent.getByRole('button', { name: 'Download', exact: true }).click()
+ await expect(parent).not.toBeVisible()
+ const calls = await parentSubmissions(page)
+ expect(calls).toHaveLength(2)
+ expect(taskCreateRequestSchema.parse(calls[1].args[0])).toMatchObject({
+ requestId: first.requestId,
+ })
+})
+
test('Web star saves the browsed directory and only accepted AddTask updates shared recent history', async ({
page,
}) => {
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index 33ac3b83..3b7981df 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -22,6 +22,7 @@ import {
TaskType,
TransitionPhase,
} from '@shared/types/task'
+import { v7 as uuidv7 } from 'uuid'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Aria2Adapter } from '../engine/aria2/aria2-adapter'
import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'
@@ -214,7 +215,7 @@ describe('source admission before side effects', () => {
const tasks: DownloadTask[] = []
vi.mocked(deps.taskManager.getAll).mockImplementation(() => tasks)
add.mockImplementation((task) => tasks.push(task))
- const request = { ...httpRequest(), requestId: crypto.randomUUID() }
+ const request = { ...httpRequest(), requestId: uuidv7() }
const first = await handleCreateTask(request, deps)
const second = await handleCreateTask(request, deps)
expect(second).toMatchObject({ outcome: 'reused', taskId: first.taskId })
diff --git a/src/core/task/media-task-coordinator.test.ts b/src/core/task/media-task-coordinator.test.ts
index 72ed0026..d456fc2a 100644
--- a/src/core/task/media-task-coordinator.test.ts
+++ b/src/core/task/media-task-coordinator.test.ts
@@ -20,6 +20,7 @@ import {
} from '@shared/types/task'
import { canPause } from '@shared/types/task-actions'
import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'
+import { version as uuidVersion } from 'uuid'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { MediaCoordinatorDeps, MediaJob } from './media-task-coordinator'
import { MediaTaskCoordinator } from './media-task-coordinator'
@@ -748,6 +749,20 @@ describe('MediaTaskCoordinator.start', () => {
expect(taskManager.getById(taskId)?.finishedAt).not.toBeNull()
})
+ it.each(['start', 'submit'] as const)(
+ '%s defaults to a UUID v7 task ID when no ID factory is injected',
+ async (method) => {
+ const { deps, taskManager } = makeDeps({ mintTaskId: undefined })
+ const coordinator = new MediaTaskCoordinator(deps)
+ try {
+ const { taskId } = await coordinator[method](baseJob())
+ expect(uuidVersion(taskId)).toBe(7)
+ expect(taskManager.getById(taskId)).toBeDefined()
+ } finally {
+ await coordinator.stopAndDrain()
+ }
+ }
+ )
it('uses taskId from job when provided', async () => {
const { deps, taskManager } = makeDeps({
mintTaskId: () => 'should-not-use',
diff --git a/src/core/task/media-task-coordinator.ts b/src/core/task/media-task-coordinator.ts
index a9259eb8..f865d55e 100644
--- a/src/core/task/media-task-coordinator.ts
+++ b/src/core/task/media-task-coordinator.ts
@@ -12,6 +12,7 @@ import {
} from '@core/ffmpeg/ffmpeg-service'
import { ensureDirectory } from '@core/fs/ensure-directory'
import { pathExists } from '@core/fs/path-exists'
+import { newTaskId } from '@core/lib/ids'
import { getLogger } from '@core/logger'
import type { assembleSegments } from '@core/media/segment-assembler'
import type { SegmentDecryptor } from '@core/media/segment-decryptor'
@@ -189,7 +190,7 @@ export class MediaTaskCoordinator {
throw new Error('MediaTaskCoordinator is stopped')
}
- const taskId = job.taskId ?? this.deps.mintTaskId?.() ?? crypto.randomUUID()
+ const taskId = job.taskId ?? this.deps.mintTaskId?.() ?? newTaskId()
let accepted = false
let resolveAccepted!: () => void
let rejectAccepted!: (error: unknown) => void
@@ -229,7 +230,7 @@ export class MediaTaskCoordinator {
* contract. Production bridge and desktop submit paths use submit().
*/
async start(job: MediaJob): Promise<{ taskId: string }> {
- const taskId = job.taskId ?? this.deps.mintTaskId?.() ?? crypto.randomUUID()
+ const taskId = job.taskId ?? this.deps.mintTaskId?.() ?? newTaskId()
return this.run(job, taskId)
}
diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsx
index f504a945..46a15e0b 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -1,6 +1,7 @@
import { invalidateTaskList } from '@renderer/hooks/use-task-list'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { version as uuidVersion } from 'uuid'
import { afterEach, describe, expect, it, vi } from 'vitest'
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
@@ -245,6 +246,8 @@ describe('AddTaskForm', () => {
.filter(([channel]) => channel === 'command:createTask')
.map(([, request]) => request)
expect(submitted).toHaveLength(3)
+ for (const request of submitted)
+ expect(uuidVersion(request.requestId)).toBe(7)
expect(submitted[0].requestId).not.toBe(submitted[1].requestId)
expect(submitted[1].requestId).toBe(submitted[2].requestId)
expect(submitted[2].uris).toEqual(['https://a/second'])
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 02d96510..eed23386 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -59,7 +59,7 @@ import {
useWatch,
} from 'react-hook-form'
import { useTranslation } from 'react-i18next'
-import { v4 as uuid } from 'uuid'
+import { v7 as uuidv7 } from 'uuid'
import { AddTaskLayoutProvider } from './add-task-layout-context'
import { FooterActions } from './footer-actions'
import { LinksTabPanel } from './links-tab-panel'
@@ -537,7 +537,7 @@ export function AddTaskForm({
const identity = createInputIdentity(request)
const index = unused.findIndex((input) => input.identity === identity)
return index < 0
- ? { id: uuid(), identity }
+ ? { id: uuidv7(), identity }
: unused.splice(index, 1)[0]
})
submissionInputs.current = inputs
diff --git a/src/renderer/features/plugin-operations/operation-form.test.tsx b/src/renderer/features/plugin-operations/operation-form.test.tsx
index 9476e2c6..bff1e08a 100644
--- a/src/renderer/features/plugin-operations/operation-form.test.tsx
+++ b/src/renderer/features/plugin-operations/operation-form.test.tsx
@@ -7,10 +7,11 @@ import { electronServices } from '@renderer/platform/electron-services'
import { PlatformServicesProvider } from '@renderer/platform/services'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
-import type {
- OperationDescriptor,
- OperationDraft,
- OperationJob,
+import {
+ type OperationDescriptor,
+ type OperationDraft,
+ type OperationJob,
+ operationStartSchema,
} from '@shared/schemas/plugin-operations'
import { textOperationManifest } from '@test-utils/plugin-operation-fixture'
import {
@@ -21,6 +22,7 @@ import {
screen,
waitFor,
} from '@testing-library/react'
+import { version as uuidVersion } from 'uuid'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import OperationForm from './operation-form'
import { operationSessionKey, useOperationSessions } from './operation-store'
@@ -161,6 +163,7 @@ describe('declarative operation form', () => {
})
afterEach(async () => {
cleanup()
+ vi.unstubAllGlobals()
await applyRendererLocale('en-US')
})
it('shows a skeleton while loading and resumes the host draft after repeated document reloads', async () => {
@@ -219,6 +222,42 @@ describe('declarative operation form', () => {
).not.toBeInTheDocument()
expect(invoke).toHaveBeenCalledWith(Commands.CancelPluginOperation, job.id)
})
+ it.each([undefined, '00000000-0000-4000-8000-000000000005'])(
+ 'starts without native randomUUID and reuses the idempotency key after a lost response (cached: %s)',
+ async (cachedKey) => {
+ vi.stubGlobal('crypto', {
+ getRandomValues: crypto.getRandomValues.bind(crypto),
+ })
+ const base = invoke.getMockImplementation()
+ let starts = 0
+ invoke.mockImplementation(async (channel, ...args) => {
+ if (channel === Commands.StartPluginOperation && ++starts === 1)
+ throw new TypeError('Failed to fetch')
+ return base?.(channel, ...args)
+ })
+ mount()
+ const run = await screen.findByRole('button', { name: 'Run operation' })
+ if (cachedKey)
+ useOperationSessions.getState().save(operationSessionKey(request), {
+ key: cachedKey,
+ })
+ fireEvent.click(run)
+ await screen.findByText(
+ 'The operation failed. See the plugin log for details.'
+ )
+ fireEvent.click(run)
+ await screen.findByText('Running')
+ const calls = invoke.mock.calls.filter(
+ ([channel]) => channel === Commands.StartPluginOperation
+ )
+ expect(calls).toHaveLength(2)
+ const first = operationStartSchema.parse(calls[0][1])
+ const second = operationStartSchema.parse(calls[1][1])
+ expect(second).toEqual(first)
+ if (cachedKey) expect(first.idempotencyKey).toBe(cachedKey)
+ else expect(uuidVersion(first.idempotencyKey)).toBe(7)
+ }
+ )
it('recovers a running job after reload without issuing a new start', async () => {
const base = invoke.getMockImplementation()
invoke.mockImplementation(async (channel, ...args) =>
diff --git a/src/renderer/features/plugin-operations/operation-form.tsx b/src/renderer/features/plugin-operations/operation-form.tsx
index 70063243..2d18c3b4 100644
--- a/src/renderer/features/plugin-operations/operation-form.tsx
+++ b/src/renderer/features/plugin-operations/operation-form.tsx
@@ -15,6 +15,7 @@ import {
import { useCallback, useEffect, useRef, useState } from 'react'
import { FormProvider, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
+import { v7 as uuidv7 } from 'uuid'
import { OperationFields } from './operation-fields'
import { OperationIcon } from './operation-icon'
import { OperationSkeleton } from './operation-skeleton'
@@ -412,8 +413,7 @@ function OperationFormContent({
return
}
const key =
- useOperationSessions.getState().sessions[sessionKey]?.key ??
- crypto.randomUUID()
+ useOperationSessions.getState().sessions[sessionKey]?.key ?? uuidv7()
save({ key })
if (cancelRequested.current) return
let next = await invokeOperation<OperationJob>(
diff --git a/src/renderer/lib/transport/electron.test.ts b/src/renderer/lib/transport/electron.test.ts
index 0819afc9..8a3f1201 100644
--- a/src/renderer/lib/transport/electron.test.ts
+++ b/src/renderer/lib/transport/electron.test.ts
@@ -8,14 +8,66 @@ import {
} from '@shared/protocol/errors'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
+import { rendererSubmissionSchema } from '@shared/schemas/renderer-submission'
+import { version as uuidVersion } from 'uuid'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ElectronTransport } from './electron'
afterEach(() => {
Reflect.deleteProperty(window, 'motrix')
+ vi.unstubAllGlobals()
})
describe('ElectronTransport', () => {
+ it('wraps submissions with distinct UUID v7 IDs without native randomUUID', async () => {
+ vi.stubGlobal('crypto', {
+ getRandomValues: crypto.getRandomValues.bind(crypto),
+ })
+ const generation = '00000000-0000-4000-8000-000000000001'
+ const invoke = vi.fn(async (channel: string, ..._args: unknown[]) =>
+ channel === Queries.GetRendererSession
+ ? {
+ generation,
+ windowId: 'add-task',
+ recovered: false,
+ submissionNeedsReview: false,
+ strings: {
+ title: '',
+ description: '',
+ recovering: '',
+ recover: '',
+ diagnostics: '',
+ downloads: '',
+ failed: '',
+ restored: '',
+ },
+ }
+ : { taskId: 'task-1' }
+ )
+ Object.defineProperty(window, 'motrix', {
+ configurable: true,
+ value: { invoke, platform: 'darwin' },
+ })
+ const transport = new ElectronTransport()
+ const args = { type: 'http', uris: ['https://example.test/file'] }
+ await expect(transport.invoke(Commands.CreateTask, args)).resolves.toEqual({
+ taskId: 'task-1',
+ })
+ await transport.invoke(Commands.CreateTask, args)
+ const submissions = invoke.mock.calls
+ .filter(([channel]) => channel === Commands.ExecuteRendererSubmission)
+ .map((call) => rendererSubmissionSchema.parse(call[1]))
+ expect(submissions).toHaveLength(2)
+ for (const submission of submissions) {
+ expect(submission).toMatchObject({
+ generation,
+ channel: Commands.CreateTask,
+ args: [args],
+ })
+ expect(uuidVersion(submission.id)).toBe(7)
+ }
+ expect(submissions[0].id).not.toBe(submissions[1].id)
+ })
it('retains preload disposers per callback and channel without passing callbacks back across the bridge', () => {
const first = vi.fn()
const second = vi.fn()
diff --git a/src/renderer/lib/transport/electron.ts b/src/renderer/lib/transport/electron.ts
index 7a1c84e3..57c965db 100644
--- a/src/renderer/lib/transport/electron.ts
+++ b/src/renderer/lib/transport/electron.ts
@@ -4,6 +4,7 @@ import type { EventChannel } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import { rendererSessionSchema } from '@shared/schemas/renderer-health'
import { rendererSubmissionChannelSchema } from '@shared/schemas/renderer-submission'
+import { v7 as uuidv7 } from 'uuid'
import { registerIntentConsumer } from '../renderer-intents'
import type { AnyChannel, EventListener, Transport } from './types'
@@ -28,7 +29,7 @@ export class ElectronTransport implements Transport {
await getMotrix().invoke(Queries.GetRendererSession)
)
return getMotrix().invoke(Commands.ExecuteRendererSubmission, {
- id: crypto.randomUUID(),
+ id: uuidv7(),
generation: session.generation,
channel,
args,