Skip to content

A full-featured download manager.

feat(server): complete app rpc parity (#2037)

Dr_rOote3efa6a72e06
diff --git a/e2e/add-task.spec.ts b/e2e/add-task.spec.ts
index c67bad03..93860d2b 100644
--- a/e2e/add-task.spec.ts
+++ b/e2e/add-task.spec.ts
@@ -1,3 +1,6 @@
+import { writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import type { Page } from '@playwright/test'
import {
expect,
findAddTaskWindow,
@@ -5,6 +8,46 @@ import {
waitForEngineReady,
} from './fixtures/electron-app'
+const TORRENT_ANNOUNCE = 'http://127.0.0.1:9/announce'
+
+function singleFileTorrent(name: string): Buffer {
+ return Buffer.from(
+ `d8:announce${TORRENT_ANNOUNCE.length}:${TORRENT_ANNOUNCE}4:infod6:lengthi1e4:name${name.length}:${name}12:piece lengthi16384e6:pieces20:00000000000000000000ee`
+ )
+}
+
+async function writeTorrentFixtures(
+ directory: string,
+ names: readonly string[]
+): Promise<string[]> {
+ return Promise.all(
+ names.map(async (name) => {
+ const filePath = path.join(directory, `${name}.torrent`)
+ await writeFile(filePath, singleFileTorrent(name))
+ return filePath
+ })
+ )
+}
+
+async function removeAllTasks(page: Page): Promise<void> {
+ await page.evaluate(async () => {
+ const api = (
+ window as unknown as {
+ motrix?: {
+ invoke: (channel: string, ...args: unknown[]) => Promise<unknown>
+ }
+ }
+ ).motrix
+ if (!api) return
+ const tasks = (await api.invoke('query:listTasks')) as Array<{ id: string }>
+ if (tasks.length === 0) return
+ await api.invoke('command:removeTasks', {
+ taskIds: tasks.map((task) => task.id),
+ deleteWithFiles: true,
+ })
+ })
+}
+
test.describe('add task', () => {
test('http url submitted via the add-task window appears in Downloads', async ({
electronApp,
@@ -68,4 +111,77 @@ test.describe('add task', () => {
})
expect(status).not.toBe('error')
})
+
+ test('macOS open-file queues multiple torrents and downloads the remaining batch', async ({
+ electronApp,
+ mainWindow,
+ userDataDir,
+ }) => {
+ await waitForEngineReady(mainWindow)
+
+ const torrentPaths = await writeTorrentFixtures(userDataDir, [
+ 'alpha.bin',
+ 'beta.bin',
+ 'gamma.bin',
+ ])
+
+ try {
+ // macOS sends one open-file event per Finder selection. Emit the three
+ // events in one main-process turn so the test covers the real launcher →
+ // parser → add-task queue rather than calling an IPC command directly.
+ await electronApp.evaluate(({ app }, filePaths) => {
+ for (const filePath of filePaths) {
+ app.emit(
+ 'open-file',
+ { preventDefault: () => undefined } as Electron.Event,
+ filePath
+ )
+ }
+ }, torrentPaths)
+
+ const addTaskPage = await findAddTaskWindow(electronApp)
+ await expect(
+ addTaskPage.getByText('Torrent 1 of 3', { exact: true })
+ ).toBeVisible()
+ await expect(
+ addTaskPage.getByText('alpha.bin', { exact: true }).first()
+ ).toBeVisible()
+ await expect(
+ addTaskPage.getByRole('button', { name: 'Download All (3)' })
+ ).toBeVisible()
+
+ await addTaskPage.getByRole('button', { name: 'Skip' }).click()
+
+ await expect(
+ addTaskPage.getByText('Torrent 2 of 3', { exact: true })
+ ).toBeVisible()
+ await expect(
+ addTaskPage.getByText('beta.bin', { exact: true }).first()
+ ).toBeVisible()
+ await expect(
+ addTaskPage.getByRole('button', { name: 'Download All (2)' })
+ ).toBeVisible()
+
+ await addTaskPage
+ .getByRole('button', { name: 'Download All (2)' })
+ .click()
+
+ await expect
+ .poll(() => mainWindow.url())
+ .toContain('#/downloads/all?task=')
+ await expect(
+ mainWindow.getByRole('option').filter({ hasText: 'beta.bin' })
+ ).toBeVisible({ timeout: 15_000 })
+ await expect(
+ mainWindow.getByRole('option').filter({ hasText: 'gamma.bin' })
+ ).toBeVisible({ timeout: 15_000 })
+ await expect(
+ mainWindow.getByRole('option').filter({ hasText: 'alpha.bin' })
+ ).toHaveCount(0)
+ } finally {
+ // These unreachable-tracker one-byte tasks intentionally remain active.
+ // Remove them so aria2 has no live BT jobs keeping E2E teardown open.
+ await removeAllTasks(mainWindow).catch(() => undefined)
+ }
+ })
})
diff --git a/src/core/engine/get-engine-task-options.ts b/src/core/engine/get-engine-task-options.ts
new file mode 100644
index 00000000..9d14ea79
--- /dev/null
+++ b/src/core/engine/get-engine-task-options.ts
@@ -0,0 +1,14 @@
+import type { EngineAdapter } from '@core/engine/engine-adapter'
+import type { EngineTaskOptions } from '@shared/types/engine-task-options'
+
+interface Deps {
+ engine: Pick<EngineAdapter, 'getEngineTaskOptions'>
+}
+
+export function createGetEngineTaskOptionsHandler(deps: Deps) {
+ return async function getEngineTaskOptions(
+ engineTaskId: string
+ ): Promise<EngineTaskOptions | null> {
+ return deps.engine.getEngineTaskOptions(engineTaskId)
+ }
+}
diff --git a/src/core/engine/get-tuning-recommendation.ts b/src/core/engine/get-tuning-recommendation.ts
new file mode 100644
index 00000000..01671fb0
--- /dev/null
+++ b/src/core/engine/get-tuning-recommendation.ts
@@ -0,0 +1,23 @@
+import { probePrecise } from '@core/probe/disk-probe'
+import type { TuningContext } from '@shared/types/tuning'
+import { recommend } from './aria2/aria2-tuning'
+
+export interface GetTuningRecommendationParams {
+ downloadPath: string
+ totalSizeBytes?: number
+ protocol?: string
+ isMultiFile?: boolean
+}
+
+export async function getTuningRecommendation(
+ params: GetTuningRecommendationParams
+) {
+ const probe = await probePrecise(params.downloadPath)
+ const context: TuningContext = {
+ downloadPath: params.downloadPath,
+ totalSizeBytes: params.totalSizeBytes ?? null,
+ protocol: (params.protocol as TuningContext['protocol']) ?? 'http',
+ isMultiFile: params.isMultiFile ?? null,
+ }
+ return recommend(probe, context)
+}
diff --git a/src/core/proxy/system-proxy.test.ts b/src/core/proxy/system-proxy.test.ts
index 445e9191..37f09fb4 100644
--- a/src/core/proxy/system-proxy.test.ts
+++ b/src/core/proxy/system-proxy.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { parseElectronProxyChain } from './system-proxy'
+import { parseElectronProxyChain, parseProxyEnvironment } from './system-proxy'
describe('parseElectronProxyChain', () => {
it('returns null for DIRECT', () => {
@@ -49,3 +49,46 @@ describe('parseElectronProxyChain', () => {
expect(parseElectronProxyChain('PROXY foo')).toBeNull()
})
})
+
+describe('parseProxyEnvironment', () => {
+ it('prefers HTTPS_PROXY and imports credentials plus NO_PROXY', () => {
+ expect(
+ parseProxyEnvironment({
+ HTTPS_PROXY: 'http://alice:p%[email protected]:3128',
+ HTTP_PROXY: 'http://fallback.example:8080',
+ NO_PROXY: 'localhost, 127.0.0.1, .internal',
+ })
+ ).toEqual({
+ protocol: 'http',
+ host: 'proxy.example',
+ port: 3128,
+ user: 'alice',
+ password: 'p@ss',
+ bypass: ['localhost', '127.0.0.1', '.internal'],
+ })
+ })
+
+ it('supports lowercase SOCKS and default ports', () => {
+ expect(parseProxyEnvironment({ all_proxy: 'socks5h://127.0.0.1' })).toEqual(
+ {
+ protocol: 'socks5',
+ host: '127.0.0.1',
+ port: 1080,
+ }
+ )
+ })
+
+ it('accepts a host and port without an explicit scheme', () => {
+ expect(parseProxyEnvironment({ http_proxy: 'proxy.local:8888' })).toEqual({
+ protocol: 'http',
+ host: 'proxy.local',
+ port: 8888,
+ })
+ })
+
+ it('returns null for absent, malformed, or unsupported proxy values', () => {
+ expect(parseProxyEnvironment({})).toBeNull()
+ expect(parseProxyEnvironment({ HTTPS_PROXY: 'not a proxy' })).toBeNull()
+ expect(parseProxyEnvironment({ HTTPS_PROXY: 'ftp://proxy:21' })).toBeNull()
+ })
+})
diff --git a/src/core/proxy/system-proxy.ts b/src/core/proxy/system-proxy.ts
index 6d16f62a..0223577c 100644
--- a/src/core/proxy/system-proxy.ts
+++ b/src/core/proxy/system-proxy.ts
@@ -1,8 +1,6 @@
-export interface SystemProxyResult {
- protocol: 'http' | 'https' | 'socks5'
- host: string
- port: number
-}
+import type { SystemProxyResult } from '@shared/types/system-proxy'
+
+export type { SystemProxyResult } from '@shared/types/system-proxy'
/**
* Parses Electron `session.resolveProxy(url)` output.
@@ -38,3 +36,69 @@ export function parseElectronProxyChain(s: string): SystemProxyResult | null {
}
return null
}
+
+const PROXY_ENVIRONMENT_KEYS = [
+ 'HTTPS_PROXY',
+ 'https_proxy',
+ 'HTTP_PROXY',
+ 'http_proxy',
+ 'ALL_PROXY',
+ 'all_proxy',
+] as const
+
+function decodeUrlCredential(value: string): string {
+ try {
+ return decodeURIComponent(value)
+ } catch {
+ return value
+ }
+}
+
+/** Parses the conventional proxy variables inherited by a Server process. */
+export function parseProxyEnvironment(
+ environment: Readonly<Record<string, string | undefined>>
+): SystemProxyResult | null {
+ const raw = PROXY_ENVIRONMENT_KEYS.map((key) =>
+ environment[key]?.trim()
+ ).find((value): value is string => Boolean(value))
+ if (!raw) return null
+
+ let url: URL
+ try {
+ url = new URL(raw.includes('://') ? raw : `http://${raw}`)
+ } catch {
+ return null
+ }
+ const protocol =
+ url.protocol === 'http:'
+ ? 'http'
+ : url.protocol === 'https:'
+ ? 'https'
+ : ['socks:', 'socks5:', 'socks5h:'].includes(url.protocol)
+ ? 'socks5'
+ : null
+ if (!protocol || !url.hostname) return null
+ const defaultPort =
+ protocol === 'http' ? 80 : protocol === 'https' ? 443 : 1080
+ const port = url.port ? Number.parseInt(url.port, 10) : defaultPort
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535) return null
+
+ const rawBypass =
+ environment.NO_PROXY?.trim() || environment.no_proxy?.trim() || ''
+ const bypass = rawBypass
+ .split(',')
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0)
+ .slice(0, 64)
+ const user = decodeUrlCredential(url.username)
+ const password = decodeUrlCredential(url.password)
+
+ return {
+ protocol,
+ host: url.hostname,
+ port,
+ ...(user ? { user } : {}),
+ ...(password ? { password } : {}),
+ ...(bypass.length > 0 ? { bypass } : {}),
+ }
+}
diff --git a/src/core/task/get-task-files.ts b/src/core/task/get-task-files.ts
new file mode 100644
index 00000000..d9ca2fd9
--- /dev/null
+++ b/src/core/task/get-task-files.ts
@@ -0,0 +1,110 @@
+import path from 'node:path'
+import type { EngineAdapter } from '@core/engine/engine-adapter'
+import { getLogger } from '@core/logger'
+import type { MotrixDatabase } from '@core/session/motrix-database'
+import {
+ getBtPayloadPath,
+ getBtStorageLayout,
+} from '@core/task/bt-storage-layout'
+import { toFinalPath } from '@core/task/paths'
+import type { TaskManager } from '@core/task/task-manager'
+import { relativizeTorrentPath } from '@shared/lib/path-ext'
+import type { DownloadTask, TaskFile } from '@shared/types/task'
+import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'
+
+const log = getLogger('TaskFilesProvider')
+const ACTIVE_STATES = new Set<TaskStatus>([
+ TaskStatus.Downloading,
+ TaskStatus.Seeding,
+ TaskStatus.FetchingMetadata,
+])
+
+interface Deps {
+ db: Pick<MotrixDatabase, 'getTaskFiles'>
+ taskManager: Pick<TaskManager, 'getById'>
+ engine: Pick<EngineAdapter, 'getTaskFiles'>
+}
+
+function relativize(absolutePath: string, task: DownloadTask): string {
+ const layout = getBtStorageLayout(task)
+ const payloadPath = getBtPayloadPath(task)
+ if (
+ layout &&
+ !layout.multiFile &&
+ payloadPath &&
+ path.normalize(absolutePath) === path.normalize(payloadPath)
+ ) {
+ return layout.torrentRootName
+ }
+ return relativizeTorrentPath(
+ absolutePath,
+ payloadPath,
+ task.diskPath,
+ task.finalPath,
+ task.saveDir
+ )
+}
+
+function toDisplayPath(physicalPath: string, task: DownloadTask): string {
+ const relativePath = relativize(physicalPath, task)
+ if (
+ task.kind === TaskKind.Direct &&
+ (task.type === TaskType.Http || task.type === TaskType.Ftp)
+ ) {
+ if (task.finalName) return task.finalName
+ return toFinalPath(relativePath)
+ }
+ return relativePath
+}
+
+export function createGetTaskFilesHandler(deps: Deps) {
+ return async function getTaskFiles(taskId: string): Promise<TaskFile[]> {
+ const task = deps.taskManager.getById(taskId)
+ const base: TaskFile[] = deps.db.getTaskFiles(taskId).map((row) => ({
+ index: row.fileIndex,
+ path: task ? toDisplayPath(row.path, task) : row.path,
+ size: row.size,
+ selected: row.selected,
+ completedBytes: 0,
+ }))
+ if (!task) return base
+
+ const needsStructure =
+ base.length === 0 || base.some((file) => file.path.length === 0)
+
+ if (task.status === TaskStatus.Completed && !needsStructure) {
+ for (const file of base) file.completedBytes = file.size
+ return base
+ }
+ if (!ACTIVE_STATES.has(task.status) && !needsStructure) return base
+ if (!task.engineTaskId) return base
+
+ try {
+ const live = await deps.engine.getTaskFiles(task.engineTaskId)
+ if (needsStructure && live.length > 0) {
+ return live.map((file) => ({
+ index: file.index,
+ path: toDisplayPath(file.path, task),
+ size: file.size,
+ selected: file.selected,
+ completedBytes: file.completedBytes,
+ }))
+ }
+ const byIndex = new Map(
+ live.map((file) => [file.index, file.completedBytes])
+ )
+ for (const file of base) {
+ file.completedBytes = byIndex.get(file.index) ?? 0
+ }
+ } catch (error) {
+ log.warn(
+ { err: error, taskId },
+ 'engine.getTaskFiles failed; degrading to 0'
+ )
+ }
+ if (task.status === TaskStatus.Completed) {
+ for (const file of base) file.completedBytes = file.size
+ }
+ return base
+ }
+}
diff --git a/src/core/task/set-selected-files.ts b/src/core/task/set-selected-files.ts
new file mode 100644
index 00000000..5ab8ee89
--- /dev/null
+++ b/src/core/task/set-selected-files.ts
@@ -0,0 +1,95 @@
+import type { EngineAdapter } from '@core/engine/engine-adapter'
+import type { EventBus } from '@core/events/event-bus'
+import { getLogger } from '@core/logger'
+import type { MotrixDatabase } from '@core/session/motrix-database'
+import type { TaskManager } from '@core/task/task-manager'
+import { AppError, ErrorCode } from '@shared/errors'
+import { Events } from '@shared/protocol/events'
+import { setSelectedFilesPayloadSchema } from '@shared/schemas/task-file-selection'
+
+const log = getLogger('SetSelectedFilesHandler')
+
+interface Deps {
+ taskManager: Pick<TaskManager, 'getById' | 'set'>
+ engine: Pick<EngineAdapter, 'changeOption' | 'getTaskFiles'>
+ db: Pick<MotrixDatabase, 'replaceTaskFiles'>
+ eventBus: Pick<EventBus, 'emit'>
+ runTaskMutation: <T>(
+ taskIds: readonly string[],
+ operation: () => Promise<T>
+ ) => Promise<T>
+}
+
+export function createSetSelectedFilesHandler(deps: Deps) {
+ return async function setSelectedFiles(rawPayload: unknown): Promise<void> {
+ const parsed = setSelectedFilesPayloadSchema.safeParse(rawPayload)
+ if (!parsed.success) {
+ throw new AppError(
+ ErrorCode.InvalidSelection,
+ parsed.error.issues[0]?.message ?? 'Invalid file selection'
+ )
+ }
+ const { taskId, indices } = parsed.data
+
+ await deps.runTaskMutation([taskId], async () => {
+ const task = deps.taskManager.getById(taskId)
+ if (!task) {
+ throw new AppError(ErrorCode.TaskNotFound, `Task ${taskId} not found`)
+ }
+
+ await deps.engine.changeOption(task.engineTaskId, {
+ 'select-file': formatRange(indices),
+ })
+
+ const live = await deps.engine.getTaskFiles(task.engineTaskId)
+ deps.db.replaceTaskFiles(
+ taskId,
+ live.map((file) => ({
+ fileIndex: file.index,
+ path: file.path,
+ size: file.size,
+ selected: file.selected,
+ }))
+ )
+
+ if (task.bt) {
+ deps.taskManager.set(taskId, {
+ ...task,
+ bt: { ...task.bt, selectedFiles: indices },
+ })
+ }
+ deps.eventBus.emit(Events.TaskFilesUpdated, { taskId })
+ log.info({ taskId, count: indices.length }, 'selected files updated')
+ })
+ }
+}
+
+export function formatRange(indices: number[]): string {
+ if (indices.length === 0) return ''
+ const sorted = [...indices].sort((a, b) => a - b).map((index) => index + 1)
+ const parts: string[] = []
+ let start = sorted[0] as number
+ let previous = start
+ const flush = () => {
+ const length = previous - start + 1
+ if (length >= 3) {
+ parts.push(`${start}-${previous}`)
+ } else {
+ for (let value = start; value <= previous; value++) {
+ parts.push(`${value}`)
+ }
+ }
+ }
+ for (let index = 1; index < sorted.length; index++) {
+ const current = sorted[index] as number
+ if (current === previous + 1) {
+ previous = current
+ } else {
+ flush()
+ start = current
+ previous = current
+ }
+ }
+ flush()
+ return parts.join(',')
+}
diff --git a/src/core/torrent/torrent-parser.ts b/src/core/torrent/torrent-parser.ts
index 9a20f9fc..26b1b16d 100644
--- a/src/core/torrent/torrent-parser.ts
+++ b/src/core/torrent/torrent-parser.ts
@@ -1,16 +1,17 @@
-import { extname } from 'node:path'
import { getLogger } from '@core/logger'
import { AppError, ErrorCode } from '@shared/errors'
-import type { TorrentFileInfo, TorrentMeta } from '@shared/types/torrent'
+import {
+ MAX_TORRENT_BASE64_SIZE,
+ projectTorrentMeta,
+} from '@shared/lib/torrent-meta'
+import type { TorrentMeta } from '@shared/types/torrent'
import parseTorrent from 'parse-torrent'
const log = getLogger('torrent-parser')
-const MAX_BASE64_SIZE = 50 * 1024 * 1024
-
export class TorrentParser {
async parse(base64: string): Promise<TorrentMeta> {
- if (base64.length > MAX_BASE64_SIZE) {
+ if (base64.length > MAX_TORRENT_BASE64_SIZE) {
throw new AppError(
ErrorCode.TorrentParseFailed,
'Torrent file is too large'
@@ -30,27 +31,15 @@ export class TorrentParser {
)
}
- const files: TorrentFileInfo[] = (parsed.files ?? []).map((f, i) => ({
- index: i,
- path: f.path,
- size: f.length,
- extension: extname(f.path) || '',
- }))
+ const meta = projectTorrentMeta(parsed)
- if (files.length === 0) {
+ if (meta.files.length === 0) {
throw new AppError(
ErrorCode.TorrentParseFailed,
'Torrent contains no files'
)
}
- return {
- name: parsed.name ?? 'Unknown',
- infoHash: parsed.infoHash ?? '',
- totalSize: files.reduce((sum, f) => sum + f.size, 0),
- files,
- comment: parsed.comment ?? null,
- isPrivate: parsed.private ?? false,
- }
+ return meta
}
}
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index f1b96636..349d6270 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -142,7 +142,7 @@ function fakeCtx() {
resetDialogState: vi.fn(),
register: vi.fn(),
nextTorrent: vi.fn(),
- downloadAllTorrents: vi.fn(),
+ downloadAllTorrents: vi.fn(() => []),
},
windowManager: {
open: vi.fn(),
@@ -790,7 +790,13 @@ describe('buildCommandHandlers', () => {
handlers[Commands.ConfirmPortSwitch]?.(16801)
).resolves.toEqual({ ok: true })
await handlers[Commands.NextTorrent]?.()
- await handlers[Commands.DownloadAllTorrents]?.()
+ await handlers[Commands.DownloadAllTorrents]?.({
+ selectedFiles: [0],
+ saveDir: '/tmp',
+ dlLimit: 1024,
+ ulLimit: 512,
+ seedRatio: 1.5,
+ })
await handlers[Commands.ShowMainWindow]?.()
await handlers[Commands.CheckForUpdates]?.()
await handlers[Commands.DownloadUpdate]?.()
@@ -816,6 +822,71 @@ describe('buildCommandHandlers', () => {
})
})
+ it('applies the current form options when creating an App torrent batch', async () => {
+ const ctx = fakeCtx()
+ ctx.protocolManager.downloadAllTorrents.mockResolvedValueOnce([
+ {
+ payload: { name: 'first.torrent', dataBase64: 'Zmlyc3Q=' },
+ meta: {
+ name: 'first.bin',
+ files: [
+ { index: 0, path: 'skip.bin' },
+ { index: 1, path: 'keep.bin' },
+ ],
+ },
+ },
+ {
+ payload: { name: 'second.torrent', dataBase64: 'c2Vjb25k' },
+ meta: {
+ name: 'second.bin',
+ files: [
+ { index: 0, path: 'one.bin' },
+ { index: 1, path: 'two.bin' },
+ ],
+ },
+ },
+ ] as never)
+ // @ts-expect-error partial ctx
+ const handlers = buildCommandHandlers(ctx)
+
+ await expect(
+ handlers[Commands.DownloadAllTorrents]?.({
+ selectedFiles: [1],
+ saveDir: '/tmp/batch',
+ dlLimit: 2048,
+ ulLimit: 1024,
+ seedRatio: 1.5,
+ })
+ ).resolves.toEqual({
+ total: 2,
+ succeeded: 2,
+ failed: 0,
+ firstTaskId: expect.any(String),
+ })
+ expect(ctx.rpcClient.addTorrent).toHaveBeenNthCalledWith(
+ 1,
+ 'Zmlyc3Q=',
+ [],
+ expect.objectContaining({
+ 'select-file': '2',
+ 'max-download-limit': '2048K',
+ 'max-upload-limit': '1024K',
+ 'seed-ratio': '1.5',
+ })
+ )
+ expect(ctx.rpcClient.addTorrent).toHaveBeenNthCalledWith(
+ 2,
+ 'c2Vjb25k',
+ [],
+ expect.objectContaining({
+ 'select-file': '1,2',
+ 'max-download-limit': '2048K',
+ 'max-upload-limit': '1024K',
+ 'seed-ratio': '1.5',
+ })
+ )
+ })
+
it('rejects menu-context updates from auxiliary windows', async () => {
const ctx = fakeCtx()
ctx.windowManager.getWindowIdBySender.mockReturnValue('add-task')
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index cadc81a1..5a2b0d46 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -81,13 +81,17 @@ import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
import type { CommandHandlerMap } from '@shared/protocol/handler-types'
-import type { TaskCreateCommandResult } from '@shared/schemas/add-task'
-import { taskCreateRequestSchema } from '@shared/schemas/add-task'
+import {
+ type TaskCreateCommandResult,
+ taskCreateRequestSchema,
+ torrentBatchCreateOptionsSchema,
+} from '@shared/schemas/add-task'
import {
removeTasksPayloadSchema,
taskIdsPayloadSchema,
} from '@shared/schemas/bulk-task-command'
import { closeCurrentWindowSchema } from '@shared/schemas/close-current-window'
+import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'
import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'
import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'
import { showAddTaskWindowSchema } from '@shared/schemas/show-add-task-window'
@@ -475,10 +479,6 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
{ sourceType: 'registry' }
>
- const checkPluginUpdatesPayloadSchema = z
- .object({ force: z.boolean().optional() })
- .optional()
-
const confirmPluginInstallPayloadSchema = z.object({
stagingId: z.string().min(1),
grants: z.record(z.string(), z.enum(['granted', 'denied'])),
@@ -625,27 +625,6 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
cliInstallRequestSchema.parse(payload) as CliInstallRequest
),
- [Commands.CreateDownload]: async (params: {
- uris: string[] | string
- saveDir?: string
- }) => {
- const uris = Array.isArray(params.uris) ? params.uris : [params.uris]
- log.info(
- {
- uris,
- activePluginIds: pluginHost.allActive().map((p) => p.id),
- },
- 'Commands.CreateDownload received'
- )
- await activatePluginsForTask('http', uris[0] ?? '')
- return createAndPersist({
- type: 'http',
- uris,
- saveDir: params.saveDir || settingsManager.getApp().defaultSaveDir,
- headers: [],
- })
- },
-
[Commands.ParseTorrent]: async ({ base64 }: { base64: string }) => {
return torrentParser.parse(base64)
},
@@ -784,6 +763,7 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
engine: adapter,
db: motrixDatabase,
eventBus,
+ runTaskMutation,
}),
[Commands.ReopenMagnetFileSelection]: async (taskId: string) => {
@@ -1088,13 +1068,57 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
},
[Commands.NextTorrent]: async () => {
- protocolManager.nextTorrent()
- return { ok: true }
+ const advanced = await protocolManager.nextTorrent()
+ return { advanced }
},
- [Commands.DownloadAllTorrents]: async () => {
- protocolManager.downloadAllTorrents()
- return { ok: true }
+ [Commands.DownloadAllTorrents]: async (rawOptions: unknown) => {
+ const options = torrentBatchCreateOptionsSchema.parse(rawOptions)
+ const torrents = await protocolManager.downloadAllTorrents()
+ let succeeded = 0
+ let failed = 0
+ let firstTaskId: string | null = null
+
+ for (const [index, torrent] of torrents.entries()) {
+ try {
+ await activatePluginsForTask('bt', '')
+ const result = await createAndPersist({
+ type: 'bt',
+ payload: {
+ kind: 'torrent-base64',
+ base64: torrent.payload.dataBase64,
+ },
+ selectedFiles:
+ index === 0
+ ? options.selectedFiles
+ : torrent.meta.files.map((file) => file.index),
+ saveDir: options.saveDir,
+ dlLimit: options.dlLimit,
+ ulLimit: options.ulLimit,
+ seedRatio: options.seedRatio,
+ displayName: torrent.meta.name,
+ })
+ if (result.outcome === 'conflict') {
+ failed += 1
+ continue
+ }
+ succeeded += 1
+ firstTaskId ??= result.taskId
+ } catch (err) {
+ failed += 1
+ log.warn(
+ { err, torrent: torrent.payload.name },
+ 'batch torrent creation failed'
+ )
+ }
+ }
+
+ return {
+ total: torrents.length,
+ succeeded,
+ failed,
+ firstTaskId,
+ }
},
// CloseCurrentWindow needs event.sender — the wrapper in registerCommandHandlers
diff --git a/src/main/ipc/commands/set-selected-files.test.ts b/src/main/ipc/commands/set-selected-files.test.ts
index 2d32c358..548fe103 100644
--- a/src/main/ipc/commands/set-selected-files.test.ts
+++ b/src/main/ipc/commands/set-selected-files.test.ts
@@ -84,14 +84,20 @@ describe('setSelectedFiles handler', () => {
}
const db = { replaceTaskFiles: vi.fn() }
const eventBus = { emit: vi.fn() }
+ const runTaskMutation = vi.fn(
+ async (_taskIds: readonly string[], operation: () => Promise<unknown>) =>
+ operation()
+ )
const handler = createSetSelectedFilesHandler({
taskManager,
engine,
db,
eventBus,
+ runTaskMutation,
} as unknown as Parameters<typeof createSetSelectedFilesHandler>[0])
await handler({ taskId: 't1', indices: [0, 1] })
+ expect(runTaskMutation).toHaveBeenCalledWith(['t1'], expect.any(Function))
expect(engine.changeOption).toHaveBeenCalledWith('gid1', {
'select-file': '1,2',
})
@@ -111,6 +117,25 @@ describe('setSelectedFiles handler', () => {
})
})
+ it('rejects non-integer and duplicate indices before entering the task lock', async () => {
+ const runTaskMutation = vi.fn()
+ const handler = createSetSelectedFilesHandler({
+ taskManager: { getById: vi.fn(), set: vi.fn() },
+ engine: { changeOption: vi.fn(), getTaskFiles: vi.fn() },
+ db: { replaceTaskFiles: vi.fn() },
+ eventBus: { emit: vi.fn() },
+ runTaskMutation,
+ })
+
+ await expect(
+ handler({ taskId: 't1', indices: [0, 0] })
+ ).rejects.toBeInstanceOf(AppError)
+ await expect(
+ handler({ taskId: 't1', indices: [0.5] })
+ ).rejects.toBeInstanceOf(AppError)
+ expect(runTaskMutation).not.toHaveBeenCalled()
+ })
+
it('changeOption failure: no db write, no emit, error rethrown', async () => {
const taskManager = { getById: vi.fn(() => mkTask()), set: vi.fn() }
const engine = {
@@ -126,6 +151,10 @@ describe('setSelectedFiles handler', () => {
engine,
db,
eventBus,
+ runTaskMutation: async (
+ _taskIds: readonly string[],
+ operation: () => Promise<unknown>
+ ) => operation(),
} as unknown as Parameters<typeof createSetSelectedFilesHandler>[0])
await expect(handler({ taskId: 't1', indices: [0] })).rejects.toThrow()
expect(db.replaceTaskFiles).not.toHaveBeenCalled()
diff --git a/src/main/ipc/commands/set-selected-files.ts b/src/main/ipc/commands/set-selected-files.ts
index a6ab1536..17165e94 100644
--- a/src/main/ipc/commands/set-selected-files.ts
+++ b/src/main/ipc/commands/set-selected-files.ts
@@ -1,100 +1,4 @@
-import type { EngineAdapter } from '@core/engine/engine-adapter'
-import type { EventBus } from '@core/events/event-bus'
-import { getLogger } from '@core/logger'
-import type { MotrixDatabase } from '@core/session/motrix-database'
-import type { TaskManager } from '@core/task/task-manager'
-import { AppError, ErrorCode } from '@shared/errors'
-import { Events } from '@shared/protocol/events'
-
-const log = getLogger('SetSelectedFilesHandler')
-
-interface Deps {
- taskManager: Pick<TaskManager, 'getById' | 'set'>
- engine: Pick<EngineAdapter, 'changeOption' | 'getTaskFiles'>
- db: Pick<MotrixDatabase, 'replaceTaskFiles'>
- eventBus: Pick<EventBus, 'emit'>
-}
-
-export function createSetSelectedFilesHandler(deps: Deps) {
- return async function setSelectedFiles(args: {
- taskId: string
- indices: number[]
- }): Promise<void> {
- if (args.indices.length === 0) {
- throw new AppError(
- ErrorCode.InvalidSelection,
- 'At least one file must be selected'
- )
- }
- const task = deps.taskManager.getById(args.taskId)
- if (!task) {
- throw new AppError(
- ErrorCode.TaskNotFound,
- `Task ${args.taskId} not found`
- )
- }
-
- const selectFile = formatRange(args.indices)
- await deps.engine.changeOption(task.engineTaskId, {
- 'select-file': selectFile,
- })
-
- const live = await deps.engine.getTaskFiles(task.engineTaskId)
- deps.db.replaceTaskFiles(
- args.taskId,
- live.map((f) => ({
- fileIndex: f.index,
- path: f.path,
- size: f.size,
- selected: f.selected,
- }))
- )
-
- if (task.bt) {
- deps.taskManager.set(args.taskId, {
- ...task,
- bt: { ...task.bt, selectedFiles: args.indices },
- })
- }
- deps.eventBus.emit(Events.TaskFilesUpdated, { taskId: args.taskId })
- log.info(
- { taskId: args.taskId, count: args.indices.length },
- 'selected files updated'
- )
- }
-}
-
-/**
- * Convert 0-based indices to aria2 1-based comma-range form. Runs of three
- * or more consecutive values collapse to `start-end`; pairs stay
- * comma-separated:
- * `[0, 1]` -> `'1,2'`
- * `[0, 2, 3, 4, 7]` -> `'1,3-5,8'`
- */
-export function formatRange(indices: number[]): string {
- if (indices.length === 0) return ''
- const sorted = [...indices].sort((a, b) => a - b).map((i) => i + 1)
- const parts: string[] = []
- let start = sorted[0] as number
- let prev = start
- const flush = () => {
- const length = prev - start + 1
- if (length >= 3) {
- parts.push(`${start}-${prev}`)
- } else {
- for (let v = start; v <= prev; v++) parts.push(`${v}`)
- }
- }
- for (let i = 1; i < sorted.length; i++) {
- const cur = sorted[i] as number
- if (cur === prev + 1) {
- prev = cur
- } else {
- flush()
- start = cur
- prev = cur
- }
- }
- flush()
- return parts.join(',')
-}
+export {
+ createSetSelectedFilesHandler,
+ formatRange,
+} from '@core/task/set-selected-files'
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 4223a891..05986894 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -1,8 +1,8 @@
import path from 'node:path'
import type { TaskActivityService } from '@core/activity'
-import { recommend } from '@core/engine/aria2/aria2-tuning'
import type { EngineAdapter } from '@core/engine/engine-adapter'
import type { EngineSupervisor } from '@core/engine/engine-supervisor'
+import { getTuningRecommendation } from '@core/engine/get-tuning-recommendation'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { createGetGeoIPStatusHandler } from '@core/geoip/get-geo-ip-status'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
@@ -16,7 +16,6 @@ import {
readPluginConfig,
} from '@core/plugin/queries'
import type { RegistryClient } from '@core/plugin/registry/registry-client'
-import { probePrecise } from '@core/probe/disk-probe'
import { parseElectronProxyChain } from '@core/proxy/system-proxy'
import type { MotrixDatabase } from '@core/session/motrix-database'
import type { SettingsManager } from '@core/settings/settings-manager'
@@ -43,7 +42,6 @@ import { Queries } from '@shared/protocol/queries'
import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspector-activity'
import type { GetTransferStatsParams } from '@shared/types/stats'
import type { GetTaskActivityParams } from '@shared/types/task-activity'
-import type { TuningContext } from '@shared/types/tuning'
import { ipcMain, session } from 'electron'
import type { CliToolService } from '../cli/cli-tool-service'
import type { UpdateManager } from '../core/update-manager'
@@ -226,21 +224,7 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
[Queries.GetNatDiagnostic]: async () =>
natManager.getStatus().lastDiagnostic,
- [Queries.GetTuningRecommendation]: async (params: {
- downloadPath: string
- totalSizeBytes?: number
- protocol?: string
- isMultiFile?: boolean
- }) => {
- const probe = await probePrecise(params.downloadPath)
- const context: TuningContext = {
- downloadPath: params.downloadPath,
- totalSizeBytes: params.totalSizeBytes ?? null,
- protocol: (params.protocol as TuningContext['protocol']) ?? 'http',
- isMultiFile: params.isMultiFile ?? null,
- }
- return recommend(probe, context)
- },
+ [Queries.GetTuningRecommendation]: getTuningRecommendation,
[Queries.GetTrackerList]: async () => {
return trackerManager.getCuratedList()
diff --git a/src/main/ipc/queries/get-engine-task-options.ts b/src/main/ipc/queries/get-engine-task-options.ts
index 9d14ea79..d4832372 100644
--- a/src/main/ipc/queries/get-engine-task-options.ts
+++ b/src/main/ipc/queries/get-engine-task-options.ts
@@ -1,14 +1 @@
-import type { EngineAdapter } from '@core/engine/engine-adapter'
-import type { EngineTaskOptions } from '@shared/types/engine-task-options'
-
-interface Deps {
- engine: Pick<EngineAdapter, 'getEngineTaskOptions'>
-}
-
-export function createGetEngineTaskOptionsHandler(deps: Deps) {
- return async function getEngineTaskOptions(
- engineTaskId: string
- ): Promise<EngineTaskOptions | null> {
- return deps.engine.getEngineTaskOptions(engineTaskId)
- }
-}
+export { createGetEngineTaskOptionsHandler } from '@core/engine/get-engine-task-options'
diff --git a/src/main/ipc/queries/get-task-files.ts b/src/main/ipc/queries/get-task-files.ts
index a38ba956..4861ee5a 100644
--- a/src/main/ipc/queries/get-task-files.ts
+++ b/src/main/ipc/queries/get-task-files.ts
@@ -1,128 +1 @@
-import path from 'node:path'
-import type { EngineAdapter } from '@core/engine/engine-adapter'
-import { getLogger } from '@core/logger'
-import type { MotrixDatabase } from '@core/session/motrix-database'
-import {
- getBtPayloadPath,
- getBtStorageLayout,
-} from '@core/task/bt-storage-layout'
-import { toFinalPath } from '@core/task/paths'
-import type { TaskManager } from '@core/task/task-manager'
-import { relativizeTorrentPath } from '@shared/lib/path-ext'
-import type { DownloadTask, TaskFile } from '@shared/types/task'
-import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'
-
-const log = getLogger('TaskFilesProvider')
-
-const ACTIVE_STATES = new Set<TaskStatus>([
- TaskStatus.Downloading,
- TaskStatus.Seeding,
- TaskStatus.FetchingMetadata,
-])
-
-interface Deps {
- db: Pick<MotrixDatabase, 'getTaskFiles'>
- taskManager: Pick<TaskManager, 'getById'>
- engine: Pick<EngineAdapter, 'getTaskFiles'>
-}
-
-function relativize(absolutePath: string, task: DownloadTask): string {
- const layout = getBtStorageLayout(task)
- const payloadPath = getBtPayloadPath(task)
- if (
- layout &&
- !layout.multiFile &&
- payloadPath &&
- path.normalize(absolutePath) === path.normalize(payloadPath)
- ) {
- return layout.torrentRootName
- }
- return relativizeTorrentPath(
- absolutePath,
- payloadPath,
- task.diskPath,
- task.finalPath,
- task.saveDir
- )
-}
-
-function toDisplayPath(physicalPath: string, task: DownloadTask): string {
- const relativePath = relativize(physicalPath, task)
-
- // Direct HTTP/FTP tasks contain exactly one logical output. Use the task's
- // authoritative final name instead of guessing from the physical path:
- // while active it ends in the reserved `.motrix` staging suffix, while a
- // completed file may legitimately have `.motrix` as part of its real name.
- // Keep Mux/BT/Magnet paths untouched because they can expose real payload
- // structure rather than a single direct output.
- if (
- task.kind === TaskKind.Direct &&
- (task.type === TaskType.Http || task.type === TaskType.Ftp)
- ) {
- if (task.finalName) return task.finalName
- return toFinalPath(relativePath)
- }
- return relativePath
-}
-
-export function createGetTaskFilesHandler(deps: Deps) {
- return async function getTaskFiles(taskId: string): Promise<TaskFile[]> {
- const task = deps.taskManager.getById(taskId)
- const base: TaskFile[] = deps.db.getTaskFiles(taskId).map((row) => ({
- index: row.fileIndex,
- path: task ? toDisplayPath(row.path, task) : row.path,
- size: row.size,
- selected: row.selected,
- completedBytes: 0,
- }))
- if (!task) return base
-
- // Magnet swaps in affected builds persisted selected-index placeholders
- // with empty paths and zero sizes. Treat those rows like an empty cache so
- // an available engine result can supply the real structure immediately;
- // the polling sync repairs the durable rows independently.
- const needsStructure =
- base.length === 0 || base.some((file) => file.path.length === 0)
-
- if (task.status === TaskStatus.Completed && !needsStructure) {
- for (const f of base) f.completedBytes = f.size
- return base
- }
- if (!ACTIVE_STATES.has(task.status) && !needsStructure) {
- return base
- }
- // Coordinator-managed media tasks (Mux/Hls) have no aria2 handle
- // (engineTaskId ''); engine.getTaskFiles('') would just fail and log a
- // warning on every Files-tab open. Their per-file structure, if any, is
- // already in the db rows above — never call the engine with an empty gid.
- if (!task.engineTaskId) {
- return base
- }
- try {
- const live = await deps.engine.getTaskFiles(task.engineTaskId)
- // db is the source of structure (path/size/selected) once the auto-sync
- // has produced complete rows. Before that — an empty fresh-task cache
- // or legacy magnet placeholders — fall back to engine for the full
- // structure. Persistence remains owned by polling; this query is pure.
- if (needsStructure && live.length > 0) {
- return live.map((f) => ({
- index: f.index,
- path: toDisplayPath(f.path, task),
- size: f.size,
- selected: f.selected,
- completedBytes: f.completedBytes,
- }))
- }
- const byIndex = new Map(live.map((f) => [f.index, f.completedBytes]))
- for (const f of base) {
- f.completedBytes = byIndex.get(f.index) ?? 0
- }
- } catch (err) {
- log.warn({ err, taskId }, 'engine.getTaskFiles failed; degrading to 0')
- }
- if (task.status === TaskStatus.Completed) {
- for (const f of base) f.completedBytes = f.size
- }
- return base
- }
-}
+export { createGetTaskFilesHandler } from '@core/task/get-task-files'
diff --git a/src/main/launcher.ts b/src/main/launcher.ts
index 05177a49..40973f0b 100644
--- a/src/main/launcher.ts
+++ b/src/main/launcher.ts
@@ -30,7 +30,8 @@ function extractUrlFromArgv(argv: string[]): string | undefined {
return undefined
}
-function extractFileFromArgv(argv: string[]): string | undefined {
+function extractFilesFromArgv(argv: string[]): string[] {
+ const files: string[] = []
for (let i = 1; i < argv.length; i++) {
let arg = argv[i]
if (arg.startsWith('--')) continue
@@ -38,10 +39,10 @@ function extractFileFromArgv(argv: string[]): string | undefined {
arg = arg.replace(/^file:\/\//, '')
}
if (arg.toLowerCase().endsWith('.torrent')) {
- return arg
+ files.push(arg)
}
}
- return undefined
+ return files
}
export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
@@ -103,8 +104,9 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
const url = extractUrlFromArgv(process.argv)
if (url) dispatchUrl(url)
- const file = extractFileFromArgv(process.argv)
- if (file) dispatchFile(file)
+ for (const file of extractFilesFromArgv(process.argv)) {
+ dispatchFile(file)
+ }
}
// second-instance (Windows/Linux: second launch passes argv)
@@ -119,8 +121,9 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {
return
}
- const file = extractFileFromArgv(argv)
- if (file) dispatchFile(file)
+ for (const file of extractFilesFromArgv(argv)) {
+ dispatchFile(file)
+ }
}
})
diff --git a/src/main/platform/protocol-manager.test.ts b/src/main/platform/protocol-manager.test.ts
index 6e892a68..33919c4d 100644
--- a/src/main/platform/protocol-manager.test.ts
+++ b/src/main/platform/protocol-manager.test.ts
@@ -536,7 +536,7 @@ describe('createProtocolManager', () => {
await pm.handleTorrentFile('/path/to/b.torrent')
deliverToAddTask.mockClear()
- pm.nextTorrent()
+ expect(pm.nextTorrent()).toBe(true)
expect(deliverToAddTask).toHaveBeenCalledWith(
Events.ProtocolTorrentFile,
@@ -546,6 +546,31 @@ describe('createProtocolManager', () => {
)
})
+ it('reports exhaustion when a pending next torrent fails to parse', async () => {
+ mockReadFile
+ .mockResolvedValueOnce(Buffer.from('torrent-1'))
+ .mockResolvedValueOnce(Buffer.from('broken-torrent'))
+ let rejectBroken!: (error: Error) => void
+ mockParse.mockResolvedValueOnce(defaultMeta).mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectBroken = reject
+ })
+ )
+
+ const deps = makeDeps()
+ const pm = createProtocolManager(deps)
+ await pm.handleTorrentFile('/path/to/a.torrent')
+ const pendingBroken = pm.handleTorrentFile('/path/to/broken.torrent')
+ const advancing = pm.nextTorrent()
+ await vi.waitFor(() => expect(rejectBroken).toBeTypeOf('function'))
+ rejectBroken(new Error('invalid torrent'))
+
+ await expect(advancing).resolves.toBe(false)
+ await pendingBroken
+ expect(pm.getTorrentQueueSize()).toBe(0)
+ })
+
it('downloadAllTorrents drains queue', async () => {
mockReadFile
.mockResolvedValueOnce(Buffer.from('torrent-1'))
diff --git a/src/main/platform/protocol-manager.ts b/src/main/platform/protocol-manager.ts
index 33a6bb69..9e8c5f20 100644
--- a/src/main/platform/protocol-manager.ts
+++ b/src/main/platform/protocol-manager.ts
@@ -6,6 +6,7 @@ import type { TorrentParser } from '@core/torrent/torrent-parser'
import { Events } from '@shared/protocol/events'
import type { AddTaskUrlParams } from '@shared/schemas/add-task'
import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'
+import type { TorrentMeta } from '@shared/types/torrent'
import type { BrowserWindow } from 'electron'
import { app } from 'electron'
@@ -42,9 +43,12 @@ export interface ProtocolRegistrationResult {
magnetMatchesSetting: boolean | null
}
-interface TorrentPayload {
- name: string
- dataBase64: string
+interface QueuedTorrent {
+ payload: {
+ name: string
+ dataBase64: string
+ }
+ meta: TorrentMeta
}
const RESOURCE_PREFIXES = ['magnet:', 'http:', 'https:', 'ftp:']
@@ -66,22 +70,92 @@ function uriToAddTaskParams(url: string): AddTaskUrlParams | null {
export function createProtocolManager(deps: ProtocolManagerDeps) {
const log = getLogger('protocol')
- const torrentQueue: TorrentPayload[] = []
+ const torrentQueue: QueuedTorrent[] = []
let dialogActive = false
let totalSent = 0
+ let torrentIngress = Promise.resolve()
+ let pendingIngestions = 0
+ let queueGeneration = 0
+ let currentTorrentDelivered = false
+ let lastReportedQueueTotal = 0
+
+ function getKnownQueueTotal(currentIngestion = false) {
+ const alreadyRemoved = currentTorrentDelivered ? totalSent - 1 : totalSent
+ const notYetQueued = Math.max(
+ 0,
+ pendingIngestions - (currentIngestion ? 1 : 0)
+ )
+ return alreadyRemoved + torrentQueue.length + notYetQueued
+ }
function sendNextTorrentToRenderer() {
if (torrentQueue.length === 0) {
dialogActive = false
- return
+ currentTorrentDelivered = false
+ lastReportedQueueTotal = 0
+ return false
}
dialogActive = true
totalSent++
+ currentTorrentDelivered = true
+ const torrent = torrentQueue[0]
+ const queueTotal = getKnownQueueTotal()
+ lastReportedQueueTotal = queueTotal
deps.deliverToAddTask(Events.ProtocolTorrentFile, {
- payload: torrentQueue[0],
+ payload: torrent.payload,
+ meta: torrent.meta,
queuePosition: totalSent,
- queueTotal: totalSent + torrentQueue.length - 1,
+ queueTotal,
})
+ return true
+ }
+
+ async function ingestTorrentFile(filePath: string, generation: number) {
+ log.info({ filePath }, 'torrent file received')
+
+ try {
+ const data = await readFile(filePath)
+ const dataBase64 = data.toString('base64')
+ const meta = await deps.torrentParser.parse(dataBase64)
+ if (generation !== queueGeneration) return
+
+ const torrent: QueuedTorrent = {
+ payload: {
+ name: basename(filePath),
+ dataBase64,
+ },
+ meta,
+ }
+
+ torrentQueue.push(torrent)
+
+ if (!dialogActive) {
+ totalSent = 0
+ dialogActive = true
+ totalSent++
+ currentTorrentDelivered = true
+ const queueTotal = getKnownQueueTotal(true)
+ lastReportedQueueTotal = queueTotal
+ log.info(
+ { name: torrent.payload.name, infoHash: meta.infoHash },
+ 'delivering torrent to add-task'
+ )
+ deps.deliverToAddTask(Events.ProtocolTorrentFile, {
+ payload: torrent.payload,
+ meta,
+ queuePosition: totalSent,
+ queueTotal,
+ })
+ } else {
+ const queueTotal = getKnownQueueTotal(true)
+ lastReportedQueueTotal = queueTotal
+ deps.deliverToAddTask(Events.TorrentQueueSizeChanged, {
+ queueTotal,
+ })
+ }
+ } catch (err) {
+ log.warn({ err, filePath }, 'failed to read/parse torrent file')
+ }
}
return {
@@ -178,60 +252,63 @@ export function createProtocolManager(deps: ProtocolManagerDeps) {
log.warn({ url }, 'unrecognized protocol url')
},
- async handleTorrentFile(filePath: string) {
- if (extname(filePath).toLowerCase() !== '.torrent') return
-
- log.info({ filePath }, 'torrent file received')
-
- try {
- const data = await readFile(filePath)
- const dataBase64 = data.toString('base64')
- const meta = await deps.torrentParser.parse(dataBase64)
-
- const payload: TorrentPayload = {
- name: basename(filePath),
- dataBase64,
- }
-
- torrentQueue.push(payload)
-
- if (!dialogActive) {
- totalSent = 0
- dialogActive = true
- totalSent++
- log.info(
- { name: payload.name, infoHash: meta.infoHash },
- 'delivering torrent to add-task'
- )
- deps.deliverToAddTask(Events.ProtocolTorrentFile, {
- payload,
- meta,
- queuePosition: totalSent,
- queueTotal: totalSent + torrentQueue.length - 1,
- })
- } else {
- deps.deliverToAddTask(Events.TorrentQueueSizeChanged, {
- queueTotal: totalSent + torrentQueue.length - 1,
- })
- }
- } catch (err) {
- log.warn({ err, filePath }, 'failed to read/parse torrent file')
+ handleTorrentFile(filePath: string) {
+ if (extname(filePath).toLowerCase() !== '.torrent') {
+ return Promise.resolve()
}
+
+ // Windows/Linux can pass several associated files in one argv. Keep
+ // parsing serial so the review queue follows the user's file order even
+ // when individual reads/parses complete at different speeds.
+ const generation = queueGeneration
+ pendingIngestions += 1
+ const result = torrentIngress
+ .then(() => ingestTorrentFile(filePath, generation))
+ .finally(() => {
+ pendingIngestions -= 1
+ if (
+ generation === queueGeneration &&
+ dialogActive &&
+ currentTorrentDelivered
+ ) {
+ const queueTotal = getKnownQueueTotal()
+ if (queueTotal > 0 && queueTotal !== lastReportedQueueTotal) {
+ lastReportedQueueTotal = queueTotal
+ deps.deliverToAddTask(Events.TorrentQueueSizeChanged, {
+ queueTotal,
+ })
+ }
+ }
+ })
+ torrentIngress = result.catch(() => undefined)
+ return result
},
nextTorrent() {
torrentQueue.shift()
- sendNextTorrentToRenderer()
+ currentTorrentDelivered = false
+ if (torrentQueue.length === 0 && pendingIngestions > 0) {
+ return torrentIngress.then(() => sendNextTorrentToRenderer())
+ }
+ return sendNextTorrentToRenderer()
},
downloadAllTorrents() {
- log.info(
- { count: torrentQueue.length },
- 'downloading all remaining torrents'
- )
- torrentQueue.length = 0
- dialogActive = false
- totalSent = 0
+ const takeAll = () => {
+ const torrents = torrentQueue.splice(0)
+ log.info(
+ { count: torrents.length },
+ 'taking all remaining torrents for batch creation'
+ )
+ dialogActive = false
+ currentTorrentDelivered = false
+ lastReportedQueueTotal = 0
+ totalSent = 0
+ return torrents
+ }
+ return pendingIngestions > 0
+ ? torrentIngress.then(() => takeAll())
+ : takeAll()
},
// Called by main/index.ts when the add-task window is closed/destroyed.
@@ -247,7 +324,10 @@ export function createProtocolManager(deps: ProtocolManagerDeps) {
)
torrentQueue.length = 0
dialogActive = false
+ currentTorrentDelivered = false
+ lastReportedQueueTotal = 0
totalSent = 0
+ queueGeneration += 1
},
getTorrentQueueSize() {
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 85ffdb62..a13d800e 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -1,8 +1,9 @@
-import { act, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
+import { readTorrentFile } from '@renderer/lib/parse-torrent-file'
import type { PlatformServices } from '@renderer/platform/services'
import { PlatformServicesProvider } from '@renderer/platform/services'
import { Events } from '@shared/protocol/events'
@@ -16,6 +17,10 @@ vi.mock('@renderer/lib/transport', () => ({
},
}))
+vi.mock('@renderer/lib/parse-torrent-file', () => ({
+ readTorrentFile: vi.fn(),
+}))
+
const mockServices: PlatformServices = {
kind: 'electron',
pickSaveDir: vi.fn().mockResolvedValue('/picked'),
@@ -25,9 +30,9 @@ const mockServices: PlatformServices = {
notify: vi.fn(),
}
-function renderForm(props = {}) {
+function renderForm(props = {}, services: PlatformServices = mockServices) {
return render(
- <PlatformServicesProvider services={mockServices}>
+ <PlatformServicesProvider services={services}>
<AddTaskForm
onCancel={vi.fn()}
onSubmitSuccess={vi.fn()}
@@ -318,6 +323,201 @@ describe('AddTaskForm', () => {
expect(mockServices.notify).toHaveBeenCalledWith('info', 'task.add.created')
})
+ it('parses and creates a local multi-torrent batch without shell RPCs', async () => {
+ const onSubmitSuccess = vi.fn()
+ const user = userEvent.setup()
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(readTorrentFile).mockImplementation(async (file) => {
+ const isAlpha = file.name.startsWith('alpha')
+ return {
+ name: file.name,
+ base64: isAlpha ? 'YWxwaGE=' : 'YmV0YQ==',
+ meta: {
+ name: isAlpha ? 'alpha.bin' : 'beta.bin',
+ infoHash: isAlpha ? 'a'.repeat(40) : 'b'.repeat(40),
+ totalSize: 1,
+ comment: '',
+ isPrivate: false,
+ files: [
+ {
+ index: 0,
+ path: isAlpha ? 'alpha.bin' : 'beta.bin',
+ size: 1,
+ extension: 'bin',
+ },
+ ],
+ },
+ }
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (channel, request) => {
+ if (channel === 'query:getSettings') {
+ return { app: { defaultSaveDir: '/d' } }
+ }
+ if (channel === 'command:createTask') {
+ const base64 = (request as { payload?: { base64?: string } }).payload
+ ?.base64
+ return {
+ outcome: 'created',
+ gid: base64 === 'YWxwaGE=' ? 'alpha-gid' : 'beta-gid',
+ taskId: base64 === 'YWxwaGE=' ? 'alpha-task' : 'beta-task',
+ }
+ }
+ return {}
+ })
+ const webServices = { ...mockServices, kind: 'web' as const }
+ const { container } = renderForm(
+ {
+ onSubmitSuccess,
+ defaultValues: { tab: 'torrent', saveDir: '/d' },
+ },
+ webServices
+ )
+ const input =
+ container.querySelector<HTMLInputElement>('input[type="file"]')
+ expect(input).toHaveAttribute('multiple')
+
+ fireEvent.change(input as HTMLInputElement, {
+ target: {
+ files: [
+ new File(['alpha'], 'alpha.torrent'),
+ new File(['beta'], 'beta.torrent'),
+ ],
+ },
+ })
+
+ expect(await screen.findByText('Torrent 1 of 2')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Download All (2)' }))
+
+ await waitFor(() =>
+ expect(onSubmitSuccess).toHaveBeenCalledWith('alpha-task')
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(
+ 'command:createTask',
+ expect.objectContaining({
+ payload: { kind: 'torrent-base64', base64: 'YWxwaGE=' },
+ })
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(
+ 'command:createTask',
+ expect.objectContaining({
+ payload: { kind: 'torrent-base64', base64: 'YmV0YQ==' },
+ })
+ )
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ 'command:downloadAllTorrents'
+ )
+ })
+
+ it('passes the current torrent form options to the App batch command', async () => {
+ const onSubmitSuccess = vi.fn()
+ const user = userEvent.setup()
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === 'query:getSettings') {
+ return { app: { defaultSaveDir: '/default' } }
+ }
+ if (channel === 'command:downloadAllTorrents') {
+ return {
+ total: 2,
+ succeeded: 2,
+ failed: 0,
+ firstTaskId: 'first-task',
+ }
+ }
+ return {}
+ })
+ renderForm({
+ subscribeEvents: true,
+ onSubmitSuccess,
+ defaultValues: {
+ tab: 'torrent',
+ source: 'file',
+ base64: 'dG9ycmVudA==',
+ torrentMeta: {
+ name: 'current.bin',
+ infoHash: 'a'.repeat(40),
+ totalSize: 2,
+ files: [
+ { index: 0, path: 'skip.bin', size: 1, extension: '.bin' },
+ { index: 1, path: 'keep.bin', size: 1, extension: '.bin' },
+ ],
+ },
+ selectedFiles: [1],
+ saveDir: '/custom',
+ dlLimit: 2048,
+ ulLimit: 1024,
+ seedRatio: 1.5,
+ },
+ })
+
+ const queueListener = vi
+ .mocked(transport.on)
+ .mock.calls.find(
+ ([channel]) => channel === Events.TorrentQueueSizeChanged
+ )?.[1]
+ act(() => queueListener?.({ queueTotal: 2 }))
+ await user.click(
+ await screen.findByRole('button', { name: 'Download All (2)' })
+ )
+
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ 'command:downloadAllTorrents',
+ {
+ selectedFiles: [1],
+ saveDir: '/custom',
+ dlLimit: 2048,
+ ulLimit: 1024,
+ seedRatio: 1.5,
+ }
+ )
+ )
+ expect(onSubmitSuccess).toHaveBeenCalledWith('first-task')
+ })
+
+ it('closes an external queue when the shell reports no valid next torrent', async () => {
+ const onCancel = vi.fn()
+ const user = userEvent.setup()
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === 'query:getSettings') {
+ return { app: { defaultSaveDir: '/default' } }
+ }
+ if (channel === 'command:nextTorrent') return { advanced: false }
+ return {}
+ })
+ renderForm({
+ subscribeEvents: true,
+ onCancel,
+ defaultValues: {
+ tab: 'torrent',
+ source: 'file',
+ base64: 'dG9ycmVudA==',
+ torrentMeta: {
+ name: 'current.bin',
+ infoHash: 'a'.repeat(40),
+ totalSize: 1,
+ files: [
+ { index: 0, path: 'current.bin', size: 1, extension: '.bin' },
+ ],
+ },
+ selectedFiles: [0],
+ saveDir: '/custom',
+ },
+ })
+
+ const queueListener = vi
+ .mocked(transport.on)
+ .mock.calls.find(
+ ([channel]) => channel === Events.TorrentQueueSizeChanged
+ )?.[1]
+ act(() => queueListener?.({ queueTotal: 2 }))
+ await user.click(await screen.findByRole('button', { name: 'Skip' }))
+
+ await waitFor(() => expect(onCancel).toHaveBeenCalledOnce())
+ expect(screen.queryByText('Torrent 1 of 2')).not.toBeInTheDocument()
+ })
+
it('reports a partial failure when some lines fail', async () => {
const onSubmitSuccess = vi.fn()
const user = userEvent.setup()
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 6a84b7bf..2c49ff8c 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -15,6 +15,7 @@ import {
TabsList,
TabsTrigger,
} from '@renderer/components/ui/tabs'
+import type { ParsedTorrentFile } from '@renderer/lib/parse-torrent-file'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import { usePlatformServices } from '@renderer/platform/services'
@@ -26,6 +27,9 @@ import {
formValuesToTaskCreateRequests,
type TaskCreateCommandResult,
type TaskCreateRequest,
+ type TorrentBatchCreateOptions,
+ type TorrentBatchCreateResult,
+ type TorrentQueueAdvanceResult,
} from '@shared/schemas/add-task'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
@@ -44,6 +48,8 @@ import { TorrentTabPanel } from './torrent-tab-panel'
import { parseUrlLines } from './url-interpreters/multiline-url'
import {
type AddTaskModeHydrationContext,
+ type TorrentQueueState,
+ type TorrentQueueUpdate,
useExternalHydration,
} from './use-external-hydration'
@@ -62,6 +68,11 @@ const BASE_DEFAULTS: DeepPartial<AddTaskFormValues> = {
saveDir: '',
}
+interface LocalTorrentQueue {
+ files: ParsedTorrentFile[]
+ currentIndex: number
+}
+
function taskCreateFailureReason(error: unknown): string | null {
if (!(error instanceof Error)) return null
const reason = error.message
@@ -82,6 +93,13 @@ export function AddTaskForm({
const platform = usePlatformServices()
const { t } = useTranslation()
const [submitting, setSubmitting] = useState(false)
+ const [advancingTorrent, setAdvancingTorrent] = useState(false)
+ const [batchSubmitting, setBatchSubmitting] = useState(false)
+ const [torrentQueue, setTorrentQueue] = useState<TorrentQueueState | null>(
+ null
+ )
+ const [localTorrentQueue, setLocalTorrentQueue] =
+ useState<LocalTorrentQueue | null>(null)
const [duplicateConflict, setDuplicateConflict] = useState<{
request: TaskCreateRequest
result: Extract<TaskCreateCommandResult, { outcome: 'conflict' }>
@@ -145,7 +163,66 @@ export function AddTaskForm({
[form, platform]
)
- useExternalHydration(form, subscribeEvents, hydrateOpenState)
+ const handleTorrentQueueChanged = useCallback(
+ (update: TorrentQueueUpdate) => {
+ setLocalTorrentQueue(null)
+ if (!update) {
+ setTorrentQueue(null)
+ setAdvancingTorrent(false)
+ return
+ }
+ setTorrentQueue((current) => ({
+ queuePosition:
+ 'queuePosition' in update
+ ? update.queuePosition
+ : (current?.queuePosition ?? 1),
+ queueTotal: update.queueTotal,
+ }))
+ if ('queuePosition' in update) setAdvancingTorrent(false)
+ },
+ []
+ )
+
+ const hydrateLocalTorrent = useCallback(
+ (torrent: ParsedTorrentFile) => {
+ form.setValue('tab' as never, 'torrent' as never, { shouldDirty: true })
+ form.setValue('torrentMeta' as never, torrent.meta as never, {
+ shouldDirty: true,
+ })
+ form.setValue('source' as never, 'file' as never, { shouldDirty: true })
+ form.setValue('base64' as never, torrent.base64 as never, {
+ shouldDirty: true,
+ })
+ form.setValue('magnetUri' as never, undefined as never, {
+ shouldDirty: true,
+ })
+ form.setValue(
+ 'selectedFiles' as never,
+ torrent.meta.files.map((file) => file.index) as never,
+ { shouldDirty: true, shouldValidate: true }
+ )
+ },
+ [form]
+ )
+
+ const handleLocalTorrentFilesLoaded = useCallback(
+ (files: ParsedTorrentFile[]) => {
+ if (files.length === 0) return
+ setLocalTorrentQueue({ files, currentIndex: 0 })
+ setTorrentQueue(
+ files.length > 1 ? { queuePosition: 1, queueTotal: files.length } : null
+ )
+ setAdvancingTorrent(false)
+ },
+ []
+ )
+
+ useExternalHydration(
+ form,
+ subscribeEvents,
+ hydrateOpenState,
+ handleTorrentQueueChanged
+ )
// Backfill the default save directory for the initially mounted form.
// Desktop opens refresh it again through hydrateOpenState above.
@@ -181,8 +258,173 @@ export function AddTaskForm({
}
}, [hydrateOpenState, subscribeEvents])
+ const hasNextQueuedTorrent = useCallback(
+ () =>
+ Boolean(
+ torrentQueue && torrentQueue.queuePosition < torrentQueue.queueTotal
+ ),
+ [torrentQueue]
+ )
+
+ const advanceTorrentQueue = useCallback(async () => {
+ setAdvancingTorrent(true)
+ if (localTorrentQueue) {
+ const nextIndex = localTorrentQueue.currentIndex + 1
+ const next = localTorrentQueue.files[nextIndex]
+ if (!next) {
+ setLocalTorrentQueue(null)
+ setTorrentQueue(null)
+ setAdvancingTorrent(false)
+ return false
+ }
+ hydrateLocalTorrent(next)
+ setLocalTorrentQueue({ ...localTorrentQueue, currentIndex: nextIndex })
+ setTorrentQueue({
+ queuePosition: nextIndex + 1,
+ queueTotal: localTorrentQueue.files.length,
+ })
+ setAdvancingTorrent(false)
+ return true
+ }
+ try {
+ const result = (await transport.invoke(
+ Commands.NextTorrent
+ )) as TorrentQueueAdvanceResult
+ if (!result.advanced) {
+ setTorrentQueue(null)
+ setAdvancingTorrent(false)
+ }
+ return result.advanced
+ } catch (error) {
+ console.error(error)
+ setAdvancingTorrent(false)
+ platform.notify('error', 'task.add.queueAdvanceFailed')
+ return true
+ }
+ }, [hydrateLocalTorrent, localTorrentQueue, platform])
+
+ const completeCurrentSubmission = useCallback(
+ async (taskId: string) => {
+ const values = form.getValues()
+ if (
+ hasNextQueuedTorrent() &&
+ values.tab === 'torrent' &&
+ values.source === 'file'
+ ) {
+ if (await advanceTorrentQueue()) return
+ }
+ setLocalTorrentQueue(null)
+ setTorrentQueue(null)
+ onSubmitSuccess?.(taskId)
+ },
+ [advanceTorrentQueue, form, hasNextQueuedTorrent, onSubmitSuccess]
+ )
+
+ const handleCancel = useCallback(async () => {
+ if (hasNextQueuedTorrent()) {
+ if (await advanceTorrentQueue()) return
+ }
+ onCancel()
+ }, [advanceTorrentQueue, hasNextQueuedTorrent, onCancel])
+
+ const handleDownloadAllTorrents = useCallback(async () => {
+ if (!hasNextQueuedTorrent()) return
+ setBatchSubmitting(true)
+ try {
+ const parsedValues = addTaskFormSchema.safeParse(form.getValues())
+ if (!parsedValues.success) return
+ const values = parsedValues.data
+ if (values.tab !== 'torrent' || values.source !== 'file') return
+ const currentRequest = formValuesToTaskCreateRequests(values)[0]
+ if (currentRequest?.type !== 'bt') return
+
+ let result: TorrentBatchCreateResult
+ if (localTorrentQueue) {
+ const requests: TaskCreateRequest[] = [
+ currentRequest,
+ ...localTorrentQueue.files
+ .slice(localTorrentQueue.currentIndex + 1)
+ .map((torrent) => ({
+ type: 'bt' as const,
+ payload: {
+ kind: 'torrent-base64' as const,
+ base64: torrent.base64,
+ },
+ selectedFiles: torrent.meta.files.map((file) => file.index),
+ saveDir: values.saveDir,
+ dlLimit: values.dlLimit,
+ ulLimit: values.ulLimit,
+ seedRatio: values.seedRatio,
+ displayName: torrent.meta.name,
+ })),
+ ]
+ let succeeded = 0
+ let failed = 0
+ let firstTaskId: string | null = null
+ for (const request of requests) {
+ try {
+ const created = (await transport.invoke(
+ Commands.CreateTask,
+ request
+ )) as TaskCreateCommandResult
+ if (created.outcome === 'conflict') {
+ failed += 1
+ continue
+ }
+ succeeded += 1
+ firstTaskId ??= created.taskId ?? created.gid
+ } catch (error) {
+ console.error(error)
+ failed += 1
+ }
+ }
+ result = {
+ total: requests.length,
+ succeeded,
+ failed,
+ firstTaskId,
+ }
+ } else {
+ const options: TorrentBatchCreateOptions = {
+ selectedFiles: values.selectedFiles,
+ saveDir: currentRequest.saveDir,
+ dlLimit: currentRequest.dlLimit,
+ ulLimit: currentRequest.ulLimit,
+ seedRatio: currentRequest.seedRatio,
+ }
+ result = (await transport.invoke(
+ Commands.DownloadAllTorrents,
+ options
+ )) as TorrentBatchCreateResult
+ }
+ setLocalTorrentQueue(null)
+ setTorrentQueue(null)
+ if (result.succeeded > 0) {
+ if (result.failed > 0) {
+ platform.notify('warn', 'task.add.createdPartial', {
+ ok: result.succeeded,
+ failed: result.failed,
+ })
+ } else {
+ platform.notify('info', 'task.add.batchCreated', {
+ count: result.succeeded,
+ })
+ }
+ if (result.firstTaskId) onSubmitSuccess?.(result.firstTaskId)
+ } else {
+ platform.notify('error', 'task.add.createFailed')
+ }
+ } catch (error) {
+ console.error(error)
+ platform.notify('error', 'task.add.createFailed')
+ } finally {
+ setBatchSubmitting(false)
+ }
+ }, [form, hasNextQueuedTorrent, localTorrentQueue, onSubmitSuccess, platform])
+
const onSubmit = useCallback(
async (values: AddTaskFormValues) => {
+ if (submitting || advancingTorrent || batchSubmitting) return
setSubmitting(true)
try {
const requests = formValuesToTaskCreateRequests(values)
@@ -228,13 +470,21 @@ export function AddTaskForm({
}
}
if (successes.length > 0) {
- onSubmitSuccess?.(successes[0].taskId ?? successes[0].gid)
+ await completeCurrentSubmission(
+ successes[0].taskId ?? successes[0].gid
+ )
}
} finally {
setSubmitting(false)
}
},
- [onSubmitSuccess, platform]
+ [
+ advancingTorrent,
+ batchSubmitting,
+ completeCurrentSubmission,
+ platform,
+ submitting,
+ ]
)
const createSeparateCopy = useCallback(async () => {
@@ -251,7 +501,7 @@ export function AddTaskForm({
}
setDuplicateConflict(null)
platform.notify('info', 'task.add.createdCopy')
- onSubmitSuccess?.(result.taskId)
+ await completeCurrentSubmission(result.taskId)
} catch (error) {
console.error(error)
const reason = taskCreateFailureReason(error)
@@ -263,7 +513,7 @@ export function AddTaskForm({
} finally {
setSubmitting(false)
}
- }, [duplicateConflict, onSubmitSuccess, platform])
+ }, [completeCurrentSubmission, duplicateConflict, platform])
// ⌘↵ / Ctrl+Enter submit
useEffect(() => {
@@ -296,7 +546,7 @@ export function AddTaskForm({
presentation === 'dialog' ? 'pb-4' : 'pb-[72px]'
)}
>
- <TabsSection />
+ <TabsSection onTorrentFilesLoaded={handleLocalTorrentFilesLoaded} />
</div>
</div>
<div
@@ -307,9 +557,11 @@ export function AddTaskForm({
)}
>
<FooterActionsBridge
- onCancel={onCancel}
+ onCancel={() => void handleCancel()}
+ onDownloadAll={handleDownloadAllTorrents}
onSubmit={() => void form.handleSubmit(onSubmit)()}
- submitting={submitting}
+ submitting={submitting || advancingTorrent || batchSubmitting}
+ torrentQueue={torrentQueue}
/>
</div>
<AlertDialog
@@ -340,7 +592,7 @@ export function AddTaskForm({
const taskId =
duplicateConflict.result.conflict.existingTaskId
setDuplicateConflict(null)
- if (taskId) onSubmitSuccess?.(taskId)
+ if (taskId) void completeCurrentSubmission(taskId)
}}
>
{t('task.add.duplicate.showExisting')}
@@ -359,7 +611,11 @@ export function AddTaskForm({
)
}
-function TabsSection() {
+function TabsSection({
+ onTorrentFilesLoaded,
+}: {
+ onTorrentFilesLoaded: (files: ParsedTorrentFile[]) => void
+}) {
const { t } = useTranslation()
const { setValue } = useFormContext<AddTaskFormValues>()
const tab = useWatch<AddTaskFormValues, 'tab'>({ name: 'tab' })
@@ -387,7 +643,7 @@ function TabsSection() {
keepMounted
className="mt-2 flex min-h-0 min-w-0 flex-1 data-hidden:hidden"
>
- <TorrentTabPanel />
+ <TorrentTabPanel onFilesLoaded={onTorrentFilesLoaded} />
</TabsContent>
</Tabs>
)
@@ -395,12 +651,16 @@ function TabsSection() {
function FooterActionsBridge({
onCancel,
+ onDownloadAll,
onSubmit,
submitting,
+ torrentQueue,
}: {
onCancel: () => void
+ onDownloadAll: () => void
onSubmit: () => void
submitting: boolean
+ torrentQueue: TorrentQueueState | null
}) {
const tab = useWatch<AddTaskFormValues, 'tab'>({ name: 'tab' })
const urls = useWatch<AddTaskFormValues, 'urls'>({ name: 'urls' })
@@ -423,7 +683,16 @@ function FooterActionsBridge({
<FooterActions
submitting={submitting}
canSubmit={canSubmit}
+ torrentQueue={
+ torrentQueue
+ ? {
+ current: torrentQueue.queuePosition,
+ total: torrentQueue.queueTotal,
+ }
+ : undefined
+ }
onCancel={onCancel}
+ onDownloadAll={onDownloadAll}
onSubmit={onSubmit}
/>
)
diff --git a/src/renderer/components/add-task/drop-zone.tsx b/src/renderer/components/add-task/drop-zone.tsx
index 3cfbe77a..74322eeb 100644
--- a/src/renderer/components/add-task/drop-zone.tsx
+++ b/src/renderer/components/add-task/drop-zone.tsx
@@ -1,47 +1,54 @@
-import { transport } from '@renderer/lib/transport'
+import {
+ type ParsedTorrentFile,
+ readTorrentFile,
+} from '@renderer/lib/parse-torrent-file'
import { cn } from '@renderer/lib/utils'
import { usePlatformServices } from '@renderer/platform/services'
-import { Commands } from '@shared/protocol/commands'
import type { AddTaskFormValues } from '@shared/schemas/add-task'
-import type { TorrentMeta } from '@shared/types/torrent'
import { Upload } from 'lucide-react'
import { useCallback, useRef, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
-export function DropZone() {
+export function DropZone({
+ onFilesLoaded,
+}: {
+ onFilesLoaded: (files: ParsedTorrentFile[]) => void
+}) {
const { t } = useTranslation()
const { setValue } = useFormContext<AddTaskFormValues>()
const platform = usePlatformServices()
const [dragOver, setDragOver] = useState(false)
const fileRef = useRef<HTMLInputElement>(null)
- const loadFile = useCallback(
- async (file: File) => {
- try {
- const buf = await file.arrayBuffer()
- const bytes = new Uint8Array(buf)
- const chunks: string[] = []
- for (let i = 0; i < bytes.length; i += 8192) {
- chunks.push(String.fromCharCode(...bytes.subarray(i, i + 8192)))
+ const loadFiles = useCallback(
+ async (files: FileList | File[]) => {
+ const parsed: ParsedTorrentFile[] = []
+ let failed = false
+ for (const file of Array.from(files)) {
+ try {
+ parsed.push(await readTorrentFile(file))
+ } catch {
+ failed = true
}
- const base64 = btoa(chunks.join(''))
- const meta = (await transport.invoke(Commands.ParseTorrent, {
- base64,
- })) as TorrentMeta
- setValue('torrentMeta' as never, meta as never, { shouldDirty: true })
- setValue('source' as never, 'file' as never, { shouldDirty: true })
- setValue('base64' as never, base64 as never, { shouldDirty: true })
- setValue(
- 'selectedFiles' as never,
- meta.files.map((f) => f.index) as never,
- { shouldDirty: true, shouldValidate: true }
- )
- } catch {
- platform.notify('error', 'task.add.parseFailed')
}
+ if (failed) platform.notify('error', 'task.add.parseFailed')
+ if (parsed.length === 0) return
+
+ const first = parsed[0]
+ setValue('torrentMeta' as never, first.meta as never, {
+ shouldDirty: true,
+ })
+ setValue('source' as never, 'file' as never, { shouldDirty: true })
+ setValue('base64' as never, first.base64 as never, { shouldDirty: true })
+ setValue(
+ 'selectedFiles' as never,
+ first.meta.files.map((file) => file.index) as never,
+ { shouldDirty: true, shouldValidate: true }
+ )
+ onFilesLoaded(parsed)
},
- [setValue, platform]
+ [onFilesLoaded, platform, setValue]
)
return (
@@ -57,8 +64,9 @@ export function DropZone() {
onDrop={(e) => {
e.preventDefault()
setDragOver(false)
- const file = e.dataTransfer.files[0]
- if (file) loadFile(file)
+ if (e.dataTransfer.files.length > 0) {
+ void loadFiles(e.dataTransfer.files)
+ }
}}
className={cn(
'flex h-40 w-full flex-col items-center justify-center gap-2 rounded-md border-2 border-dashed transition-colors',
@@ -77,10 +85,10 @@ export function DropZone() {
ref={fileRef}
type="file"
accept=".torrent"
+ multiple
className="hidden"
onChange={(e) => {
- const file = e.target.files?.[0]
- if (file) loadFile(file)
+ if (e.target.files?.length) void loadFiles(e.target.files)
e.target.value = ''
}}
/>
diff --git a/src/renderer/components/add-task/footer-actions.tsx b/src/renderer/components/add-task/footer-actions.tsx
index f134fe77..8982df8b 100644
--- a/src/renderer/components/add-task/footer-actions.tsx
+++ b/src/renderer/components/add-task/footer-actions.tsx
@@ -4,39 +4,69 @@ import { useTranslation } from 'react-i18next'
interface FooterActionsProps {
submitting: boolean
canSubmit: boolean
+ torrentQueue?: { current: number; total: number }
onCancel: () => void
+ onDownloadAll: () => void
onSubmit: () => void
}
export function FooterActions({
submitting,
canSubmit,
+ torrentQueue,
onCancel,
+ onDownloadAll,
onSubmit,
}: FooterActionsProps) {
const { t } = useTranslation()
+ const queuedCount = torrentQueue
+ ? torrentQueue.total - torrentQueue.current + 1
+ : 0
+ const hasQueuedTorrents = queuedCount > 1
return (
- <div className="flex items-center justify-end gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={onCancel}
- disabled={submitting}
- >
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- variant="default"
- size="sm"
- onClick={onSubmit}
- disabled={!canSubmit || submitting}
- className="gap-2"
- >
- <span>{submitting ? t('task.add.adding') : t('common.download')}</span>
- </Button>
+ <div className="flex items-center justify-between gap-3">
+ <span className="min-w-0 truncate text-xs text-muted-foreground">
+ {torrentQueue ? t('task.add.torrentQueueProgress', torrentQueue) : null}
+ </span>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onCancel}
+ disabled={submitting}
+ >
+ {hasQueuedTorrents ? t('task.add.skipTorrent') : t('common.cancel')}
+ </Button>
+ {hasQueuedTorrents && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={onDownloadAll}
+ disabled={!canSubmit || submitting}
+ >
+ {t('task.add.downloadAllTorrents', { count: queuedCount })}
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="default"
+ size="sm"
+ onClick={onSubmit}
+ disabled={!canSubmit || submitting}
+ className="gap-2"
+ >
+ <span>
+ {submitting
+ ? t('task.add.adding')
+ : torrentQueue && torrentQueue.current < torrentQueue.total
+ ? t('task.add.downloadAndContinue')
+ : t('common.download')}
+ </span>
+ </Button>
+ </div>
</div>
)
}
diff --git a/src/renderer/components/add-task/torrent-tab-panel.tsx b/src/renderer/components/add-task/torrent-tab-panel.tsx
index d8bd57a0..fc54382d 100644
--- a/src/renderer/components/add-task/torrent-tab-panel.tsx
+++ b/src/renderer/components/add-task/torrent-tab-panel.tsx
@@ -1,10 +1,15 @@
+import type { ParsedTorrentFile } from '@renderer/lib/parse-torrent-file'
import type { AddTaskFormValues } from '@shared/schemas/add-task'
import { useCallback } from 'react'
import { useFormContext, useWatch } from 'react-hook-form'
import { DropZone } from './drop-zone'
import { TorrentFilePanel } from './torrent-file-panel'
-export function TorrentTabPanel() {
+export function TorrentTabPanel({
+ onFilesLoaded,
+}: {
+ onFilesLoaded: (files: ParsedTorrentFile[]) => void
+}) {
const { setValue } = useFormContext<AddTaskFormValues>()
const meta = useWatch<AddTaskFormValues, 'torrentMeta'>({
name: 'torrentMeta',
@@ -17,5 +22,9 @@ export function TorrentTabPanel() {
setValue('selectedFiles' as never, [] as never, { shouldDirty: true })
}, [setValue])
- return meta ? <TorrentFilePanel onClear={handleClear} /> : <DropZone />
+ return meta ? (
+ <TorrentFilePanel onClear={handleClear} />
+ ) : (
+ <DropZone onFilesLoaded={onFilesLoaded} />
+ )
}
diff --git a/src/renderer/components/add-task/use-external-hydration.ts b/src/renderer/components/add-task/use-external-hydration.ts
index 01b4e59b..1715967d 100644
--- a/src/renderer/components/add-task/use-external-hydration.ts
+++ b/src/renderer/components/add-task/use-external-hydration.ts
@@ -5,6 +5,7 @@ import {
magnetFileSelectionPayloadSchema,
protocolTorrentFilePayloadSchema,
setAddTaskModeEventPayloadSchema,
+ torrentQueueSizeChangedPayloadSchema,
urlParamsToFormDefaults,
} from '@shared/schemas/add-task'
import { useEffect } from 'react'
@@ -14,10 +15,21 @@ export interface AddTaskModeHydrationContext {
refreshDefaultSaveDir: boolean
}
+export interface TorrentQueueState {
+ queuePosition: number
+ queueTotal: number
+}
+
+export type TorrentQueueUpdate =
+ | TorrentQueueState
+ | { queueTotal: number }
+ | null
+
export function useExternalHydration(
form: UseFormReturn<AddTaskFormValues>,
enabled: boolean,
- onModeHydrated?: (context: AddTaskModeHydrationContext) => void
+ onModeHydrated?: (context: AddTaskModeHydrationContext) => void,
+ onTorrentQueueChanged?: (update: TorrentQueueUpdate) => void
) {
useEffect(() => {
if (!enabled) return
@@ -25,6 +37,7 @@ export function useExternalHydration(
const onMagnet = (...args: unknown[]) => {
const parsed = magnetFileSelectionPayloadSchema.safeParse(args[0])
if (!parsed.success) return
+ onTorrentQueueChanged?.(null)
form.reset(
{
tab: 'torrent',
@@ -46,6 +59,10 @@ export function useExternalHydration(
const onProtocol = (...args: unknown[]) => {
const parsed = protocolTorrentFilePayloadSchema.safeParse(args[0])
if (!parsed.success) return
+ onTorrentQueueChanged?.({
+ queuePosition: parsed.data.queuePosition,
+ queueTotal: parsed.data.queueTotal,
+ })
form.reset(
{
tab: 'torrent',
@@ -62,6 +79,7 @@ export function useExternalHydration(
const onSetMode = (...args: unknown[]) => {
const parsed = setAddTaskModeEventPayloadSchema.safeParse(args[0])
if (!parsed.success) return
+ onTorrentQueueChanged?.(null)
const defaults = urlParamsToFormDefaults(parsed.data)
const refreshDefaultSaveDir =
defaults.saveDir === undefined && !form.getFieldState('saveDir').isDirty
@@ -77,14 +95,22 @@ export function useExternalHydration(
onModeHydrated?.({ refreshDefaultSaveDir })
}
+ const onTorrentQueueSizeChanged = (...args: unknown[]) => {
+ const parsed = torrentQueueSizeChangedPayloadSchema.safeParse(args[0])
+ if (!parsed.success) return
+ onTorrentQueueChanged?.(parsed.data)
+ }
+
transport.on(Events.MagnetFileSelection, onMagnet)
transport.on(Events.ProtocolTorrentFile, onProtocol)
transport.on(Events.SetAddTaskMode, onSetMode)
+ transport.on(Events.TorrentQueueSizeChanged, onTorrentQueueSizeChanged)
return () => {
transport.off(Events.MagnetFileSelection, onMagnet)
transport.off(Events.ProtocolTorrentFile, onProtocol)
transport.off(Events.SetAddTaskMode, onSetMode)
+ transport.off(Events.TorrentQueueSizeChanged, onTorrentQueueSizeChanged)
}
- }, [form, enabled, onModeHydrated])
+ }, [form, enabled, onModeHydrated, onTorrentQueueChanged])
}
diff --git a/src/renderer/components/ui/toast.test.tsx b/src/renderer/components/ui/toast.test.tsx
index adb7b7fb..58f6bf3e 100644
--- a/src/renderer/components/ui/toast.test.tsx
+++ b/src/renderer/components/ui/toast.test.tsx
@@ -191,7 +191,7 @@ describe('toast', () => {
expect(onDeny).not.toHaveBeenCalled()
await userEvent.click(
- screen.getByRole('button', { name: "Don't allow", hidden: true })
+ screen.getByRole('button', { name: 'Don’t allow', hidden: true })
)
expect(onDeny).toHaveBeenCalledOnce()
})
diff --git a/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx b/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx
index 442ecfe5..578c88c1 100644
--- a/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx
+++ b/src/renderer/features/engine-diagnostics/engine-diagnostics-dialog.test.tsx
@@ -98,7 +98,7 @@ describe('EngineDiagnosticsDialogHost', () => {
expect(await screen.findByText('Engine diagnostics')).toBeVisible()
expect(
- await screen.findByText(/matches Motrix's bundled binary/i)
+ await screen.findByText(/matches Motrix’s bundled binary/i)
).toBeVisible()
expect(
screen.getByRole('button', { name: 'Force stop & recover' })
diff --git a/src/renderer/hooks/use-notification-toasts.test.tsx b/src/renderer/hooks/use-notification-toasts.test.tsx
index 8f4a5c90..f73f1ef0 100644
--- a/src/renderer/hooks/use-notification-toasts.test.tsx
+++ b/src/renderer/hooks/use-notification-toasts.test.tsx
@@ -336,7 +336,7 @@ describe('useNotificationToasts', () => {
id: 'engine-start-failed',
title: 'aria2 engine could not start',
description:
- "Motrix's RPC port is occupied, so aria2 engine could not start.",
+ 'Motrix’s RPC port is occupied, so aria2 engine could not start.',
type: 'error',
timeout: 0,
})
diff --git a/src/renderer/lib/parse-torrent-file.ts b/src/renderer/lib/parse-torrent-file.ts
new file mode 100644
index 00000000..5c554b09
--- /dev/null
+++ b/src/renderer/lib/parse-torrent-file.ts
@@ -0,0 +1,44 @@
+import {
+ MAX_TORRENT_BASE64_SIZE,
+ projectTorrentMeta,
+} from '@shared/lib/torrent-meta'
+import type { TorrentMeta } from '@shared/types/torrent'
+import parseTorrent from 'parse-torrent'
+
+export interface ParsedTorrentFile {
+ name: string
+ base64: string
+ meta: TorrentMeta
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ const chunks: string[] = []
+ for (let index = 0; index < bytes.length; index += 8192) {
+ chunks.push(String.fromCharCode(...bytes.subarray(index, index + 8192)))
+ }
+ return btoa(chunks.join(''))
+}
+
+export async function parseTorrentFile(
+ bytes: Uint8Array
+): Promise<TorrentMeta> {
+ const encodedSize = Math.ceil(bytes.byteLength / 3) * 4
+ if (encodedSize > MAX_TORRENT_BASE64_SIZE) {
+ throw new Error('Torrent file is too large')
+ }
+
+ const meta = projectTorrentMeta(await parseTorrent(bytes))
+ if (meta.files.length === 0) {
+ throw new Error('Torrent contains no files')
+ }
+ return meta
+}
+
+export async function readTorrentFile(file: File): Promise<ParsedTorrentFile> {
+ const bytes = new Uint8Array(await file.arrayBuffer())
+ return {
+ name: file.name,
+ base64: bytesToBase64(bytes),
+ meta: await parseTorrentFile(bytes),
+ }
+}
diff --git a/src/renderer/lib/path-browser-shim.ts b/src/renderer/lib/path-browser-shim.ts
new file mode 100644
index 00000000..0ff0a09a
--- /dev/null
+++ b/src/renderer/lib/path-browser-shim.ts
@@ -0,0 +1,18 @@
+export const sep = '/'
+
+export function join(...parts: string[]): string {
+ const segments: string[] = []
+ for (const part of parts) {
+ for (const segment of part.split('/')) {
+ if (!segment || segment === '.') continue
+ if (segment === '..') {
+ segments.pop()
+ continue
+ }
+ segments.push(segment)
+ }
+ }
+ return `/${segments.join('/')}`
+}
+
+export default { join, sep }
diff --git a/src/renderer/routes/dashboard/tiles/nat-tile.tsx b/src/renderer/routes/dashboard/tiles/nat-tile.tsx
index 62c617bb..60c971a5 100644
--- a/src/renderer/routes/dashboard/tiles/nat-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/nat-tile.tsx
@@ -63,6 +63,12 @@ interface NatAction {
}
export function NatTile({ viewport, className }: NatTileProps) {
+ return __MOTRIX_TARGET__ === 'electron' ? (
+ <ElectronNatTile viewport={viewport} className={className} />
+ ) : null
+}
+
+function ElectronNatTile({ viewport, className }: NatTileProps) {
const { t, i18n } = useTranslation()
const services = usePlatformServices()
const status = useNatStatus()
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx
index 9672bdad..8e7f818b 100644
--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx
@@ -41,10 +41,10 @@ describe('RemoveTasksDialog', () => {
onConfirm={vi.fn()}
/>
)
- const title = screen.getByText(/Remove "/)
+ const title = screen.getByText(/Remove “/)
// Middle ellipsis: a head, the '…', then a tail that preserves the
// extension — NOT a silent end-cut that drops it.
- expect(title.textContent).toMatch(/X+…X*\.mkv"\?$/)
+ expect(title.textContent).toMatch(/X+…X*\.mkv”\?$/)
expect(title.textContent?.length).toBeLessThan(100)
})
diff --git a/src/renderer/routes/downloads/nat-badge.tsx b/src/renderer/routes/downloads/nat-badge.tsx
index f3d23e04..7f9b8f70 100644
--- a/src/renderer/routes/downloads/nat-badge.tsx
+++ b/src/renderer/routes/downloads/nat-badge.tsx
@@ -31,6 +31,10 @@ const TEXT_KEY: Record<NatBucket, string> = {
}
export function NatBadge() {
+ return __MOTRIX_TARGET__ === 'electron' ? <ElectronNatBadge /> : null
+}
+
+function ElectronNatBadge() {
const { t, i18n } = useTranslation()
const services = usePlatformServices()
const status = useNatStatus()
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsx
index e878ca1d..89ca554f 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx
@@ -135,31 +135,32 @@ export function TaskInspectorDrawer({
</span>
</div>
- {canRevealTaskFolder(single) && (
- <div className="min-w-0 flex items-center gap-1 text-xs text-muted-foreground">
- <Button
- className="min-w-0 flex-1 justify-start overflow-hidden text-muted-foreground hover:no-underline cursor-pointer"
- variant="secondary"
- size="xs"
- dir="ltr"
- onClick={() =>
- transport.invoke(Commands.RevealInFolder, {
- taskId: single.id,
- })
- }
- >
- <HardDrive className="mr-1 size-3.5 shrink-0 text-muted-foreground" />
- <span className="truncate">
- {single.finalPath || single.diskPath}
- </span>
- </Button>
- <CopyButton
- variant="ghost"
- className="ml-1 h-4.5 w-4.5 shrink-0 rounded-md p-0 has-[>svg]:px-0 [&_svg:not([class*='size-'])]:size-3"
- content={single.finalPath || single.diskPath}
- />
- </div>
- )}
+ {__MOTRIX_TARGET__ === 'electron' &&
+ canRevealTaskFolder(single) && (
+ <div className="min-w-0 flex items-center gap-1 text-xs text-muted-foreground">
+ <Button
+ className="min-w-0 flex-1 justify-start overflow-hidden text-muted-foreground hover:no-underline cursor-pointer"
+ variant="secondary"
+ size="xs"
+ dir="ltr"
+ onClick={() =>
+ transport.invoke(Commands.RevealInFolder, {
+ taskId: single.id,
+ })
+ }
+ >
+ <HardDrive className="mr-1 size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">
+ {single.finalPath || single.diskPath}
+ </span>
+ </Button>
+ <CopyButton
+ variant="ghost"
+ className="ml-1 h-4.5 w-4.5 shrink-0 rounded-md p-0 has-[>svg]:px-0 [&_svg:not([class*='size-'])]:size-3"
+ content={single.finalPath || single.diskPath}
+ />
+ </div>
+ )}
</div>
<StatusPill status={single.status} />
</div>
diff --git a/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx b/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx
index 5f8c69ca..fb9c8de3 100644
--- a/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx
+++ b/src/renderer/routes/plugins/components/registry-detail-panel.test.tsx
@@ -83,12 +83,9 @@ describe('RegistryDetailPanel install affordance', () => {
expect(screen.getByTestId('registry-install-btn')).toBeDisabled()
})
- it('renders no Install button on web, keeping the pending copy', () => {
+ it('shows the verified registry Install button on web', () => {
renderPanel('web', entry())
- expect(screen.queryByTestId('registry-install-btn')).toBeNull()
- expect(
- screen.getByText(/straight from the registry is coming soon/i)
- ).toBeInTheDocument()
+ expect(screen.getByTestId('registry-install-btn')).toBeEnabled()
})
it('resolves sparse fields and honors an explicit empty features override', () => {
diff --git a/src/renderer/routes/plugins/components/registry-detail-panel.tsx b/src/renderer/routes/plugins/components/registry-detail-panel.tsx
index c2d60131..1e03d2cb 100644
--- a/src/renderer/routes/plugins/components/registry-detail-panel.tsx
+++ b/src/renderer/routes/plugins/components/registry-detail-panel.tsx
@@ -21,17 +21,14 @@ interface Props {
/**
* Detail view for a registry plugin that is not installed — the landing
- * surface of the motrix://plugins/<id> deeplink. On Electron the panel
- * installs through PluginInstallDialog's fixed-source mode (the §6.3
- * verified flow in the main process); incompatible entries render the
- * button disabled (viewable but not installable). On web it stays
- * browse-only with the pending copy.
+ * surface of the motrix://plugins/<id> deeplink. Both hosts install through
+ * PluginInstallDialog's fixed-source mode and their shell-owned verified
+ * registry flow; incompatible entries remain viewable but not installable.
*/
export function RegistryDetailPanel({ entry }: Props) {
const { t, i18n } = useTranslation()
const services = usePlatformServices()
const [installOpen, setInstallOpen] = useState(false)
- const isElectron = services.kind === 'electron'
const { name, description, features } = registryListing(
entry.listing,
i18n.language
@@ -87,17 +84,15 @@ export function RegistryDetailPanel({ entry }: Props) {
})}
</Badge>
)}
- {isElectron && (
- <Button
- size="sm"
- disabled={!entry.compatible}
- onClick={() => setInstallOpen(true)}
- data-testid="registry-install-btn"
- >
- <Download className="size-3.5" />
- {t('plugins.registry.install')}
- </Button>
- )}
+ <Button
+ size="sm"
+ disabled={!entry.compatible}
+ onClick={() => setInstallOpen(true)}
+ data-testid="registry-install-btn"
+ >
+ <Download className="size-3.5" />
+ {t('plugins.registry.install')}
+ </Button>
<Button
variant="outline"
size="sm"
@@ -111,11 +106,6 @@ export function RegistryDetailPanel({ entry }: Props) {
{t('plugins.registry.viewOnWebsite')}
</Button>
</div>
- {!isElectron && (
- <p className="text-xs text-muted-foreground">
- {t('plugins.registry.installPending')}
- </p>
- )}
</Card>
{features.length > 0 && (
diff --git a/src/renderer/routes/plugins/hooks/use-registry.ts b/src/renderer/routes/plugins/hooks/use-registry.ts
index 7feba8c2..79bd73fa 100644
--- a/src/renderer/routes/plugins/hooks/use-registry.ts
+++ b/src/renderer/routes/plugins/hooks/use-registry.ts
@@ -83,11 +83,10 @@ function toUpdatesMap(
}
/**
- * Registry update scan. `enabled` gates the whole surface to the Electron
- * shell — the server registers no CheckPluginUpdates handler, so the web
- * renderer must never invoke it. Mount-time check is cache-only inside the
- * client TTL; `refresh()` forces a conditional refetch AND re-pulls the
- * directory so the available-section and badges move together.
+ * Registry update scan. Both shells expose CheckPluginUpdates; the server
+ * returns community updates only because builtin overlays ship with a new
+ * container image. Mount-time check is cache-only inside the client TTL;
+ * `refresh()` forces a conditional refetch and re-pulls the directory.
*/
export function useRegistryUpdates(enabled: boolean): {
refreshing: boolean
diff --git a/src/renderer/routes/plugins/plugin-detail-page.test.tsx b/src/renderer/routes/plugins/plugin-detail-page.test.tsx
index 68622a53..ec1f0277 100644
--- a/src/renderer/routes/plugins/plugin-detail-page.test.tsx
+++ b/src/renderer/routes/plugins/plugin-detail-page.test.tsx
@@ -264,12 +264,10 @@ describe('PluginDetailPage', () => {
expect(mockInvoke).toHaveBeenCalledWith(Commands.CheckPluginUpdates, {})
})
- it('does not scan for plugin updates on the web platform', () => {
- // CheckPluginUpdates has no server-side handler; the electron gate must
- // hold on the detail page exactly as it does on PluginsPage.
+ it('scans for community plugin updates on the web platform', () => {
renderAt('/plugins/test.demo', 'web')
- expect(mockInvoke).not.toHaveBeenCalledWith(Commands.CheckPluginUpdates, {})
+ expect(mockInvoke).toHaveBeenCalledWith(Commands.CheckPluginUpdates, {})
})
it('offers a manual check that forces a registry rescan', async () => {
@@ -285,10 +283,10 @@ describe('PluginDetailPage', () => {
)
})
- it('does not render the manual check button on the web platform', () => {
+ it('renders the manual community check button on the web platform', () => {
renderAt('/plugins/test.demo', 'web')
- expect(screen.queryByTestId('plugin-detail-refresh-btn')).toBeNull()
+ expect(screen.getByTestId('plugin-detail-refresh-btn')).toBeInTheDocument()
})
it('renders the update button once the scan populates the updates map', () => {
diff --git a/src/renderer/routes/plugins/plugin-detail-page.tsx b/src/renderer/routes/plugins/plugin-detail-page.tsx
index c7ca33e9..f8cc4bc0 100644
--- a/src/renderer/routes/plugins/plugin-detail-page.tsx
+++ b/src/renderer/routes/plugins/plugin-detail-page.tsx
@@ -53,9 +53,9 @@ export function PluginDetailPage() {
// Deeplinks (motrix://plugins/<id>) mount this sibling route directly, so
// PluginsPage — the only other caller — never runs. Trigger the update scan
// here too so the "Update to vX" affordance appears on cold-start deeplinks.
- // Cache-backed and Electron-gated, mirroring PluginsPage. refresh() backs
- // the manual check icon in the tab-strip row (force refetch + re-pull).
- const { refreshing, refresh } = useRegistryUpdates(isElectron)
+ // Cache-backed on both shells, mirroring PluginsPage. Server scans only the
+ // community channel; builtin overlay updates remain Electron-only.
+ const { refreshing, refresh } = useRegistryUpdates(true)
usePlugins()
const pluginsLoaded = usePluginsStore((s) => s.loaded)
const listEntry = usePluginsStore((s) => s.list.find((p) => p.id === id))
@@ -206,7 +206,7 @@ export function PluginDetailPage() {
</TooltipContent>
</Tooltip>
</TooltipProvider>
- {isElectron && (
+ {(isElectron || update?.channel !== 'builtin') && (
<Tooltip>
<TooltipTrigger
render={
diff --git a/src/renderer/routes/plugins/plugins-page.test.tsx b/src/renderer/routes/plugins/plugins-page.test.tsx
index 63fd6a01..a96aae3f 100644
--- a/src/renderer/routes/plugins/plugins-page.test.tsx
+++ b/src/renderer/routes/plugins/plugins-page.test.tsx
@@ -257,9 +257,9 @@ describe('PluginsPage', () => {
expect(screen.getByTestId('registry-refresh-btn')).toBeInTheDocument()
})
- it('hides the registry refresh button on web', () => {
+ it('shows the community registry refresh button on web', () => {
renderPage('web')
- expect(screen.queryByTestId('registry-refresh-btn')).toBeNull()
+ expect(screen.getByTestId('registry-refresh-btn')).toBeInTheDocument()
})
it('marks an installed plugin that has a registry update', () => {
diff --git a/src/renderer/routes/plugins/plugins-page.tsx b/src/renderer/routes/plugins/plugins-page.tsx
index fec9d2fb..952ad4a5 100644
--- a/src/renderer/routes/plugins/plugins-page.tsx
+++ b/src/renderer/routes/plugins/plugins-page.tsx
@@ -8,7 +8,6 @@ import {
TooltipContent,
TooltipTrigger,
} from '@renderer/components/ui/tooltip'
-import { usePlatformServices } from '@renderer/platform/services'
import { ListFilter, Plus, RefreshCw, Workflow } from 'lucide-react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -28,9 +27,7 @@ export function PluginsPage() {
const pluginsLoaded = usePluginsStore((state) => state.loaded)
const [installOpen, setInstallOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
- const services = usePlatformServices()
- const isElectron = services.kind === 'electron'
- const { refreshing, refresh } = useRegistryUpdates(isElectron)
+ const { refreshing, refresh } = useRegistryUpdates(true)
const refreshLabel = t('plugins.registry.refresh')
const filtered = useMemo(() => {
@@ -114,28 +111,26 @@ export function PluginsPage() {
<TooltipContent side="bottom">{diagnosticsLabel}</TooltipContent>
</Tooltip>
- {isElectron && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="outline"
- size="icon"
- onClick={() => void refresh()}
- disabled={refreshing}
- aria-label={refreshLabel}
- data-testid="registry-refresh-btn"
- >
- <RefreshCw
- aria-hidden
- className={refreshing ? 'animate-spin' : undefined}
- />
- </Button>
- }
- />
- <TooltipContent side="bottom">{refreshLabel}</TooltipContent>
- </Tooltip>
- )}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => void refresh()}
+ disabled={refreshing}
+ aria-label={refreshLabel}
+ data-testid="registry-refresh-btn"
+ >
+ <RefreshCw
+ aria-hidden
+ className={refreshing ? 'animate-spin' : undefined}
+ />
+ </Button>
+ }
+ />
+ <TooltipContent side="bottom">{refreshLabel}</TooltipContent>
+ </Tooltip>
</div>
<div
diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsx
index 10e01bc8..44429e30 100644
--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx
@@ -91,6 +91,23 @@ describe('<GeneralDialog>', () => {
})
})
+ it('hides host startup and quit controls in the web client', async () => {
+ transportMock.platform = 'web'
+ render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)
+
+ await waitFor(() =>
+ expect(
+ screen.getByDisplayValue('/Users/me/Downloads')
+ ).toBeInTheDocument()
+ )
+ expect(
+ screen.queryByRole('switch', { name: /launch at startup/i })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('switch', { name: /confirm before quitting/i })
+ ).not.toBeInTheDocument()
+ })
+
it('saves notifyOnError when toggled', async () => {
render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)
diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsx
index b1e02253..ff7fac7c 100644
--- a/src/renderer/routes/settings/cards/general-dialog.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.tsx
@@ -57,6 +57,7 @@ export function GeneralDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
+ const isWeb = transport.platform === 'web'
const form = useForm<GeneralFields>({ defaultValues: DEFAULTS })
// biome-ignore lint/correctness/useExhaustiveDependencies: form is stable across renders; this is a mount-only fetch
@@ -111,28 +112,30 @@ export function GeneralDialog({
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
<Form {...form}>
<form className="space-y-4">
- <FormField
- control={form.control}
- name="launchAtStartup"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.launchAtStartup')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.launchAtStartupDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
+ {!isWeb && (
+ <FormField
+ control={form.control}
+ name="launchAtStartup"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.launchAtStartup')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.launchAtStartupDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ )}
<FormField
control={form.control}
@@ -221,28 +224,30 @@ export function GeneralDialog({
)}
/>
- <FormField
- control={form.control}
- name="warnBeforeQuit"
- render={({ field }) => (
- <FormItem className="flex items-start justify-between gap-4">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.warnBeforeQuit')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.warnBeforeQuitDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
+ {!isWeb && (
+ <FormField
+ control={form.control}
+ name="warnBeforeQuit"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.warnBeforeQuit')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.warnBeforeQuitDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ )}
</form>
</Form>
</div>
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx
index 93c2a2e4..e0e2ab72 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx
@@ -100,6 +100,7 @@ import { IntegrationDialog } from './integration-dialog'
describe('IntegrationDialog scaffold', () => {
beforeEach(() => {
+ transport.platform = 'darwin'
bridgeStatus.current = {
port: 16802,
degraded: false,
@@ -130,6 +131,25 @@ describe('IntegrationDialog scaffold', () => {
expect(screen.getByRole('heading', { name: /media tools/i })).toBeTruthy()
})
+ it('hides desktop protocol associations in the web client', async () => {
+ transport.platform = 'web'
+ render(
+ <IntegrationDialog
+ open={true}
+ onClose={() => {}}
+ labelKey="settings.cards.integration.title"
+ descKey="settings.cards.integration.desc"
+ />
+ )
+
+ expect(
+ screen.queryByRole('heading', { name: /system protocols/i })
+ ).not.toBeInTheDocument()
+ expect(
+ await screen.findByRole('heading', { name: /browser extensions/i })
+ ).toBeInTheDocument()
+ })
+
it('places the local CLI card before paired remote tools', async () => {
render(
<IntegrationDialog
diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
index 95a380e0..51ecfe34 100644
--- a/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.tsx
@@ -61,6 +61,7 @@ export function IntegrationDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
+ const isWeb = transport.platform === 'web'
const [protocolRevision, setProtocolRevision] = useState(0)
const [saveError, setSaveError] = useState<string | null>(null)
const form = useForm<IntegrationFormValues>({
@@ -130,25 +131,31 @@ export function IntegrationDialog({
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
<FormProvider {...form}>
<div className="flex flex-col gap-6">
- <section
- aria-labelledby="integration-system"
- className="flex flex-col gap-3"
- >
- <h3
- id="integration-system"
- className="text-sm font-semibold text-foreground"
- >
- {t('settings.integration.system.title')}
- </h3>
- <SystemProtocolsSection refreshRevision={protocolRevision} />
- <AppImageIntegrationSection
- onIntegrationChange={() =>
- setProtocolRevision((revision) => revision + 1)
- }
- />
- </section>
+ {!isWeb && (
+ <>
+ <section
+ aria-labelledby="integration-system"
+ className="flex flex-col gap-3"
+ >
+ <h3
+ id="integration-system"
+ className="text-sm font-semibold text-foreground"
+ >
+ {t('settings.integration.system.title')}
+ </h3>
+ <SystemProtocolsSection
+ refreshRevision={protocolRevision}
+ />
+ <AppImageIntegrationSection
+ onIntegrationChange={() =>
+ setProtocolRevision((revision) => revision + 1)
+ }
+ />
+ </section>
- <Separator />
+ <Separator />
+ </>
+ )}
<section
aria-labelledby="integration-browser"
diff --git a/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx b/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
index 8ef937c2..5a5fb07e 100644
--- a/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
+++ b/src/renderer/routes/settings/cards/integration/system-protocols-section.test.tsx
@@ -214,7 +214,7 @@ describe('<SystemProtocolsSection>', () => {
renderSection('linux')
expect(await screen.findByText('Package: Flatpak')).toBeVisible()
- expect(screen.getAllByText("Couldn't verify")).toHaveLength(2)
+ expect(screen.getAllByText('Couldn’t verify')).toHaveLength(2)
fireEvent.click(screen.getByRole('button', { name: 'View setup steps' }))
expect(
await screen.findByText(/Setup instructions were opened instead/u)
diff --git a/src/renderer/routes/settings/cards/network-dialog.test.tsx b/src/renderer/routes/settings/cards/network-dialog.test.tsx
index 23891649..1c92d4b5 100644
--- a/src/renderer/routes/settings/cards/network-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/network-dialog.test.tsx
@@ -178,6 +178,54 @@ describe('<NetworkDialog>', () => {
})
})
+ it('clears stale bypass and authentication fields on system import', async () => {
+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
+ if (channel === Queries.GetSettings) {
+ return {
+ ...FIXTURE,
+ proxy: {
+ ...FIXTURE.proxy,
+ enabled: true,
+ user: 'stale-user',
+ password: 'stale-password',
+ bypass: ['stale.internal'],
+ },
+ }
+ }
+ if (channel === Queries.GetSystemProxy) {
+ return { protocol: 'http', host: '10.0.0.2', port: 8080 }
+ }
+ return { saved: true, requiresRestart: false, changedRestartKeys: [] }
+ })
+ render(
+ <NetworkDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.network.title"
+ descKey="settings.cards.network.desc"
+ />
+ )
+
+ const user = userEvent.setup()
+ await user.click(
+ await screen.findByRole('button', { name: /import from system/i })
+ )
+ await user.click(screen.getByRole('button', { name: /save/i }))
+
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.UpdateSettings,
+ expect.objectContaining({
+ proxy: expect.objectContaining({
+ user: '',
+ password: '',
+ bypass: [],
+ }),
+ })
+ )
+ )
+ })
+
it('keeps download proxying enabled when importing socks5', async () => {
vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
if (channel === Queries.GetSettings) {
diff --git a/src/renderer/routes/settings/cards/proxy-section.tsx b/src/renderer/routes/settings/cards/proxy-section.tsx
index 6d1d5e54..cd6a736d 100644
--- a/src/renderer/routes/settings/cards/proxy-section.tsx
+++ b/src/renderer/routes/settings/cards/proxy-section.tsx
@@ -27,18 +27,13 @@ import { toast } from '@renderer/components/ui/toast'
import { transport } from '@renderer/lib/transport'
import { Queries } from '@shared/protocol/queries'
import type { ProxySettings } from '@shared/types/settings'
+import type { SystemProxyResult } from '@shared/types/system-proxy'
import { ChevronDown, Eye, EyeOff } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import type { UseFormReturn } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import type { NetworkFields } from './network-dialog'
-interface SystemProxyResult {
- protocol: 'http' | 'https' | 'socks5'
- host: string
- port: number
-}
-
export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {
const { t } = useTranslation()
@@ -89,6 +84,15 @@ export function ProxySection({ form }: { form: UseFormReturn<NetworkFields> }) {
updateProtocol(detected.protocol)
form.setValue('proxy.host', detected.host, { shouldDirty: true })
form.setValue('proxy.port', detected.port, { shouldDirty: true })
+ form.setValue('proxy.user', detected.user ?? '', { shouldDirty: true })
+ form.setValue('proxy.password', detected.password ?? '', {
+ shouldDirty: true,
+ })
+ form.setValue('proxy.bypass', detected.bypass ?? [], { shouldDirty: true })
+ const hasAuth = Boolean(detected.user || detected.password)
+ setShowAuth(hasAuth)
+ seededRef.current = hasAuth
+ if (!hasAuth) setRevealPassword(false)
// Importing implies the user wants to USE this proxy; flip the master
// toggle on so the rest of the form reveals.
if (!form.getValues('proxy.enabled')) {
diff --git a/src/server/bridge/bootstrap.test.ts b/src/server/bridge/bootstrap.test.ts
index f8c4761d..674c1d9d 100644
--- a/src/server/bridge/bootstrap.test.ts
+++ b/src/server/bridge/bootstrap.test.ts
@@ -9,7 +9,10 @@ import {
runPake,
startPair,
} from '@core/bridge/__tests__/mbp1-client'
-import { BRIDGE_DATA_DIR_LOCK_FILE_NAME } from '@core/bridge/bridge-data-dir-lock'
+import {
+ acquireBridgeDataDirLock,
+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,
+} from '@core/bridge/bridge-data-dir-lock'
import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'
import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'
import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'
@@ -19,7 +22,7 @@ import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'
import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'
import { EventBus } from '@core/events/event-bus'
import { Notifications } from '@motrix/mdxp'
-import { BridgeEvents } from '@shared/protocol/bridge'
+import { BridgeEvents, BridgeQueries } from '@shared/protocol/bridge'
import { Events } from '@shared/protocol/events'
import { EngineState } from '@shared/types/engine'
import { TaskStatus } from '@shared/types/task'
@@ -260,6 +263,54 @@ describe('bootstrapBridgeForServer', () => {
expect(res.status).toBe(401)
})
+ it('reports the persisted fixed-port policy separately from the bound port', async () => {
+ runtime = await bootstrapBridgeForServer({
+ userDataDir,
+ host: '127.0.0.1',
+ port: 0,
+ fixedPort: 'auto',
+ motrixVersion: '2.0',
+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
+ readHandlerDeps: readDeps(),
+ writeHandlerDeps: writeDeps(),
+ })
+
+ await expect(
+ runtime.bridgeQueryHandlers[BridgeQueries.GetStatus]?.()
+ ).resolves.toEqual(
+ expect.objectContaining({
+ port: runtime.port,
+ fixedPort: 'auto',
+ })
+ )
+ })
+
+ it('borrows a process-lifetime data-directory lock across runtime shutdown', async () => {
+ const bridgeDir = join(userDataDir, 'bridge')
+ await mkdir(bridgeDir, { recursive: true })
+ const processLock = await acquireBridgeDataDirLock(bridgeDir)
+ runtime = await bootstrapBridgeForServer({
+ userDataDir,
+ host: '127.0.0.1',
+ port: 0,
+ motrixVersion: '2.0',
+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
+ readHandlerDeps: readDeps(),
+ writeHandlerDeps: writeDeps(),
+ bridgeDataDirLock: processLock,
+ })
+
+ await runtime.shutdown()
+ runtime = null
+ await expect(acquireBridgeDataDirLock(bridgeDir)).rejects.toThrow(
+ 'bridge data directory lock unavailable'
+ )
+
+ await processLock.release()
+ const reacquired = await acquireBridgeDataDirLock(bridgeDir)
+ await reacquired.release()
+ })
+
it('opens an explicit WS public route bundle with stable Server identity', async () => {
const remoteExtensionConfig = parseRemoteExtensionConfig({
MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',
diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.ts
index 07cdd388..d8dce5d2 100644
--- a/src/server/bridge/bootstrap.ts
+++ b/src/server/bridge/bootstrap.ts
@@ -3,6 +3,7 @@ import { mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import {
acquireBridgeDataDirLock,
+ type BridgeDataDirLockHandle,
type BridgeDataDirLockRecoveryAuthority,
} from '@core/bridge/bridge-data-dir-lock'
import { BridgeEventBus } from '@core/bridge/bridge-event-bus'
@@ -18,6 +19,10 @@ import { FileRegistryStoreAdapter } from '@core/bridge/registry-store-adapter'
import { resolveCliPair } from '@core/bridge/resolve-cli-pair'
import { toPairedClientInfo } from '@core/bridge/to-paired-client-info'
import { TrustedExtensionRegistry } from '@core/bridge/trusted-extension-registry'
+import {
+ type ResolveOptions,
+ UrlResolutionService,
+} from '@core/bridge/url-resolution-service'
import {
type MethodHandlers,
WebSocketBridgeServer,
@@ -36,6 +41,7 @@ import {
type ResolvePairResult,
} from '@shared/protocol/bridge'
import type { Handler } from '@shared/protocol/handler-types'
+import { CancellationTokenSource } from 'vscode-jsonrpc'
import {
isIssuedRemoteExtensionConfig,
type RemoteExtensionConfig,
@@ -73,6 +79,9 @@ export interface ServerBridgeOptions {
userDataDir: string
host: string
port: number
+ /** Persisted bridge port policy. Isolated tests may omit it and fall back to
+ * the requested listener port. */
+ fixedPort?: BridgeStatusInfo['fixedPort']
motrixVersion: string
/** The process-lifetime core EventBus (for the SSE firehose + re-emitting
* bridge approval events so the web broadcaster forwards them). */
@@ -96,8 +105,13 @@ export interface ServerBridgeOptions {
/** Production supplies an authority derived from the already-bound main
* control-plane port. Omitted only by isolated tests with a fresh data dir. */
bridgeDataDirLockRecoveryAuthority?: BridgeDataDirLockRecoveryAuthority
+ /** Process-lifetime lock supplied by the Server composition root. When
+ * present, this runtime borrows it and never releases it on restart. */
+ bridgeDataDirLock?: BridgeDataDirLockHandle
/** Parser-issued all-or-nothing remote Extension configuration. */
remoteExtensionConfig?: RemoteExtensionConfig
+ /** Preloaded process-lifetime registry supplied by ServerBridgeManager. */
+ trustedExtensionRegistry?: TrustedExtensionRegistry
/** Required when remote Extension support is enabled. Absence keeps the
* public MBP1 surface from starting instead of exposing a connect-only shell. */
createExtensionReceiver?: (context: {
@@ -124,10 +138,14 @@ export async function bootstrapBridgeForServer(
const dataDir = join(opts.userDataDir, 'bridge')
await mkdir(dataDir, { recursive: true })
const ownership = new BridgeOwnership()
- const dataDirLock = await acquireBridgeDataDirLock(dataDir, {
- recoverExisting: opts.bridgeDataDirLockRecoveryAuthority,
- })
- ownership.own('bridge-data-dir-lock', () => dataDirLock.release())
+ const dataDirLock =
+ opts.bridgeDataDirLock ??
+ (await acquireBridgeDataDirLock(dataDir, {
+ recoverExisting: opts.bridgeDataDirLockRecoveryAuthority,
+ }))
+ if (opts.bridgeDataDirLock === undefined) {
+ ownership.own('bridge-data-dir-lock', () => dataDirLock.release())
+ }
try {
const pairing = new PairingService(
new FilePairingStore(join(dataDir, 'pairing.json'))
@@ -193,13 +211,15 @@ export async function bootstrapBridgeForServer(
await extensionReceiver.restoreInflight()
}
let boundPort = opts.port
- const registry = new TrustedExtensionRegistry(
- new FileRegistryStoreAdapter(join(dataDir, 'registry.json')),
- extensionMbp1 === null
- ? []
- : [...extensionMbp1.identityResolver.officialEntries]
- )
- await registry.load()
+ const registry =
+ opts.trustedExtensionRegistry ??
+ new TrustedExtensionRegistry(
+ new FileRegistryStoreAdapter(join(dataDir, 'registry.json')),
+ extensionMbp1 === null
+ ? []
+ : [...extensionMbp1.identityResolver.officialEntries]
+ )
+ if (opts.trustedExtensionRegistry === undefined) await registry.load()
// Machine-owner Bearer token for the unary/SSE transports (same model as the
// desktop). On a NAS it lives in endpoint.json (readable only on the host); a
@@ -291,6 +311,17 @@ export async function bootstrapBridgeForServer(
await extensionMbp1.recoverBeforeListen()
}
+ const urlResolution = new UrlResolutionService(() =>
+ Array.from(server.iterSessions())
+ .filter((session) => session.conn.isReady())
+ .map((session) => session.conn)
+ )
+ const inFlightResolves = new Map<string, CancellationTokenSource>()
+ ownership.own('url-resolutions', () => {
+ for (const cts of inFlightResolves.values()) cts.cancel()
+ inFlightResolves.clear()
+ })
+
// bridge:* RPC handlers the web renderer reaches via /rpc/{command,query}.
const bridgeCommandHandlers: Record<string, Handler> = {
[BridgeCommands.ResolvePair]: async (
@@ -321,6 +352,24 @@ export async function bootstrapBridgeForServer(
await pairing.revoke(params.identity, 'user-revoked')
bridgeBus.emitRevoked({ identity: params.identity })
},
+ [BridgeCommands.AddTrusted]: async (params: {
+ id: string
+ browser: 'chromium' | 'firefox'
+ label?: string
+ }) => {
+ await registry.add(
+ params.id,
+ params.browser,
+ 'user-added',
+ params.label
+ )
+ },
+ [BridgeCommands.RemoveTrusted]: async (params: {
+ id: string
+ browser: 'chromium' | 'firefox'
+ }) => {
+ await registry.remove(params.id, params.browser)
+ },
}
const bridgeQueryHandlers: Record<string, Handler> = {
[BridgeQueries.ListPaired]: async () => [
@@ -333,6 +382,23 @@ export async function bootstrapBridgeForServer(
...(extensionMbp1?.prompts.listPending() ?? []),
],
[BridgeQueries.ListTrusted]: async () => registry.list(),
+ [BridgeQueries.ProbeUrl]: async (url: string) => urlResolution.probe(url),
+ [BridgeQueries.ResolveUrl]: async (
+ requestId: string,
+ url: string,
+ options: ResolveOptions = {}
+ ) => {
+ const cts = new CancellationTokenSource()
+ inFlightResolves.set(requestId, cts)
+ try {
+ return await urlResolution.resolve(url, options, cts.token)
+ } finally {
+ inFlightResolves.delete(requestId)
+ }
+ },
+ [BridgeQueries.CancelResolveUrl]: async (requestId: string) => {
+ inFlightResolves.get(requestId)?.cancel()
+ },
[BridgeQueries.GetStatus]: async (): Promise<BridgeStatusInfo> => ({
port: boundPort,
degraded: false,
@@ -341,7 +407,7 @@ export async function bootstrapBridgeForServer(
extensionMbp1.extensionPairings.getHealth() === 'ready'
? 'ready'
: 'degraded',
- fixedPort: opts.port,
+ fixedPort: opts.fixedPort ?? opts.port,
instanceId: extensionMbp1?.instanceId ?? 'extension-mbp1-disabled',
}),
}
diff --git a/src/server/bridge/manager.test.ts b/src/server/bridge/manager.test.ts
new file mode 100644
index 00000000..01ea08ef
--- /dev/null
+++ b/src/server/bridge/manager.test.ts
@@ -0,0 +1,145 @@
+import { TrustedExtensionRegistry } from '@core/bridge/trusted-extension-registry'
+import { BridgeCommands, BridgeQueries } from '@shared/protocol/bridge'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ServiceUnavailableError } from '../http/service-unavailable-error'
+import type { ServerBridgeRuntime } from './bootstrap'
+import { ServerBridgeManager } from './manager'
+
+function makeRegistry() {
+ let content: string | null = null
+ return new TrustedExtensionRegistry(
+ {
+ read: vi.fn(async () => content),
+ write: vi.fn(async (next: string) => {
+ content = next
+ }),
+ },
+ []
+ )
+}
+
+function makeRuntime(): ServerBridgeRuntime {
+ return {
+ server: {} as ServerBridgeRuntime['server'],
+ port: 16801,
+ localToken: 'token',
+ bridgeCommandHandlers: {
+ [BridgeCommands.ResolvePair]: vi.fn(async () => ({ ok: true })),
+ [BridgeCommands.RevokePair]: vi.fn(async () => undefined),
+ },
+ bridgeQueryHandlers: {
+ [BridgeQueries.ListPaired]: vi.fn(async () => ['paired']),
+ [BridgeQueries.GetStatus]: vi.fn(async () => ({ port: 16801 })),
+ },
+ shutdown: vi.fn(async () => undefined),
+ }
+}
+
+describe('ServerBridgeManager', () => {
+ let registry: TrustedExtensionRegistry
+
+ beforeEach(async () => {
+ registry = makeRegistry()
+ await registry.load()
+ })
+
+ it('keeps trusted-extension management available while disabled', async () => {
+ const manager = new ServerBridgeManager(registry, vi.fn())
+
+ await manager.bridgeCommandHandlers[BridgeCommands.AddTrusted]?.({
+ id: 'abcdefghijklmnopabcdefghijklmnop',
+ browser: 'chromium',
+ label: 'Local test',
+ })
+
+ await expect(
+ manager.bridgeQueryHandlers[BridgeQueries.ListTrusted]?.()
+ ).resolves.toEqual([
+ expect.objectContaining({
+ id: 'abcdefghijklmnopabcdefghijklmnop',
+ browser: 'chromium',
+ source: 'user-added',
+ }),
+ ])
+ })
+
+ it('keeps registry RPC unavailable until process ownership is established', async () => {
+ let ready = false
+ const manager = new ServerBridgeManager(registry, vi.fn(), () => ready)
+
+ await expect(
+ manager.bridgeQueryHandlers[BridgeQueries.ListTrusted]?.()
+ ).rejects.toBeInstanceOf(ServiceUnavailableError)
+
+ ready = true
+ await expect(
+ manager.bridgeQueryHandlers[BridgeQueries.ListTrusted]?.()
+ ).resolves.toEqual([])
+ })
+
+ it('returns a typed unavailable failure instead of dropping channels', async () => {
+ const manager = new ServerBridgeManager(registry, vi.fn())
+
+ await expect(
+ manager.bridgeQueryHandlers[BridgeQueries.ListPaired]?.()
+ ).rejects.toBeInstanceOf(ServiceUnavailableError)
+ expect(Object.keys(manager.bridgeCommandHandlers).sort()).toEqual(
+ Object.values(BridgeCommands).sort()
+ )
+ expect(Object.keys(manager.bridgeQueryHandlers).sort()).toEqual(
+ Object.values(BridgeQueries).sort()
+ )
+ })
+
+ it('waits for an enabled bridge that is still starting', async () => {
+ const runtime = makeRuntime()
+ let release!: (runtime: ServerBridgeRuntime) => void
+ const starting = new Promise<ServerBridgeRuntime>((resolve) => {
+ release = resolve
+ })
+ const manager = new ServerBridgeManager(registry, () => starting)
+
+ const start = manager.start()
+ const query = manager.bridgeQueryHandlers[BridgeQueries.ListPaired]?.()
+ release(runtime)
+
+ await expect(query).resolves.toEqual(['paired'])
+ await start
+ })
+
+ it('retries a failed enabled start on restart', async () => {
+ const runtime = makeRuntime()
+ const factory = vi
+ .fn<() => Promise<ServerBridgeRuntime>>()
+ .mockRejectedValueOnce(new Error('port occupied'))
+ .mockResolvedValueOnce(runtime)
+ const manager = new ServerBridgeManager(registry, factory)
+
+ await expect(manager.start()).rejects.toThrow('port occupied')
+ await manager.restart()
+
+ expect(manager.current).toBe(runtime)
+ expect(factory).toHaveBeenCalledTimes(2)
+ })
+
+ it('serializes disable behind an in-flight start', async () => {
+ const runtime = makeRuntime()
+ let release!: (runtime: ServerBridgeRuntime) => void
+ const manager = new ServerBridgeManager(
+ registry,
+ () =>
+ new Promise<ServerBridgeRuntime>((resolve) => {
+ release = resolve
+ })
+ )
+
+ const start = manager.start()
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'))
+ const stop = manager.stop()
+ release(runtime)
+ await Promise.all([start, stop])
+
+ expect(runtime.shutdown).toHaveBeenCalledOnce()
+ expect(manager.current).toBeNull()
+ })
+})
diff --git a/src/server/bridge/manager.ts b/src/server/bridge/manager.ts
new file mode 100644
index 00000000..6a8f687b
--- /dev/null
+++ b/src/server/bridge/manager.ts
@@ -0,0 +1,180 @@
+import type { TrustedExtensionRegistry } from '@core/bridge/trusted-extension-registry'
+import {
+ BridgeCommands,
+ BridgeQueries,
+ type Browser,
+} from '@shared/protocol/bridge'
+import type { Handler } from '@shared/protocol/handler-types'
+import { ServiceUnavailableError } from '../http/service-unavailable-error'
+import type { ServerBridgeRuntime } from './bootstrap'
+
+export type ServerBridgeRuntimeFactory = () => Promise<ServerBridgeRuntime>
+
+/**
+ * Owns the optional Server bridge runtime while keeping the renderer-facing
+ * bridge RPC surface stable for the lifetime of the HTTP control plane.
+ * Trusted-extension management is deliberately independent of the MDXP
+ * listener: an occupied port must not make the durable registry disappear.
+ */
+export class ServerBridgeManager {
+ private runtime: ServerBridgeRuntime | null = null
+ private transition: Promise<void> = Promise.resolve()
+ private registryTransition: Promise<void> = Promise.resolve()
+ private desiredEnabled = false
+ private registryAccepting = true
+
+ readonly bridgeCommandHandlers: Record<string, Handler>
+ readonly bridgeQueryHandlers: Record<string, Handler>
+
+ constructor(
+ private readonly registry: TrustedExtensionRegistry,
+ private readonly factory: ServerBridgeRuntimeFactory,
+ private readonly isRegistryReady: () => boolean = () => true
+ ) {
+ this.bridgeCommandHandlers = {
+ [BridgeCommands.AddTrusted]: async (params: {
+ id: string
+ browser: Browser
+ label?: string
+ }) => {
+ await this.enqueueRegistry(() =>
+ this.registry.add(
+ params.id,
+ params.browser,
+ 'user-added',
+ params.label
+ )
+ )
+ },
+ [BridgeCommands.RemoveTrusted]: async (params: {
+ id: string
+ browser: Browser
+ }) => {
+ await this.enqueueRegistry(() =>
+ this.registry.remove(params.id, params.browser)
+ )
+ },
+ [BridgeCommands.ResolvePair]: (...args: unknown[]) =>
+ this.invokeCommand(BridgeCommands.ResolvePair, args),
+ [BridgeCommands.RevokePair]: (...args: unknown[]) =>
+ this.invokeCommand(BridgeCommands.RevokePair, args),
+ }
+ this.bridgeQueryHandlers = {
+ [BridgeQueries.ListTrusted]: async () =>
+ this.enqueueRegistry(async () => this.registry.list()),
+ [BridgeQueries.ListPaired]: (...args: unknown[]) =>
+ this.invokeQuery(BridgeQueries.ListPaired, args),
+ [BridgeQueries.ProbeUrl]: (...args: unknown[]) =>
+ this.invokeQuery(BridgeQueries.ProbeUrl, args),
+ [BridgeQueries.ResolveUrl]: (...args: unknown[]) =>
+ this.invokeQuery(BridgeQueries.ResolveUrl, args),
+ [BridgeQueries.CancelResolveUrl]: (...args: unknown[]) =>
+ this.invokeQuery(BridgeQueries.CancelResolveUrl, args),
+ [BridgeQueries.ListPendingPairRequests]: (...args: unknown[]) =>
+ this.invokeQuery(BridgeQueries.ListPendingPairRequests, args),
+ [BridgeQueries.GetStatus]: (...args: unknown[]) =>
+ this.invokeQuery(BridgeQueries.GetStatus, args),
+ }
+ }
+
+ get current(): ServerBridgeRuntime | null {
+ return this.runtime
+ }
+
+ start(): Promise<void> {
+ this.desiredEnabled = true
+ return this.enqueue(() => this.startCurrent())
+ }
+
+ stop(): Promise<void> {
+ this.desiredEnabled = false
+ return this.enqueue(() => this.stopCurrent())
+ }
+
+ setEnabled(enabled: boolean): Promise<void> {
+ return enabled ? this.start() : this.stop()
+ }
+
+ restart(): Promise<void> {
+ return this.enqueue(async () => {
+ if (!this.desiredEnabled) return
+ await this.stopCurrent()
+ await this.startCurrent()
+ })
+ }
+
+ async shutdown(): Promise<void> {
+ this.desiredEnabled = false
+ this.registryAccepting = false
+ await Promise.all([
+ this.enqueue(() => this.stopCurrent()),
+ this.registryTransition,
+ ])
+ }
+
+ private enqueue(operation: () => Promise<void>): Promise<void> {
+ const result = this.transition.then(operation, operation)
+ this.transition = result.then(
+ () => undefined,
+ () => undefined
+ )
+ return result
+ }
+
+ private enqueueRegistry<T>(operation: () => Promise<T>): Promise<T> {
+ if (!this.registryAccepting || !this.isRegistryReady()) {
+ throw new ServiceUnavailableError(
+ 'Trusted extension registry unavailable'
+ )
+ }
+ const result = this.registryTransition.then(operation, operation)
+ this.registryTransition = result.then(
+ () => undefined,
+ () => undefined
+ )
+ return result
+ }
+
+ private async startCurrent(): Promise<void> {
+ if (this.runtime) return
+ const runtime = await this.factory()
+ if (!this.desiredEnabled) {
+ await runtime.shutdown()
+ return
+ }
+ this.runtime = runtime
+ }
+
+ private async stopCurrent(): Promise<void> {
+ const runtime = this.runtime
+ this.runtime = null
+ await runtime?.shutdown()
+ }
+
+ private async availableRuntime(): Promise<ServerBridgeRuntime> {
+ if (this.runtime) return this.runtime
+ if (this.desiredEnabled) await this.transition
+ if (this.runtime) return this.runtime
+ throw new ServiceUnavailableError('Bridge is unavailable')
+ }
+
+ private async invokeCommand(
+ channel: string,
+ args: unknown[]
+ ): Promise<unknown> {
+ const runtime = await this.availableRuntime()
+ const handler = runtime.bridgeCommandHandlers[channel]
+ if (!handler) throw new ServiceUnavailableError('Bridge is unavailable')
+ return handler(...args)
+ }
+
+ private async invokeQuery(
+ channel: string,
+ args: unknown[]
+ ): Promise<unknown> {
+ const runtime = await this.availableRuntime()
+ const handler = runtime.bridgeQueryHandlers[channel]
+ if (!handler) throw new ServiceUnavailableError('Bridge is unavailable')
+ return handler(...args)
+ }
+}
diff --git a/src/server/http/app.test.ts b/src/server/http/app.test.ts
index 52e84784..a14575e9 100644
--- a/src/server/http/app.test.ts
+++ b/src/server/http/app.test.ts
@@ -1,5 +1,7 @@
+import { Commands } from '@shared/protocol/commands'
import { describe, expect, it } from 'vitest'
-import { createApp } from './app'
+import { createApp, RPC_BODY_LIMIT_BYTES } from './app'
+import { ServiceUnavailableError } from './service-unavailable-error'
describe('createApp', () => {
it('responds to GET /healthz', async () => {
@@ -27,4 +29,46 @@ describe('createApp', () => {
})
await app.close()
})
+
+ it('maps a registered but unavailable service handler to 503', async () => {
+ const app = await createApp({
+ bridgeQueryHandlers: {
+ 'bridge:getStatus': async () => {
+ throw new ServiceUnavailableError('Bridge is unavailable')
+ },
+ },
+ })
+ const res = await app.inject({
+ method: 'POST',
+ url: '/rpc/query/bridge:getStatus',
+ payload: { args: [] },
+ })
+
+ expect(res.statusCode).toBe(503)
+ expect(res.json()).toEqual({ error: 'Bridge is unavailable' })
+ await app.close()
+ })
+
+ it('accepts RPC bodies above Fastify default and rejects bodies above 2 MiB', async () => {
+ const app = await createApp({
+ commandHandlers: {
+ [Commands.CreateTask]: async (value: string) => value.length,
+ },
+ })
+ const accepted = await app.inject({
+ method: 'POST',
+ url: `/rpc/command/${Commands.CreateTask}`,
+ payload: { args: ['x'.repeat(1024 * 1024)] },
+ })
+ const rejected = await app.inject({
+ method: 'POST',
+ url: `/rpc/command/${Commands.CreateTask}`,
+ payload: { args: ['x'.repeat(RPC_BODY_LIMIT_BYTES)] },
+ })
+
+ expect(accepted.statusCode).toBe(200)
+ expect(accepted.json()).toBe(1024 * 1024)
+ expect(rejected.statusCode).toBe(413)
+ await app.close()
+ })
})
diff --git a/src/server/http/app.ts b/src/server/http/app.ts
index d96cf938..6f05a4fb 100644
--- a/src/server/http/app.ts
+++ b/src/server/http/app.ts
@@ -1,4 +1,5 @@
import type { EventBus } from '@core/events/event-bus'
+import type { CapabilityHost } from '@core/plugin/capabilities/interface'
import fastifyStatic from '@fastify/static'
import websocket from '@fastify/websocket'
import {
@@ -6,6 +7,7 @@ import {
makeProtocolFailure,
makeProtocolSuccess,
} from '@shared/protocol/errors'
+import { Events } from '@shared/protocol/events'
import type {
CommandHandlerMap,
Handler,
@@ -16,6 +18,9 @@ import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspect
import Fastify, { type FastifyInstance } from 'fastify'
import { bindEventBroadcaster } from './events'
import { type OperatorAuthOptions, registerOperatorAuth } from './operator-auth'
+import { ServiceUnavailableError } from './service-unavailable-error'
+
+export const RPC_BODY_LIMIT_BYTES = 2 * 1024 * 1024
export interface AppOptions {
commandHandlers?: CommandHandlerMap
@@ -35,6 +40,7 @@ export interface AppOptions {
bridgeCommandHandlers?: Record<string, Handler>
bridgeQueryHandlers?: Record<string, Handler>
eventBus?: EventBus
+ pluginLogSource?: Pick<CapabilityHost, 'subscribeLog'>
rendererDir?: string
healthCheck?: () => { ok: boolean } | Promise<{ ok: boolean }>
}
@@ -42,7 +48,10 @@ export interface AppOptions {
export async function createApp(
opts: AppOptions = {}
): Promise<FastifyInstance> {
- const app = Fastify({ logger: false })
+ const app = Fastify({
+ logger: false,
+ bodyLimit: RPC_BODY_LIMIT_BYTES,
+ })
// Register the deny-by-default operator gate FIRST so its onRequest hook runs
// before every route (including /api/* added by the caller post-createApp and
// the /rpc/events WS upgrade).
@@ -68,7 +77,9 @@ export async function createApp(
return await handler(...(req.body?.args ?? []))
} catch (err) {
req.log.error({ err }, 'command handler failed')
- return reply.code(500).send({ error: (err as Error).message })
+ return reply
+ .code(err instanceof ServiceUnavailableError ? 503 : 500)
+ .send({ error: (err as Error).message })
}
}
)
@@ -99,13 +110,23 @@ export async function createApp(
if (usesSharedEnvelope) {
return reply.code(200).send(makeProtocolFailure(err))
}
- return reply.code(500).send({ error: (err as Error).message })
+ return reply
+ .code(err instanceof ServiceUnavailableError ? 503 : 500)
+ .send({ error: (err as Error).message })
}
}
)
if (opts.eventBus) {
const broadcaster = bindEventBroadcaster(opts.eventBus)
+ const unsubscribePluginLogs = opts.pluginLogSource?.subscribeLog(
+ (pluginId, entry) => {
+ broadcaster.broadcast(`${Events.PluginLog}:${pluginId}`, [entry])
+ }
+ )
+ if (unsubscribePluginLogs) {
+ app.addHook('onClose', async () => unsubscribePluginLogs())
+ }
await app.register(websocket)
app.get('/rpc/events', { websocket: true }, (socket) => {
broadcaster.register(socket)
diff --git a/src/server/http/events.ts b/src/server/http/events.ts
index 82e19eef..315c5bb6 100644
--- a/src/server/http/events.ts
+++ b/src/server/http/events.ts
@@ -9,6 +9,10 @@ export function bindEventBroadcaster(bus: EventBus) {
const sockets = new Set<SocketLike>()
subscribeForwardableEvents(bus, (channel, args) => {
+ broadcast(channel, args)
+ })
+
+ function broadcast(channel: string, args: unknown[]): void {
if (sockets.size === 0) return
const frame = JSON.stringify({ channel, args })
for (const s of sockets) {
@@ -18,9 +22,10 @@ export function bindEventBroadcaster(bus: EventBus) {
// Drop broken sockets silently; ws close handler unregisters.
}
}
- })
+ }
return {
+ broadcast,
register: (s: SocketLike) => sockets.add(s),
unregister: (s: SocketLike) => sockets.delete(s),
count: () => sockets.size,
diff --git a/src/server/http/service-unavailable-error.ts b/src/server/http/service-unavailable-error.ts
new file mode 100644
index 00000000..75918411
--- /dev/null
+++ b/src/server/http/service-unavailable-error.ts
@@ -0,0 +1,6 @@
+export class ServiceUnavailableError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options)
+ this.name = 'ServiceUnavailableError'
+ }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index b9564b40..1ef8ec15 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -3,6 +3,14 @@ import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { TaskActivityService, TaskActivityStore } from '@core/activity'
+import {
+ acquireBridgeDataDirLock,
+ type BridgeDataDirLockHandle,
+ type BridgeDataDirLockRecoveryAuthority,
+} from '@core/bridge/bridge-data-dir-lock'
+import { createExtensionIdentityResolver } from '@core/bridge/extension-identity-resolver'
+import { FileRegistryStoreAdapter } from '@core/bridge/registry-store-adapter'
+import { TrustedExtensionRegistry } from '@core/bridge/trusted-extension-registry'
import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'
import { Aria2SegmentClient } from '@core/download/aria2-segment-client'
import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'
@@ -104,7 +112,6 @@ import {
} from '@core/tracker'
import { resolveSupportedLocale } from '@shared/constants/locales'
import { Events } from '@shared/protocol/events'
-import type { Handler } from '@shared/protocol/handler-types'
import { REGISTRY_CACHE_FILENAME } from '@shared/schemas/registry'
import type { AppSettings } from '@shared/types/settings'
import type { DownloadTask } from '@shared/types/task'
@@ -115,6 +122,10 @@ import {
bootstrapBridgeForServer,
type ServerBridgeRuntime,
} from './bridge/bootstrap'
+import {
+ ServerBridgeManager,
+ type ServerBridgeRuntimeFactory,
+} from './bridge/manager'
import { diagnoseMdxpPublicUrl } from './bridge/public-url-diagnostic'
import { parseRemoteExtensionConfig } from './bridge/remote-extension-config'
import { logRemoteExtensionPairingReady } from './bridge/remote-extension-startup-log'
@@ -932,6 +943,32 @@ async function main() {
log: getLogger('dns-fallback'),
})
+ const bridgeDataDir = path.join(platform.userDataDir, 'bridge')
+ const bridgeIdentityResolver = createExtensionIdentityResolver({
+ environment: 'production',
+ developmentEntries: [],
+ })
+ const trustedExtensionRegistry = new TrustedExtensionRegistry(
+ new FileRegistryStoreAdapter(path.join(bridgeDataDir, 'registry.json')),
+ [...bridgeIdentityResolver.officialEntries]
+ )
+ let bridgeRegistryReady = false
+ let bridgeProcessDataDirLock: BridgeDataDirLockHandle | null = null
+ let bridgeDataDirLockRecoveryAuthority: BridgeDataDirLockRecoveryAuthority | null =
+ null
+ let bridgeOwnershipSetup: Promise<void> = Promise.resolve()
+ let bridgeRuntimeFactory: ServerBridgeRuntimeFactory | null = null
+ const bridgeManager = new ServerBridgeManager(
+ trustedExtensionRegistry,
+ async () => {
+ if (bridgeRuntimeFactory === null) {
+ throw new Error('Bridge runtime factory is not ready')
+ }
+ return bridgeRuntimeFactory()
+ },
+ () => bridgeRegistryReady
+ )
+
// ─── HTTP App ─────────────────────────────────────────────────
const commandHandlers = buildServerCommandHandlers({
supervisor,
@@ -944,6 +981,7 @@ async function main() {
rpcClient,
adapter,
trackerManager,
+ bridgeControl: bridgeManager,
aria2BinaryPath: platform.aria2BinaryPath,
finalNamePicker,
torrentMetaStore,
@@ -956,6 +994,8 @@ async function main() {
notificationCenter,
taskPersistence: sessionManager,
pluginRegistry,
+ registryClient,
+ hostVersion,
pluginStateStore,
pluginHost,
pluginInstaller,
@@ -995,8 +1035,10 @@ async function main() {
geoipManager: activeGeoipManager,
trackerManager,
engineAdapter: adapter,
+ motrixDatabase: db,
notificationCenter,
pluginRegistry,
+ capabilityHost: pluginCapHost,
pluginGrants,
registryClient,
pluginsDir,
@@ -1004,18 +1046,13 @@ async function main() {
userDataDir: platform.userDataDir,
speedLimitController,
downloadPathPolicy,
+ environment: process.env,
})
const rendererDir =
process.env.MOTRIX_RENDERER_DIR ??
path.resolve(serverDir, '..', 'renderer-web')
- // bridge:* RPC handlers are populated AFTER the (non-fatal, later) bridge
- // bootstrap; createApp captures these by reference, so a post-hoc Object.assign
- // makes the routes see them.
- const bridgeCommandHandlers: Record<string, Handler> = {}
- const bridgeQueryHandlers: Record<string, Handler> = {}
-
// Operator (control-plane) secret — provisioned INDEPENDENTLY of the
// (non-fatal) MDXP bridge so a bridge bootstrap failure can never lock the web
// UI behind an unrecoverable in-memory token (Spec 9 / F1). Distinct from the
@@ -1032,9 +1069,10 @@ async function main() {
const app = await createApp({
commandHandlers,
queryHandlers,
- bridgeCommandHandlers,
- bridgeQueryHandlers,
+ bridgeCommandHandlers: bridgeManager.bridgeCommandHandlers,
+ bridgeQueryHandlers: bridgeManager.bridgeQueryHandlers,
eventBus,
+ pluginLogSource: pluginCapHost,
rendererDir,
operatorAuth: {
operatorToken: operator.token,
@@ -1114,8 +1152,14 @@ async function main() {
// Startup itself is tracked below so a signal cannot race past cleanup and
// publish a resource after its corresponding shutdown step has already run.
- let bridgeRuntime: ServerBridgeRuntime | null = null
- shutdownActions.closeBridge = () => bridgeRuntime?.shutdown()
+ shutdownActions.closeBridge = async () => {
+ await bridgeOwnershipSetup
+ await bridgeManager.shutdown()
+ bridgeRegistryReady = false
+ const dataDirLock = bridgeProcessDataDirLock
+ bridgeProcessDataDirLock = null
+ await dataDirLock?.release()
+ }
const startServer = async (): Promise<void> => {
await activeGeoipManager.start()
@@ -1451,11 +1495,58 @@ async function main() {
const serverUrl = `http://localhost:${port}`
log.info({ port, url: serverUrl }, `server listening at ${serverUrl}`)
+ bridgeOwnershipSetup = (async () => {
+ bridgeDataDirLockRecoveryAuthority =
+ await establishServerProcessOwnershipAuthority({
+ userDataDir: platform.userDataDir,
+ port,
+ assertControlPlaneOwnership: () => {
+ if (!app.server.listening) return false
+ const address = app.server.address()
+ return (
+ typeof address === 'object' &&
+ address !== null &&
+ address.port === port
+ )
+ },
+ })
+ const dataDirLock = await acquireBridgeDataDirLock(bridgeDataDir, {
+ recoverExisting: bridgeDataDirLockRecoveryAuthority,
+ })
+ if (!shellAsyncWork.isAccepting()) {
+ await dataDirLock.release()
+ return
+ }
+ bridgeProcessDataDirLock = dataDirLock
+ try {
+ await trustedExtensionRegistry.load()
+ } catch (error) {
+ bridgeProcessDataDirLock = null
+ await dataDirLock.release()
+ throw error
+ }
+ if (!shellAsyncWork.isAccepting()) {
+ bridgeProcessDataDirLock = null
+ await dataDirLock.release()
+ return
+ }
+ bridgeRegistryReady = true
+ })().catch((err) => {
+ log.error(
+ { err },
+ 'bridge data ownership unavailable — trusted registry and MDXP bridge disabled'
+ )
+ })
+ await bridgeOwnershipSetup
+ if (!shellAsyncWork.isAccepting()) return
+
// ─── MDXP bridge (Spec 6) ─────────────────────────────────────
// Agent-facing unary POST /mdxp + SSE GET /mdxp/events, on its OWN port
// (default loopback:16801), separate from the Fastify web/RPC server above.
// Non-fatal: a bind failure (e.g. port in use) must not take down the web UI.
- try {
+ // The manager keeps every bridge:* RPC registered while this factory owns
+ // only the optional listener/runtime portion.
+ bridgeRuntimeFactory = async (): Promise<ServerBridgeRuntime> => {
const removeTaskDeps = {
taskManager,
adapter,
@@ -1546,12 +1637,15 @@ async function main() {
},
directResourceProxyPolicy: appliedDownloadProxyPolicy,
}
- const mdxpPort = parseServerPort(
- process.env.MOTRIX_MDXP_PORT,
- 'MOTRIX_MDXP_PORT',
- 16801,
- { allowZero: true }
- )
+ const configuredMdxpPort = process.env.MOTRIX_MDXP_PORT?.trim()
+ const fixedPort = settingsManager.get().bridge.fixedPort
+ const mdxpPort = configuredMdxpPort
+ ? parseServerPort(configuredMdxpPort, 'MOTRIX_MDXP_PORT', 16801, {
+ allowZero: true,
+ })
+ : fixedPort === 'auto'
+ ? 16801
+ : fixedPort
const mdxpHost = process.env.MOTRIX_MDXP_HOST ?? '127.0.0.1'
const remoteExtensionConfig = parseRemoteExtensionConfig(process.env)
if (remoteExtensionConfig.status === 'invalid') {
@@ -1576,28 +1670,25 @@ async function main() {
'non-loopback MDXP bind has no usable MOTRIX_PUBLIC_URL; remote clients may not receive a usable approval URL'
)
}
- const bridgeDataDirLockRecoveryAuthority =
- await establishServerProcessOwnershipAuthority({
- userDataDir: platform.userDataDir,
- port,
- assertControlPlaneOwnership: () => {
- if (!app.server.listening) return false
- const address = app.server.address()
- return (
- typeof address === 'object' &&
- address !== null &&
- address.port === port
- )
- },
- })
+ const dataDirLock = bridgeProcessDataDirLock
+ if (
+ dataDirLock === null ||
+ bridgeDataDirLockRecoveryAuthority === null ||
+ !bridgeRegistryReady
+ ) {
+ throw new Error('Bridge data ownership is unavailable')
+ }
const candidateBridgeRuntime = await bootstrapBridgeForServer({
userDataDir: platform.userDataDir,
host: mdxpHost,
port: mdxpPort,
+ fixedPort,
motrixVersion: appVersion,
eventBus,
bridgeDataDirLockRecoveryAuthority,
+ bridgeDataDirLock: dataDirLock,
remoteExtensionConfig,
+ trustedExtensionRegistry,
createExtensionReceiver: ({ dataDir, bridgeBus }) =>
new BridgeReceiver({
dataDir,
@@ -1671,15 +1762,17 @@ async function main() {
})
if (!shellAsyncWork.isAccepting()) {
await candidateBridgeRuntime.shutdown()
- return
+ throw new Error('Bridge startup cancelled during Server shutdown')
}
- bridgeRuntime = candidateBridgeRuntime
- // Make the bridge:* RPC handlers reachable through the already-listening
- // Fastify routes (createApp captured the maps by reference).
- Object.assign(bridgeCommandHandlers, bridgeRuntime.bridgeCommandHandlers)
- Object.assign(bridgeQueryHandlers, bridgeRuntime.bridgeQueryHandlers)
- log.info({ port: bridgeRuntime.port }, 'MDXP bridge listening')
+ log.info({ port: candidateBridgeRuntime.port }, 'MDXP bridge listening')
logRemoteExtensionPairingReady(log, remoteExtensionConfig)
+ return candidateBridgeRuntime
+ }
+
+ try {
+ await bridgeManager.setEnabled(
+ settingsManager.getApp().browserBridgeEnabled
+ )
} catch (err) {
log.error({ err }, 'MDXP bridge bootstrap failed — continuing without it')
}
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index b7077e30..db9ee305 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -10,6 +10,7 @@ import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatch
import type { PluginHost } from '@core/plugin/host/plugin-host'
import type { PluginInstaller } from '@core/plugin/install/plugin-installer'
import type { PluginRegistry } from '@core/plugin/plugin-registry'
+import type { RegistryClient } from '@core/plugin/registry/registry-client'
import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'
import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
import { MotrixDatabase } from '@core/session/motrix-database'
@@ -75,7 +76,12 @@ function makeFakeCtx() {
trackerManager: {
applySourcesChange: vi.fn().mockResolvedValue(undefined),
applyBlacklistChange: vi.fn().mockResolvedValue(undefined),
+ applySyncScheduleChange: vi.fn(),
} as unknown as TrackerManager,
+ bridgeControl: {
+ setEnabled: vi.fn().mockResolvedValue(undefined),
+ restart: vi.fn().mockResolvedValue(undefined),
+ },
aria2BinaryPath: '/usr/bin/aria2c',
finalNamePicker: {} as FinalNamePicker,
torrentMetaStore: {} as TorrentMetaStore,
@@ -106,7 +112,13 @@ function makeFakeCtx() {
},
pluginRegistry: {
refreshState: vi.fn(),
+ list: vi.fn(() => []),
} as unknown as PluginRegistry,
+ registryClient: {
+ refresh: vi.fn().mockResolvedValue(undefined),
+ list: vi.fn().mockResolvedValue([]),
+ } as unknown as RegistryClient,
+ hostVersion: '2.0',
pluginStateStore: {
setEnabled: vi.fn(),
get: vi.fn().mockReturnValue(undefined),
@@ -161,19 +173,29 @@ function makeFakeCtx() {
function makeSettings(
proxy: typeof PROXY_OFF,
- tracker: { sourcesEnabled?: boolean; blacklistEnabled?: boolean } = {},
+ tracker: {
+ sourcesEnabled?: boolean
+ blacklistEnabled?: boolean
+ autoSync?: boolean
+ syncIntervalHours?: number
+ } = {},
engine: { dnsMode?: 'auto' | 'system' | 'engine'; split?: number } = {},
- app: { defaultSaveDir?: string } = {}
+ app: { defaultSaveDir?: string; browserBridgeEnabled?: boolean } = {},
+ bridge: { fixedPort?: 'auto' | number } = {}
) {
return {
app: {
defaultSaveDir: '/downloads',
+ browserBridgeEnabled: true,
...app,
},
+ bridge: { fixedPort: 'auto' as const, ...bridge },
proxy,
tracker: {
sourcesEnabled: true,
blacklistEnabled: true,
+ autoSync: true,
+ syncIntervalHours: 24,
...tracker,
},
engine: {
@@ -403,6 +425,49 @@ describe('server Commands.UpdateSettings', () => {
)
})
+ it('hot-applies the browser bridge master switch', async () => {
+ const ctx = makeFakeCtx()
+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)
+ .mockReturnValueOnce(
+ makeSettings(PROXY_OFF, {}, {}, { browserBridgeEnabled: true })
+ )
+ .mockReturnValueOnce(
+ makeSettings(PROXY_OFF, {}, {}, { browserBridgeEnabled: false })
+ )
+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(
+ { ok: true, requiresRestart: false, changedRestartKeys: [] }
+ )
+ const handlers = buildServerCommandHandlers(
+ ctx as Parameters<typeof buildServerCommandHandlers>[0]
+ )
+
+ await handlers[Commands.UpdateSettings]?.({
+ app: { browserBridgeEnabled: false },
+ })
+
+ expect(ctx.bridgeControl.setEnabled).toHaveBeenCalledExactlyOnceWith(false)
+ expect(ctx.bridgeControl.restart).not.toHaveBeenCalled()
+ })
+
+ it('restarts an enabled bridge when its fixed port changes', async () => {
+ const ctx = makeFakeCtx()
+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)
+ .mockReturnValueOnce(makeSettings(PROXY_OFF))
+ .mockReturnValueOnce(
+ makeSettings(PROXY_OFF, {}, {}, {}, { fixedPort: 18080 })
+ )
+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(
+ { ok: true, requiresRestart: false, changedRestartKeys: [] }
+ )
+ const handlers = buildServerCommandHandlers(
+ ctx as Parameters<typeof buildServerCommandHandlers>[0]
+ )
+
+ await handlers[Commands.UpdateSettings]?.({ bridge: { fixedPort: 18080 } })
+
+ expect(ctx.bridgeControl.restart).toHaveBeenCalledOnce()
+ })
+
it('hot-applies async-dns and resets the fallback latch when dnsMode changes', async () => {
const ctx = makeFakeCtx()
;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)
@@ -583,6 +648,30 @@ describe('server Commands.UpdateSettings', () => {
await handlers[Commands.UpdateSettings]?.({})
expect(ctx.trackerManager.applySourcesChange).not.toHaveBeenCalled()
expect(ctx.trackerManager.applyBlacklistChange).not.toHaveBeenCalled()
+ expect(ctx.trackerManager.applySyncScheduleChange).not.toHaveBeenCalled()
+ })
+
+ it('re-arms tracker auto-sync when its enablement or interval changes', async () => {
+ const ctx = makeFakeCtx()
+ ;(ctx.settingsManager.get as ReturnType<typeof vi.fn>)
+ .mockReturnValueOnce(
+ makeSettings(PROXY_OFF, { autoSync: true, syncIntervalHours: 24 })
+ )
+ .mockReturnValueOnce(
+ makeSettings(PROXY_OFF, { autoSync: false, syncIntervalHours: 12 })
+ )
+ ;(ctx.settingsManager.update as ReturnType<typeof vi.fn>).mockResolvedValue(
+ { ok: true, requiresRestart: false, changedRestartKeys: [] }
+ )
+ const handlers = buildServerCommandHandlers(
+ ctx as Parameters<typeof buildServerCommandHandlers>[0]
+ )
+
+ await handlers[Commands.UpdateSettings]?.({
+ tracker: { autoSync: false, syncIntervalHours: 12 },
+ })
+
+ expect(ctx.trackerManager.applySyncScheduleChange).toHaveBeenCalledOnce()
})
it('validates a default save directory before persisting settings', async () => {
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index d395ebc1..cf8a3252 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -20,6 +20,8 @@ import type { ActivationDispatcher } from '@core/plugin/host/activation-dispatch
import type { PluginHost } from '@core/plugin/host/plugin-host'
import type { PluginInstaller } from '@core/plugin/install/plugin-installer'
import type { PluginRegistry } from '@core/plugin/plugin-registry'
+import type { RegistryClient } from '@core/plugin/registry/registry-client'
+import { scanForUpdates } from '@core/plugin/registry/update-scan'
import type { PluginStateStore } from '@core/plugin/state/plugin-state-store'
import {
type AppliedDownloadProxyPolicy,
@@ -55,6 +57,7 @@ import { DirectResourceValidatorService } from '@core/task/direct-resource-valid
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'
+import { createSetSelectedFilesHandler } from '@core/task/set-selected-files'
import type { TaskManager } from '@core/task/task-manager'
import type { TorrentMetaStore } from '@core/task/torrent-meta-store'
import type { MagnetTracker } from '@core/torrent/magnet-tracker'
@@ -69,6 +72,8 @@ import {
removeTasksPayloadSchema,
taskIdsPayloadSchema,
} from '@shared/schemas/bulk-task-command'
+import { supportedLocaleSchema } from '@shared/schemas/locale'
+import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'
import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'
import { EngineRecoveryAction } from '@shared/types/engine'
import type { ProxySettings } from '@shared/types/settings'
@@ -97,6 +102,10 @@ export interface ServerCommandContext {
rpcClient: Aria2RpcClient
adapter: EngineAdapter
trackerManager: TrackerManager
+ bridgeControl?: {
+ setEnabled(enabled: boolean): Promise<void>
+ restart(): Promise<void>
+ }
aria2BinaryPath: string
finalNamePicker: FinalNamePicker
torrentMetaStore: TorrentMetaStore
@@ -109,6 +118,8 @@ export interface ServerCommandContext {
notificationCenter: NotificationCenter
taskPersistence: Pick<SessionManager, 'runExclusivePersistence'>
pluginRegistry: PluginRegistry
+ registryClient: RegistryClient
+ hostVersion: string
pluginStateStore: PluginStateStore
pluginHost: PluginHost
pluginInstaller: PluginInstaller
@@ -157,6 +168,7 @@ export function buildServerCommandHandlers(
bindTaskRetry,
adapter,
trackerManager,
+ bridgeControl,
finalNamePicker,
torrentMetaStore,
taskManager,
@@ -168,6 +180,8 @@ export function buildServerCommandHandlers(
notificationCenter,
taskPersistence,
pluginRegistry,
+ registryClient,
+ hostVersion,
pluginStateStore,
pluginHost,
pluginInstaller,
@@ -351,8 +365,18 @@ export function buildServerCommandHandlers(
action: z.enum(EngineRecoveryAction),
expectedPid: z.number().int().positive().optional(),
})
-
return {
+ [Commands.SetDisclaimerLanguage]: async (payload: unknown) => {
+ const language = supportedLocaleSchema.parse(payload)
+ await settingsManager.setDisclaimerLanguage(language)
+ return { ok: true }
+ },
+
+ [Commands.AcceptDisclaimer]: async () => {
+ await settingsManager.acceptDisclaimer()
+ return { ok: true }
+ },
+
[Commands.AddMagnetTask]: async (params: {
uri: string
selectedFiles: number[]
@@ -613,6 +637,14 @@ export function buildServerCommandHandlers(
return { ok: true }
},
+ [Commands.SetSelectedFiles]: createSetSelectedFilesHandler({
+ taskManager,
+ engine: adapter,
+ db: motrixDatabase,
+ eventBus,
+ runTaskMutation,
+ }),
+
[Commands.RestartEngine]: async () => {
await supervisor.restart()
return { ok: true }
@@ -676,6 +708,15 @@ export function buildServerCommandHandlers(
await supervisor.applyDefaultSaveDir(newFull.app.defaultSaveDir)
}
+ if (
+ oldFull.app.browserBridgeEnabled !== newFull.app.browserBridgeEnabled
+ ) {
+ await bridgeControl?.setEnabled(newFull.app.browserBridgeEnabled)
+ }
+ if (oldFull.bridge.fixedPort !== newFull.bridge.fixedPort) {
+ await bridgeControl?.restart()
+ }
+
if (oldFull.tracker.sourcesEnabled !== newFull.tracker.sourcesEnabled) {
await trackerManager.applySourcesChange(newFull.tracker.sourcesEnabled)
}
@@ -688,6 +729,13 @@ export function buildServerCommandHandlers(
)
}
+ if (
+ oldFull.tracker.autoSync !== newFull.tracker.autoSync ||
+ oldFull.tracker.syncIntervalHours !== newFull.tracker.syncIntervalHours
+ ) {
+ trackerManager.applySyncScheduleChange()
+ }
+
await supervisor.applyEngineSettings(oldFull.engine, newFull.engine)
if (oldFull.engine.dnsMode !== newFull.engine.dnsMode) {
@@ -818,6 +866,15 @@ export function buildServerCommandHandlers(
return { ok: true }
},
+ [Commands.CheckPluginUpdates]: async (payload: unknown) => {
+ const parsed = checkPluginUpdatesPayloadSchema.parse(payload)
+ if (parsed?.force) await registryClient.refresh()
+ const entries = await registryClient.list(hostVersion)
+ return scanForUpdates(pluginRegistry.list(), entries).filter(
+ (update) => update.channel === 'community'
+ )
+ },
+
[Commands.InstallPlugin]: async (payload: unknown) => {
const result = await pluginInstallService.stage(payload, pluginHost)
if (result.committed && result.pluginId) {
diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.ts
index f4d75742..7a967ede 100644
--- a/src/server/ipc/queries.test.ts
+++ b/src/server/ipc/queries.test.ts
@@ -136,23 +136,44 @@ function makeCtx(over: Record<string, unknown> = {}) {
unreadCount: vi.fn(() => 0),
},
pluginRegistry: { list: vi.fn(() => []), entries: vi.fn(() => []) },
+ capabilityHost: { getTail: vi.fn(() => []) },
pluginGrants: {
getGrants: vi.fn(async () => ({})),
listAllGrants: vi.fn(async () => ({})),
},
pluginsDir: '',
hostVersion: '2.0',
+ motrixDatabase: { getMetadata: vi.fn() },
userDataDir: '',
speedLimitController: { getState: vi.fn() },
downloadPathPolicy: {
allowedSaveDirs: [],
prepareSaveDir: vi.fn(),
},
+ environment: {},
...over,
}
}
describe('buildServerQueryHandlers — allowed save directories', () => {
+ it('reports the proxy inherited by the Server process', async () => {
+ const handlers = buildServerQueryHandlers(
+ makeCtx({
+ environment: {
+ HTTPS_PROXY: 'http://proxy.internal:3128',
+ NO_PROXY: 'localhost,.lan',
+ },
+ }) as never
+ )
+
+ await expect(handlers[Queries.GetSystemProxy]?.()).resolves.toEqual({
+ protocol: 'http',
+ host: 'proxy.internal',
+ port: 3128,
+ bypass: ['localhost', '.lan'],
+ })
+ })
+
it('reports Linux associations as unsupported on the web server', async () => {
const handlers = buildServerQueryHandlers(makeCtx() as never)
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index 5fa93ca5..bc680a9f 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -2,9 +2,12 @@ import path from 'node:path'
import type { TaskActivityService } from '@core/activity'
import type { EngineAdapter } from '@core/engine/engine-adapter'
import type { EngineSupervisor } from '@core/engine/engine-supervisor'
+import { createGetEngineTaskOptionsHandler } from '@core/engine/get-engine-task-options'
+import { getTuningRecommendation } from '@core/engine/get-tuning-recommendation'
import type { GeoIPManager } from '@core/geoip/geo-ip-manager'
import { createGetGeoIPStatusHandler } from '@core/geoip/get-geo-ip-status'
import type { NotificationCenter } from '@core/notifications/notification-center'
+import type { CapabilityHost } from '@core/plugin/capabilities/interface'
import { readCommandGraph } from '@core/plugin/commands/command-graph'
import type { GrantsManager } from '@core/plugin/grants/grants-manager'
import type { PluginRegistry } from '@core/plugin/plugin-registry'
@@ -15,6 +18,8 @@ import {
readPluginConfig,
} from '@core/plugin/queries'
import type { RegistryClient } from '@core/plugin/registry/registry-client'
+import { parseProxyEnvironment } from '@core/proxy/system-proxy'
+import type { MotrixDatabase } from '@core/session/motrix-database'
import type { SettingsManager } from '@core/settings/settings-manager'
import type { SpeedLimitController } from '@core/speed-limit/speed-limit-controller'
import type {
@@ -23,6 +28,7 @@ import type {
TaskSpeedHistoryStore,
TransferStatsRuntime,
} from '@core/stats'
+import { createGetTaskFilesHandler } from '@core/task/get-task-files'
import { createGetTaskPeersHandler } from '@core/task/get-task-peers'
import { createGetTaskPiecesHandler } from '@core/task/get-task-pieces'
import { slimTasksForBroadcast } from '@core/task/slim-task-for-broadcast'
@@ -30,6 +36,8 @@ import type { TaskManager } from '@core/task/task-manager'
import type { TrackerManager } from '@core/tracker'
import type { QueryHandlerMap } from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import type { AppUpdateState } from '@shared/types/app-update'
+import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
import {
CliInstallCapability,
CliPackageManager,
@@ -81,6 +89,10 @@ const UNSUPPORTED_WEB_CLI_STATUS: CliToolStatus = {
detail: null,
}
+const UNSUPPORTED_APPIMAGE_INTEGRATION: AppImageIntegrationView = {
+ supported: false,
+}
+
export interface ServerQueryContext {
taskManager: TaskManager
statsAggregator: StatsAggregator
@@ -95,9 +107,11 @@ export interface ServerQueryContext {
settingsManager: SettingsManager
trackerManager: TrackerManager
engineAdapter: EngineAdapter
+ motrixDatabase: MotrixDatabase
geoipManager: Pick<GeoIPManager, 'getStatus' | 'isEnabled' | 'lookupCountry'>
notificationCenter: NotificationCenter
pluginRegistry: PluginRegistry
+ capabilityHost: CapabilityHost
pluginGrants: GrantsManager
registryClient: RegistryClient
pluginsDir: string
@@ -105,6 +119,7 @@ export interface ServerQueryContext {
userDataDir: string
speedLimitController: SpeedLimitController
downloadPathPolicy: ServerDownloadPathPolicy
+ environment: NodeJS.ProcessEnv
}
export function buildServerQueryHandlers(
@@ -122,9 +137,11 @@ export function buildServerQueryHandlers(
settingsManager,
trackerManager,
engineAdapter,
+ motrixDatabase,
geoipManager,
notificationCenter,
pluginRegistry,
+ capabilityHost,
pluginGrants,
registryClient,
pluginsDir,
@@ -132,6 +149,7 @@ export function buildServerQueryHandlers(
userDataDir,
speedLimitController,
downloadPathPolicy,
+ environment,
} = ctx
const detectFfmpeg = makeServerFfmpegDetect({
@@ -140,6 +158,10 @@ export function buildServerQueryHandlers(
})
return {
+ [Queries.GetDisclaimerState]: async () => ({
+ language: settingsManager.getApp().language,
+ }),
+
[Queries.GetCliToolStatus]: async () => UNSUPPORTED_WEB_CLI_STATUS,
// Same slim projection as the TaskUpdated broadcast so hydration and
@@ -152,6 +174,16 @@ export function buildServerQueryHandlers(
[Queries.GetTaskDetail]: async (taskId: string) =>
taskManager.getById(taskId) ?? null,
+ [Queries.GetTaskFiles]: createGetTaskFilesHandler({
+ db: motrixDatabase,
+ taskManager,
+ engine: engineAdapter,
+ }),
+
+ [Queries.GetEngineTaskOptions]: createGetEngineTaskOptionsHandler({
+ engine: engineAdapter,
+ }),
+
[Queries.GetTaskPieces]: createGetTaskPiecesHandler({
engineAdapter,
taskManager,
@@ -186,11 +218,25 @@ export function buildServerQueryHandlers(
[Queries.GetEngineDiagnostics]: async () => supervisor.diagnose(),
+ [Queries.GetTuningRecommendation]: getTuningRecommendation,
+
+ [Queries.GetNatStatus]: async () => null,
+
+ [Queries.GetNatDiagnostic]: async () => null,
+
[Queries.GetSettings]: async () => settingsManager.get(),
[Queries.GetGeoIPStatus]: createGetGeoIPStatusHandler({ geoipManager }),
- [Queries.GetSystemProxy]: async () => null,
+ [Queries.GetSystemProxy]: async () => parseProxyEnvironment(environment),
+
+ [Queries.GetUpdateState]: async (): Promise<AppUpdateState> => ({
+ phase: 'unsupported',
+ currentVersion: hostVersion,
+ }),
+
+ [Queries.GetAppImageIntegrationStatus]: async () =>
+ UNSUPPORTED_APPIMAGE_INTEGRATION,
[Queries.GetLinuxDefaultAssociations]: async () => ({
supported: false,
@@ -244,6 +290,11 @@ export function buildServerQueryHandlers(
path.join(pluginsDir, '_audit', 'command-invokes.ndjson')
),
+ [Queries.GetPluginLogs]: async (params: {
+ pluginId: string
+ limit?: number
+ }) => capabilityHost.getTail(params.pluginId, params.limit ?? 100),
+
[Queries.GetPluginConfig]: async (pluginId: string) =>
readPluginConfig(settingsManager.get(), pluginId),
diff --git a/src/server/shutdown.test.ts b/src/server/shutdown.test.ts
index 45a72e5a..0684cf87 100644
--- a/src/server/shutdown.test.ts
+++ b/src/server/shutdown.test.ts
@@ -400,25 +400,20 @@ describe('server lifecycle production wiring', () => {
'utf8'
)
const runtimeAccepted = source.indexOf(
- 'bridgeRuntime = candidateBridgeRuntime'
+ 'const candidateBridgeRuntime = await bootstrapBridgeForServer('
)
- const commandHandlersPublished = source.indexOf(
- 'Object.assign(bridgeCommandHandlers, bridgeRuntime.bridgeCommandHandlers)',
+ const bridgeListeningLog = source.indexOf(
+ "log.info({ port: candidateBridgeRuntime.port }, 'MDXP bridge listening')",
runtimeAccepted
)
- const queryHandlersPublished = source.indexOf(
- 'Object.assign(bridgeQueryHandlers, bridgeRuntime.bridgeQueryHandlers)',
- commandHandlersPublished
- )
const pairingAddressLog = source.indexOf(
'logRemoteExtensionPairingReady(log, remoteExtensionConfig)',
- queryHandlersPublished
+ bridgeListeningLog
)
expect(runtimeAccepted).toBeGreaterThan(-1)
- expect(commandHandlersPublished).toBeGreaterThan(runtimeAccepted)
- expect(queryHandlersPublished).toBeGreaterThan(commandHandlersPublished)
- expect(pairingAddressLog).toBeGreaterThan(queryHandlersPublished)
+ expect(bridgeListeningLog).toBeGreaterThan(runtimeAccepted)
+ expect(pairingAddressLog).toBeGreaterThan(bridgeListeningLog)
})
it('wires TrackerManager stopAndDrain into production shutdown', () => {
diff --git a/src/shared/lib/torrent-meta.ts b/src/shared/lib/torrent-meta.ts
new file mode 100644
index 00000000..bea789a1
--- /dev/null
+++ b/src/shared/lib/torrent-meta.ts
@@ -0,0 +1,37 @@
+import type { TorrentMeta } from '@shared/types/torrent'
+
+export const MAX_TORRENT_BASE64_SIZE = 50 * 1024 * 1024
+
+export interface ParsedTorrentMetaInput {
+ name?: string
+ infoHash?: string
+ files?: Array<{ path: string; length: number }>
+ comment?: string
+ private?: boolean
+}
+
+function fileExtension(path: string): string {
+ const name = path.replaceAll('\\', '/').split('/').at(-1) ?? ''
+ const dot = name.lastIndexOf('.')
+ return dot <= 0 ? '' : name.slice(dot)
+}
+
+export function projectTorrentMeta(
+ parsed: ParsedTorrentMetaInput
+): TorrentMeta {
+ const files = (parsed.files ?? []).map((file, index) => ({
+ index,
+ path: file.path,
+ size: file.length,
+ extension: fileExtension(file.path),
+ }))
+
+ return {
+ name: parsed.name ?? 'Unknown',
+ infoHash: parsed.infoHash ?? '',
+ totalSize: files.reduce((sum, file) => sum + file.size, 0),
+ files,
+ comment: parsed.comment ?? null,
+ isPrivate: parsed.private ?? false,
+ }
+}
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index f06ef93c..d66d6448 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -809,8 +809,14 @@
"saveDirEmpty": "Choose a folder…",
"changeSaveDir": "Change save directory",
"created": "Task added",
+ "batchCreated": "{{count}} tasks added",
"createdCopy": "Separate copy added",
"createdPartial": "{{ok}} added · {{failed}} failed",
+ "torrentQueueProgress": "Torrent {{current}} of {{total}}",
+ "downloadAndContinue": "Download & Continue",
+ "downloadAllTorrents": "Download All ({{count}})",
+ "skipTorrent": "Skip",
+ "queueAdvanceFailed": "Could not open the next torrent.",
"duplicate": {
"title": "This torrent already exists",
"active-info-hash": "{{name}} is already active. aria2 cannot run the same torrent content twice at the same time.",
@@ -1919,7 +1925,6 @@
"notInstalled": "Not installed",
"notFound": "Plugin “{{id}}” was not found in the registry",
"viewOnWebsite": "View on motrix.app",
- "installPending": "Installing straight from the registry is coming soon. Until then you can review the plugin here and on the website.",
"updated": "updated {{date}}",
"featuresTitle": "What it does",
"permissionsTitle": "Permissions",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index cce1e2a2..5380c5d5 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -797,8 +797,14 @@
"saveDirEmpty": "选择文件夹…",
"changeSaveDir": "更改保存目录",
"created": "任务已添加",
+ "batchCreated": "已添加 {{count}} 个任务",
"createdCopy": "独立副本已添加",
"createdPartial": "已添加 {{ok}} 个,{{failed}} 个失败",
+ "torrentQueueProgress": "种子 {{current}} / {{total}}",
+ "downloadAndContinue": "下载并继续",
+ "downloadAllTorrents": "全部下载({{count}})",
+ "skipTorrent": "跳过",
+ "queueAdvanceFailed": "无法打开下一个种子。",
"duplicate": {
"title": "此种子已经存在",
"active-info-hash": "「{{name}}」正在运行。aria2 无法同时运行两个内容相同的种子任务。",
@@ -1901,7 +1907,6 @@
"notInstalled": "未安装",
"notFound": "插件「{{id}}」不在插件注册表中",
"viewOnWebsite": "在 motrix.app 查看",
- "installPending": "从注册表直接安装即将推出,目前可先在这里或官网查看该插件的完整信息。",
"updated": "更新于 {{date}}",
"featuresTitle": "功能",
"permissionsTitle": "权限",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index c233db49..8d36547f 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -797,8 +797,14 @@
"saveDirEmpty": "選擇資料夾…",
"changeSaveDir": "變更儲存目錄",
"created": "已新增任務",
+ "batchCreated": "已新增 {{count}} 個任務",
"createdCopy": "已新增獨立副本",
"createdPartial": "已新增 {{ok}} 個,{{failed}} 個失敗",
+ "torrentQueueProgress": "Torrent {{current}} / {{total}}",
+ "downloadAndContinue": "下載並繼續",
+ "downloadAllTorrents": "全部下載({{count}})",
+ "skipTorrent": "略過",
+ "queueAdvanceFailed": "無法開啟下一個 Torrent。",
"duplicate": {
"title": "此 Torrent 已經存在",
"active-info-hash": "「{{name}}」正在執行。aria2 無法同時執行兩個內容相同的 Torrent 任務。",
@@ -1994,7 +2000,6 @@
"notInstalled": "未安裝",
"notFound": "在 registry 中找不到外掛程式「{{id}}」",
"viewOnWebsite": "在 motrix.app 檢視",
- "installPending": "即將支援直接從 registry 安裝。在此之前,您可在這裡和網站上檢閱外掛程式。",
"updated": "更新於 {{date}}",
"featuresTitle": "功能",
"permissionsTitle": "權限",
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 646299d2..83d7eb37 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -1,5 +1,4 @@
export const Commands = {
- CreateDownload: 'command:createDownload',
PauseTask: 'command:pauseTask',
ResumeTask: 'command:resumeTask',
RemoveTask: 'command:removeTask',
diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.ts
index 8e28444a..582444c1 100644
--- a/src/shared/schemas/add-task.ts
+++ b/src/shared/schemas/add-task.ts
@@ -157,6 +157,31 @@ export type TaskCreateCommandResult =
conflict: TorrentDuplicateConflict
}
+export interface TorrentBatchCreateResult {
+ total: number
+ succeeded: number
+ failed: number
+ firstTaskId: string | null
+}
+
+export const torrentBatchCreateOptionsSchema = z.object({
+ selectedFiles: z
+ .array(z.number().int().nonnegative())
+ .min(1, { message: 'task.add.errors.noFilesSelected' }),
+ saveDir: z.string().min(1, { message: 'task.add.errors.saveDirRequired' }),
+ dlLimit: z.number().int().nonnegative().optional(),
+ ulLimit: z.number().int().nonnegative().optional(),
+ seedRatio: z.number().nonnegative().optional(),
+})
+
+export type TorrentBatchCreateOptions = z.infer<
+ typeof torrentBatchCreateOptionsSchema
+>
+
+export interface TorrentQueueAdvanceResult {
+ advanced: boolean
+}
+
// ── URL params ──────────────────────────────────────────────
export const addTaskUrlParamsSchema = z.object({
@@ -191,6 +216,12 @@ export const magnetFileSelectionPayloadSchema = z.object({
export const protocolTorrentFilePayloadSchema = z.object({
payload: z.object({ name: z.string(), dataBase64: z.string() }),
meta: torrentMetaSchema,
+ queuePosition: z.number().int().positive().default(1),
+ queueTotal: z.number().int().positive().default(1),
+})
+
+export const torrentQueueSizeChangedPayloadSchema = z.object({
+ queueTotal: z.number().int().positive(),
})
// ── Pure helpers ────────────────────────────────────────────
diff --git a/src/shared/schemas/plugin-update.ts b/src/shared/schemas/plugin-update.ts
new file mode 100644
index 00000000..c4bb2a34
--- /dev/null
+++ b/src/shared/schemas/plugin-update.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod'
+
+export const checkPluginUpdatesPayloadSchema = z
+ .object({ force: z.boolean().optional() })
+ .optional()
diff --git a/src/shared/schemas/task-file-selection.ts b/src/shared/schemas/task-file-selection.ts
new file mode 100644
index 00000000..22cc9740
--- /dev/null
+++ b/src/shared/schemas/task-file-selection.ts
@@ -0,0 +1,15 @@
+import { z } from 'zod'
+
+export const setSelectedFilesPayloadSchema = z
+ .object({
+ taskId: z.string().min(1),
+ indices: z.array(z.number().int().nonnegative()).min(1),
+ })
+ .refine((value) => new Set(value.indices).size === value.indices.length, {
+ message: 'File selection contains duplicate indices',
+ path: ['indices'],
+ })
+
+export type SetSelectedFilesPayload = z.infer<
+ typeof setSelectedFilesPayloadSchema
+>
diff --git a/src/shared/types/system-proxy.ts b/src/shared/types/system-proxy.ts
new file mode 100644
index 00000000..1fdc1e60
--- /dev/null
+++ b/src/shared/types/system-proxy.ts
@@ -0,0 +1,8 @@
+export interface SystemProxyResult {
+ protocol: 'http' | 'https' | 'socks5'
+ host: string
+ port: number
+ user?: string
+ password?: string
+ bypass?: string[]
+}
diff --git a/vite.renderer.config.ts b/vite.renderer.config.ts
index a1630d8f..318c5d9f 100644
--- a/vite.renderer.config.ts
+++ b/vite.renderer.config.ts
@@ -28,6 +28,10 @@ export default defineConfig(({ command }) => ({
alias: {
'@shared': path.resolve(import.meta.dirname, 'src/shared'),
'@renderer': path.resolve(import.meta.dirname, 'src/renderer'),
+ path: path.resolve(
+ import.meta.dirname,
+ 'src/renderer/lib/path-browser-shim.ts'
+ ),
},
},
}))
diff --git a/vite.renderer.web.config.ts b/vite.renderer.web.config.ts
index 181edcf6..f57183b5 100644
--- a/vite.renderer.web.config.ts
+++ b/vite.renderer.web.config.ts
@@ -24,6 +24,10 @@ export default defineConfig({
alias: {
'@shared': path.resolve(import.meta.dirname, 'src/shared'),
'@renderer': path.resolve(import.meta.dirname, 'src/renderer'),
+ path: path.resolve(
+ import.meta.dirname,
+ 'src/renderer/lib/path-browser-shim.ts'
+ ),
},
},
})