A full-featured download manager.
refactor(runtime): isolate host-specific services (#1841)
Dr_rOota1c713ea802f
diff --git a/scripts/check-boundaries.mjs b/scripts/check-boundaries.mjsindex 28908baf..dad2d9b3 100644--- a/scripts/check-boundaries.mjs+++ b/scripts/check-boundaries.mjs@@ -12,6 +12,11 @@ const rules = [pattern: `from ['"]@?fastify`,dir: 'src/core/',},+ {+ label: 'shared must not use Node-specific APIs or globals',+ pattern: `from ['"]node:|require\\(['"]node:|import\\(['"]node:|(^|[^[:alnum:]_$])process\\.|(^|[^[:alnum:]_$])NodeJS\\.`,+ dir: 'src/shared/',+ },{label: 'renderer must not import core or main',pattern: `from ['"][^'"]*(core|main)/`,@@ -27,6 +32,11 @@ const rules = [pattern: `from ['"]@main/|from ['"][^'"]*src/main/`,dir: 'src/server/',},+ {+ label: 'production source must not reference deployment staging contracts',+ pattern: String.raw`(electron|server)-runtime-dependencies\.json|\.motrix-(package|server)-stage\.json|dist/(electron|server)-app`,+ dir: 'src/',+ },{label:'add-task UI must not import transport or protocol commands (except the IPC-aware hook/dialog/form)',diff --git a/scripts/fetch-engine.mjs b/scripts/fetch-engine.mjsindex 6deda690..71ed0784 100644--- a/scripts/fetch-engine.mjs+++ b/scripts/fetch-engine.mjs@@ -7,10 +7,10 @@//// Runs on plain Node 20 with NO loader and NO TypeScript — it is wired into// `postinstall`, which executes before any build tooling exists. The path-// logic below is therefore an INLINE copy of `@shared/platform/aria2.ts`-// (a `.mjs` cannot import the `@shared` alias or a `.ts` source at runtime).-// `tests/scripts/fetch-engine-path-parity.test.ts` guards this copy against-// drift.+// logic below mirrors the host-owned resource layout and the pure binary-name+// rule in `@shared/platform/aria2.ts` (a `.mjs` cannot import the `@shared`+// alias or a `.ts` source at runtime). The path-parity test guards this copy+// against drift.import { spawn, spawnSync } from 'node:child_process'import { createHash, randomBytes } from 'node:crypto'@@ -80,7 +80,7 @@ export function binaryName(platform) {return platform === 'win32' ? 'aria2c.exe' : 'aria2c'}-// INLINE copy of `@shared/platform/aria2.ts::bundledAria2Path` — see header.+// Host-owned resource layout mirror — see file header.export function bundledPath(extraDir, platform, arch) {return path.join(extraDir, platform, arch, binaryName(platform))}diff --git a/src/core/bridge/__tests__/device-code-mdxp.test.ts b/src/core/bridge/__tests__/device-code-mdxp.test.tsindex 0747156b..f907d513 100644--- a/src/core/bridge/__tests__/device-code-mdxp.test.ts+++ b/src/core/bridge/__tests__/device-code-mdxp.test.ts@@ -67,6 +67,7 @@ describe('device-code HTTP endpoints', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'deny', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: 'local',deviceCode,@@ -165,6 +166,7 @@ describe('device-code verificationUri', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'deny', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: 'local',deviceCode: new DeviceCodeService(makeStatefulFakePairing()),@@ -190,6 +192,7 @@ describe('device-code endpoints disabled when no DeviceCodeService', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'deny', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: 'local',})diff --git a/src/core/bridge/__tests__/initialize-handler.test.ts b/src/core/bridge/__tests__/initialize-handler.test.tsindex 0fd6a263..c3bd98f1 100644--- a/src/core/bridge/__tests__/initialize-handler.test.ts+++ b/src/core/bridge/__tests__/initialize-handler.test.ts@@ -6,6 +6,7 @@ import { describe, expect, it, vi } from 'vitest'const baseCapabilities = {motrixVersion: '2.0',+ runtime: 'electron' as const,ffmpegAvailable: true,}@@ -81,6 +82,23 @@ describe('initialize handler', () => {expect(markAuthorized).toHaveBeenCalledOnce()})+ it('reports the runtime injected by the Server composition root', async () => {+ const handler = createInitializeHandler({+ ...baseCapabilities,+ runtime: 'server',+ pairing: { issueToken: vi.fn() } as never,+ registry: { has: () => true } as never,+ onPairRequest: vi.fn(),+ })++ const result = await handler(+ validClientInfo as never,+ makeCtx({ pendingPair: null })+ )++ expect(result.server.runtime).toBe('server')+ })+it('first-pair deny: does NOT authorize the session', async () => {const markAuthorized = vi.fn()const onPairRequest = vi@@ -210,6 +228,7 @@ describe('initialize handler', () => {.mockResolvedValue({ decision: 'allow', addToRegistry: false })const handler = createInitializeHandler({motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: false,pairing: {issueToken: vi.fn().mockResolvedValue({ token: 'tok' }),@@ -230,6 +249,7 @@ describe('initialize handler', () => {.mockResolvedValue({ decision: 'allow', addToRegistry: false })const handler = createInitializeHandler({motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,pairing: {issueToken: vi.fn().mockResolvedValue({ token: 'tok' }),diff --git a/src/core/bridge/__tests__/integration.e2e.test.ts b/src/core/bridge/__tests__/integration.e2e.test.tsindex ab9396a8..837bc1d9 100644--- a/src/core/bridge/__tests__/integration.e2e.test.ts+++ b/src/core/bridge/__tests__/integration.e2e.test.ts@@ -18,6 +18,7 @@ describe('integration: ext ↔ Motrix end-to-end (MDXP spec appendix B.2)', () =registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: 'test-token',})diff --git a/src/core/bridge/__tests__/sse-mdxp.test.ts b/src/core/bridge/__tests__/sse-mdxp.test.tsindex 7f7d47a0..0898bbad 100644--- a/src/core/bridge/__tests__/sse-mdxp.test.ts+++ b/src/core/bridge/__tests__/sse-mdxp.test.ts@@ -89,6 +89,7 @@ describe('SSE GET /mdxp/events', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: LOCAL_TOKEN,})@@ -169,6 +170,7 @@ describe('SSE revocation closes live streams', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: LOCAL_TOKEN,})@@ -262,6 +264,7 @@ describe('SSE rotation on device-code re-pair (end-to-end)', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'deny', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: LOCAL_TOKEN,deviceCode,diff --git a/src/core/bridge/__tests__/unary-mdxp.test.ts b/src/core/bridge/__tests__/unary-mdxp.test.tsindex 35b88ef8..a61a6d4b 100644--- a/src/core/bridge/__tests__/unary-mdxp.test.ts+++ b/src/core/bridge/__tests__/unary-mdxp.test.ts@@ -68,6 +68,7 @@ describe('unary POST /mdxp', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: LOCAL_TOKEN,})@@ -265,6 +266,7 @@ describe('unary POST /mdxp — AppError normalization', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: LOCAL_TOKEN,})@@ -329,6 +331,7 @@ describe('unary POST /mdxp — paired-token auth (device-code)', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'deny', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: LOCAL_TOKEN,})diff --git a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts b/src/core/bridge/__tests__/web-socket-bridge-server.test.tsindex d9973b26..c88565fc 100644--- a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts+++ b/src/core/bridge/__tests__/web-socket-bridge-server.test.ts@@ -34,6 +34,7 @@ describe('WebSocketBridgeServer (JSON-RPC)', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: 'test-token',})@@ -269,6 +270,7 @@ describe('WebSocketBridgeServer.start() bind guard', () => {registry: makeFakeRegistry(),onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken,})@@ -411,6 +413,7 @@ describe('WebSocketBridgeServer – v1 control-plane over WS', () => {} as unknown as TrustedExtensionRegistry,onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '2.0',+ runtime: 'electron',ffmpegAvailable: true,localToken: 'test-token',})diff --git a/src/core/bridge/handlers/initialize-handler.ts b/src/core/bridge/handlers/initialize-handler.tsindex 5e65db8e..6a055b58 100644--- a/src/core/bridge/handlers/initialize-handler.ts+++ b/src/core/bridge/handlers/initialize-handler.ts@@ -11,6 +11,7 @@ import type { PairDecision, PairRequestArgs } from '../web-socket-bridge-server'export interface InitializeHandlerDeps {motrixVersion: string+ runtime: 'electron' | 'server'ffmpegAvailable: booleanpairing: PairingServiceregistry: TrustedExtensionRegistry@@ -105,7 +106,7 @@ function buildResult(server: {name: 'motrix',version: deps.motrixVersion,- runtime: 'electron',+ runtime: deps.runtime,},capabilities: {ffmpegAvailable: deps.ffmpegAvailable,diff --git a/src/core/bridge/web-socket-bridge-server.authz.test.ts b/src/core/bridge/web-socket-bridge-server.authz.test.tsindex 5985a76c..cadf1300 100644--- a/src/core/bridge/web-socket-bridge-server.authz.test.ts+++ b/src/core/bridge/web-socket-bridge-server.authz.test.ts@@ -69,6 +69,7 @@ async function makeServer(): Promise<{registry,onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '0.0.0-test',+ runtime: 'electron',ffmpegAvailable: false,localToken: 'test-local-token',})diff --git a/src/core/bridge/web-socket-bridge-server.stop.test.ts b/src/core/bridge/web-socket-bridge-server.stop.test.tsindex 3fdd124e..04ca45e9 100644--- a/src/core/bridge/web-socket-bridge-server.stop.test.ts+++ b/src/core/bridge/web-socket-bridge-server.stop.test.ts@@ -55,6 +55,7 @@ async function makeServer(): Promise<WebSocketBridgeServer> {registry,onPairRequest: async () => ({ decision: 'allow', addToRegistry: false }),motrixVersion: '0.0.0-test',+ runtime: 'electron',ffmpegAvailable: false,localToken: 'test-local-token',})diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.tsindex c8f1a9ef..40c0a102 100644--- a/src/core/bridge/web-socket-bridge-server.ts+++ b/src/core/bridge/web-socket-bridge-server.ts@@ -61,6 +61,7 @@ export interface BridgeServerOptions {registry: TrustedExtensionRegistryonPairRequest: (args: PairRequestArgs) => Promise<PairDecision>motrixVersion: string+ runtime: 'electron' | 'server'ffmpegAvailable: boolean/*** Machine-owner Bearer token for the unary `POST /mdxp` transport. Generated@@ -169,6 +170,7 @@ export class WebSocketBridgeServer {InitializeParamsSchema,createInitializeHandler({motrixVersion: opts.motrixVersion,+ runtime: opts.runtime,ffmpegAvailable: opts.ffmpegAvailable,pairing: opts.pairing,registry: opts.registry,diff --git a/src/core/ffmpeg/ffmpeg-locator.test.ts b/src/core/ffmpeg/ffmpeg-locator.test.tsindex 2d7dac5f..e08d61a7 100644--- a/src/core/ffmpeg/ffmpeg-locator.test.ts+++ b/src/core/ffmpeg/ffmpeg-locator.test.ts@@ -9,7 +9,12 @@ describe('locateFfmpeg', () => {: { available: false })const r = await locateFfmpeg(- { manualPath: '', userDataBinariesDir: '/x', envPath: undefined },+ {+ manualPath: '',+ userDataBinariesDir: '/x',+ platform: 'linux',+ envPath: null,+ },probe)expect(r.available).toBe(true)@@ -20,7 +25,12 @@ describe('locateFfmpeg', () => {it('reports unavailable when nothing probes', async () => {const probe = vi.fn(async () => ({ available: false }))const r = await locateFfmpeg(- { manualPath: '', userDataBinariesDir: '/x' },+ {+ manualPath: '',+ userDataBinariesDir: '/x',+ platform: 'linux',+ envPath: null,+ },probe)expect(r.available).toBe(false)diff --git a/src/core/plugin/capabilities/app.test.ts b/src/core/plugin/capabilities/app.test.tsindex 4510e4ee..15748ef8 100644--- a/src/core/plugin/capabilities/app.test.ts+++ b/src/core/plugin/capabilities/app.test.ts@@ -1,34 +1,22 @@-import { DEFAULT_LOCALE } from '@shared/constants/locales'-import { afterEach, describe, expect, it } from 'vitest'+import { describe, expect, it } from 'vitest'import { AppCapabilityHost } from './app'-const originalLang = process.env.LANG--afterEach(() => {- if (originalLang === undefined) delete process.env.LANG- else process.env.LANG = originalLang-})--describe('AppCapabilityHost locale', () => {- it('resolves platform locale syntax through the shared catalog', () => {- process.env.LANG = 'zh_CN.UTF-8'-+describe('AppCapabilityHost', () => {+ it('returns the runtime snapshot supplied by the host adapter', () => {const snapshot = new AppCapabilityHost({appVersion: '2.0.0',+ platform: 'linux',runtime: 'server',+ locale: 'zh-CN',+ arch: 'arm64',}).snapshot()- expect(snapshot.locale).toBe('zh-CN')- })-- it('uses the shared default for unsupported environment locales', () => {- process.env.LANG = 'fr_FR.UTF-8'-- const snapshot = new AppCapabilityHost({- appVersion: '2.0.0',+ expect(snapshot).toEqual({+ version: '2.0.0',+ platform: 'linux',runtime: 'server',- }).snapshot()-- expect(snapshot.locale).toBe(DEFAULT_LOCALE)+ locale: 'zh-CN',+ arch: 'arm64',+ })})})diff --git a/src/core/plugin/capabilities/app.ts b/src/core/plugin/capabilities/app.tsindex be57adaf..b11eb90e 100644--- a/src/core/plugin/capabilities/app.ts+++ b/src/core/plugin/capabilities/app.ts@@ -1,9 +1,11 @@-import { resolveSupportedLocale } from '@shared/constants/locales'import type { AppCapabilitySnapshot } from './interface'export interface AppCapabilityHostOptions {appVersion: string+ platform: AppCapabilitySnapshot['platform']runtime: 'electron' | 'server'+ locale: string+ arch: AppCapabilitySnapshot['arch']}export class AppCapabilityHost {@@ -11,10 +13,10 @@ export class AppCapabilityHost {snapshot(): AppCapabilitySnapshot {return {version: this.opts.appVersion,- platform: process.platform as 'darwin' | 'win32' | 'linux',+ platform: this.opts.platform,runtime: this.opts.runtime,- locale: resolveSupportedLocale(process.env.LANG),- arch: process.arch as 'x64' | 'arm64',+ locale: this.opts.locale,+ arch: this.opts.arch,}}}diff --git a/src/core/plugin/capabilities/ffmpeg-detect.test.ts b/src/core/plugin/capabilities/ffmpeg-detect.test.tsindex a1fb006c..591421bf 100644--- a/src/core/plugin/capabilities/ffmpeg-detect.test.ts+++ b/src/core/plugin/capabilities/ffmpeg-detect.test.ts@@ -6,7 +6,7 @@// shell script — overkill for a one-liner regex. The happy-path is covered// when MOTRIX_TEST_FFMPEG is set.-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { describe, expect, it } from 'vitest'import {detectFromCandidates,detectInOrder,@@ -73,18 +73,6 @@ function makeProbe(map: Record<string, FfmpegDetection>) {}describe('detectInOrder', () => {- let originalEnv: string | undefined-- beforeEach(() => {- originalEnv = process.env.MOTRIX_FFMPEG_PATH- delete process.env.MOTRIX_FFMPEG_PATH- })-- afterEach(() => {- if (originalEnv === undefined) delete process.env.MOTRIX_FFMPEG_PATH- else process.env.MOTRIX_FFMPEG_PATH = originalEnv- })-it('manual path wins when present and probes succeed', async () => {const probe = makeProbe({'/u/bin/ffmpeg': {@@ -100,7 +88,12 @@ describe('detectInOrder', () => {},})const r = await detectInOrder(- { manualPath: '/u/bin/ffmpeg', userDataBinariesDir: '/data/binaries' },+ {+ manualPath: '/u/bin/ffmpeg',+ userDataBinariesDir: '/data/binaries',+ platform: 'linux',+ envPath: null,+ },probe)expect(r.active).toEqual({ path: '/u/bin/ffmpeg', version: '6.0.1' })@@ -135,7 +128,12 @@ describe('detectInOrder', () => {},})const r = await detectInOrder(- { manualPath: '', userDataBinariesDir: '/data/binaries' },+ {+ manualPath: '',+ userDataBinariesDir: '/data/binaries',+ platform: 'linux',+ envPath: null,+ },probe)expect(r.active?.path).toBe('/data/binaries/ffmpeg')@@ -147,10 +145,15 @@ describe('detectInOrder', () => {expect(r.candidates[1]).toMatchObject({ kind: 'userData', state: 'active' })})- it('env candidate is unconfigured when both envPath and process env are unset', async () => {+ it('env candidate is unconfigured when the host provides no path', async () => {const probe = makeProbe({})const r = await detectInOrder(- { manualPath: '', userDataBinariesDir: '/data/binaries' },+ {+ manualPath: '',+ userDataBinariesDir: '/data/binaries',+ platform: 'linux',+ envPath: null,+ },probe)expect(r.candidates[2]).toMatchObject({@@ -160,7 +163,7 @@ describe('detectInOrder', () => {})})- it('reads envPath from process.env when not in input', async () => {+ it('uses the environment candidate supplied by the host', async () => {const probe = makeProbe({'/env/ffmpeg': {available: true,@@ -168,9 +171,13 @@ describe('detectInOrder', () => {binaryPath: '/env/ffmpeg',},})- process.env.MOTRIX_FFMPEG_PATH = '/env/ffmpeg'const r = await detectInOrder(- { manualPath: '', userDataBinariesDir: '/data/binaries' },+ {+ manualPath: '',+ userDataBinariesDir: '/data/binaries',+ platform: 'linux',+ envPath: '/env/ffmpeg',+ },probe)expect(r.candidates[2]).toMatchObject({@@ -183,7 +190,12 @@ describe('detectInOrder', () => {it('returns active: null and 4 candidates when all miss', async () => {const probe = makeProbe({})const r = await detectInOrder(- { manualPath: '', userDataBinariesDir: '/data/binaries' },+ {+ manualPath: '',+ userDataBinariesDir: '/data/binaries',+ platform: 'linux',+ envPath: null,+ },probe)expect(r.active).toBeNull()@@ -191,6 +203,24 @@ describe('detectInOrder', () => {expect(r.candidates[0].state).toBe('unconfigured')expect(r.candidates[1].state).toBe('missing')})++ it('derives the Windows userData candidate from the supplied platform', async () => {+ const probe = makeProbe({})+ const r = await detectInOrder(+ {+ manualPath: '',+ userDataBinariesDir: '/data/binaries',+ platform: 'win32',+ envPath: null,+ },+ probe+ )+ expect(r.candidates[1]).toMatchObject({+ kind: 'userData',+ path: '/data/binaries/ffmpeg.exe',+ state: 'missing',+ })+ })})describe('projectActiveToLegacy', () => {diff --git a/src/core/plugin/capabilities/ffmpeg-detect.ts b/src/core/plugin/capabilities/ffmpeg-detect.tsindex 4eb18bb2..36d0f362 100644--- a/src/core/plugin/capabilities/ffmpeg-detect.ts+++ b/src/core/plugin/capabilities/ffmpeg-detect.ts@@ -18,7 +18,6 @@import { spawn } from 'node:child_process'import { existsSync } from 'node:fs'import path from 'node:path'-import process from 'node:process'// ---------------------------------------------------------------------------// Types@@ -132,8 +131,10 @@ export interface FfmpegDetectionInput {manualPath: string/** userData binaries directory (required; the candidate path is derived). */userDataBinariesDir: string- /** Override for MOTRIX_FFMPEG_PATH; defaults to `process.env` lookup. */- envPath?: string+ /** Host platform snapshot used to derive the userData binary name. */+ platform: string+ /** Host-provided environment candidate; `null` means unconfigured. */+ envPath: string | null}export type CandidateKind = 'manual' | 'userData' | 'env' | 'path'@@ -155,8 +156,8 @@ export interface FfmpegDetectionResult {}>}-function ffmpegBinName(): string {- return process.platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'+function ffmpegBinName(platform: string): string {+ return platform === 'win32' ? 'ffmpeg.exe' : 'ffmpeg'}/**@@ -185,13 +186,12 @@ export async function detectInOrder(): Promise<FfmpegDetectionResult> {const userDataCandidate = path.join(input.userDataBinariesDir,- ffmpegBinName()+ ffmpegBinName(input.platform))- const envCandidate = input.envPath ?? process.env.MOTRIX_FFMPEG_PATH ?? nullconst order: Array<{ kind: CandidateKind; path: string | null }> = [{ kind: 'manual', path: input.manualPath || null },{ kind: 'userData', path: userDataCandidate },- { kind: 'env', path: envCandidate },+ { kind: 'env', path: input.envPath },{ kind: 'path', path: 'ffmpeg' },]diff --git a/src/core/plugin/host/capability-bridge.test.ts b/src/core/plugin/host/capability-bridge.test.tsindex 221f130e..cf4a12c9 100644--- a/src/core/plugin/host/capability-bridge.test.ts+++ b/src/core/plugin/host/capability-bridge.test.ts@@ -37,7 +37,13 @@ function makeBridge(opts?: { workerPath?: string }): {const workerPath = opts?.workerPath ?? writeReadyOnlyStubWorker(dir)const logsDir = path.join(dir, 'plugin-logs')const log = new LogCapabilityHost({ pluginLogsDir: logsDir })- const app = new AppCapabilityHost({ appVersion: '2.5.0', runtime: 'server' })+ const app = new AppCapabilityHost({+ appVersion: '2.5.0',+ platform: 'linux',+ runtime: 'server',+ locale: 'en-US',+ arch: 'x64',+ })const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })const capHost: CapabilityHost = {createLog: (id: string) => log.create(id),@@ -97,7 +103,10 @@ describe('CapabilityBridge', () => {const log = new LogCapabilityHost({ pluginLogsDir: logsDir })const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })diff --git a/src/core/plugin/host/e2e.test.ts b/src/core/plugin/host/e2e.test.tsindex 4db7a3c0..9db007c1 100644--- a/src/core/plugin/host/e2e.test.ts+++ b/src/core/plugin/host/e2e.test.ts@@ -49,7 +49,10 @@ describe('Plugin runtime end-to-end (real QuickJS)', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })// Cast: this test only exercises Plan A surfaces; Plan B fields are unused.diff --git a/src/core/plugin/host/orchestrator.e2e.test.ts b/src/core/plugin/host/orchestrator.e2e.test.tsindex b6b09203..883adfd2 100644--- a/src/core/plugin/host/orchestrator.e2e.test.ts+++ b/src/core/plugin/host/orchestrator.e2e.test.ts@@ -47,7 +47,10 @@ function buildCapHost(rootDir: string): CapabilityHost {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })// Plan A surface only: the role-band fixtures call ctx.update which isdiff --git a/src/core/plugin/host/plugin-host.test.ts b/src/core/plugin/host/plugin-host.test.tsindex b5893071..e22b47af 100644--- a/src/core/plugin/host/plugin-host.test.ts+++ b/src/core/plugin/host/plugin-host.test.ts@@ -15,7 +15,20 @@ import type { CapabilityHost } from '../capabilities/interface'import { LogCapabilityHost } from '../capabilities/log'import { PluginRegistry } from '../plugin-registry'import { PluginStateStore } from '../state/plugin-state-store'-import { PluginHost } from './plugin-host'+import { PluginHost, parsePluginIdleDisposeMs } from './plugin-host'++describe('parsePluginIdleDisposeMs', () => {+ it.each([+ [undefined, undefined],+ ['', undefined],+ ['0', undefined],+ ['-1', undefined],+ ['invalid', undefined],+ ['1234', 1234],+ ])('maps %j to %j', (input, expected) => {+ expect(parsePluginIdleDisposeMs(input)).toBe(expected)+ })+})function writeStubWorker(dir: string): string {const file = path.join(dir, 'StubWorker.cjs')@@ -127,7 +140,10 @@ describe('PluginHost', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })// Cast: these tests only exercise Plan A surfaces; Plan B fields are unused.@@ -397,7 +413,10 @@ describe('PluginHost.deactivate — lifecycle wiring', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })capHost = {@@ -623,7 +642,10 @@ describe('PluginHost locale change propagation', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })const capHost = {@@ -689,7 +711,10 @@ describe('PluginHost locale change propagation', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const capHost = {createLog: (id: string) => log.create(id),@@ -742,7 +767,10 @@ describe('PluginHost.activate — ffmpeg snapshot', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })capHost = {@@ -914,7 +942,10 @@ describe('PluginHost.activate — builtin overlay bundle read path', () => {})const app = new AppCapabilityHost({appVersion: '2.5.0',+ platform: 'linux',runtime: 'server',+ locale: 'en-US',+ arch: 'x64',})const i18n = new I18nCapabilityHost({ hostLanguage: 'en-US' })capHost = {diff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.tsindex 6071684a..b6910566 100644--- a/src/core/plugin/host/plugin-host.ts+++ b/src/core/plugin/host/plugin-host.ts@@ -118,12 +118,8 @@ export class PluginHost {constructor(private readonly opts: PluginHostOptions) {this.maxActivePlugins = opts.maxActivePlugins ?? DEFAULT_MAX_ACTIVE_PLUGINS// Spec §7 L2149 — Plugin Active → 5 min no hook/capability/timer activity- // → dispose VM → Inactive. Env override exists for ops tuning (e.g. a- // long-running server with rare hooks may want a higher value).- this.idleDisposeMs =- opts.idleDisposeMs ??- parsePositiveInt(process.env.MOTRIX_PLUGIN_IDLE_DISPOSE_MS) ??- 5 * 60_000+ // → dispose VM → Inactive. Shells may inject an operations override.+ this.idleDisposeMs = opts.idleDisposeMs ?? 5 * 60_000this.activationTimeoutMs = opts.activationTimeoutMs ?? 5_000this.deactivateBudgetMs = opts.deactivateBudgetMs ?? 2_000this.idleTimer = setInterval(() => this.sweepIdle(), 30_000)@@ -572,7 +568,9 @@ export class PluginHost {}}-function parsePositiveInt(raw: string | undefined): number | undefined {+export function parsePluginIdleDisposeMs(+ raw: string | undefined+): number | undefined {if (!raw) return undefinedconst n = Number.parseInt(raw, 10)return Number.isFinite(n) && n > 0 ? n : undefineddiff --git a/src/core/plugin/plugin-registry.test.ts b/src/core/plugin/plugin-registry.test.tsindex 5a4bac41..c4bd4e28 100644--- a/src/core/plugin/plugin-registry.test.ts+++ b/src/core/plugin/plugin-registry.test.ts@@ -34,17 +34,22 @@ describe('PluginRegistry', () => {let store: PluginStateStorelet reg: PluginRegistry- beforeEach(() => {- dir = mkdtempSync(path.join(tmpdir(), 'mreg-'))- const db = new Database(':memory:')- migrate(db)- store = new PluginStateStore(db)- reg = new PluginRegistry({+ function makeRegistry(devPath?: string): PluginRegistry {+ return new PluginRegistry({pluginsDir: path.join(dir, 'community'),builtinDir: path.join(dir, 'builtin'),stateStore: store,hostVersion: '2.5.0',+ devPath,})+ }++ beforeEach(() => {+ dir = mkdtempSync(path.join(tmpdir(), 'mreg-'))+ const db = new Database(':memory:')+ migrate(db)+ store = new PluginStateStore(db)+ reg = makeRegistry()})afterEach(() => {@@ -163,12 +168,6 @@ describe('PluginRegistry', () => {// M7 — MOTRIX_PLUGIN_DEV_PATH bypasses installer / consent (spec §7 L2418)// -------------------------------------------------------------------------describe('MOTRIX_PLUGIN_DEV_PATH', () => {- const ORIGINAL = process.env.MOTRIX_PLUGIN_DEV_PATH- afterEach(() => {- if (ORIGINAL === undefined) delete process.env.MOTRIX_PLUGIN_DEV_PATH- else process.env.MOTRIX_PLUGIN_DEV_PATH = ORIGINAL- })-it('indexes a dev plugin and tags its source as type: "dev"', async () => {const devDir = path.join(dir, 'dev')mkdirSync(path.join(devDir, 'dist'), { recursive: true })@@ -177,7 +176,7 @@ describe('PluginRegistry', () => {JSON.stringify(minimalManifest('alice.dev')))writeFileSync(path.join(devDir, 'dist', 'plugin.js'), 'export default {}')- process.env.MOTRIX_PLUGIN_DEV_PATH = devDir+ reg = makeRegistry(devDir)await reg.discover()const entry = reg.list().find((p) => p.id === 'alice.dev')expect(entry).toBeDefined()@@ -193,7 +192,7 @@ describe('PluginRegistry', () => {JSON.stringify(minimalManifest('alice.dev2')))writeFileSync(path.join(devDir, 'dist', 'plugin.js'), 'export default {}')- process.env.MOTRIX_PLUGIN_DEV_PATH = devDir+ reg = makeRegistry(devDir)await reg.discover()// Dev path bypasses the installer entirely — registry.discover() reads// the manifest directly. The install dir must remain free of host-@@ -603,10 +602,6 @@ describe('PluginRegistry', () => {})describe('MOTRIX_PLUGIN_DEV_PATH', () => {- afterEach(() => {- delete process.env.MOTRIX_PLUGIN_DEV_PATH- })-it('adds a dev plugin from the env-var path', async () => {const devDir = path.join(dir, 'dev-plugin')mkdirSync(path.join(devDir, 'dist'), { recursive: true })@@ -615,7 +610,7 @@ describe('PluginRegistry', () => {JSON.stringify(minimalManifest('dev.plugin')))writeFileSync(path.join(devDir, 'dist', 'plugin.js'), 'export default {}')- process.env.MOTRIX_PLUGIN_DEV_PATH = devDir+ reg = makeRegistry(devDir)await reg.discover()expect(reg.list().map((p) => p.id)).toContain('dev.plugin')})@@ -628,7 +623,7 @@ describe('PluginRegistry', () => {JSON.stringify(minimalManifest('dev.plugin')))writeFileSync(path.join(devDir, 'dist', 'plugin.js'), 'export default {}')- process.env.MOTRIX_PLUGIN_DEV_PATH = devDir+ reg = makeRegistry(devDir)await reg.discover()const indexed = reg.get('dev.plugin')expect(indexed?.rootDir).toBe(devDir)@@ -636,7 +631,7 @@ describe('PluginRegistry', () => {})it('silently skips dev path if manifest is missing', async () => {- process.env.MOTRIX_PLUGIN_DEV_PATH = path.join(dir, 'nonexistent')+ reg = makeRegistry(path.join(dir, 'nonexistent'))await reg.discover()expect(reg.list()).toHaveLength(0)expect(reg.loadErrors()).toHaveLength(0)@@ -646,7 +641,7 @@ describe('PluginRegistry', () => {const devDir = path.join(dir, 'dev-bad')mkdirSync(devDir, { recursive: true })writeFileSync(path.join(devDir, 'motrix-plugin.json'), '{ broken json')- process.env.MOTRIX_PLUGIN_DEV_PATH = devDir+ reg = makeRegistry(devDir)await reg.discover()expect(reg.list()).toHaveLength(0)// Dev-path failures are logged, not pushed to loadErrors().@@ -662,7 +657,7 @@ describe('PluginRegistry', () => {JSON.stringify(minimalManifest('dev.plugin')))writeFileSync(path.join(devDir, 'dist', 'plugin.js'), 'export default {}')- process.env.MOTRIX_PLUGIN_DEV_PATH = devDir+ reg = makeRegistry(devDir)await reg.discover()expect(regdiff --git a/src/core/plugin/plugin-registry.ts b/src/core/plugin/plugin-registry.tsindex a7565e69..1bc7abfb 100644--- a/src/core/plugin/plugin-registry.ts+++ b/src/core/plugin/plugin-registry.ts@@ -44,6 +44,8 @@ export interface PluginRegistryOptions {signingPubkeys?: ReadonlyArray<string>/** Injectable locale reader for deterministic prepare/commit race tests. */readLocaleFile?: (filePath: string) => Promise<string>+ /** Shell-provided plugin development directory; omitted outside dev mode. */+ devPath?: string}export interface IndexedPlugin {@@ -227,7 +229,7 @@ export class PluginRegistry {await this.scanInto(this.opts.builtinDir, 'builtin')if (this.opts.overlayDir) await this.applyOverlay(this.opts.overlayDir)await this.scanInto(this.opts.pluginsDir, 'community')- const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH+ const devPath = this.opts.devPathif (devPath) {try {const raw = await readFile(diff --git a/src/core/plugin/secret-store-libsodium.test.ts b/src/core/plugin/secret-store-libsodium.test.tsindex 98808d91..c8db2fa1 100644--- a/src/core/plugin/secret-store-libsodium.test.ts+++ b/src/core/plugin/secret-store-libsodium.test.ts@@ -7,7 +7,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'import os from 'node:os'import path from 'node:path'import { FailingSecretStore } from '@core/plugin/capabilities/secret-store'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { LibsodiumSecretStore } from './secret-store-libsodium'// Deterministic env seed for tests (64 hex chars = 32 bytes).@@ -38,6 +38,7 @@ describe('LibsodiumSecretStore', () => {})afterEach(() => {+ vi.unstubAllEnvs()rmSync(tmpDir, { recursive: true, force: true })})@@ -53,6 +54,15 @@ describe('LibsodiumSecretStore', () => {expect(store.available()).toBe(false)})+ it('does not read a secret seed from the ambient process environment', async () => {+ vi.stubEnv('MOTRIX_SECRETS_SEED', TEST_SEED)+ const store = await LibsodiumSecretStore.create({+ userDataDir: '/proc/non-existent-dir-that-cannot-be-created',+ envSeed: undefined,+ })+ expect(store).toBeInstanceOf(FailingSecretStore)+ })+// Test 2: create with valid env seed returns LibsodiumSecretStore.it('create with env seed returns LibsodiumSecretStore', async () => {const store = await LibsodiumSecretStore.create({diff --git a/src/core/plugin/secret-store-libsodium.ts b/src/core/plugin/secret-store-libsodium.tsindex 23fa7477..92dd2814 100644--- a/src/core/plugin/secret-store-libsodium.ts+++ b/src/core/plugin/secret-store-libsodium.ts@@ -10,7 +10,7 @@// Token format: "box:<base64(nonce 24 bytes)>:<base64(crypto_secretbox_easy ct)>"//// Key source priority (resolved by static factory LibsodiumSecretStore.create):-// 1. envSeed option or MOTRIX_SECRETS_SEED env var — 64 hex chars (32 bytes)+// 1. shell-provided envSeed option — 64 hex chars (32 bytes)// 2. <userDataDir>/secrets.lockbox file — 32 raw bytes// 3. If userDataDir is writable, generate and write a new lockbox (chmod 0600)// 4. Otherwise return FailingSecretStore (no encrypt/decrypt possible)@@ -40,7 +40,7 @@ const LOCKBOX_FILE = 'secrets.lockbox'export interface LibsodiumSecretStoreOptions {userDataDir: string- /** Optional override for process.env.MOTRIX_SECRETS_SEED (64 hex chars). */+ /** Shell-provided secret seed (64 hex chars); omitted to use the lockbox. */envSeed?: string}@@ -57,7 +57,7 @@ export class LibsodiumSecretStore implements SecretStore {): Promise<LibsodiumSecretStore | FailingSecretStore> {await sodium.ready- const rawSeed = opts.envSeed ?? process.env.MOTRIX_SECRETS_SEED+ const rawSeed = opts.envSeed// Priority 1: env seed (64 hex chars = 32 bytes)if (rawSeed) {diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex 3b0a7dee..e245ab0e 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -562,6 +562,7 @@ export async function bootstrapBridge(args: {pairing,registry,motrixVersion: args.motrixVersion,+ runtime: 'electron',ffmpegAvailable: args.ffmpegAvailable,onPairRequest,localToken,diff --git a/src/main/index.ts b/src/main/index.tsindex b55991ee..6e05e374 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -37,7 +37,10 @@ import { createNotificationOccurrenceConsumer } from '@core/notifications/occurrimport { wireCommandSystem } from '@core/plugin/commands/wire'import { GrantsManager } from '@core/plugin/grants/grants-manager'import { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'-import { PluginHost } from '@core/plugin/host/plugin-host'+import {+ PluginHost,+ parsePluginIdleDisposeMs,+} from '@core/plugin/host/plugin-host'import { PluginInstaller } from '@core/plugin/install/plugin-installer'import { PluginRegistry } from '@core/plugin/plugin-registry'import { RegistryClient } from '@core/plugin/registry/registry-client'@@ -1496,6 +1499,7 @@ async function initializeMainProcess(): Promise<void> {// down) because PluginRegistry needs it immediately for overlay-aware// manifest resolution.const overlayDir = path.join(platform.userDataDir, 'builtin-updates')+ const devPath = process.env.MOTRIX_PLUGIN_DEV_PATHconst pluginRegistry = new PluginRegistry({pluginsDir,builtinDir,@@ -1503,6 +1507,7 @@ async function initializeMainProcess(): Promise<void> {stateStore: pluginStateStore,hostVersion: app.getVersion(),hostLanguage: pluginBootstrapLocale,+ devPath,})await pluginRegistry.discover()if (!mainProcessWork.isAccepting()) return@@ -1549,6 +1554,9 @@ async function initializeMainProcess(): Promise<void> {runtime: 'electron',hostLanguage: resolvedApplicationLocale,pluginGrants,+ idleDisposeMs: parsePluginIdleDisposeMs(+ process.env.MOTRIX_PLUGIN_IDLE_DISPOSE_MS+ ),})pluginHost = activePluginHost// Spec §I30 — real-time grant revocation. On a grants change, deactivate@@ -1591,7 +1599,6 @@ async function initializeMainProcess(): Promise<void> {return}- const devPath = process.env.MOTRIX_PLUGIN_DEV_PATHif (devPath) {runShellAsyncWork('dev watcher start', async () => {const handle = await startDevWatcher(@@ -1950,9 +1957,8 @@ async function initializeMainProcess(): Promise<void> {const ff = await locateFfmpeg({manualPath: settingsManager.getMedia().ffmpegBinaryPath,userDataBinariesDir: ffmpegBinariesDir,- ...(process.env.MOTRIX_FFMPEG_BIN- ? { envPath: process.env.MOTRIX_FFMPEG_BIN }- : {}),+ platform: process.platform,+ envPath: process.env.MOTRIX_FFMPEG_BIN ?? null,})const segmentAria2Client = new Aria2SegmentClient(rpcClient)segmentClient = segmentAria2Clientdiff --git a/src/main/platform/services.ts b/src/main/platform/services.tsindex 65bc03e0..686fe046 100644--- a/src/main/platform/services.ts+++ b/src/main/platform/services.ts@@ -1,5 +1,5 @@import path from 'node:path'-import { bundledAria2Path } from '@shared/platform/aria2'+import { aria2BinaryName } from '@shared/platform/aria2'import { type PlatformServices, RunHost } from '@shared/platform/services'import { app } from 'electron'@@ -24,7 +24,12 @@ export function createElectronPlatformServices(): PlatformServices {host: RunHost.Electron,userDataDir: app.getPath('userData'),extraResourceDir: extraDir,- aria2BinaryPath: bundledAria2Path(extraDir, process.platform, process.arch),+ aria2BinaryPath: path.join(+ extraDir,+ process.platform,+ process.arch,+ aria2BinaryName(process.platform)+ ),isDev,}}diff --git a/src/main/plugin/capability-host.test.ts b/src/main/plugin/capability-host.test.tsindex 51a4dfeb..a6bb97ec 100644--- a/src/main/plugin/capability-host.test.ts+++ b/src/main/plugin/capability-host.test.ts@@ -221,7 +221,12 @@ describe('createElectronCapabilityHost', () => {host.setLocale('zh-CN')expect(changed).toHaveBeenCalledWith('zh-CN')- expect(host.appSnapshot().locale).toBe('zh-CN')+ expect(host.appSnapshot()).toMatchObject({+ runtime: 'electron',+ platform: process.platform,+ arch: process.arch,+ locale: 'zh-CN',+ })expect(host.i18nSnapshot('alice.demo')).toEqual({language: 'zh-CN',dir: 'ltr',diff --git a/src/main/plugin/capability-host.ts b/src/main/plugin/capability-host.tsindex 8fb24d40..1b00d135 100644--- a/src/main/plugin/capability-host.ts+++ b/src/main/plugin/capability-host.ts@@ -70,7 +70,10 @@ export async function createElectronCapabilityHost(})const appCap = new AppCapabilityHost({appVersion: opts.appVersion,+ platform: process.platform as 'darwin' | 'win32' | 'linux',runtime: 'electron',+ locale: opts.hostLanguage,+ arch: process.arch as 'x64' | 'arm64',})const i18nCap = new I18nCapabilityHost({ hostLanguage: opts.hostLanguage })@@ -102,6 +105,7 @@ export async function createElectronCapabilityHost(const notify = new ElectronNotifyHost()const secrets = await LibsodiumSecretStore.create({userDataDir: opts.userDataDir,+ envSeed: process.env.MOTRIX_SECRETS_SEED,})const detectFfmpeg = makeElectronFfmpegDetect({settingsManager: opts.settingsManager,diff --git a/src/main/plugin/ffmpeg-detect-electron.test.ts b/src/main/plugin/ffmpeg-detect-electron.test.tsindex 7bc9528b..7f60415c 100644--- a/src/main/plugin/ffmpeg-detect-electron.test.ts+++ b/src/main/plugin/ffmpeg-detect-electron.test.ts@@ -100,6 +100,22 @@ describe('makeElectronFfmpegDetect', () => {expect(arg.envPath).toBe('/opt/ff')})+ it('passes the Electron host platform and normalizes an unset env path', async () => {+ const { manager } = makeSettingsManager({+ ffmpegBinaryPath: '',+ ffmpegStagingMB: 4096,+ ffmpegOpTimeoutSec: 1800,+ })+ const detect = makeElectronFfmpegDetect({+ settingsManager: manager,+ userDataDir: '/tmp/userdata',+ })+ await detect()+ const arg = mockedDetectInOrder.mock.calls[0][0]+ expect(arg.platform).toBe(process.platform)+ expect(arg.envPath).toBeNull()+ })+it('re-reads settings on each invocation (live SettingsManager read)', async () => {const { manager, setMedia } = makeSettingsManager({ffmpegBinaryPath: '/a',diff --git a/src/main/plugin/ffmpeg-detect-electron.ts b/src/main/plugin/ffmpeg-detect-electron.tsindex c96452a4..e19d5e10 100644--- a/src/main/plugin/ffmpeg-detect-electron.ts+++ b/src/main/plugin/ffmpeg-detect-electron.ts@@ -30,6 +30,7 @@ export function makeElectronFfmpegDetect(detectInOrder({manualPath: opts.settingsManager.get().media.ffmpegBinaryPath,userDataBinariesDir,- envPath: process.env.MOTRIX_FFMPEG_PATH,+ platform: process.platform,+ envPath: process.env.MOTRIX_FFMPEG_PATH ?? null,})}diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.tsindex b8743ec3..44133fcf 100644--- a/src/server/bridge/bootstrap.ts+++ b/src/server/bridge/bootstrap.ts@@ -143,6 +143,7 @@ export async function bootstrapBridgeForServer(// the device-code flow below, approved in the web UI.onPairRequest: async () => ({ decision: 'deny', addToRegistry: false }),motrixVersion: opts.motrixVersion,+ runtime: 'server',ffmpegAvailable: false,localToken,deviceCode,diff --git a/src/server/index.ts b/src/server/index.tsindex 2eee1907..fd674258 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -36,7 +36,10 @@ import { NotificationCenter } from '@core/notifications/notification-center'import { createNotificationOccurrenceConsumer } from '@core/notifications/occurrence-consumer'import { wireCommandSystem } from '@core/plugin/commands/wire'import { ActivationDispatcher } from '@core/plugin/host/activation-dispatcher'-import { PluginHost } from '@core/plugin/host/plugin-host'+import {+ PluginHost,+ parsePluginIdleDisposeMs,+} from '@core/plugin/host/plugin-host'import { PluginRegistry } from '@core/plugin/plugin-registry'import { RegistryClient } from '@core/plugin/registry/registry-client'import { PluginStateStore } from '@core/plugin/state/plugin-state-store'@@ -359,12 +362,14 @@ async function main() {)if (!shellAsyncWork.isAccepting()) returnconst pluginStateStore = new PluginStateStore(db.database)+ const devPath = process.env.MOTRIX_PLUGIN_DEV_PATHconst pluginRegistry = new PluginRegistry({pluginsDir,builtinDir,stateStore: pluginStateStore,hostVersion: process.env.MOTRIX_APP_VERSION ?? '2.0.0',hostLanguage,+ devPath,})await pluginRegistry.discover()if (!shellAsyncWork.isAccepting()) return@@ -404,6 +409,9 @@ async function main() {appVersion: process.env.MOTRIX_APP_VERSION ?? '2.0.0',runtime: 'server',hostLanguage,+ idleDisposeMs: parsePluginIdleDisposeMs(+ process.env.MOTRIX_PLUGIN_IDLE_DISPOSE_MS+ ),})shutdownActions.drainPluginHost = () => pluginHost.shutdown()// Wire Plan D: cross-plugin command safeguards (schema cache + rate limit@@ -420,7 +428,6 @@ async function main() {const pluginActivation = new ActivationDispatcher(pluginRegistry, pluginHost)let devWatcherHandle: { close(): Promise<void> } | null = nullshutdownActions.drainDevWatcher = () => devWatcherHandle?.close()- const devPath = process.env.MOTRIX_PLUGIN_DEV_PATH// ─── Engine + Session ─────────────────────────────────────────const engineSettings = settingsManager.getEngine()diff --git a/src/server/platform/services.ts b/src/server/platform/services.tsindex 889748c6..5792c021 100644--- a/src/server/platform/services.ts+++ b/src/server/platform/services.ts@@ -1,7 +1,7 @@import os from 'node:os'import path from 'node:path'import { fileURLToPath } from 'node:url'-import { bundledAria2Path } from '@shared/platform/aria2'+import { aria2BinaryName } from '@shared/platform/aria2'import type { PlatformServices } from '@shared/platform/services'import { RunHost } from '@shared/platform/services'@@ -49,7 +49,7 @@ function defaultAria2Path(if (platform !== 'darwin' && platform !== 'win32') {return '/usr/bin/aria2c'}- return bundledAria2Path(extraResourceDir, platform, arch)+ return path.join(extraResourceDir, platform, arch, aria2BinaryName(platform))}export function createNodePlatformServices(diff --git a/src/server/plugin/capability-host.test.ts b/src/server/plugin/capability-host.test.tsindex 11b19046..4c364ac2 100644--- a/src/server/plugin/capability-host.test.ts+++ b/src/server/plugin/capability-host.test.ts@@ -212,7 +212,12 @@ describe('createServerCapabilityHost', () => {host.setLocale('zh-CN')expect(changed).toHaveBeenCalledWith('zh-CN')- expect(host.appSnapshot().locale).toBe('zh-CN')+ expect(host.appSnapshot()).toMatchObject({+ runtime: 'server',+ platform: process.platform,+ arch: process.arch,+ locale: 'zh-CN',+ })expect(host.i18nSnapshot('alice.demo')).toEqual({language: 'zh-CN',dir: 'ltr',diff --git a/src/server/plugin/capability-host.ts b/src/server/plugin/capability-host.tsindex e3a46220..d3f7733e 100644--- a/src/server/plugin/capability-host.ts+++ b/src/server/plugin/capability-host.ts@@ -70,7 +70,10 @@ export async function createServerCapabilityHost(})const appCap = new AppCapabilityHost({appVersion: opts.appVersion,+ platform: process.platform as 'darwin' | 'win32' | 'linux',runtime: 'server',+ locale: opts.hostLanguage,+ arch: process.arch as 'x64' | 'arm64',})const i18nCap = new I18nCapabilityHost({ hostLanguage: opts.hostLanguage })@@ -103,6 +106,7 @@ export async function createServerCapabilityHost(// secrets: prefer env seed, fall back to lockbox file, else FailingSecretStoreconst secrets = await LibsodiumSecretStore.create({userDataDir: opts.userDataDir,+ envSeed: process.env.MOTRIX_SECRETS_SEED,})const detectFfmpeg = makeServerFfmpegDetect({settingsManager: opts.settingsManager,diff --git a/src/server/plugin/ffmpeg-detect-server.test.ts b/src/server/plugin/ffmpeg-detect-server.test.tsindex bf72de8e..91942a60 100644--- a/src/server/plugin/ffmpeg-detect-server.test.ts+++ b/src/server/plugin/ffmpeg-detect-server.test.ts@@ -100,6 +100,22 @@ describe('makeServerFfmpegDetect', () => {)})+ it('passes the Server host platform and normalizes an unset env path', async () => {+ const { manager } = makeSettingsManager({+ ffmpegBinaryPath: '',+ ffmpegStagingMB: 4096,+ ffmpegOpTimeoutSec: 1800,+ })+ const detect = makeServerFfmpegDetect({+ settingsManager: manager,+ userDataDir: '/srv/motrix',+ })+ await detect()+ const arg = mockedDetectInOrder.mock.calls[0][0]+ expect(arg.platform).toBe(process.platform)+ expect(arg.envPath).toBeNull()+ })+it('re-reads settings on each invocation (live SettingsManager read)', async () => {const { manager, setMedia } = makeSettingsManager({ffmpegBinaryPath: '/a',diff --git a/src/server/plugin/ffmpeg-detect-server.ts b/src/server/plugin/ffmpeg-detect-server.tsindex 8d014b07..be5a200c 100644--- a/src/server/plugin/ffmpeg-detect-server.ts+++ b/src/server/plugin/ffmpeg-detect-server.ts@@ -28,6 +28,7 @@ export function makeServerFfmpegDetect(detectInOrder({manualPath: opts.settingsManager.get().media.ffmpegBinaryPath,userDataBinariesDir,- envPath: process.env.MOTRIX_FFMPEG_PATH,+ platform: process.platform,+ envPath: process.env.MOTRIX_FFMPEG_PATH ?? null,})}diff --git a/src/shared/platform/aria2.test.ts b/src/shared/platform/aria2.test.tsindex ce349c20..f77cbf36 100644--- a/src/shared/platform/aria2.test.ts+++ b/src/shared/platform/aria2.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { aria2BinaryName, bundledAria2Path } from './aria2'+import { aria2BinaryName } from './aria2'describe('aria2BinaryName', () => {it('returns aria2c.exe on win32', () => {@@ -12,21 +12,3 @@ describe('aria2BinaryName', () => {expect(aria2BinaryName('linux')).toBe('aria2c')})})--describe('bundledAria2Path', () => {- it('joins extraDir/platform/arch/aria2c for darwin', () => {- expect(bundledAria2Path('/fake/extra', 'darwin', 'arm64')).toBe(- '/fake/extra/darwin/arm64/aria2c'- )- })- it('appends .exe suffix for win32', () => {- expect(bundledAria2Path('/fake/extra', 'win32', 'x64')).toBe(- '/fake/extra/win32/x64/aria2c.exe'- )- })- it('joins extraDir/platform/arch/aria2c for linux', () => {- expect(bundledAria2Path('/fake/extra', 'linux', 'x64')).toBe(- '/fake/extra/linux/x64/aria2c'- )- })-})diff --git a/src/shared/platform/aria2.ts b/src/shared/platform/aria2.tsindex ac83e4cb..bdd32f18 100644--- a/src/shared/platform/aria2.ts+++ b/src/shared/platform/aria2.ts@@ -1,13 +1,3 @@-import path from 'node:path'--export function aria2BinaryName(platform: NodeJS.Platform): string {+export function aria2BinaryName(platform: string): string {return platform === 'win32' ? 'aria2c.exe' : 'aria2c'}--export function bundledAria2Path(- extraResourceDir: string,- platform: NodeJS.Platform,- arch: string-): string {- return path.join(extraResourceDir, platform, arch, aria2BinaryName(platform))-}diff --git a/src/test-utils/aria2.ts b/src/test-utils/aria2.tsindex ed54ccd7..70affa38 100644--- a/src/test-utils/aria2.ts+++ b/src/test-utils/aria2.ts@@ -9,7 +9,7 @@import { type ChildProcess, spawn, spawnSync } from 'node:child_process'import { accessSync } from 'node:fs'import path from 'node:path'-import { bundledAria2Path } from '@shared/platform/aria2'+import { aria2BinaryName } from '@shared/platform/aria2'import { Aria2Adapter } from '../core/engine/aria2/aria2-adapter'import { Aria2RpcClient } from '../core/engine/aria2/aria2-rpc-client'import { JsonRpcProtocol } from '../core/engine/aria2/json-rpc-protocol'@@ -38,7 +38,12 @@ export function bundledAria2ExtraDir(): string {}export function resolveBundledAria2(): string {- return bundledAria2Path(EXTRA_DIR, process.platform, process.arch)+ return path.join(+ EXTRA_DIR,+ process.platform,+ process.arch,+ aria2BinaryName(process.platform)+ )}/** Returns true iff the bundled aria2 binary for the current platform exists. */diff --git a/tests/scripts/fetch-engine-path-parity.test.ts b/tests/scripts/fetch-engine-path-parity.test.tsindex d577760a..c316bd96 100644--- a/tests/scripts/fetch-engine-path-parity.test.ts+++ b/tests/scripts/fetch-engine-path-parity.test.ts@@ -1,5 +1,5 @@import path from 'node:path'-import { bundledAria2Path } from '@shared/platform/aria2'+import { aria2BinaryName } from '@shared/platform/aria2'import { describe, expect, it } from 'vitest'// @ts-expect-error — .mjs without typesimport { bundledPath } from '../../scripts/fetch-engine.mjs'@@ -7,7 +7,8 @@ import { bundledPath } from '../../scripts/fetch-engine.mjs'// Anti-drift guard for rev-2 §3.1: fetch-engine.mjs owns an INLINE copy of the// path logic (it must run under bare Node, so it cannot import @shared at// runtime). This test runs under Vitest — where the alias + TS ARE available —-// and asserts the inline copy stays identical to the runtime source of truth.+// and asserts the inline copy stays identical to the host-owned layout plus+// the shared binary-name rule.const MATRIX: Array<[NodeJS.Platform, string]> = [['darwin', 'arm64'],['darwin', 'x64'],@@ -18,12 +19,12 @@ const MATRIX: Array<[NodeJS.Platform, string]> = [['linux', 'arm'],]-describe('fetch-engine inline bundledPath parity with @shared', () => {+describe('fetch-engine inline bundledPath parity with host layout', () => {const extra = path.join('/repo', 'extra')for (const [platform, arch] of MATRIX) {- it(`matches bundledAria2Path for ${platform}/${arch}`, () => {+ it(`matches the host layout for ${platform}/${arch}`, () => {expect(bundledPath(extra, platform, arch)).toBe(- bundledAria2Path(extra, platform, arch)+ path.join(extra, platform, arch, aria2BinaryName(platform)))})}