A full-featured download manager.
feat(downloads): add performance profiles and 64 connections (#1909)
Dr_rOotb6f293ad19c1
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex 5e669eee..8b8d5dcf 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -484,6 +484,69 @@ describe('Aria2Adapter', () => {)})+ it('auto profile applies per-file tuning without sending global disk-cache', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ performanceProfile: 'auto',+ protocol: 'http',+ totalSizeBytes: 10 * 1024 * 1024 * 1024,+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['u'],+ expect.objectContaining({+ split: '32',+ 'min-split-size': String(10 * 1024 * 1024),+ })+ )+ const options = vi.mocked(rpc.addUri).mock.calls[0][1]+ expect(options).not.toHaveProperty('disk-cache')+ })++ it('fixed profiles keep their global tuning values', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ performanceProfile: 'high',+ protocol: 'http',+ totalSizeBytes: 10 * 1024 * 1024 * 1024,+ })++ expect(rpc.addUri).toHaveBeenCalledWith(['u'], { dir: '/d' })+ })++ it('auto tuning preserves an explicit connection count', async () => {+ const rpc = createMockRpc()+ vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')+ const adapter = new Aria2Adapter(rpc)++ await adapter.createDownload({+ uris: ['u'],+ saveDir: '/d',+ performanceProfile: 'auto',+ protocol: 'http',+ totalSizeBytes: 10 * 1024 * 1024 * 1024,+ connections: 8,+ })++ expect(rpc.addUri).toHaveBeenCalledWith(+ ['u'],+ expect.objectContaining({+ split: '8',+ 'max-connection-per-server': '8',+ })+ )+ })+it('createDownload maps proxy to all-proxy and merges extraEngineOptions', async () => {const rpc = createMockRpc()vi.mocked(rpc.addUri).mockResolvedValue('gidXYZ')diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex 4e900e12..8216cbdd 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -206,9 +206,15 @@ export class Aria2Adapter implements EngineAdapter {options[k] = v}+ const automaticTuning =+ params.performanceProfile === undefined ||+ params.performanceProfile === 'auto'if (params.fileAllocation) {options['file-allocation'] = params.fileAllocation- } else if (params.totalSizeBytes != null || params.protocol != null) {+ } else if (+ automaticTuning &&+ (params.totalSizeBytes != null || params.protocol != null)+ ) {const probe = probeQuick(params.saveDir)const context: TuningContext = {downloadPath: params.saveDir,@@ -218,10 +224,13 @@ export class Aria2Adapter implements EngineAdapter {}const rec = recommend(probe, context)options['file-allocation'] = rec.fileAllocation- if (params.split == null) options.split = String(rec.split)- if (params.minSplitSize == null) {+ if (!options.split) options.split = String(rec.split)+ if (!options['min-split-size']) {options['min-split-size'] = String(rec.minSplitSize)}+ // disk-cache is an aria2 instance-wide startup option, shared by all+ // downloads. EngineSupervisor applies the automatic recommendation+ // before process launch; it is intentionally not sent to addUri here.}if (params.split != null && !options.split) {options.split = String(params.split)diff --git a/src/core/engine/aria2/aria2-tuning.test.ts b/src/core/engine/aria2/aria2-tuning.test.tsindex 882963ff..ff6d8365 100644--- a/src/core/engine/aria2/aria2-tuning.test.ts+++ b/src/core/engine/aria2/aria2-tuning.test.ts@@ -249,33 +249,43 @@ describe('recommend', () => {expect(rec.detectedEnv).toBe(probe)})- it('SSD + small -> diskCache 16MB, split 5, minSplitSize 1MB', () => {+ it('SSD + small -> diskCache 32MB, split 8, minSplitSize 1MB', () => {const rec = recommend(makeProbe({ diskType: 'ssd' }),makeContext({ totalSizeBytes: 100 * MB }))- expect(rec.diskCache).toBe(16 * MB)- expect(rec.split).toBe(5)+ expect(rec.diskCache).toBe(32 * MB)+ expect(rec.split).toBe(8)expect(rec.minSplitSize).toBe(1 * MB)})- it('SSD + large -> diskCache 32MB, split 10, minSplitSize 20MB', () => {+ it('SSD + large -> diskCache 64MB, split 32, minSplitSize 10MB', () => {const rec = recommend(makeProbe({ diskType: 'ssd' }),makeContext({ totalSizeBytes: 10 * GB }))- expect(rec.diskCache).toBe(32 * MB)- expect(rec.split).toBe(10)+ expect(rec.diskCache).toBe(64 * MB)+ expect(rec.split).toBe(32)+ expect(rec.minSplitSize).toBe(10 * MB)+ })++ it('SSD + huge -> diskCache 64MB, split 64, minSplitSize 20MB', () => {+ const rec = recommend(+ makeProbe({ diskType: 'ssd' }),+ makeContext({ totalSizeBytes: 30 * GB })+ )+ expect(rec.diskCache).toBe(64 * MB)+ expect(rec.split).toBe(64)expect(rec.minSplitSize).toBe(20 * MB)})- it('HDD -> diskCache 64MB, split 5, minSplitSize 20MB', () => {+ it('HDD -> diskCache 64MB, split 8, minSplitSize 20MB', () => {const rec = recommend(makeProbe({ diskType: 'hdd' }),makeContext({ totalSizeBytes: 1 * GB }))expect(rec.diskCache).toBe(64 * MB)- expect(rec.split).toBe(5)+ expect(rec.split).toBe(8)expect(rec.minSplitSize).toBe(20 * MB)})diff --git a/src/core/engine/aria2/aria2-tuning.ts b/src/core/engine/aria2/aria2-tuning.tsindex 9f076d91..f814456c 100644--- a/src/core/engine/aria2/aria2-tuning.ts+++ b/src/core/engine/aria2/aria2-tuning.ts@@ -169,17 +169,20 @@ function recommendTuningParams(}if (probe.diskType === 'hdd') {- return { diskCache: 64 * MB, split: 5, minSplitSize: 20 * MB }+ return { diskCache: 64 * MB, split: 8, minSplitSize: 20 * MB }}// SSD or unknownif (tier === 'small') {- return { diskCache: 16 * MB, split: 5, minSplitSize: 1 * MB }+ return { diskCache: 32 * MB, split: 8, minSplitSize: 1 * MB }}if (tier === 'medium') {- return { diskCache: 16 * MB, split: 5, minSplitSize: 4 * MB }+ return { diskCache: 32 * MB, split: 16, minSplitSize: 4 * MB }}- return { diskCache: 32 * MB, split: 10, minSplitSize: 20 * MB }+ if (tier === 'large') {+ return { diskCache: 64 * MB, split: 32, minSplitSize: 10 * MB }+ }+ return { diskCache: 64 * MB, split: 64, minSplitSize: 20 * MB }}export function recommend(diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex ecdfa568..862dcb7a 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -1,3 +1,4 @@+import type { EnginePerformanceProfile } from '@shared/constants/engine-performance-profiles'import type {EngineCapability,EngineFeatureReport,@@ -67,6 +68,7 @@ export interface CreateDownloadParams {pause?: boolean// Tuning hints+ performanceProfile?: EnginePerformanceProfiletotalSizeBytes?: numberprotocol?: 'http' | 'ftp' | 'sftp' | 'bt' | 'magnet' | 'metalink'isMultiFile?: booleandiff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex 14cde3c5..66d9abc3 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -24,6 +24,14 @@ import type { Aria2RpcClient } from './aria2/aria2-rpc-client'import { EngineSupervisor } from './engine-supervisor'import { checkPort } from './port-check'+const { probePreciseMock } = vi.hoisted(() => ({+ probePreciseMock: vi.fn(),+}))++vi.mock('../probe/disk-probe', () => ({+ probePrecise: probePreciseMock,+}))+// checkPort uses node:net I/O which doesn't fire under fake timers, and// a live aria2 on the dev port would make it return false. Mock the// port-check module so the supervisor always sees the port as available.@@ -51,14 +59,15 @@ function createMockSettingsManager(): SettingsManager {dhtEnabled: true,listenPort: 6881,dhtListenPort: 6881,+ performanceProfile: 'auto',maxConcurrentDownloads: 5,- maxConnectionPerServer: 1,- split: 5,- minSplitSize: 20971520,+ maxConnectionPerServer: 64,+ split: 16,+ minSplitSize: 4194304,userAgent: 'Motrix/2.0',sessionSaveInterval: 60,fileAllocation: 'none',- diskCache: 16777216,+ diskCache: 33554432,})),getApp: vi.fn(() => ({defaultSaveDir: '/Users/test/Downloads',@@ -133,6 +142,17 @@ describe('EngineSupervisor', () => {beforeEach(() => {vi.useFakeTimers()+ probePreciseMock.mockReset()+ probePreciseMock.mockResolvedValue({+ platform: 'darwin',+ mountPoint: '/',+ fsType: 'apfs',+ diskType: 'ssd',+ isInternal: true,+ isNetworkFs: false,+ freeBytes: 100 * 1024 * 1024 * 1024,+ confidence: 'high',+ })eventBus = new EventBus()settings = createMockSettingsManager()processManager = createMockProcessManager()@@ -205,6 +225,60 @@ describe('EngineSupervisor', () => {await supervisor.start('/usr/bin/aria2c')expect(settings.update).not.toHaveBeenCalled()})++ it('applies automatic storage tuning to runtime args', async () => {+ probePreciseMock.mockResolvedValue({+ platform: 'linux',+ mountPoint: '/downloads',+ fsType: 'ext4',+ diskType: 'hdd',+ isInternal: true,+ isNetworkFs: false,+ freeBytes: 100 * 1024 * 1024 * 1024,+ confidence: 'high',+ })++ await supervisor.start('/usr/bin/aria2c')++ expect(configBuilder.buildArgs).toHaveBeenCalledWith(+ expect.objectContaining({+ performanceProfile: 'auto',+ diskCache: 64 * 1024 * 1024,+ split: 8,+ minSplitSize: 20 * 1024 * 1024,+ }),+ expect.anything(),+ expect.anything(),+ expect.anything()+ )+ expect(settings.update).not.toHaveBeenCalled()+ })++ it('keeps custom performance values unchanged at runtime', async () => {+ const configured = settings.getEngine()+ vi.mocked(settings.getEngine).mockReturnValue({+ ...configured,+ performanceProfile: 'custom',+ diskCache: 48 * 1024 * 1024,+ split: 24,+ minSplitSize: 2 * 1024 * 1024,+ })++ await supervisor.start('/usr/bin/aria2c')++ expect(probePreciseMock).not.toHaveBeenCalled()+ expect(configBuilder.buildArgs).toHaveBeenCalledWith(+ expect.objectContaining({+ performanceProfile: 'custom',+ diskCache: 48 * 1024 * 1024,+ split: 24,+ minSplitSize: 2 * 1024 * 1024,+ }),+ expect.anything(),+ expect.anything(),+ expect.anything()+ )+ })})describe('start — probe failure', () => {diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex a22fc579..a3d4c6ba 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -19,11 +19,13 @@ import {} from '@shared/types/engine'import type { EngineSettings } from '@shared/types/settings'import type { EventBus } from '../events/event-bus'+import { probePrecise } from '../probe/disk-probe'import type { SettingsManager } from '../settings/settings-manager'import type { Aria2Adapter } from './aria2/aria2-adapter'import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'import type { Aria2ProcessManager } from './aria2/aria2-process-manager'import type { Aria2RpcClient } from './aria2/aria2-rpc-client'+import { recommend } from './aria2/aria2-tuning'import { checkPort, findAvailablePort } from './port-check'const log = getLogger('engine')@@ -194,6 +196,30 @@ export class EngineSupervisor {await this.rpcClient.changeGlobalOption(params)}+ private async resolveRuntimeEngineSettings(+ settings: EngineSettings+ ): Promise<EngineSettings> {+ if (settings.performanceProfile !== 'auto') return settings++ const downloadPath = this.settingsManager.getApp().defaultSaveDir+ try {+ const probe = await probePrecise(downloadPath)+ const tuning = recommend(probe, null)+ return {+ ...settings,+ diskCache: tuning.diskCache,+ split: tuning.split,+ minSplitSize: tuning.minSplitSize,+ }+ } catch (error) {+ log.warn(+ { err: error, downloadPath },+ 'automatic performance probe failed; using profile defaults'+ )+ return settings+ }+ }+/*** HOT-update the aria2 proxy via `aria2.changeGlobalOption`. No-op when* the engine is not Ready (cold start picks up proxy via `buildArgs`).@@ -274,7 +300,10 @@ export class EngineSupervisor {await this.configBuilder.ensureUserConfig()if (this.stopping) return- const engineSettings = this.settingsManager.getEngine()+ const configuredEngineSettings = this.settingsManager.getEngine()+ const engineSettings = await this.resolveRuntimeEngineSettings(+ configuredEngineSettings+ )const proxy = this.settingsManager.getProxy()// Provider is wired by the shell (Task 8) before start() in production;// the { 0, 0 } (unlimited) fallback only fires in tests or if start()diff --git a/src/core/settings/migrations.test.ts b/src/core/settings/migrations.test.tsindex e1eebe67..0610c5e6 100644--- a/src/core/settings/migrations.test.ts+++ b/src/core/settings/migrations.test.ts@@ -87,8 +87,8 @@ describe('migrate', () => {})describe('migration v3 → v4', () => {- it('targets version 8', () => {- expect(CURRENT_SETTINGS_VERSION).toBe(8)+ it('targets version 9', () => {+ expect(CURRENT_SETTINGS_VERSION).toBe(9)})it('adds dhtListenPort defaulting to listenPort value', () => {@@ -175,7 +175,7 @@ describe('migration v5 → v6 (media namespace)', () => {it('migrates v5 → v6 by injecting media defaults', () => {const v5 = { version: 5, engine: {}, app: {} }const out = migrate(v5)- expect(out.version).toBe(8)+ expect(out.version).toBe(9)expect(out.media).toEqual(DEFAULT_MEDIA_SETTINGS)})@@ -198,8 +198,8 @@ describe('migration v5 → v6 (media namespace)', () => {})describe('migration v6 → v7 (speedLimit namespace)', () => {- it('targets version 8', () => {- expect(CURRENT_SETTINGS_VERSION).toBe(8)+ it('targets version 9', () => {+ expect(CURRENT_SETTINGS_VERSION).toBe(9)})it('v6→v7: maps a configured limit to base, turtle off', () => {@@ -210,7 +210,7 @@ describe('migration v6 → v7 (speedLimit namespace)', () => {maxOverallUploadLimit: 256000,},})- expect(result.version).toBe(8)+ expect(result.version).toBe(9)expect((result.engine as Record<string, unknown>).maxOverallDownloadLimit).toBeUndefined()@@ -259,7 +259,7 @@ describe('migration v7 → v8 (application update channel)', () => {it('defaults existing users to stable', () => {const result = migrate({ version: 7, app: { theme: 'dark' } })- expect(result.version).toBe(8)+ expect(result.version).toBe(9)expect(result.app).toEqual({ theme: 'dark', updateChannel: 'stable' })})@@ -278,3 +278,40 @@ describe('migration v7 → v8 (application update channel)', () => {expect(result.app).toEqual({ updateChannel: 'stable' })})})++describe('migration v8 → v9 (performance profiles)', () => {+ it('moves the previous defaults to the automatic profile', () => {+ const result = migrate({+ version: 8,+ engine: {+ maxConnectionPerServer: 16,+ split: 16,+ minSplitSize: 10 * 1024 * 1024,+ diskCache: 64 * 1024 * 1024,+ },+ })++ expect(result.version).toBe(9)+ expect(result.engine).toMatchObject({ performanceProfile: 'auto' })+ })++ it('preserves tuned values through the custom profile', () => {+ const result = migrate({+ version: 8,+ engine: {+ maxConnectionPerServer: 24,+ split: 12,+ minSplitSize: 2 * 1024 * 1024,+ diskCache: 48 * 1024 * 1024,+ },+ })++ expect(result.engine).toMatchObject({+ performanceProfile: 'custom',+ maxConnectionPerServer: 24,+ split: 12,+ minSplitSize: 2 * 1024 * 1024,+ diskCache: 48 * 1024 * 1024,+ })+ })+})diff --git a/src/core/settings/migrations.ts b/src/core/settings/migrations.tsindex a5c5a27c..fe5bc19b 100644--- a/src/core/settings/migrations.ts+++ b/src/core/settings/migrations.ts@@ -1,4 +1,4 @@-export const CURRENT_SETTINGS_VERSION = 8+export const CURRENT_SETTINGS_VERSION = 9interface Migration {version: number@@ -165,6 +165,46 @@ function migrateV7ToV8(data: Record<string, unknown>): Record<string, unknown> {}}+const LEGACY_PERFORMANCE_DEFAULTS = {+ maxConnectionPerServer: 16,+ split: 16,+ minSplitSize: 10 * 1024 * 1024,+ diskCache: 64 * 1024 * 1024,+} as const++function migrateV8ToV9(data: Record<string, unknown>): Record<string, unknown> {+ const engine = (data.engine ?? {}) as Record<string, unknown>+ const performanceKeys = Object.keys(LEGACY_PERFORMANCE_DEFAULTS) as Array<+ keyof typeof LEGACY_PERFORMANCE_DEFAULTS+ >+ const hasPerformanceValues = performanceKeys.some(+ (key) => typeof engine[key] === 'number'+ )+ const matchesLegacyDefaults = performanceKeys.every(+ (key) => engine[key] === LEGACY_PERFORMANCE_DEFAULTS[key]+ )+ const existingProfile = engine.performanceProfile+ const performanceProfile =+ existingProfile === 'auto' ||+ existingProfile === 'balanced' ||+ existingProfile === 'high' ||+ existingProfile === 'maximum' ||+ existingProfile === 'custom'+ ? existingProfile+ : !hasPerformanceValues || matchesLegacyDefaults+ ? 'auto'+ : 'custom'++ return {+ ...data,+ version: 9,+ engine: {+ ...engine,+ performanceProfile,+ },+ }+}+const migrations: Migration[] = [{ version: 1, migrate: migrateV0ToV1 },{ version: 2, migrate: migrateV1ToV2 },@@ -174,6 +214,7 @@ const migrations: Migration[] = [{ version: 6, migrate: migrateV5ToV6 },{ version: 7, migrate: migrateV6ToV7 },{ version: 8, migrate: migrateV7ToV8 },+ { version: 9, migrate: migrateV8ToV9 },]export function migrate(diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.tsindex 9f0c5ef6..26e54198 100644--- a/src/core/settings/settings-manager.test.ts+++ b/src/core/settings/settings-manager.test.ts@@ -400,6 +400,7 @@ describe('SettingsManager', () => {expect(manager.getEngine()).toEqual(expect.objectContaining({+ performanceProfile: 'custom',split: 32,fileAllocation: 'prealloc',diskCache: 32 * 1024 * 1024,@@ -410,6 +411,7 @@ describe('SettingsManager', () => {) as AppSettingsexpect(persisted.engine).toEqual(expect.objectContaining({+ performanceProfile: 'custom',split: 32,fileAllocation: 'prealloc',diskCache: 32 * 1024 * 1024,@@ -417,6 +419,24 @@ describe('SettingsManager', () => {)})+ it('applies every linked value when selecting a performance profile', async () => {+ const result = await manager.update({+ engine: { performanceProfile: 'high' },+ })++ expect(manager.getEngine()).toEqual(+ expect.objectContaining({+ performanceProfile: 'high',+ maxConnectionPerServer: 32,+ split: 32,+ minSplitSize: 4 * 1024 * 1024,+ diskCache: 64 * 1024 * 1024,+ })+ )+ expect(result.requiresRestart).toBe(true)+ expect(result.changedRestartKeys).toContain('diskCache')+ })+it('updates app settings and persists', async () => {const before = manager.get()const result = await manager.update({@@ -600,6 +620,7 @@ describe('SettingsManager', () => {})it('does not flag restart for non-restart keys', async () => {+ await manager.update({ engine: { performanceProfile: 'custom' } })const result = await manager.update({engine: { split: 10, maxConcurrentDownloads: 8 },})diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.tsindex 60136d8d..c33591d2 100644--- a/src/core/settings/settings-manager.ts+++ b/src/core/settings/settings-manager.ts@@ -1,6 +1,7 @@import { mkdir, readFile } from 'node:fs/promises'import os from 'node:os'import path from 'node:path'+import { ENGINE_PERFORMANCE_TUNING_KEYS } from '@shared/constants/engine-performance-profiles'import {APP_RESTART_REQUIRED_KEYS,ENGINE_RESTART_REQUIRED_KEYS,@@ -364,16 +365,19 @@ export class SettingsManager {// Merge engine settingsif (partial.engine) {const merged = { ...next.engine, ...partial.engine }+ if (+ partial.engine.performanceProfile === undefined &&+ ENGINE_PERFORMANCE_TUNING_KEYS.some(+ (key) => partial.engine?.[key] !== undefined+ )+ ) {+ merged.performanceProfile = 'custom'+ }const validated = validateEngineSettings(merged as EngineSettings)// Detect restart-required key changes- for (const key of Object.keys(partial.engine) as Array<- keyof EngineSettings- >) {- if (- ENGINE_RESTART_REQUIRED_KEYS.has(key) &&- validated[key] !== next.engine[key]- ) {+ for (const key of ENGINE_RESTART_REQUIRED_KEYS) {+ if (validated[key] !== next.engine[key]) {changedRestartKeys.push(key)}}diff --git a/src/core/settings/validators.test.ts b/src/core/settings/validators.test.tsindex 7ad4728d..416b9954 100644--- a/src/core/settings/validators.test.ts+++ b/src/core/settings/validators.test.ts@@ -75,10 +75,16 @@ describe('validateEngineSettings', () => {expect(tooHigh.split).toBe(DEFAULT_ENGINE_SETTINGS.split)})- it('clamps maxConnectionPerServer to valid range (1-16)', () => {+ it('clamps maxConnectionPerServer to valid range (1-64)', () => {+ const atLimit = validateEngineSettings({+ ...DEFAULT_ENGINE_SETTINGS,+ maxConnectionPerServer: 64,+ })+ expect(atLimit.maxConnectionPerServer).toBe(64)+const tooHigh = validateEngineSettings({...DEFAULT_ENGINE_SETTINGS,- maxConnectionPerServer: 32,+ maxConnectionPerServer: 65,})expect(tooHigh.maxConnectionPerServer).toBe(DEFAULT_ENGINE_SETTINGS.maxConnectionPerServerdiff --git a/src/core/task/create-task-handler.plugin-hook-e2e.test.ts b/src/core/task/create-task-handler.plugin-hook-e2e.test.tsindex 41a523b6..27347e3b 100644--- a/src/core/task/create-task-handler.plugin-hook-e2e.test.ts+++ b/src/core/task/create-task-handler.plugin-hook-e2e.test.ts@@ -189,7 +189,10 @@ function makeBaseDeps(saveDir: string): Deps & {const adapter = new Aria2Adapter(rpcClient as never)const settingsManager = {getApp: () => ({ defaultSaveDir: saveDir }),- getEngine: () => ({ maxConnectionPerServer: 16 }),+ getEngine: () => ({+ performanceProfile: 'custom',+ maxConnectionPerServer: 16,+ }),} as unknown as Deps['settingsManager']const finalNamePicker = {pick: vi.fn(async (_dir: string, name: string) => name),diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex 0ce01e27..0d95c6aa 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -1,5 +1,6 @@import { initLogger } from '@core/logger'import { AppError, ErrorCode } from '@shared/errors'+import { DEFAULT_ENGINE_SETTINGS } from '@shared/schemas/engine-settings'import type { DownloadTask } from '@shared/types/task'import { TaskType, TransitionPhase } from '@shared/types/task'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -170,7 +171,10 @@ function makeDeps(overrides: DepOverrides = {}): Deps & {getApp: () => ({defaultSaveDir: overrides.defaultSaveDir ?? '/fallback',}),- getEngine: () => ({ maxConnectionPerServer: 16 }),+ getEngine: () => ({+ performanceProfile: DEFAULT_ENGINE_SETTINGS.performanceProfile,+ maxConnectionPerServer: DEFAULT_ENGINE_SETTINGS.maxConnectionPerServer,+ }),} as unknown as Deps['settingsManager']const finalNamePicker = { pick } as unknown as Deps['finalNamePicker']const torrentMetaStore = {@@ -1453,8 +1457,8 @@ describe('characterization: aria2 RPC args', () => {expect(options['all-proxy']).toBeUndefined()})- // (b) HTTP with headers + proxy + connections (clamped to maxConnectionPerServer=16)- it('HTTP full: connections clamped to 16, header array, all-proxy, out=.motrix', async () => {+ // (b) HTTP with headers + proxy + connections (clamped to the engine default)+ it('HTTP full: connections clamped to 64, header array, all-proxy, out=.motrix', async () => {const deps = makeDeps()await handleCreateTask({@@ -1462,7 +1466,7 @@ describe('characterization: aria2 RPC args', () => {uris: ['https://example.com/file.zip'],saveDir: '/dl',filename: 'file.zip',- connections: 64, // clamped to maxConnectionPerServer=16+ connections: 128, // clamped to maxConnectionPerServer=64headers: [{ name: 'Cookie', value: 'a=b' }],proxy: 'http://p:1080',},@@ -1476,9 +1480,9 @@ describe('characterization: aria2 RPC args', () => {expect(uris).toEqual(['https://example.com/file.zip'])expect(options.dir).toBe('/dl')expect(options.out).toBe('file.zip.motrix')- // connections: min(64, 16) = 16, both keys identical string- expect(options.split).toBe('16')- expect(options['max-connection-per-server']).toBe('16')+ // connections: min(128, 64) = 64, both keys identical string+ expect(options.split).toBe('64')+ expect(options['max-connection-per-server']).toBe('64')expect(options.split).toBe(options['max-connection-per-server'])expect(options.header).toEqual(['Cookie: a=b'])expect(options['all-proxy']).toBe('http://p:1080')diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.tsindex 400da2e9..12c45d18 100644--- a/src/core/task/create-task-handler.ts+++ b/src/core/task/create-task-handler.ts@@ -306,6 +306,7 @@ export async function handleCreateTask(// applyPathOverrides HTTP equivalent: dir = saveDir, out = <name>.motrixsaveDir: effectiveSaveDir,filename: `${finalName}${INCOMPLETE_SUFFIX}`,+ performanceProfile: engineSettings.performanceProfile,connections: clampedConnections,headers: headersRecord,proxy: req.proxy,diff --git a/src/renderer/components/ui/toggle-group.tsx b/src/renderer/components/ui/toggle-group.tsxnew file mode 100644index 00000000..918e7b92--- /dev/null+++ b/src/renderer/components/ui/toggle-group.tsx@@ -0,0 +1,41 @@+import { ToggleGroup as ToggleGroupPrimitive } from '@base-ui/react/toggle-group'+import { cn } from '@renderer/lib/utils'+import type { ComponentProps } from 'react'+import { Toggle } from './toggle'++function ToggleGroup<Value extends string>({+ className,+ ...props+}: ToggleGroupPrimitive.Props<Value>) {+ return (+ <ToggleGroupPrimitive+ data-slot="toggle-group"+ className={cn(+ 'flex w-fit items-center gap-0 rounded-lg bg-tab-background p-[3px] text-muted-foreground',+ className+ )}+ {...props}+ />+ )+}++function ToggleGroupItem({+ className,+ ...props+}: ComponentProps<typeof Toggle>) {+ return (+ <Toggle+ data-slot="toggle-group-item"+ size="sm"+ className={cn(+ 'h-7 min-w-0 shrink-0 rounded-md border-0 bg-transparent px-2.5 text-xs shadow-none',+ 'data-pressed:bg-background! data-pressed:text-foreground! data-pressed:shadow-sm',+ 'hover:bg-background/60 hover:text-foreground',+ className+ )}+ {...props}+ />+ )+}++export { ToggleGroup, ToggleGroupItem }diff --git a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx b/src/renderer/routes/settings/cards/downloads-dialog.test.tsxindex cda13337..f18f0038 100644--- a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx@@ -1,8 +1,10 @@import '@renderer/lib/i18n'import '@testing-library/jest-dom/vitest'import { transport } from '@renderer/lib/transport'+import { ENGINE_PERFORMANCE_PROFILES } from '@shared/constants/engine-performance-profiles'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'+import { MAX_CONNECTIONS_PER_SERVER } from '@shared/schemas/engine-settings'import { DEFAULT_SPEED_LIMIT_SETTINGS } from '@shared/schemas/speed-limit'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -33,10 +35,11 @@ if (typeof globalThis.ResizeObserver === 'undefined') {const FIXTURE = {engine: {+ performanceProfile: 'auto',maxConcurrentDownloads: 5,- maxConnectionPerServer: 16,+ maxConnectionPerServer: MAX_CONNECTIONS_PER_SERVER,split: 16,- minSplitSize: 10485760,+ minSplitSize: 4 * 1024 * 1024,userAgent: 'Motrix/2.0',connectTimeout: 30,socketTimeout: 30,@@ -44,7 +47,7 @@ const FIXTURE = {retryWait: 10,lowestSpeedLimit: 0,fileAllocation: 'none',- diskCache: 67108864,+ diskCache: 32 * 1024 * 1024,sessionSaveInterval: 15,magnetResolveTimeout: 120,listenPort: 6881,@@ -103,7 +106,7 @@ describe('<DownloadsDialog>', () => {expect(onClose).toHaveBeenCalled()})- it('saves split, file allocation, and disk cache as explicit user values', async () => {+ it('exposes the Motrix aria2 connection limit in the performance settings', async () => {render(<DownloadsDialogopen@@ -112,28 +115,112 @@ describe('<DownloadsDialog>', () => {descKey="settings.cards.downloads.desc"/>)- await waitFor(() => {- expect(screen.getByLabelText(/split connections per file/i)).toHaveValue(- 16- )++ const user = userEvent.setup()+ await user.click(+ await screen.findByRole('combobox', { name: /performance profile/i })+ )+ await user.click(await screen.findByRole('option', { name: /^custom$/i }))++ const input = screen.getByLabelText(/max connections per server/i)+ expect(input).toHaveValue(MAX_CONNECTIONS_PER_SERVER)+ expect(input).toHaveAttribute('max', String(MAX_CONNECTIONS_PER_SERVER))+ expect(+ screen.getAllByRole('button', {+ name: String(MAX_CONNECTIONS_PER_SERVER),+ }).length+ ).toBeGreaterThan(0)+ })++ it('links the high-speed profile to all performance parameters', async () => {+ render(+ <DownloadsDialog+ open+ onClose={vi.fn()}+ labelKey="settings.cards.downloads.title"+ descKey="settings.cards.downloads.desc"+ />+ )++ const user = userEvent.setup()+ await user.click(+ await screen.findByRole('combobox', { name: /performance profile/i })+ )+ await user.click(+ await screen.findByRole('option', { name: /^high speed$/i })+ )+ expect(screen.getAllByText('32')).toHaveLength(2)+ expect(screen.getByText(/per server/i)).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: /save/i }))+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {+ engine: {+ performanceProfile: 'high',+ maxConnectionPerServer:+ ENGINE_PERFORMANCE_PROFILES.high.maxConnectionPerServer,+ split: ENGINE_PERFORMANCE_PROFILES.high.split,+ diskCache: ENGINE_PERFORMANCE_PROFILES.high.diskCache,+ },})+ })++ it('places custom performance parameters before concurrent downloads', async () => {+ render(+ <DownloadsDialog+ open+ onClose={vi.fn()}+ labelKey="settings.cards.downloads.title"+ descKey="settings.cards.downloads.desc"+ />+ )++ const user = userEvent.setup()+ await user.click(+ await screen.findByRole('combobox', { name: /performance profile/i })+ )+ await user.click(await screen.findByRole('option', { name: /^custom$/i }))++ const customParameters = screen.getByText(/custom performance parameters/i)+ const concurrentDownloads = screen.getByText(/max concurrent downloads/i)+ expect(+ customParameters.compareDocumentPosition(concurrentDownloads) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy()+ })++ it('saves split, file allocation, and disk cache as explicit user values', async () => {+ render(+ <DownloadsDialog+ open+ onClose={vi.fn()}+ labelKey="settings.cards.downloads.title"+ descKey="settings.cards.downloads.desc"+ />+ )+ const user = userEvent.setup()+ await user.click(+ await screen.findByRole('combobox', { name: /performance profile/i })+ )+ await user.click(await screen.findByRole('option', { name: /^custom$/i }))++ expect(screen.getByLabelText(/split connections per file/i)).toHaveValue(16)fireEvent.change(screen.getByLabelText(/split connections per file/i), {target: { value: '32' },})fireEvent.change(screen.getByLabelText(/disk cache/i), {- target: { value: '32' },+ target: { value: '64' },})- const user = userEvent.setup()await user.click(screen.getByRole('combobox', { name: /file allocation/i }))await user.click(await screen.findByRole('option', { name: /^prealloc$/i }))await user.click(screen.getByRole('button', { name: /save/i }))expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {engine: {+ performanceProfile: 'custom',split: 32,fileAllocation: 'prealloc',- diskCache: 32 * 1024 * 1024,+ diskCache: 64 * 1024 * 1024,},})expect(screen.queryByText(/restart to apply changes/i)).toBeNull()@@ -165,6 +252,42 @@ describe('<DownloadsDialog>', () => {).toBeInTheDocument()})+ it('places compact speed limits between performance and reliability', async () => {+ render(+ <DownloadsDialog+ open+ onClose={vi.fn()}+ labelKey="settings.cards.downloads.title"+ descKey="settings.cards.downloads.desc"+ />+ )++ const standard = await screen.findByRole('button', { name: /^standard$/i })+ const performance = screen.getByRole('heading', { name: 'Performance' })+ const speedLimits = screen.getByRole('heading', { name: 'Speed limits' })+ const reliability = screen.getByRole('heading', {+ name: 'Network reliability',+ })+ const follows = (first: Element, second: Element) =>+ Boolean(+ first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING+ )++ expect(follows(performance, speedLimits)).toBe(true)+ expect(follows(speedLimits, reliability)).toBe(true)++ const modeGroup = screen.getByRole('group', { name: 'Current mode' })+ expect(modeGroup).toHaveClass(+ 'gap-0',+ 'rounded-lg',+ 'bg-tab-background',+ 'p-[3px]'+ )+ expect(standard).toHaveAttribute('data-slot', 'toggle-group-item')+ expect(standard).toHaveAttribute('aria-pressed', 'true')+ expect(standard).toHaveClass('h-7', 'text-xs', 'shadow-none')+ })+it('changing the base download limit submits a base patch', async () => {const onClose = vi.fn()render(diff --git a/src/renderer/routes/settings/cards/downloads-dialog.tsx b/src/renderer/routes/settings/cards/downloads-dialog.tsxindex 5161b5c3..390c4e74 100644--- a/src/renderer/routes/settings/cards/downloads-dialog.tsx+++ b/src/renderer/routes/settings/cards/downloads-dialog.tsx@@ -25,11 +25,12 @@ import {ENGINE_DEFAULTS,} from './downloads-form'import { EngineTuningSection } from './engine-tuning-section'+import { PerformanceSection } from './performance-section'import { SpeedLimitSection } from './speed-limit-section'-// Form shape, defaults, and unit constants live in ./downloads-form.ts; the-// engine tuning and speed-limit field groups are rendered by the two section-// components, ProxySection-style (form passed down as a prop).+// Form shape, defaults, and unit constants live in ./downloads-form.ts. The+// compact sections are ordered by user intent: performance, limits, then+// advanced engine behavior.export function DownloadsDialog({open,@@ -94,9 +95,11 @@ export function DownloadsDialog({<div className="min-h-0 flex-1 overflow-y-auto px-6 py-4"><Form {...form}><form className="space-y-4">- <EngineTuningSection form={form} />+ <PerformanceSection form={form} /><Separator className="my-4" /><SpeedLimitSection form={form} />+ <Separator className="my-4" />+ <EngineTuningSection form={form} /></form></Form></div>diff --git a/src/renderer/routes/settings/cards/downloads-form.ts b/src/renderer/routes/settings/cards/downloads-form.tsindex 88d9e878..04ca3562 100644--- a/src/renderer/routes/settings/cards/downloads-form.ts+++ b/src/renderer/routes/settings/cards/downloads-form.ts@@ -11,6 +11,7 @@ import type { EngineSettings, SpeedLimitSettings } from '@shared/types/settings'export type EngineFields = Pick<EngineSettings,+ | 'performanceProfile'| 'maxConcurrentDownloads'| 'maxConnectionPerServer'| 'split'@@ -42,6 +43,7 @@ export const MBPS = 125_000// Defaults are sourced from the schema; the renderer mirrors the subset of// fields it edits. Keep this Pick<> in sync if the schema fields change.export const ENGINE_DEFAULTS: EngineFields = {+ performanceProfile: DEFAULT_ENGINE_SETTINGS.performanceProfile,maxConcurrentDownloads: DEFAULT_ENGINE_SETTINGS.maxConcurrentDownloads,maxConnectionPerServer: DEFAULT_ENGINE_SETTINGS.maxConnectionPerServer,split: DEFAULT_ENGINE_SETTINGS.split,diff --git a/src/renderer/routes/settings/cards/engine-number-setting-row.tsx b/src/renderer/routes/settings/cards/engine-number-setting-row.tsxnew file mode 100644index 00000000..0d2a5ce6--- /dev/null+++ b/src/renderer/routes/settings/cards/engine-number-setting-row.tsx@@ -0,0 +1,90 @@+import { PresetChips } from '@renderer/components/settings-kit/preset-chips'+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+} from '@renderer/components/ui/form'+import { Input } from '@renderer/components/ui/input'+import type { UseFormReturn } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import {+ type DownloadsFields,+ ENGINE_DEFAULTS,+ type EngineFields,+} from './downloads-form'++export interface EngineNumberSettingRowProps {+ form: UseFormReturn<DownloadsFields>+ name: keyof EngineFields+ labelKey: string+ descKey: string+ bounds: { min?: number; max?: number; step?: number; scale?: number }+ presets?: { label: string; value: number }[]+}++// Compact numeric setting row shared by the performance and engine sections.+// `bounds.scale` is the stored-per-displayed multiplier (for example MB).+export function EngineNumberSettingRow({+ form,+ name,+ labelKey,+ descKey,+ bounds,+ presets,+}: EngineNumberSettingRowProps) {+ const { t } = useTranslation()+ const scale = bounds.scale ?? 1+ const scaledPresets = presets?.map((preset) => ({+ ...preset,+ value: preset.value * scale,+ }))++ return (+ <FormField+ control={form.control}+ name={`engine.${name}` as never}+ render={({ field }) => {+ const stored = field.value as number+ const displayed = scale === 1 ? stored : Math.round(stored / scale)+ return (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>{t(labelKey)}</FormLabel>+ <FormDescription className="text-xs">+ {t(descKey)}+ </FormDescription>+ </div>+ <FormControl>+ <Input+ type="number"+ min={bounds.min}+ max={bounds.max}+ step={bounds.step}+ className="h-8 w-28"+ value={displayed}+ onChange={(event) => {+ const value = Number.parseInt(event.target.value, 10)+ field.onChange(+ Number.isFinite(value)+ ? value * scale+ : (ENGINE_DEFAULTS as never)[name]+ )+ }}+ />+ </FormControl>+ </div>+ {scaledPresets && (+ <PresetChips+ name={`engine.${name}`}+ options={scaledPresets as never}+ />+ )}+ </FormItem>+ )+ }}+ />+ )+}diff --git a/src/renderer/routes/settings/cards/engine-tuning-section.tsx b/src/renderer/routes/settings/cards/engine-tuning-section.tsxindex bfd20477..137a84c1 100644--- a/src/renderer/routes/settings/cards/engine-tuning-section.tsx+++ b/src/renderer/routes/settings/cards/engine-tuning-section.tsx@@ -19,16 +19,11 @@ import { Separator } from '@renderer/components/ui/separator'import { BUILTIN_USER_AGENTS } from '@shared/constants/user-agents'import type { UseFormReturn } from 'react-hook-form'import { useTranslation } from 'react-i18next'-import {- type DownloadsFields,- ENGINE_DEFAULTS,- type EngineFields,- KB,- MB,-} from './downloads-form'+import { type DownloadsFields, type EngineFields, KB } from './downloads-form'+import { EngineNumberSettingRow } from './engine-number-setting-row'-// Engine tuning groups of the Downloads dialog: performance, reliability,-// disk, magnet. All fields live under the `engine.*` form namespace.+// Advanced engine groups of the Downloads dialog: reliability, disk, magnet.+// Performance is rendered separately so speed limits can sit directly below it.export function EngineTuningSection({form,}: {@@ -53,128 +48,25 @@ export function EngineTuningSection({label: t('settings.downloads.disk.fileAllocationFalloc'),},] as const-- // Helper to render a numeric form row + optional preset chips.- // `bounds.scale` (default 1) is the stored-per-displayed multiplier:- // 1 — no conversion (counts, seconds)- // KB — displayed KB/s, stored bytes/sec- // MB — displayed MB, stored bytes- // bounds.min / bounds.max are in DISPLAYED units; call sites read naturally.const numericRow = (name: keyof EngineFields,labelKey: string,descKey: string,bounds: { min?: number; max?: number; step?: number; scale?: number },presets?: { label: string; value: number }[]- ) => {- const scale = bounds.scale ?? 1- const scaledPresets = presets?.map((p) => ({- ...p,- value: p.value * scale,- }))- return (- <FormField- control={form.control}- name={`engine.${name}` as never}- render={({ field }) => {- const stored = field.value as number- const displayed = scale === 1 ? stored : Math.round(stored / scale)- return (- <FormItem className="space-y-2">- <div className="flex items-start justify-between gap-4">- <div className="space-y-1">- <FormLabel>{t(labelKey)}</FormLabel>- <FormDescription className="text-xs">- {t(descKey)}- </FormDescription>- </div>- <FormControl>- <Input- type="number"- min={bounds.min}- max={bounds.max}- step={bounds.step}- className="w-28 h-8"- value={displayed}- onChange={(e) => {- const n = Number.parseInt(e.target.value, 10)- field.onChange(- Number.isFinite(n)- ? n * scale- : (ENGINE_DEFAULTS as never)[name]- )- }}- />- </FormControl>- </div>- {scaledPresets && (- <PresetChips- name={`engine.${name}`}- options={scaledPresets as never}- />- )}- </FormItem>- )- }}- />- )- }+ ) => (+ <EngineNumberSettingRow+ form={form}+ name={name}+ labelKey={labelKey}+ descKey={descKey}+ bounds={bounds}+ presets={presets}+ />+ )return (<>- <h3 className="text-sm font-semibold text-foreground">- {t('settings.downloads.performance.title')}- </h3>- {numericRow(- 'maxConcurrentDownloads',- 'settings.downloads.performance.maxConcurrentDownloads',- 'settings.downloads.performance.maxConcurrentDownloadsDesc',- { min: 1, max: 100 },- [- { label: '1', value: 1 },- { label: '3', value: 3 },- { label: '5', value: 5 },- { label: '10', value: 10 },- ]- )}- {numericRow(- 'maxConnectionPerServer',- 'settings.downloads.performance.maxConnectionPerServer',- 'settings.downloads.performance.maxConnectionPerServerDesc',- { min: 1, max: 16 },- [- { label: '1', value: 1 },- { label: '4', value: 4 },- { label: '8', value: 8 },- { label: '16', value: 16 },- ]- )}- {numericRow(- 'split',- 'settings.downloads.performance.split',- 'settings.downloads.performance.splitDesc',- { min: 1, max: 128 },- [- { label: '4', value: 4 },- { label: '8', value: 8 },- { label: '16', value: 16 },- { label: '32', value: 32 },- ]- )}- {numericRow(- 'minSplitSize',- 'settings.downloads.performance.minSplitSize',- 'settings.downloads.performance.minSplitSizeDesc',- { min: 1, scale: MB }, // displayed MB → stored bytes- [- { label: '1 MB', value: 1 },- { label: '10 MB', value: 10 },- { label: '50 MB', value: 50 },- ]- )}-- <Separator className="my-4" />-<h3 className="text-sm font-semibold text-foreground">{t('settings.downloads.reliability.title')}</h3>@@ -296,12 +188,6 @@ export function EngineTuningSection({</FormItem>)}/>- {numericRow(- 'diskCache',- 'settings.downloads.disk.diskCache',- 'settings.downloads.disk.diskCacheDesc',- { min: 0, max: 128, scale: MB } // displayed MB → stored bytes- )}{numericRow('sessionSaveInterval','settings.downloads.disk.sessionSaveInterval',diff --git a/src/renderer/routes/settings/cards/performance-section.tsx b/src/renderer/routes/settings/cards/performance-section.tsxnew file mode 100644index 00000000..0647b6cd--- /dev/null+++ b/src/renderer/routes/settings/cards/performance-section.tsx@@ -0,0 +1,281 @@+import { Badge } from '@renderer/components/ui/badge'+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+} from '@renderer/components/ui/form'+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/components/ui/select'+import {+ ENGINE_PERFORMANCE_PROFILE_IDS,+ type EnginePerformanceProfile,+ getEnginePerformanceProfileValues,+} from '@shared/constants/engine-performance-profiles'+import { MAX_CONNECTIONS_PER_SERVER } from '@shared/schemas/engine-settings'+import {+ DatabaseIcon,+ type LucideIcon,+ RulerIcon,+ ServerIcon,+ SplitIcon,+} from 'lucide-react'+import { type UseFormReturn, useWatch } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { type DownloadsFields, MB } from './downloads-form'+import { EngineNumberSettingRow } from './engine-number-setting-row'++type PerformanceMetric = {+ icon: LucideIcon+ label: string+ value: number | string+}++export function PerformanceSection({+ form,+}: {+ form: UseFormReturn<DownloadsFields>+}) {+ const { t } = useTranslation()+ const performanceProfile = useWatch({+ control: form.control,+ name: 'engine.performanceProfile',+ })+ const performanceProfileOptions = ENGINE_PERFORMANCE_PROFILE_IDS.map(+ (value) => ({+ value,+ label: t(`settings.downloads.performance.profiles.${value}.label`),+ })+ )+ const selectedPerformanceValues =+ getEnginePerformanceProfileValues(performanceProfile)+ const performanceMetrics: PerformanceMetric[] | null =+ selectedPerformanceValues+ ? [+ {+ icon: SplitIcon,+ label: t('settings.downloads.performance.metrics.segments'),+ value: selectedPerformanceValues.split,+ },+ {+ icon: ServerIcon,+ label: t('settings.downloads.performance.metrics.perServer'),+ value: selectedPerformanceValues.maxConnectionPerServer,+ },+ {+ icon: RulerIcon,+ label: t('settings.downloads.performance.metrics.minimum'),+ value: `${Math.round(selectedPerformanceValues.minSplitSize / MB)} MB`,+ },+ {+ icon: DatabaseIcon,+ label: t('settings.downloads.performance.metrics.cache'),+ value: `${Math.round(selectedPerformanceValues.diskCache / MB)} MB`,+ },+ ]+ : null++ const applyPerformanceProfile = (profile: EnginePerformanceProfile) => {+ const values = getEnginePerformanceProfileValues(profile)+ if (!values) return+ form.setValue(+ 'engine.maxConnectionPerServer',+ values.maxConnectionPerServer,+ { shouldDirty: true, shouldValidate: true }+ )+ form.setValue('engine.split', values.split, {+ shouldDirty: true,+ shouldValidate: true,+ })+ form.setValue('engine.minSplitSize', values.minSplitSize, {+ shouldDirty: true,+ shouldValidate: true,+ })+ form.setValue('engine.diskCache', values.diskCache, {+ shouldDirty: true,+ shouldValidate: true,+ })+ }++ return (+ <>+ <h3 className="text-sm font-semibold text-foreground">+ {t('settings.downloads.performance.title')}+ </h3>+ <FormField+ control={form.control}+ name="engine.performanceProfile"+ render={({ field }) => (+ <FormItem className="space-y-2">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t('settings.downloads.performance.profile')}+ </FormLabel>+ <FormDescription className="text-xs">+ {t('settings.downloads.performance.profileDesc')}+ </FormDescription>+ </div>+ <FormControl>+ <Select+ items={performanceProfileOptions}+ value={field.value}+ onValueChange={(value) => {+ if (value === null) return+ const profile = value as EnginePerformanceProfile+ field.onChange(profile)+ applyPerformanceProfile(profile)+ }}+ >+ <SelectTrigger className="w-40" size="sm">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {performanceProfileOptions.map(({ label, value }) => (+ <SelectItem key={value} value={value}>+ {label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </div>++ <div+ className="rounded-md border border-border bg-muted/40 p-3 text-xs text-muted-foreground"+ aria-live="polite"+ aria-atomic="true"+ >+ <div className="flex min-h-5 items-start justify-between gap-3">+ <p className="min-w-0 py-0.5">+ {t(+ `settings.downloads.performance.profiles.${performanceProfile}.desc`+ )}+ </p>+ {performanceProfile === 'auto' && (+ <Badge+ className="h-5 bg-transparent px-1.5 text-[10px] text-muted-foreground"+ variant="outline"+ >+ {t('settings.downloads.performance.baseline')}+ </Badge>+ )}+ </div>+ {performanceMetrics && (+ <div className="mt-2">+ <div className="grid grid-cols-4 overflow-hidden rounded-md border border-border bg-background/70">+ {performanceMetrics.map(({ icon: Icon, label, value }) => (+ <div+ className="flex min-w-0 items-center gap-2 px-2.5 py-2 [&:not(:first-child)]:border-l [&:not(:first-child)]:border-border"+ key={label}+ >+ <Icon+ aria-hidden="true"+ className="size-4 shrink-0 text-muted-foreground"+ />+ <div className="min-w-0 leading-tight">+ <p className="truncate font-semibold tabular-nums text-foreground">+ {value}+ </p>+ <p className="mt-0.5 truncate text-[10px] text-muted-foreground">+ {label}+ </p>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ </FormItem>+ )}+ />++ {performanceProfile === 'custom' && (+ <div className="space-y-4 rounded-md border border-border bg-muted/20 p-3">+ <h4 className="text-xs font-semibold text-foreground">+ {t('settings.downloads.performance.customParameters')}+ </h4>+ <EngineNumberSettingRow+ form={form}+ name="maxConnectionPerServer"+ labelKey="settings.downloads.performance.maxConnectionPerServer"+ descKey="settings.downloads.performance.maxConnectionPerServerDesc"+ bounds={{ min: 1, max: MAX_CONNECTIONS_PER_SERVER }}+ presets={[+ { label: '1', value: 1 },+ { label: '8', value: 8 },+ { label: '16', value: 16 },+ { label: '32', value: 32 },+ {+ label: String(MAX_CONNECTIONS_PER_SERVER),+ value: MAX_CONNECTIONS_PER_SERVER,+ },+ ]}+ />+ <EngineNumberSettingRow+ form={form}+ name="split"+ labelKey="settings.downloads.performance.split"+ descKey="settings.downloads.performance.splitDesc"+ bounds={{ min: 1, max: 128 }}+ presets={[+ { label: '4', value: 4 },+ { label: '16', value: 16 },+ { label: '32', value: 32 },+ { label: '64', value: 64 },+ ]}+ />+ <EngineNumberSettingRow+ form={form}+ name="minSplitSize"+ labelKey="settings.downloads.performance.minSplitSize"+ descKey="settings.downloads.performance.minSplitSizeDesc"+ bounds={{ min: 1, scale: MB }}+ presets={[+ { label: '1 MB', value: 1 },+ { label: '4 MB', value: 4 },+ { label: '10 MB', value: 10 },+ { label: '20 MB', value: 20 },+ ]}+ />+ <EngineNumberSettingRow+ form={form}+ name="diskCache"+ labelKey="settings.downloads.disk.diskCache"+ descKey="settings.downloads.disk.diskCacheDesc"+ bounds={{ min: 0, max: 128, scale: MB }}+ presets={[+ { label: '16 MB', value: 16 },+ { label: '32 MB', value: 32 },+ { label: '64 MB', value: 64 },+ ]}+ />+ </div>+ )}++ <EngineNumberSettingRow+ form={form}+ name="maxConcurrentDownloads"+ labelKey="settings.downloads.performance.maxConcurrentDownloads"+ descKey="settings.downloads.performance.maxConcurrentDownloadsDesc"+ bounds={{ min: 1, max: 100 }}+ presets={[+ { label: '1', value: 1 },+ { label: '3', value: 3 },+ { label: '5', value: 5 },+ { label: '10', value: 10 },+ ]}+ />+ </>+ )+}diff --git a/src/renderer/routes/settings/cards/speed-limit-section.tsx b/src/renderer/routes/settings/cards/speed-limit-section.tsxindex 75c7448a..307ad3ec 100644--- a/src/renderer/routes/settings/cards/speed-limit-section.tsx+++ b/src/renderer/routes/settings/cards/speed-limit-section.tsx@@ -11,6 +11,10 @@ import { Separator } from '@renderer/components/ui/separator'import { Switch } from '@renderer/components/ui/switch'import { toast } from '@renderer/components/ui/toast'import { Toggle } from '@renderer/components/ui/toggle'+import {+ ToggleGroup,+ ToggleGroupItem,+} from '@renderer/components/ui/toggle-group'import { formatBytes } from '@renderer/lib/format'import { transport } from '@renderer/lib/transport'import { Queries } from '@shared/protocol/queries'@@ -421,23 +425,21 @@ export function SpeedLimitSection({</FormDescription></div><FormControl>- <fieldset- className="flex shrink-0 gap-1"+ <ToggleGroup+ className="shrink-0"aria-label={t('settings.downloads.speedLimit.turtle')}+ value={[field.value]}+ onValueChange={(values) => {+ const value = values[0]+ if (value) field.onChange(value)+ }}>{TURTLE_STATES.map((state) => (- <Button- key={state}- type="button"- size="xs"- aria-pressed={field.value === state}- variant={field.value === state ? 'default' : 'outline'}- onClick={() => field.onChange(state)}- >+ <ToggleGroupItem key={state} value={state} type="button">{t(`settings.downloads.speedLimit.turtle_${state}`)}- </Button>+ </ToggleGroupItem>))}- </fieldset>+ </ToggleGroup></FormControl></FormItem>)}diff --git a/src/shared/constants/engine-performance-profiles.ts b/src/shared/constants/engine-performance-profiles.tsnew file mode 100644index 00000000..77528c7a--- /dev/null+++ b/src/shared/constants/engine-performance-profiles.ts@@ -0,0 +1,73 @@+export const MAX_CONNECTIONS_PER_SERVER = 64++export const ENGINE_PERFORMANCE_PROFILE_IDS = [+ 'auto',+ 'balanced',+ 'high',+ 'maximum',+ 'custom',+] as const++export type EnginePerformanceProfile =+ (typeof ENGINE_PERFORMANCE_PROFILE_IDS)[number]++export interface EnginePerformanceTuningValues {+ maxConnectionPerServer: number+ split: number+ minSplitSize: number+ diskCache: number+}++export const ENGINE_PERFORMANCE_TUNING_KEYS = [+ 'maxConnectionPerServer',+ 'split',+ 'minSplitSize',+ 'diskCache',+] as const satisfies readonly (keyof EnginePerformanceTuningValues)[]++const MB = 1024 * 1024++export const ENGINE_PERFORMANCE_PROFILES = {+ auto: {+ maxConnectionPerServer: MAX_CONNECTIONS_PER_SERVER,+ split: 16,+ minSplitSize: 4 * MB,+ diskCache: 32 * MB,+ },+ balanced: {+ maxConnectionPerServer: 16,+ split: 16,+ minSplitSize: 10 * MB,+ diskCache: 32 * MB,+ },+ high: {+ maxConnectionPerServer: 32,+ split: 32,+ minSplitSize: 4 * MB,+ diskCache: 64 * MB,+ },+ maximum: {+ maxConnectionPerServer: MAX_CONNECTIONS_PER_SERVER,+ split: 64,+ minSplitSize: 1 * MB,+ diskCache: 64 * MB,+ },+} as const satisfies Record<+ Exclude<EnginePerformanceProfile, 'custom'>,+ EnginePerformanceTuningValues+>++export function getEnginePerformanceProfileValues(+ profile: EnginePerformanceProfile+): EnginePerformanceTuningValues | null {+ return profile === 'custom' ? null : ENGINE_PERFORMANCE_PROFILES[profile]+}++export function applyEnginePerformanceProfile<+ T extends EnginePerformanceTuningValues & {+ performanceProfile: EnginePerformanceProfile+ },+>(settings: T): T {+ const values = getEnginePerformanceProfileValues(settings.performanceProfile)+ return values ? { ...settings, ...values } : settings+}diff --git a/src/shared/constants/restart-keys.ts b/src/shared/constants/restart-keys.tsindex f327a312..8a2792d9 100644--- a/src/shared/constants/restart-keys.ts+++ b/src/shared/constants/restart-keys.ts@@ -5,6 +5,7 @@ import type { EngineSettings, MotrixAppSettings } from '@shared/types/settings'// proxy / tracker changeGlobalOption.export const ENGINE_RESTART_REQUIRED_KEYS: ReadonlySet<keyof EngineSettings> =new Set([+ 'performanceProfile','rpcPort','rpcSecret','listenPort',diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 57d19c4a..de34fe27 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1119,6 +1119,38 @@"downloads": {"performance": {"title": "Performance",+ "profile": "Performance profile",+ "profileDesc": "Choose how aggressively Motrix downloads.",+ "baseline": "Baseline",+ "metrics": {+ "segments": "Segments",+ "perServer": "Per server",+ "minimum": "Minimum",+ "cache": "Cache"+ },+ "customParameters": "Custom performance parameters",+ "profiles": {+ "auto": {+ "label": "Automatic",+ "desc": "Adjusts performance to your download drive."+ },+ "balanced": {+ "label": "Balanced",+ "desc": "Uses fewer resources for everyday downloads."+ },+ "high": {+ "label": "High speed",+ "desc": "Uses more connections for faster downloads."+ },+ "maximum": {+ "label": "Maximum",+ "desc": "Uses maximum parallelism. Some servers may reject it."+ },+ "custom": {+ "label": "Custom",+ "desc": "Set connections, segments, and cache manually."+ }+ },"maxConcurrentDownloads": "Max concurrent downloads","maxConcurrentDownloadsDesc": "Number of tasks downloading in parallel.","maxConnectionPerServer": "Max connections per server",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 92c23a09..6a3e9055 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1106,6 +1106,38 @@"downloads": {"performance": {"title": "性能",+ "profile": "性能档位",+ "profileDesc": "选择 Motrix 的下载强度。",+ "baseline": "基线",+ "metrics": {+ "segments": "分段",+ "perServer": "单服务器",+ "minimum": "最小分段",+ "cache": "缓存"+ },+ "customParameters": "自定义性能参数",+ "profiles": {+ "auto": {+ "label": "自动",+ "desc": "根据下载磁盘自动调整性能。"+ },+ "balanced": {+ "label": "均衡",+ "desc": "降低资源占用,适合日常下载。"+ },+ "high": {+ "label": "高速",+ "desc": "增加连接数,提升下载速度。"+ },+ "maximum": {+ "label": "极限",+ "desc": "使用最大并发;部分服务器可能拒绝。"+ },+ "custom": {+ "label": "自定义",+ "desc": "手动设置连接、分段和缓存。"+ }+ },"maxConcurrentDownloads": "最大同时下载数","maxConcurrentDownloadsDesc": "同一时刻并行下载的任务数。","maxConnectionPerServer": "单服务器最大连接数",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 68be1da8..397119b7 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1106,6 +1106,38 @@"downloads": {"performance": {"title": "效能",+ "profile": "效能檔位",+ "profileDesc": "選擇 Motrix 的下載強度。",+ "baseline": "基準",+ "metrics": {+ "segments": "分段",+ "perServer": "單一伺服器",+ "minimum": "最小分段",+ "cache": "快取"+ },+ "customParameters": "自訂效能參數",+ "profiles": {+ "auto": {+ "label": "自動",+ "desc": "依下載磁碟自動調整效能。"+ },+ "balanced": {+ "label": "均衡",+ "desc": "降低資源用量,適合日常下載。"+ },+ "high": {+ "label": "高速",+ "desc": "增加連線數,提升下載速度。"+ },+ "maximum": {+ "label": "極限",+ "desc": "使用最大並行;部分伺服器可能拒絕。"+ },+ "custom": {+ "label": "自訂",+ "desc": "手動設定連線、分段和快取。"+ }+ },"maxConcurrentDownloads": "同時下載數量上限","maxConcurrentDownloadsDesc": "可平行下載的任務數量。","maxConnectionPerServer": "每台伺服器的連線數上限",diff --git a/src/shared/schemas/engine-settings.test.ts b/src/shared/schemas/engine-settings.test.tsindex db23e1a6..7ce3ee3b 100644--- a/src/shared/schemas/engine-settings.test.ts+++ b/src/shared/schemas/engine-settings.test.ts@@ -1,9 +1,72 @@import { describe, expect, it } from 'vitest'+import { ENGINE_PERFORMANCE_PROFILES } from '../constants/engine-performance-profiles'import {DEFAULT_ENGINE_SETTINGS,engineSettingsSchema,+ MAX_CONNECTIONS_PER_SERVER,} from './engine-settings'+describe('engineSettingsSchema maxConnectionPerServer', () => {+ it('defaults to the Motrix aria2 connection limit', () => {+ expect(DEFAULT_ENGINE_SETTINGS.maxConnectionPerServer).toBe(+ MAX_CONNECTIONS_PER_SERVER+ )+ })++ it('accepts the maximum supported Motrix value', () => {+ expect(+ engineSettingsSchema.parse({+ maxConnectionPerServer: MAX_CONNECTIONS_PER_SERVER,+ }).maxConnectionPerServer+ ).toBe(MAX_CONNECTIONS_PER_SERVER)+ })++ it('recovers values above the Motrix limit to the default', () => {+ expect(+ engineSettingsSchema.parse({+ maxConnectionPerServer: MAX_CONNECTIONS_PER_SERVER + 1,+ }).maxConnectionPerServer+ ).toBe(MAX_CONNECTIONS_PER_SERVER)+ })+})++describe('engineSettingsSchema performance profiles', () => {+ it('uses automatic performance tuning by default', () => {+ expect(DEFAULT_ENGINE_SETTINGS).toMatchObject({+ performanceProfile: 'auto',+ ...ENGINE_PERFORMANCE_PROFILES.auto,+ })+ })++ it.each(['balanced', 'high', 'maximum'] as const)(+ 'links every tuning value for the %s profile',+ (performanceProfile) => {+ expect(engineSettingsSchema.parse({ performanceProfile })).toMatchObject({+ performanceProfile,+ ...ENGINE_PERFORMANCE_PROFILES[performanceProfile],+ })+ }+ )++ it('preserves individual values in the custom profile', () => {+ expect(+ engineSettingsSchema.parse({+ performanceProfile: 'custom',+ maxConnectionPerServer: 24,+ split: 12,+ minSplitSize: 2 * 1024 * 1024,+ diskCache: 48 * 1024 * 1024,+ })+ ).toMatchObject({+ performanceProfile: 'custom',+ maxConnectionPerServer: 24,+ split: 12,+ minSplitSize: 2 * 1024 * 1024,+ diskCache: 48 * 1024 * 1024,+ })+ })+})+describe('engineSettingsSchema dnsMode', () => {it('defaults to auto', () => {expect(DEFAULT_ENGINE_SETTINGS.dnsMode).toBe('auto')diff --git a/src/shared/schemas/engine-settings.ts b/src/shared/schemas/engine-settings.tsindex 49a7437b..e7c55794 100644--- a/src/shared/schemas/engine-settings.ts+++ b/src/shared/schemas/engine-settings.ts@@ -1,61 +1,86 @@import type { EngineSettings } from '@shared/types/settings'import { z } from 'zod'+import {+ applyEnginePerformanceProfile,+ ENGINE_PERFORMANCE_PROFILE_IDS,+ ENGINE_PERFORMANCE_PROFILES,+ MAX_CONNECTIONS_PER_SERVER,+} from '../constants/engine-performance-profiles'-export const engineSettingsSchema = z.object({- // RPC & engine startup (RESTART)- rpcPort: z.number().int().min(1024).max(65535).catch(16800),- rpcSecret: z.string().catch(''), // sentinel — SettingsManager seeds on first load- listenPort: z.number().int().min(1024).max(65535).catch(6881),- dhtListenPort: z.number().int().min(1024).max(65535).catch(6881),- dhtEnabled: z.boolean().catch(true),-- // Performance (HOT)- maxConcurrentDownloads: z.number().int().min(1).max(100).catch(5),- maxConnectionPerServer: z.number().int().min(1).max(16).catch(16),- split: z.number().int().min(1).max(128).catch(16),- minSplitSize: z.number().min(1048576).catch(10485760),-- // Network reliability (HOT)- userAgent: z.string().catch('Motrix/2.0'),- connectTimeout: z.number().int().min(1).max(600).catch(30),- socketTimeout: z.number().int().min(1).max(600).catch(30),- maxTries: z.number().int().min(0).max(100).catch(5),- retryWait: z.number().int().min(0).max(300).catch(10),- lowestSpeedLimit: z.number().int().min(0).catch(0),- dnsMode: z.enum(['auto', 'system', 'engine']).catch('auto'),-- // BitTorrent (HOT)- btMaxPeers: z.number().int().min(1).max(1000).catch(128),- btEnableLpd: z.boolean().catch(true),- seedRatio: z.number().min(0).max(100).catch(1),- seedTime: z.number().int().min(0).max(525600).catch(60),-- // Disk & session- fileAllocation: z.enum(['none', 'prealloc', 'trunc', 'falloc']).catch('none'),- diskCache: z.number().int().min(0).max(134217728).catch(67108864),- sessionSaveInterval: z.number().int().min(10).max(3600).catch(15),-- // SQLite3 persistence- sqlite3Persistence: z.boolean().catch(true),- sqlite3DbPath: z- .string()- .max(1024)- .refine((p) => !p.includes('\0'), {- message: 'settings.engine.sqlite3DbPath.nullByte',- })- .catch(''),- sqlite3HistoryLimit: z- .number()- .int()- .min(-1, { message: 'settings.engine.sqlite3HistoryLimit.minBound' })- .max(1_000_000, {- message: 'settings.engine.sqlite3HistoryLimit.maxBound',- })- .catch(-1),-- // Magnet (motrix-turbo timer)- magnetResolveTimeout: z.number().int().min(30).max(600).catch(120),-})+export { MAX_CONNECTIONS_PER_SERVER } from '../constants/engine-performance-profiles'++const AUTO_PERFORMANCE = ENGINE_PERFORMANCE_PROFILES.auto++export const engineSettingsSchema = z+ .object({+ // RPC & engine startup (RESTART)+ rpcPort: z.number().int().min(1024).max(65535).catch(16800),+ rpcSecret: z.string().catch(''), // sentinel — SettingsManager seeds on first load+ listenPort: z.number().int().min(1024).max(65535).catch(6881),+ dhtListenPort: z.number().int().min(1024).max(65535).catch(6881),+ dhtEnabled: z.boolean().catch(true),++ // Performance (HOT, except diskCache)+ performanceProfile: z.enum(ENGINE_PERFORMANCE_PROFILE_IDS).catch('auto'),+ maxConcurrentDownloads: z.number().int().min(1).max(100).catch(5),+ maxConnectionPerServer: z+ .number()+ .int()+ .min(1)+ .max(MAX_CONNECTIONS_PER_SERVER)+ .catch(AUTO_PERFORMANCE.maxConnectionPerServer),+ split: z.number().int().min(1).max(128).catch(AUTO_PERFORMANCE.split),+ minSplitSize: z.number().min(1048576).catch(AUTO_PERFORMANCE.minSplitSize),++ // Network reliability (HOT)+ userAgent: z.string().catch('Motrix/2.0'),+ connectTimeout: z.number().int().min(1).max(600).catch(30),+ socketTimeout: z.number().int().min(1).max(600).catch(30),+ maxTries: z.number().int().min(0).max(100).catch(5),+ retryWait: z.number().int().min(0).max(300).catch(10),+ lowestSpeedLimit: z.number().int().min(0).catch(0),+ dnsMode: z.enum(['auto', 'system', 'engine']).catch('auto'),++ // BitTorrent (HOT)+ btMaxPeers: z.number().int().min(1).max(1000).catch(128),+ btEnableLpd: z.boolean().catch(true),+ seedRatio: z.number().min(0).max(100).catch(1),+ seedTime: z.number().int().min(0).max(525600).catch(60),++ // Disk & session+ fileAllocation: z+ .enum(['none', 'prealloc', 'trunc', 'falloc'])+ .catch('none'),+ diskCache: z+ .number()+ .int()+ .min(0)+ .max(134217728)+ .catch(AUTO_PERFORMANCE.diskCache),+ sessionSaveInterval: z.number().int().min(10).max(3600).catch(15),++ // SQLite3 persistence+ sqlite3Persistence: z.boolean().catch(true),+ sqlite3DbPath: z+ .string()+ .max(1024)+ .refine((p) => !p.includes('\0'), {+ message: 'settings.engine.sqlite3DbPath.nullByte',+ })+ .catch(''),+ sqlite3HistoryLimit: z+ .number()+ .int()+ .min(-1, { message: 'settings.engine.sqlite3HistoryLimit.minBound' })+ .max(1_000_000, {+ message: 'settings.engine.sqlite3HistoryLimit.maxBound',+ })+ .catch(-1),++ // Magnet (motrix-turbo timer)+ magnetResolveTimeout: z.number().int().min(30).max(600).catch(120),+ })+ .transform(applyEnginePerformanceProfile)export const DEFAULT_ENGINE_SETTINGS: EngineSettings =engineSettingsSchema.parse({})diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.tsindex a1aea66b..819b2442 100644--- a/src/shared/types/settings.ts+++ b/src/shared/types/settings.ts@@ -1,4 +1,5 @@import type { RunMode } from '../constants'+import type { EnginePerformanceProfile } from '../constants/engine-performance-profiles'import type { SupportedLocale } from '../constants/locales'import type { GeoIPSettings } from './geoip'import type { PluginSettings } from './plugin'@@ -167,7 +168,9 @@ export interface EngineSettings {dhtListenPort: numberdhtEnabled: boolean- // Runtime params (RPC hot-update via changeGlobalOption) — performance+ // Performance profile is resolved at engine start; individual network+ // values remain hot-updatable after entering the custom profile.+ performanceProfile: EnginePerformanceProfilemaxConcurrentDownloads: numbermaxConnectionPerServer: numbersplit: number