A full-featured download manager.
perf(memory): bound cached data and release runtime resources (#2428)
Dr_rOotf177f5fb763e
diff --git a/scripts/measure-desktop-memory.mjs b/scripts/measure-desktop-memory.mjsnew file mode 100644index 00000000..6ae2677f--- /dev/null+++ b/scripts/measure-desktop-memory.mjs@@ -0,0 +1,244 @@+import { execFile } from 'node:child_process'+import { createHash } from 'node:crypto'+import {+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises'+import net from 'node:net'+import os from 'node:os'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { parseArgs, promisify } from 'node:util'+import { _electron as electron } from 'playwright'+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations.ts'+import { Queries } from '../src/shared/protocol/queries.ts'++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')+const { values } = parseArgs({+ options: {+ app: { type: 'string', default: ROOT },+ 'settle-ms': { type: 'string', default: '50000' },+ 'interval-ms': { type: 'string', default: '1000' },+ samples: { type: 'string', default: '5' },+ out: {+ type: 'string',+ default: 'output/playwright/manual/desktop-memory/results.json',+ },+ },+})+const settleMs = Number(values['settle-ms'])+const intervalMs = Number(values['interval-ms'])+const samples = Number(values.samples)+if (+ !Number.isInteger(settleMs) ||+ settleMs < 0 ||+ settleMs > 600_000 ||+ !Number.isInteger(intervalMs) ||+ intervalMs < 100 ||+ intervalMs > 60_000 ||+ !Number.isInteger(samples) ||+ samples < 1 ||+ samples > 600+)+ throw new Error('Invalid settle time, interval, or sample count')+const execute = promisify(execFile)+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))++async function freePort() {+ const server = net.createServer()+ await new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', resolve)+ })+ const port = server.address().port+ await new Promise((resolve) => server.close(resolve))+ return port+}++// Electron's metrics omit native children such as aria2 and the finalizer.+// On Linux, sample the whole descendant tree and report incomplete reads+// explicitly; never turn permission failures or exited processes into zero PSS.+async function linuxProcessMemory(mainPid) {+ if (process.platform !== 'linux') return null+ const { stdout } = await execute('ps', ['-e', '-o', 'pid=,ppid='])+ const tree = stdout+ .trim()+ .split('\n')+ .map((line) => {+ const [pid, parent] = line.trim().split(/\s+/).map(Number)+ return { pid, parent }+ })+ const pids = new Set([mainPid])+ for (let changed = true; changed; ) {+ changed = false+ for (const row of tree) {+ if (pids.has(row.parent) && !pids.has(row.pid)) {+ pids.add(row.pid)+ changed = true+ }+ }+ }+ const processes = await Promise.all(+ [...pids].map(async (pid) => {+ try {+ const text = await readFile(`/proc/${pid}/smaps_rollup`, 'utf8')+ const rss = /^Rss:\s+(\d+) kB$/m.exec(text)+ const pss = /^Pss:\s+(\d+) kB$/m.exec(text)+ if (!rss || !pss) throw new Error('Missing RSS/PSS fields')+ return { pid, rssKiB: Number(rss[1]), pssKiB: Number(pss[1]) }+ } catch (error) {+ return { pid, error: error.code ?? error.message }+ }+ })+ )+ const complete = processes.every((entry) => entry.pssKiB !== undefined)+ return {+ complete,+ rssKiB: complete+ ? processes.reduce((sum, entry) => sum + entry.rssKiB, 0)+ : null,+ pssKiB: complete+ ? processes.reduce((sum, entry) => sum + entry.pssKiB, 0)+ : null,+ processes,+ }+}++const destination = path.resolve(values.out)+const appDirectory = path.resolve(values.app)+const mainSha256 = createHash('sha256')+ .update(await readFile(path.join(appDirectory, 'dist/main/index.cjs')))+ .digest('hex')+await mkdir(path.dirname(destination), { recursive: true })+const userData = await realpath(+ await mkdtemp(path.join(os.tmpdir(), 'motrix-memory-'))+)+let application+try {+ await writeFile(+ path.join(userData, 'settings.json'),+ JSON.stringify({+ version: CURRENT_SETTINGS_VERSION,+ onboarding: { disclaimerAccepted: true },+ app: {+ language: 'en-US',+ autofillClipboardLinks: false,+ warnBeforeQuit: false,+ traySpeedometer: false,+ browserBridgeEnabled: false,+ lightweightMode: false,+ },+ tracker: { autoSync: false },+ nat: { enabled: false },+ })+ )+ const launchedAt = Date.now()+ application = await electron.launch({+ args: [appDirectory],+ cwd: userData,+ env: {+ ...process.env,+ NODE_ENV: 'test',+ MOTRIX_USER_DATA: userData,+ MOTRIX_RPC_PORT: String(await freePort()),+ MOTRIX_DEFAULT_SAVE_DIR: path.join(userData, 'downloads'),+ },+ })+ const page = await application.firstWindow()+ await page.waitForFunction(+ async (channel) => {+ try {+ return (await window.motrix.invoke(channel)).state === 'ready'+ } catch {+ return false+ }+ },+ Queries.GetEngineStatus,+ { timeout: 30_000 }+ )+ const engineReadyMs = Date.now() - launchedAt+ console.log(+ `Engine ready; settling for ${settleMs} ms before ${samples} samples`+ )+ await sleep(settleMs)+ const report = {+ schemaVersion: 1,+ mainSha256,+ capturedAt: new Date().toISOString(),+ environment: {+ platform: process.platform,+ arch: process.arch,+ cpu: os.cpus()[0]?.model,+ },+ scenario: {+ profile:+ 'Fresh temporary profile, no tasks, built-in plugins, both renderer windows retained',+ disabled: [+ 'clipboard autofill',+ 'tray speedometer',+ 'browser bridge',+ 'tracker auto-sync',+ 'NAT',+ ],+ measurement:+ 'No forced GC. Main-process Node memory and Electron working sets. Linux additionally includes descendant RSS/PSS from smaps_rollup.',+ limits:+ 'RSS/working-set sums double-count shared pages. macOS/Windows results are not Linux PSS. This development executable loads production bundles; compare packaged release baselines separately.',+ engineReadyMs,+ settleMs,+ intervalMs,+ samples,+ },+ samples: [],+ }+ for (let index = 0; index < samples; index++) {+ if (index) await sleep(intervalMs)+ const snapshot = await application.evaluate(({ app, BrowserWindow }) => {+ const require = process+ .getBuiltinModule('module')+ .createRequire(`${process.cwd()}/memory-probe.cjs`)+ return {+ pid: process.pid,+ versions: {+ app: app.getVersion(),+ electron: process.versions.electron,+ chrome: process.versions.chrome,+ },+ main: process.memoryUsage(),+ electron: app+ .getAppMetrics()+ .map(({ pid, type, memory }) => ({ pid, type, memoryKiB: memory })),+ windows: BrowserWindow.getAllWindows().map((window) => ({+ route: new URL(window.webContents.getURL()).searchParams.get('w'),+ visible: window.isVisible(),+ })),+ // This covers CommonJS startup imports; it is not a complete ESM/worker inventory.+ commonJsWasmPackages: Object.keys(require.cache)+ .filter((file) =>+ /[\\/](libsodium(?:-wrappers)?|@resvg|@jitl)[\\/]/.test(file)+ )+ .map((file) =>+ file.replaceAll('\\', '/').split('node_modules/').at(-1)+ ),+ }+ })+ const linux = await linuxProcessMemory(snapshot.pid)+ report.samples.push({+ elapsedMs: Date.now() - launchedAt,+ ...snapshot,+ linux,+ })+ await writeFile(destination, `${JSON.stringify(report, null, 2)}\n`)+ console.log(+ `Sample ${index + 1}/${samples}: main RSS ${(snapshot.main.rss / 1048576).toFixed(1)} MiB${linux?.complete ? `; process-tree PSS ${(linux.pssKiB / 1024).toFixed(1)} MiB` : ''}`+ )+ }+ console.log(`Report: ${destination}`)+} finally {+ await application?.close().catch(() => {})+ await rm(userData, { recursive: true, force: true })+}diff --git a/src/core/legacy-import/import-service-adversarial.test.ts b/src/core/legacy-import/import-service-adversarial.test.tsindex c158e3c0..1ae8c996 100644--- a/src/core/legacy-import/import-service-adversarial.test.ts+++ b/src/core/legacy-import/import-service-adversarial.test.ts@@ -20,6 +20,7 @@ import {LegacyImportService,type LegacyImportServiceDeps,} from './import-service'+import type { LegacySnapshot } from './source-scanner'const cleanups: Array<() => Promise<void>> = []@@ -102,6 +103,119 @@ async function completed(service: LegacyImportService, runId: string) {afterEach(async () => {for (const cleanup of cleanups.splice(0)) await cleanup()vi.restoreAllMocks()+ vi.useRealTimers()+})++function previewCache(service: LegacyImportService) {+ // Observe ownership directly: GC timing and process RSS are nondeterministic.+ return Reflect.get(service, 'previews') as Map<+ string,+ {+ snapshot: LegacySnapshot | null+ dto: { items: unknown[] }+ }+ >+}++describe('legacy preview memory ownership', () => {+ it('cleans up admission ownership even when persisting its failure report also fails', async () => {+ const f = await fixture()+ const target = f.service as unknown as {+ backup(): Promise<string>+ saveReport(): void+ }+ vi.spyOn(target, 'backup').mockRejectedValueOnce(new Error('backup failed'))+ const reportFailure = new Error('report persistence failed')+ vi.spyOn(target, 'saveReport').mockImplementationOnce(() => {+ throw reportFailure+ })+ await expect(f.service.commit(f.request)).rejects.toBe(reportFailure)+ expect(previewCache(f.service).has(f.preview.previewId)).toBe(false)+ await expect(f.service.scan(f.source.sourceHandle)).resolves.toMatchObject({+ sourceHandle: f.source.sourceHandle,+ })+ })+ it('expires raw snapshots without another scan', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })+ const f = await fixture()+ expect(+ previewCache(f.service).get(f.preview.previewId)?.snapshot+ ).toBeTruthy()+ await vi.advanceTimersByTimeAsync(15 * 60_000 + 1)+ expect(previewCache(f.service).size).toBe(0)+ await expect(f.service.commit(f.request)).rejects.toThrow('expiredPreview')+ })++ it('retires completed snapshots while preserving duplicate commit results', async () => {+ const f = await fixture()+ const run = await f.service.commit(f.request)+ await completed(f.service, run.runId)+ expect(previewCache(f.service).get(f.preview.previewId)).toMatchObject({+ snapshot: null,+ dto: { items: [] },+ })+ expect((await f.service.commit(f.request)).runId).toBe(run.runId)+ f.service.releasePreview(f.preview.previewId)+ expect(previewCache(f.service).size).toBe(0)+ expect((await f.service.retry(run.runId)).runId).toBe(run.runId)+ })++ it('releases cancelled snapshots and retries from the lightweight source index', async () => {+ const f = await fixture(2)+ const run = await f.service.commit(f.request)+ f.service.cancel(run.runId)+ await completed(f.service, run.runId)+ expect(+ previewCache(f.service).get(f.preview.previewId)?.snapshot+ ).toBeNull()+ f.service.releasePreview(f.preview.previewId)+ const retried = await f.service.retry(run.runId)+ expect((await completed(f.service, retried.runId)).imported).toBe(2)+ })++ it('does not interrupt an admitted commit when its UI releases the preview', async () => {+ const f = await fixture()+ const accepting = f.service.commit(f.request)+ f.service.releasePreview(f.preview.previewId)+ const run = await accepting+ expect((await completed(f.service, run.runId)).imported).toBe(1)+ expect(previewCache(f.service).size).toBe(0)+ })++ it('rejects overlapping scans and drains the admitted scan before clearing state', async () => {+ const f = await fixture()+ const scanning = f.service.scan(f.source.sourceHandle)+ await expect(f.service.scan(f.source.sourceHandle)).rejects.toThrow('busy')+ const rejected = expect(scanning).rejects.toThrow('busy')+ await f.service.drain()+ await rejected+ expect(previewCache(f.service).size).toBe(0)+ })++ it('enforces the raw-byte budget before the four-preview count limit', async () => {+ const f = await fixture()+ const original = previewCache(f.service).get(f.preview.previewId)?.snapshot+ expect(original).toBeTruthy()+ const bytes = Buffer.alloc(24 * 1024 * 1024)+ const scanSource = vi+ .spyOn(+ f.service as unknown as {+ scanSource(): Promise<LegacySnapshot>+ },+ 'scanSource'+ )+ .mockImplementation(async () => ({+ ...original!,+ candidates: [],+ files: [{ relativePath: 'fixture', digest: 'fixture', bytes }],+ }))+ const first = await f.service.scan(f.source.sourceHandle)+ await f.service.scan(f.source.sourceHandle)+ await f.service.scan(f.source.sourceHandle)+ expect(previewCache(f.service).has(first.previewId)).toBe(false)+ expect(previewCache(f.service).size).toBe(2)+ scanSource.mockRestore()+ })})describe('legacy import service adversarial acceptance', () => {diff --git a/src/core/legacy-import/import-service.ts b/src/core/legacy-import/import-service.tsindex 299fe55c..e7b51aef 100644--- a/src/core/legacy-import/import-service.ts+++ b/src/core/legacy-import/import-service.ts@@ -48,11 +48,14 @@ export interface LegacyImportServiceDeps {}interface PreviewState {dto: LegacyImportPreview- snapshot: LegacySnapshot+ snapshot: LegacySnapshot | nullcommittedRunId?: string}const PREVIEW_TTL = 15 * 60 * 1000const BATCH_SIZE = 100+const MAX_PREVIEWS = 4+const MAX_PREVIEW_BYTES = 64 * 1024 * 1024+const MAX_RETRY_SOURCES = 32export class LegacyImportService {private sources = new Map<string, LegacySource>()@@ -66,6 +69,12 @@ export class LegacyImportService {private stopMetadataPicker: (() => void) | null = nullprivate draining = falseprivate clock: () => number+ private previewTimer: ReturnType<typeof setTimeout> | null = null+ private scanWork: Promise<LegacyImportPreview> | null = null+ private activePreviewId: string | null = null+ private metadataPreviewId: string | null = null+ private readonly releasedPreviews = new Set<string>()+ private readonly retrySources = new Map<string, string>()constructor(private readonly deps: LegacyImportServiceDeps) {this.clock = deps.now ?? Date.now@@ -154,9 +163,25 @@ export class LegacyImportService {return source.root}- async scan(+ scan(sourceHandle: string): Promise<LegacyImportPreview> {+ if (+ this.draining ||+ this.scanWork ||+ this.activeRun ||+ this.metadataAdmissions.size+ )+ return Promise.reject(this.error('busy'))+ const work = this.scanPreview(sourceHandle).finally(() => {+ if (this.scanWork === work) this.scanWork = null+ })+ this.scanWork = work+ return work+ }++ private async scanPreview(sourceHandle: string,- expectedDigest?: string+ expectedDigest?: string,+ assertAdmissionCurrent?: () => void): Promise<LegacyImportPreview> {if (this.draining) throw this.error('busy')const source = this.sources.get(sourceHandle)@@ -188,6 +213,7 @@ export class LegacyImportService {if (state.dto.sourceHandle === sourceHandle) this.previews.delete(id)}if (this.draining) throw this.error('busy')+ assertAdmissionCurrent?.()if (expectedDigest && snapshot.digest !== expectedDigest)throw this.error('changedSource')const grants = this.metadataGrants.get(sourceHandle)@@ -223,9 +249,12 @@ export class LegacyImportService {} else pendingPaths.push(candidate.outputPath)}}- for (const [id, value] of this.previews)- if (value.dto.expiresAt < this.clock()) this.previews.delete(id)- while (this.previews.size >= 4) {+ this.expirePreviews()+ const incomingBytes = this.snapshotBytes(snapshot)+ while (+ this.previews.size >= MAX_PREVIEWS ||+ this.retainedPreviewBytes() + incomingBytes > MAX_PREVIEW_BYTES+ ) {const oldest = this.previews.keys().next().valueif (!oldest) breakthis.previews.delete(oldest)@@ -240,6 +269,7 @@ export class LegacyImportService {expiresAt: this.clock() + PREVIEW_TTL,}this.previews.set(dto.previewId, { dto, snapshot })+ this.schedulePreviewExpiry()return dto}@@ -247,12 +277,20 @@ export class LegacyImportService {input: unknown,chooseFile: () => Promise<string | null>): Promise<LegacyImportPreview | null> {- if (this.draining || this.activeRun || this.metadataAdmissions.size)+ if (+ this.draining ||+ this.scanWork ||+ this.activeRun ||+ this.metadataAdmissions.size+ )return Promise.reject(this.error('busy'))const admission = this.authorizeMetadataAdmission(input, chooseFile)this.metadataAdmissions.add(admission)void admission- .finally(() => this.metadataAdmissions.delete(admission))+ .finally(() => {+ this.metadataAdmissions.delete(admission)+ this.metadataPreviewId = null+ }).catch(() => {})return admission}@@ -262,7 +300,11 @@ export class LegacyImportService {chooseFile: () => Promise<string | null>): Promise<LegacyImportPreview | null> {const { previewId, itemId } = legacyMetadataRequestSchema.parse(input)+ this.expirePreviews()const preview = this.previews.get(previewId)+ const snapshot = preview?.snapshot+ if (!preview || !snapshot) throw this.error('expiredPreview')+ this.metadataPreviewId = previewIdconst current = () => {if (!preview ||@@ -272,7 +314,7 @@ export class LegacyImportService {throw this.error('expiredPreview')if (this.draining || this.activeRun || preview.committedRunId)throw this.error('busy')- const candidate = preview.snapshot.candidates.find(+ const candidate = snapshot.candidates.find((entry) => entry.item.itemId === itemId)if (@@ -288,11 +330,11 @@ export class LegacyImportService {if (!preview) throw this.error('expiredPreview')const unchanged = async () => {current()- const snapshot = await this.scanSource(preview.snapshot.source)+ const refreshed = await this.scanSource(snapshot.source)current()- if (snapshot.digest !== preview.snapshot.digest)+ if (refreshed.digest !== snapshot.digest)throw this.error('changedSource')- if (snapshot.running) throw this.error('running')+ if (refreshed.running) throw this.error('running')}await unchanged()let selected: string | null@@ -318,7 +360,7 @@ export class LegacyImportService {const trialGrants = new Map(previous)trialGrants.set(candidate.entry.digest, grant)const trial = await scanLegacySource(- preview.snapshot.source,+ snapshot.source,this.deps.isProcessRunning,trialGrants)@@ -332,7 +374,11 @@ export class LegacyImportService {// preview changes until every chosen-file/source check has succeeded.this.metadataGrants.set(preview.dto.sourceHandle, trialGrants)try {- const refreshed = await this.scan(preview.dto.sourceHandle, trial.digest)+ const refreshed = await this.scanPreview(+ preview.dto.sourceHandle,+ trial.digest,+ current+ )for (const [id, state] of this.previews)if (id !== refreshed.previewId &&@@ -370,11 +416,15 @@ export class LegacyImportService {private async commitAdmission(input: unknown): Promise<LegacyImportReport> {const request = legacyCommitRequestSchema.parse(input)+ this.expirePreviews()const preview = this.previews.get(request.previewId)if (!preview || preview.dto.expiresAt < this.clock())throw this.error('expiredPreview')if (preview.committedRunId) return this.getRun(preview.committedRunId)- if (this.activeRun || this.metadataAdmissions.size) throw this.error('busy')+ const snapshot = preview.snapshot+ if (!snapshot) throw this.error('expiredPreview')+ if (this.activeRun || this.scanWork || this.metadataAdmissions.size)+ throw this.error('busy')const ids = new Set(request.itemIds)if (ids.size !== request.itemIds.length ||@@ -389,15 +439,13 @@ export class LegacyImportService {// Lock before the first await: two simultaneous commits cannot pass admission.const runId = randomUUID()this.activeRun = runId+ this.activePreviewId = request.previewIdtry {- const refreshed = await this.scanSource(preview.snapshot.source)- if (refreshed.digest !== preview.snapshot.digest)- throw this.error('changedSource')- if (refreshed.running) throw this.error('running')- const selected = preview.snapshot.candidates.filter((candidate) =>+ await this.assertSnapshotCurrent(snapshot)+ const selected = snapshot.candidates.filter((candidate) =>ids.has(candidate.item.itemId))- this.assertNoConflicts(selected, preview.snapshot.sourceId)+ this.assertNoConflicts(selected, snapshot.sourceId)const report: LegacyImportReport = {runId,stage: 'backing-up',@@ -421,17 +469,14 @@ export class LegacyImportService {).run(runId,- preview.snapshot.sourceId,- preview.snapshot.digest,+ snapshot.sourceId,+ snapshot.digest,JSON.stringify(report),this.clock())- const backup = await this.backup(preview.snapshot, runId)+ const backup = await this.backup(snapshot, runId)// The source and liveness guard must still hold after the potentially slow backup.- const afterBackup = await this.scanSource(preview.snapshot.source)- if (afterBackup.digest !== preview.snapshot.digest)- throw this.error('changedSource')- if (afterBackup.running) throw this.error('running')+ await this.assertSnapshotCurrent(snapshot)report.backupCreated = truereport.stage = 'committing'this.deps.db.database@@ -440,29 +485,38 @@ export class LegacyImportService {).run(backup, JSON.stringify(report), runId)preview.committedRunId = runId- const job = this.runBatches(- preview.snapshot,- selected,- backup,- report- ).finally(() => {- this.activeRun = null- this.runningJobs.delete(runId)- this.cancelled.delete(runId)- })+ this.retrySources.set(runId, preview.dto.sourceHandle)+ while (this.retrySources.size > MAX_RETRY_SOURCES) {+ const oldest = this.retrySources.keys().next().value+ if (oldest) this.retrySources.delete(oldest)+ }+ const job = this.runBatches(snapshot, selected, backup, report).finally(+ () => {+ this.activeRun = null+ this.activePreviewId = null+ this.retirePreview(request.previewId, preview)+ this.runningJobs.delete(runId)+ this.cancelled.delete(runId)+ }+ )this.runningJobs.set(runId, job)void job.catch(() => {})return this.getRun(runId)} catch (error) {- const row = this.deps.db.database- .prepare('SELECT report FROM legacy_import_runs WHERE run_id=?')- .get(runId) as { report: string } | undefined- if (row) {- const report = legacyImportReportSchema.parse(JSON.parse(row.report))- report.stage = 'failed'- this.saveReport(report)+ try {+ const row = this.deps.db.database+ .prepare('SELECT report FROM legacy_import_runs WHERE run_id=?')+ .get(runId) as { report: string } | undefined+ if (row) {+ const report = legacyImportReportSchema.parse(JSON.parse(row.report))+ report.stage = 'failed'+ this.saveReport(report)+ }+ } finally {+ this.activeRun = null+ this.activePreviewId = null+ this.releasePreview(request.previewId)}- this.activeRun = nullthrow error}}@@ -482,31 +536,115 @@ export class LegacyImportService {async drain(): Promise<void> {this.draining = true+ if (this.previewTimer) clearTimeout(this.previewTimer)+ this.previewTimer = nullthis.stopMetadataPicker?.()if (this.activeRun) this.cancelled.add(this.activeRun)// Backup and admission can still hold the database before a batch job exists.// Shutdown must wait for both phases before its caller closes the database.+ await this.scanWork?.catch(() => {})await Promise.allSettled(this.admissions)await Promise.allSettled(this.metadataAdmissions)await Promise.allSettled(this.runningJobs.values())+ this.previews.clear()+ this.sources.clear()+ this.metadataGrants.clear()+ this.retrySources.clear()+ this.releasedPreviews.clear()}async retry(runId: string): Promise<LegacyImportReport> {const report = this.getRun(runId)- const state = [...this.previews.values()].find(- (preview) => preview.committedRunId === runId- )- if (!state) throw this.error('rescanRequired')+ const sourceHandle = this.retrySources.get(runId)+ if (!sourceHandle) throw this.error('rescanRequired')const failed = report.items.filter((item) => item.outcome === 'failed' || item.outcome === 'unprocessed').map((item) => item.itemId)if (!failed.length) return report- const refreshed = await this.scan(state.dto.sourceHandle)+ const refreshed = await this.scan(sourceHandle)return this.commit({ previewId: refreshed.previewId, itemIds: failed })}+ releasePreview(previewId: string): void {+ if (this.activePreviewId === previewId) {+ this.releasedPreviews.add(previewId)+ return+ }+ this.releasedPreviews.delete(previewId)+ this.previews.delete(previewId)+ if (this.metadataPreviewId === previewId) this.stopMetadataPicker?.()+ this.schedulePreviewExpiry()+ }++ private retirePreview(id: string, preview: PreviewState): void {+ if (this.previews.get(id) === preview) {+ if (+ this.releasedPreviews.delete(id) ||+ preview.dto.expiresAt <= this.clock()+ ) {+ this.previews.delete(id)+ } else {+ this.previews.set(id, {+ dto: { ...preview.dto, items: [] },+ snapshot: null,+ committedRunId: preview.committedRunId,+ })+ }+ }+ this.releasedPreviews.delete(id)+ this.schedulePreviewExpiry()+ }++ private snapshotBytes(snapshot: LegacySnapshot): number {+ return snapshot.files.reduce((sum, file) => sum + file.bytes.byteLength, 0)+ }++ private retainedPreviewBytes(): number {+ let bytes = 0+ for (const preview of this.previews.values())+ if (preview.snapshot) bytes += this.snapshotBytes(preview.snapshot)+ return bytes+ }++ private expirePreviews(): void {+ for (const [id, preview] of this.previews) {+ if (+ id !== this.activePreviewId &&+ preview.dto.expiresAt <= this.clock()+ ) {+ this.previews.delete(id)+ if (this.metadataPreviewId === id) this.stopMetadataPicker?.()+ }+ }+ }++ private schedulePreviewExpiry(): void {+ if (this.previewTimer) clearTimeout(this.previewTimer)+ this.previewTimer = null+ if (this.draining) return+ const expiries = [...this.previews]+ .filter(([id]) => id !== this.activePreviewId)+ .map(([, preview]) => preview.dto.expiresAt)+ if (!expiries.length) return+ this.previewTimer = setTimeout(+ () => {+ this.previewTimer = null+ this.expirePreviews()+ this.schedulePreviewExpiry()+ },+ Math.max(1, Math.min(...expiries) - this.clock())+ )+ this.previewTimer.unref?.()+ }++ private async assertSnapshotCurrent(snapshot: LegacySnapshot): Promise<void> {+ const current = await this.scanSource(snapshot.source)+ if (current.digest !== snapshot.digest) throw this.error('changedSource')+ if (current.running) throw this.error('running')+ }+private async runBatches(snapshot: LegacySnapshot,selected: LegacyCandidate[],diff --git a/src/core/legacy-import/metadata-authorization.test.ts b/src/core/legacy-import/metadata-authorization.test.tsindex 8eebeda6..9be557cb 100644--- a/src/core/legacy-import/metadata-authorization.test.ts+++ b/src/core/legacy-import/metadata-authorization.test.ts@@ -289,6 +289,65 @@ describe('exact legacy torrent metadata authorization', () => {expect(f.db.getAllTasks()).toEqual([])})+ it('invalidates a released preview while its picker is pending and ignores a late selection', async () => {+ const f = await fixture()+ let selected!: (file: string) => void+ const choose = vi.fn(+ () =>+ new Promise<string>((resolve) => {+ selected = resolve+ })+ )+ const admission = f.service.authorizeMetadata(f.request, choose)+ await vi.waitFor(() => expect(choose).toHaveBeenCalledOnce())+ f.service.releasePreview(f.preview.previewId)+ await expect(admission).resolves.toBeNull()+ selected(f.metadata)+ const next = await f.service.scan(f.source.sourceHandle)+ expect(+ next.items.find((entry) => entry.itemId === f.request.itemId)?.selectable+ ).toBe(false)+ })++ it('does not publish a replacement preview when released during the final validation scan', async () => {+ const f = await fixture()+ const target = f.service as unknown as {+ scanSource(+ source: Parameters<typeof scanLegacySource>[0]+ ): ReturnType<typeof scanLegacySource>+ }+ const scan = target.scanSource.bind(f.service)+ let scans = 0+ let entered = false+ let resume!: () => void+ const gate = new Promise<void>((resolve) => {+ resume = resolve+ })+ vi.spyOn(target, 'scanSource').mockImplementation(async (source) => {+ if (++scans === 4) {+ entered = true+ await gate+ }+ return scan(source)+ })+ const admission = f.service.authorizeMetadata(+ f.request,+ async () => f.metadata+ )+ await vi.waitFor(() => expect(entered).toBe(true))+ f.service.releasePreview(f.preview.previewId)+ const rejected = expect(admission).rejects.toThrow('expiredPreview')+ resume()+ await rejected+ expect(+ (Reflect.get(f.service, 'previews') as Map<string, unknown>).size+ ).toBe(0)+ const next = await f.service.scan(f.source.sourceHandle)+ expect(+ next.items.find((entry) => entry.itemId === f.request.itemId)?.selectable+ ).toBe(false)+ })+it('rejects concurrent metadata admissions before opening a second picker', async () => {const f = await fixture()let entered = falsediff --git a/src/core/plugin/capabilities/interface.ts b/src/core/plugin/capabilities/interface.tsindex bda76934..672d1b24 100644--- a/src/core/plugin/capabilities/interface.ts+++ b/src/core/plugin/capabilities/interface.ts@@ -64,6 +64,10 @@ export interface CapabilityHost {setLocale(locale: SupportedLocale): voidonLocaleChange(handler: (lang: string) => void): () => voidflush(): Promise<void>+ /** Release a quiesced plugin's diagnostic writer without deleting its history. */+ releaseLog?(pluginId: string): Promise<void>+ /** Close all diagnostic writers during host shutdown. */+ closeLogs?(): Promise<void>// ── Plan B ────────────────────────────────────────────────────────────────/** Shared outbound HTTP host (jar injected per-request by the bridge). */diff --git a/src/core/plugin/capabilities/log-memory.test.ts b/src/core/plugin/capabilities/log-memory.test.tsnew file mode 100644index 00000000..6c79e301--- /dev/null+++ b/src/core/plugin/capabilities/log-memory.test.ts@@ -0,0 +1,276 @@+// @vitest-environment node+import fs from 'node:fs'+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+import {+ LogCapabilityHost,+ PLUGIN_LOG_MAX_BUFFER_BYTES,+ PLUGIN_LOG_MAX_RING_BYTES,+} from './log'++const cleanups: Array<() => Promise<void>> = []+afterEach(async () => {+ vi.restoreAllMocks()+ for (const cleanup of cleanups.splice(0)) await cleanup()+})+async function fixture() {+ const dir = await mkdtemp(path.join(tmpdir(), 'motrix-log-memory-'))+ const host = new LogCapabilityHost({ pluginLogsDir: dir })+ cleanups.push(async () => {+ await host.close()+ await rm(dir, { recursive: true, force: true })+ })+ const records = async () =>+ (await readFile(path.join(dir, 'alice.demo/logs/current.ndjson'), 'utf8'))+ .trim()+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line))+ return { host, records }+}+function state(host: LogCapabilityHost) {+ return (+ Reflect.get(host, 'per') as Map<+ string,+ {+ pendingBytes: number+ pending: unknown[]+ ringBytes: number+ dest?: { destroyed: boolean }+ dropped: number+ }+ >+ ).get('alice.demo')+}++it('does not open a writer for history inspection or capability creation', async () => {+ const { host } = await fixture()+ expect(host.getTail('alice.demo', 100)).toEqual([])+ const cap = host.create('alice.demo')+ await host.flush()+ expect(state(host)?.dest).toBeUndefined()+ cap.info('first write')+ await host.flush()+ expect(state(host)?.dest).toBeDefined()+})++it('bounds delayed-open floods and persists an exact loss summary after recovery', async () => {+ const { host, records } = await fixture()+ const mkdir = fs.promises.mkdir+ let resume!: () => void+ const gate = new Promise<void>((resolve) => {+ resume = resolve+ })+ vi.spyOn(fs.promises, 'mkdir').mockImplementationOnce(async (...args) => {+ await gate+ return mkdir(...args)+ })+ const cap = host.create('alice.demo')+ for (let index = 0; index < 2000; index++)+ cap.info('x'.repeat(4000), { index })+ expect(state(host)?.pendingBytes).toBeLessThanOrEqual(+ PLUGIN_LOG_MAX_BUFFER_BYTES+ )+ expect(state(host)?.pending.length).toBeLessThanOrEqual(512)+ expect(state(host)?.ringBytes).toBeLessThanOrEqual(PLUGIN_LOG_MAX_RING_BYTES)+ expect(state(host)?.dest).toBeUndefined()+ resume()+ await host.flush()+ const rows = await records()+ expect(+ rows.filter((row) => row.index !== undefined).length ++ rows.reduce((sum, row) => sum + (row.droppedEntries ?? 0), 0)+ ).toBe(2000)+ expect(rows.some((row) => row.droppedEntries > 0 && row.level === 40)).toBe(+ true+ )+})++it('bounds writes during clear without resurrecting old records', async () => {+ const { host, records } = await fixture()+ const cap = host.create('alice.demo')+ cap.info('before clear')+ await host.flush()+ const truncate = fs.promises.truncate+ let resume!: () => void+ const gate = new Promise<void>((resolve) => {+ resume = resolve+ })+ const delayed = vi+ .spyOn(fs.promises, 'truncate')+ .mockImplementationOnce(async (...args) => {+ await gate+ return truncate(...args)+ })+ const clearing = host.clear('alice.demo')+ await vi.waitFor(() => expect(delayed).toHaveBeenCalledOnce())+ for (let index = 0; index < 2000; index++)+ cap.info('new'.repeat(1400), { index })+ expect(state(host)?.pendingBytes).toBeLessThanOrEqual(+ PLUGIN_LOG_MAX_BUFFER_BYTES+ )+ resume()+ await clearing+ await host.flush()+ const rows = await records()+ expect(rows.some((row) => row.msg === 'before clear')).toBe(false)+ expect(+ rows.filter((row) => row.index !== undefined).length ++ rows.reduce((sum, row) => sum + (row.droppedEntries ?? 0), 0)+ ).toBe(2000)+})++it('bounds the underlying destination when a write stalls', async () => {+ const { host, records } = await fixture()+ const cap = host.create('alice.demo')+ cap.info('ready')+ await host.flush()+ const write = fs.write+ let resume!: () => void+ vi.spyOn(fs, 'write').mockImplementationOnce((...args: unknown[]) => {+ resume = () => Reflect.apply(write, fs, args)+ return undefined as never+ })+ for (let index = 0; index < 1000; index++)+ cap.info('x'.repeat(8000), { index })+ expect(resume).toBeTypeOf('function')+ expect(state(host)?.dropped).toBeGreaterThan(0)+ expect(state(host)?.pendingBytes).toBe(0)+ resume()+ await host.flush()+ const rows = await records()+ expect(+ rows.filter((row) => row.index !== undefined).length ++ rows.reduce((sum, row) => sum + (row.droppedEntries ?? 0), 0)+ ).toBe(1000)+})++it('closes a writer admitted during opening and prevents stale capabilities from resurrecting it', async () => {+ const { host, records } = await fixture()+ const cap = host.create('alice.demo')+ cap.info('before release')+ const releasing = host.release('alice.demo')+ expect(host.release('alice.demo')).toBe(releasing)+ cap.info('during release')+ await releasing+ cap.info('after release')+ expect(state(host)).toBeUndefined()+ const next = host.create('alice.demo')+ next.info('after reinstall')+ await host.flush()+ expect((await records()).map((row) => row.msg)).toEqual([+ 'before release',+ 'after reinstall',+ ])+})++it('retains a writer after a failed release so durable output can be retried', async () => {+ const { host, records } = await fixture()+ host.create('alice.demo').error('retained')+ await host.flush()+ const error = new Error('fsync failed')+ vi.spyOn(fs, 'fsync').mockImplementationOnce((_fd, callback) => {+ queueMicrotask(() => callback(error))+ })+ await expect(host.release('alice.demo')).rejects.toBe(error)+ expect(state(host)?.dest?.destroyed).toBe(false)+ await host.release('alice.demo')+ expect(state(host)).toBeUndefined()+ expect((await records()).map((row) => row.msg)).toEqual(['retained'])+})++it('retries a transient open failure when releasing a recovered destination', async () => {+ const { host, records } = await fixture()+ vi.spyOn(fs.promises, 'mkdir').mockRejectedValueOnce(+ new Error('temporarily unavailable')+ )+ host.create('alice.demo').info('before open failure')+ await expect(host.flush()).rejects.toThrow('unavailable')+ try {+ await host.release('alice.demo')+ expect(state(host)).toBeUndefined()+ expect((await records()).some((row) => row.droppedEntries === 1)).toBe(true)+ } finally {+ // Keep the pre-fix failure isolated from fixture teardown.+ if (state(host)) await host.clear('alice.demo')+ }+})++it('waits for an in-flight clear before releasing the destination', async () => {+ const { host, records } = await fixture()+ const cap = host.create('alice.demo')+ cap.info('old')+ await host.flush()+ const truncate = fs.promises.truncate+ let resume!: () => void+ const gate = new Promise<void>((resolve) => {+ resume = resolve+ })+ const delayed = vi+ .spyOn(fs.promises, 'truncate')+ .mockImplementationOnce(async (...args) => {+ await gate+ return truncate(...args)+ })+ const clearing = host.clear('alice.demo')+ await vi.waitFor(() => expect(delayed).toHaveBeenCalledOnce())+ cap.info('accepted during clear')+ const releasing = host.release('alice.demo')+ cap.info('stale after retirement')+ expect(state(host)?.dest?.destroyed).toBe(false)+ resume()+ await Promise.all([clearing, releasing])+ expect(state(host)).toBeUndefined()+ expect((await records()).map((row) => row.msg)).toEqual([+ 'accepted during clear',+ ])+})++it('quarantines a destroyed writer after its close reports an error', async () => {+ const { host, records } = await fixture()+ const cap = host.create('alice.demo')+ cap.info('durable before closing')+ await host.flush()+ const close = fs.close+ const failure = new Error('close reported an I/O error')+ vi.spyOn(fs, 'close').mockImplementationOnce((fd, callback) => {+ // A close error does not prove that the old numeric FD is still owned.+ if (!callback) throw new Error('Expected the asynchronous close callback')+ close(fd, (error) => callback(error ?? failure))+ })+ try {+ const releasing = host.release('alice.demo')+ await expect(releasing).rejects.toBe(failure)+ expect(() => cap.info('late write')).not.toThrow()+ expect(host.release('alice.demo')).toBe(releasing)+ await expect(host.clear('alice.demo')).rejects.toThrow('closing')+ expect((await records()).map((row) => row.msg)).toEqual([+ 'durable before closing',+ ])+ } finally {+ // The real descriptor is closed; discard only this quarantined test entry.+ ;(Reflect.get(host, 'per') as Map<string, unknown>).clear()+ }+})++it('bounds a single structured entry and closes all writers at shutdown', async () => {+ const { host, records } = await fixture()+ const cap = host.create('alice.demo')+ cap.info(+ 'large fields',+ Object.fromEntries(+ Array.from({ length: 50 }, (_, i) => [`field${i}`, 'x'.repeat(8000)])+ )+ )+ expect(host.getTail('alice.demo', 1)[0]).toMatchObject({+ fieldsTruncated: true,+ })+ const shutdown = host.close()+ cap.info('late shutdown write')+ await shutdown+ host.create('alice.demo').info('must not reopen')+ expect(state(host)).toBeUndefined()+ expect((await records()).map((row) => row.msg)).toEqual(['large fields'])+})diff --git a/src/core/plugin/capabilities/log.ts b/src/core/plugin/capabilities/log.tsindex 72c8eeb1..44d99e67 100644--- a/src/core/plugin/capabilities/log.ts+++ b/src/core/plugin/capabilities/log.ts@@ -16,47 +16,66 @@ import pino, { type DestinationStream, type Logger } from 'pino'import type { LogEntry, PluginLogCapability } from './interface'import { readPluginLogTail } from './log-history'+export const PLUGIN_LOG_MAX_BUFFER_BYTES = 1024 * 1024+export const PLUGIN_LOG_MAX_ENTRY_BYTES = 64 * 1024+export const PLUGIN_LOG_MAX_RING_BYTES = 512 * 1024+const MAX_PENDING_ENTRIES = 512+export interface LogCapabilityHostOptions {pluginLogsDir: stringringSize?: number}-export type LogStreamListener = (pluginId: string, entry: LogEntry) => voidtype LogDestination = ReturnType<typeof pino.destination>-interface Per {logger?: Loggerdest?: LogDestination- /**- * Resolves `true` once the destination owns a file descriptor, `false` if it- * failed to get one. Directory creation and opening are asynchronous;- * early entries wait until the destination has an owned descriptor.- */- opened: Promise<boolean>- retryOpen?: () => Promise<boolean>+ opened?: Promise<boolean>ring: LogEntry[]+ ringBytes: numberverboseUntil: number | nullclearing?: Promise<void>- queuedWrites: Array<() => void>+ clearThrough?: number+ pending: Array<{ data: string; sequence: number }>+ pendingBytes: numbersequence: number- openingWrites: Array<() => void>unavailable: boolean+ dropped: number+ reportingDrop: boolean+ markerRejected: boolean+ retiring: boolean+ retired: boolean+ destinationClosed: boolean+ releasing?: Promise<void>+}++function entryBytes(entry: LogEntry): number {+ return Buffer.byteLength(JSON.stringify(entry), 'utf8')+}++function boundEntry(entry: LogEntry): LogEntry {+ // Leave room for the serializer's host metadata. Oversized structured fields+ // are diagnostic only; never retain their original object in a write closure.+ if (entryBytes(entry) <= PLUGIN_LOG_MAX_ENTRY_BYTES - 1024) return entry+ return {+ entryId: entry.entryId,+ logSequence: entry.logSequence,+ ts: entry.ts,+ level: entry.level,+ msg: entry.msg.slice(0, 8192),+ fieldsTruncated: true,+ }}-/**- * Push one destination's buffer to disk. SonicBoom only honours `flush(cb)`- * when it actually buffers (`minLength > 0`): the callback then fires from the- * `drain` handler after an `fsync`, which is the only real durability signal- * it offers. `flushSync()` is not a substitute — it skips the chunk of an- * in-flight async write, so it can return before that chunk lands.- */async function flushDestination(per: Per): Promise<void> {+ if (!per.opened) returnif (!(await per.opened) || !per.dest)throw new Error('Plugin log file is unavailable')const destination = per.destawait new Promise<void>((resolve, reject) => {try {+ // minLength > 0 makes SonicBoom flush wait for drain and fsync.destination.flush((error) => (error ? reject(error) : resolve()))} catch (error) {reject(error)@@ -68,15 +87,16 @@ export class LogCapabilityHost {private readonly opts: Required<LogCapabilityHostOptions>private readonly per = new Map<string, Per>()private readonly subscribers = new Set<LogStreamListener>()+ private closing = false+ private closePromise?: Promise<void>constructor(opts: LogCapabilityHostOptions) {this.opts = { ringSize: 100, ...opts }}private logPath(pluginId: string): string {- if (!/^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/.test(pluginId)) {+ if (!/^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/.test(pluginId))throw new Error('Invalid plugin log identifier')- }return path.join(this.opts.pluginLogsDir,pluginId,@@ -85,29 +105,64 @@ export class LogCapabilityHost {)}+ private appendRing(per: Per, entry: LogEntry): void {+ per.ring.push(entry)+ per.ringBytes += entryBytes(entry)+ while (+ per.ring.length > this.opts.ringSize ||+ per.ringBytes > PLUGIN_LOG_MAX_RING_BYTES+ ) {+ const removed = per.ring.shift()+ if (removed) per.ringBytes -= entryBytes(removed)+ }+ }++ private notify(pluginId: string, entry: LogEntry): void {+ for (const listener of this.subscribers) {+ try {+ listener(pluginId, entry)+ } catch {+ /* Diagnostics must not poison their producer. */+ }+ }+ }+private getOrCreate(pluginId: string): Per {- let entry = this.per.get(pluginId)- if (entry) return entry+ const existing = this.per.get(pluginId)+ if (existing) return existingconst file = this.logPath(pluginId)- const { entries: ring, needsNewline } = readPluginLogTail(- file,- this.opts.ringSize- )- entry = {- opened: Promise.resolve(false),- ring,+ const { entries } = readPluginLogTail(file, this.opts.ringSize)+ const per: Per = {+ ring: [],+ ringBytes: 0,verboseUntil: null,- queuedWrites: [],- openingWrites: [],+ pending: [],+ pendingBytes: 0,sequence: Math.max(0,- ...ring.map((item) => pluginLogSequence(item) ?? 0)+ ...entries.map((entry) => pluginLogSequence(entry) ?? 0)),unavailable: false,+ dropped: 0,+ reportingDrop: false,+ markerRejected: false,+ retiring: false,+ retired: false,+ destinationClosed: false,}- this.per.set(pluginId, entry)- const per = entry- per.retryOpen = async () => {+ for (const entry of entries) this.appendRing(per, boundEntry(entry))+ this.per.set(pluginId, per)+ // Pino serializes synchronously into our bounded sink. History inspection+ // alone never creates a file descriptor or a periodic flush timer.+ per.logger = pino({ base: undefined, timestamp: false, level: 'trace' }, {+ write: (data: string) => this.write(pluginId, per, data),+ } as DestinationStream)+ return per+ }++ private ensureOpen(pluginId: string, per: Per): Promise<boolean> {+ per.opened ??= (async () => {+ const file = this.logPath(pluginId)try {await fs.mkdir(path.dirname(file), { recursive: true })const fd = await new Promise<number>((resolve, reject) => {@@ -116,94 +171,139 @@ export class LogCapabilityHost {)})try {- // Create the destination only with an owned descriptor. Otherwise a- // failed open leaves SonicBoom's timer and exit hook using fd=-1.const dest = pino.destination({- // A numeric string preserves descriptor zero through Pino's defaults.dest: String(fd),sync: false,minLength: 4096,periodicFlush: 1000,+ maxLength: PLUGIN_LOG_MAX_BUFFER_BYTES,+ })+ per.destinationClosed = false+ dest.once('close', () => {+ per.destinationClosed = true})dest.on('error', () => {})+ dest.on('drop', () => {+ if (per.reportingDrop) per.markerRejected = true+ else per.dropped+++ })+ dest.on('drain', () => this.reportDropped(pluginId, per))per.dest = dest- per.logger = pino(- { base: undefined, timestamp: false, level: 'trace' },- dest as DestinationStream- )- if (needsNewline) dest.write('\n')+ // Inspect the tail at open time: a read-only inspection may precede+ // opening by minutes, or another process may have finished a line.+ if (readPluginLogTail(file, 0).needsNewline) dest.write('\n')} catch (error) {close(fd, () => {})throw error}- for (const write of per.openingWrites.splice(0)) write()+ this.drainPending(per)return true} catch {per.unavailable = true- per.openingWrites.length = 0+ per.dropped += per.pending.length+ per.pending.length = 0+ per.pendingBytes = 0return false}+ })()+ return per.opened+ }++ private write(pluginId: string, per: Per, data: string): void {+ if (per.retiring || per.retired || this.closing) return+ if (per.unavailable) {+ per.dropped+++ return+ }+ const bytes = Buffer.byteLength(data, 'utf8')+ if (bytes > PLUGIN_LOG_MAX_ENTRY_BYTES) {+ per.dropped+++ return+ }+ if (!per.dest || per.clearing) {+ if (+ per.pending.length >= MAX_PENDING_ENTRIES ||+ per.pendingBytes + bytes > PLUGIN_LOG_MAX_BUFFER_BYTES+ ) {+ per.dropped+++ return+ }+ per.pending.push({ data, sequence: per.sequence })+ per.pendingBytes += bytes+ void this.ensureOpen(pluginId, per)+ } else {+ per.dest.write(data)}- per.opened = per.retryOpen()- return entry+ }++ private drainPending(per: Per): void {+ if (!per.dest) return+ while (per.pending.length) {+ const next = per.pending[0]+ if (per.clearThrough !== undefined && next.sequence > per.clearThrough)+ return+ per.dest.write(next.data)+ per.pending.shift()+ per.pendingBytes -= Buffer.byteLength(next.data, 'utf8')+ }+ }++ private reportDropped(pluginId: string, per: Per): void {+ if (+ !per.dropped ||+ per.clearing ||+ per.reportingDrop ||+ !per.dest ||+ per.destinationClosed+ )+ return+ const count = per.dropped+ const entry: LogEntry = {+ entryId: randomUUID(),+ logSequence: ++per.sequence,+ ts: Date.now(),+ level: 'warn',+ msg: 'Plugin diagnostic records were dropped because the log buffer was unavailable or full',+ droppedEntries: count,+ }+ per.reportingDrop = true+ per.markerRejected = false+ try {+ const { ts, level: _level, ...fields } = entry+ per.dest.write(`${JSON.stringify({ ...fields, level: 40, time: ts })}\n`)+ } finally {+ per.reportingDrop = false+ }+ if (per.markerRejected) return+ per.dropped -= count+ this.appendRing(per, entry)+ this.notify(pluginId, entry)}create(pluginId: string): PluginLogCapability {- const per = this.getOrCreate(pluginId)+ const per = this.closing ? undefined : this.getOrCreate(pluginId)const push = (level: LogEntry['level'],msg: string,fields?: Record<string, unknown>) => {- // Spec §7 L2391-2403 — default-redact url / headers / body / paths /- // storage value. The per-plugin verbose flag (set via SetPluginLogVerbose- // IPC + LogCapabilityHost.setVerbose) bypasses privacy-value redaction- // for diagnostic capture, while structural limits and host metadata- // integrity remain enforced; the UI shows a warning while active.+ if (!per || this.closing || per.retiring || per.retired) returnconst verbose = this.isVerbose(pluginId)const safe = fields- ? redactLogFields(fields, {- profile: 'plugin',- verbose,- })- : (fields ?? {})- const safeMessage = verbose ? truncateLogText(msg) : redactLogText(msg)- const entry: LogEntry = {+ ? redactLogFields(fields, { profile: 'plugin', verbose })+ : {}+ const entry = boundEntry({...safe,entryId: randomUUID(),logSequence: ++per.sequence,ts: Date.now(),level,- msg: safeMessage,- }- per.ring.push(entry)- while (per.ring.length > this.opts.ringSize) per.ring.shift()- const write = () => {- if (per.unavailable) return- if (!per.logger) {- per.openingWrites.push(write)- return- }- per.logger[level](- {- ...safe,- entryId: entry.entryId,- logSequence: entry.logSequence,- time: entry.ts,- },- safeMessage- )- }- if (per.clearing) per.queuedWrites.push(write)- else write()- for (const listener of this.subscribers) {- try {- listener(pluginId, entry)- } catch {- // A subscriber crashing must not poison other subscribers- // or corrupt the ring; IPC forwarders log upstream if needed.- }- }+ msg: verbose ? truncateLogText(msg) : redactLogText(msg),+ })+ this.appendRing(per, entry)+ const { ts, level: _level, msg: message, ...record } = entry+ per.logger?.[level]({ ...record, time: ts }, message)+ this.notify(pluginId, entry)}return {trace: (m, f) => push('trace', m, f),@@ -216,6 +316,7 @@ export class LogCapabilityHost {}getTail(pluginId: string, limit: number): LogEntry[] {+ if (this.closing) return []const per = this.getOrCreate(pluginId)const count = Number.isFinite(limit)? Math.max(0, Math.min(this.opts.ringSize, Math.floor(limit)))@@ -224,37 +325,47 @@ export class LogCapabilityHost {}clear(pluginId: string): Promise<void> {+ if (this.closing)+ return Promise.reject(new Error('Plugin logs are closing'))const per = this.getOrCreate(pluginId)+ if (per.retiring) return Promise.reject(new Error('Plugin log is closing'))if (per.clearing) return per.clearing- if (per.unavailable && per.retryOpen) {+ if (per.unavailable) {per.unavailable = false- per.opened = per.retryOpen()+ per.opened = undefined}+ void this.ensureOpen(pluginId, per)const previous = new Set(per.ring)+ const droppedBefore = per.dropped+ per.clearThrough = per.sequenceconst clearing = (async () => {await flushDestination(per)await fs.truncate(this.logPath(pluginId), 0)- // Commit the visible clear only after disk success. Entries captured- // during the operation remain visible and are written after truncation.- per.ring = per.ring.filter((item) => !previous.has(item))+ per.ring = per.ring.filter((entry) => !previous.has(entry))+ per.ringBytes = per.ring.reduce(+ (sum, entry) => sum + entryBytes(entry),+ 0+ )+ per.dropped = Math.max(0, per.dropped - droppedBefore)})().finally(() => {per.clearing = undefined- for (const write of per.queuedWrites.splice(0)) write()+ per.clearThrough = undefined+ this.drainPending(per)+ this.reportDropped(pluginId, per)})per.clearing = clearingreturn clearing}setVerbose(pluginId: string, verbose: boolean): void {- this.getOrCreate(pluginId).verboseUntil = verbose- ? Date.now() + PLUGIN_LOG_VERBOSE_TTL_MS- : null+ if (!this.closing)+ this.getOrCreate(pluginId).verboseUntil = verbose+ ? Date.now() + PLUGIN_LOG_VERBOSE_TTL_MS+ : null}-isVerbose(pluginId: string): boolean {return this.getState(pluginId).verbose}-getState(pluginId: string): PluginLogState {const per = this.per.get(pluginId)const expiresAt = per?.verboseUntil ?? null@@ -264,7 +375,6 @@ export class LogCapabilityHost {}return { verbose: true, expiresAt }}-subscribe(listener: LogStreamListener): () => void {this.subscribers.add(listener)return () => {@@ -272,18 +382,92 @@ export class LogCapabilityHost {}}- /**- * Resolve once every plugin's buffered output is on disk. This is the only- * durability handle over `current.ndjson` that plugins and the shells have- * — the UI reads the in-memory ring instead — so the guarantee has to be- * real rather than a timing guess.- */+ private async flushPer(pluginId: string, per: Per): Promise<void> {+ await per.clearing+ await flushDestination(per)+ this.reportDropped(pluginId, per)+ await flushDestination(per)+ }++ /** Flush accepted diagnostics and an explicit summary of overflow losses. */async flush(): Promise<void> {- await Promise.all(- [...this.per.values()].map(async (per) => {- await per.clearing- await flushDestination(per)- })+ await Promise.all([...this.per].map(([id, per]) => this.flushPer(id, per)))+ }++ /** Close a quiesced plugin's resources, preserving its persisted diagnostics. */+ release(pluginId: string): Promise<void> {+ const per = this.per.get(pluginId)+ if (!per) return Promise.resolve()+ if (per.releasing) return per.releasing+ per.retiring = true+ let closeStarted = false+ const releasing = (async () => {+ if (per.unavailable) {+ per.unavailable = false+ per.opened = undefined+ void this.ensureOpen(pluginId, per)+ }+ await this.flushPer(pluginId, per)+ const dest = per.dest+ if (dest && !per.destinationClosed) {+ await new Promise<void>((resolve, reject) => {+ const cleanup = () => {+ dest.off('close', closed)+ dest.off('error', failed)+ }+ const closed = () => {+ cleanup()+ resolve()+ }+ const failed = (error: Error) => {+ cleanup()+ reject(error)+ }+ dest.once('close', closed)+ dest.once('error', failed)+ try {+ closeStarted = true+ dest.end()+ } catch (error) {+ cleanup()+ reject(error)+ }+ })+ }+ per.retired = true+ per.ring = []+ per.ringBytes = 0+ per.pending = []+ per.pendingBytes = 0+ per.logger = undefined+ per.dest = undefined+ if (this.per.get(pluginId) === per) this.per.delete(pluginId)+ })().catch((error) => {+ // Opening/flush failures can retry. SonicBoom destroys itself before+ // closing its FD: a failed close must never re-enable that dead writer+ // or retry a numeric descriptor whose ownership is now uncertain.+ if (!closeStarted) {+ per.retiring = false+ per.releasing = undefined+ }+ throw error+ })+ per.releasing = releasing+ return releasing+ }++ close(): Promise<void> {+ this.closing = true+ this.closePromise ??= Promise.all(+ [...this.per.keys()].map((id) => this.release(id)))+ .then(() => {+ this.subscribers.clear()+ })+ .catch((error) => {+ this.closePromise = undefined+ throw error+ })+ return this.closePromise}}diff --git a/src/core/plugin/host/plugin-host.ts b/src/core/plugin/host/plugin-host.tsindex 636507d7..33734b6c 100644--- a/src/core/plugin/host/plugin-host.ts+++ b/src/core/plugin/host/plugin-host.ts@@ -1329,6 +1329,7 @@ export class PluginHost {])await Promise.all([...pluginIds].map((id) => this.deactivate(id)))await this.opts.capabilityHost.flush()+ await this.opts.capabilityHost.closeLogs?.()}private sweepIdle(): void {diff --git a/src/core/plugin/install/e2e-install.test.ts b/src/core/plugin/install/e2e-install.test.tsindex 57a4be13..75af1064 100644--- a/src/core/plugin/install/e2e-install.test.ts+++ b/src/core/plugin/install/e2e-install.test.ts@@ -647,8 +647,17 @@ describe('PluginInstaller e2e', () => {await installer.commit(stagingId, {})expect(stateStore.get('example.test')).toBeDefined()+ const releaseLog = vi.fn(async (id: string) => {+ expect(calls.deactivated).toContain(id)+ expect(stateStore.get(id)).toBeDefined()+ expect(existsSync(path.join(pluginsDir, id))).toBe(true)+ })+ ;(+ Reflect.get(installer, 'opts') as PluginInstallerOptions+ ).capabilityHost.releaseLog = releaseLogawait installer.uninstall('example.test')+ expect(releaseLog).toHaveBeenCalledExactlyOnceWith('example.test')expect(calls.deactivated).toContain('example.test')expect(calls.storageDeleteAll).toEqual(['example.test'])expect(calls.metadataDeleteAllForPlugin).toEqual(['example.test'])@@ -690,6 +699,29 @@ describe('PluginInstaller e2e', () => {expect(existsSync(path.join(pluginsDir, 'example.test'))).toBe(true)})+ it('aborts destructive uninstall if the diagnostic writer cannot be released', async () => {+ const moext = await writeMoext(+ path.join(inputDir, 'v1.moext'),+ manifestJSON()+ )+ const { stagingId } = await installer.stage(moext, {+ type: 'github',+ spec: 'example/test',+ })+ await installer.commit(stagingId, {})+ const failure = new Error('diagnostic fsync failed')+ ;(+ Reflect.get(installer, 'opts') as PluginInstallerOptions+ ).capabilityHost.releaseLog = vi.fn(async () => {+ throw failure+ })+ await expect(installer.uninstall('example.test')).rejects.toBe(failure)+ expect(stateStore.get('example.test')).toBeDefined()+ expect(calls.storageDeleteAll).toEqual([])+ expect(calls.metadataDeleteAllForPlugin).toEqual([])+ expect(existsSync(path.join(pluginsDir, 'example.test'))).toBe(true)+ })+it('uninstall rejects traversal before touching state or files', async () => {const sentinel = path.join(tmp, 'keep.txt')await writeFile(sentinel, 'keep')diff --git a/src/core/plugin/install/plugin-installer.ts b/src/core/plugin/install/plugin-installer.tsindex b636ab59..6c06c0b9 100644--- a/src/core/plugin/install/plugin-installer.ts+++ b/src/core/plugin/install/plugin-installer.ts@@ -685,6 +685,9 @@ export class PluginInstaller {.runDeactivate(pluginId).catch(() => undefined)}+ // Diagnostics remain on disk, but no writer may outlive its plugin.+ // A flush/close failure aborts before any durable plugin state is removed.+ await this.opts.capabilityHost.releaseLog?.(pluginId)const removedDir = path.join(this.opts.pluginsDir,'_staging',diff --git a/src/core/plugin/secret-store-libsodium-lazy.test.ts b/src/core/plugin/secret-store-libsodium-lazy.test.tsnew file mode 100644index 00000000..1ff69b27--- /dev/null+++ b/src/core/plugin/secret-store-libsodium-lazy.test.ts@@ -0,0 +1,55 @@+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'++const { imported, sodium } = vi.hoisted(() => ({+ imported: vi.fn(),+ sodium: {+ ready: Promise.resolve(),+ randombytes_buf: vi.fn(() => new Uint8Array(24)),+ crypto_secretbox_easy: vi.fn(() => new Uint8Array([1, 2, 3])),+ },+}))++vi.mock('libsodium-wrappers', () => {+ imported()+ return { default: sodium }+})++import { LibsodiumSecretStore } from './secret-store-libsodium'++const directories: string[] = []+afterEach(() => {+ for (const dir of directories) rmSync(dir, { recursive: true, force: true })+})++it('keeps WASM unloaded for startup, then shares initialization across secret operations', async () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'motrix-lazy-secrets-'))+ directories.push(dir)+ const first = await LibsodiumSecretStore.create({ userDataDir: dir })+ const second = await LibsodiumSecretStore.create({ userDataDir: dir })+ const seeded = await LibsodiumSecretStore.create({+ userDataDir: dir,+ envSeed: 'a'.repeat(64),+ })+ expect(first.available()).toBe(true)+ expect(second.available()).toBe(true)+ expect(seeded.available()).toBe(true)+ expect(readFileSync(path.join(dir, 'secrets.lockbox'))).toHaveLength(32)+ await expect(first.decrypt('invalid')).rejects.toThrow()+ await expect(first.decrypt('box:AA==:AQ==')).rejects.toThrow()+ expect(imported).not.toHaveBeenCalled()++ let ready!: () => void+ sodium.ready = new Promise<void>((resolve) => {+ ready = resolve+ })+ const operations = [first.encrypt('one'), second.encrypt('two')]+ await vi.waitFor(() => expect(imported).toHaveBeenCalledOnce())+ expect(sodium.crypto_secretbox_easy).not.toHaveBeenCalled()+ ready()+ await Promise.all(operations)+ expect(imported).toHaveBeenCalledOnce()+ expect(sodium.crypto_secretbox_easy).toHaveBeenCalledTimes(2)+})diff --git a/src/core/plugin/secret-store-libsodium.test.ts b/src/core/plugin/secret-store-libsodium.test.tsindex c8db2fa1..e31a00bb 100644--- a/src/core/plugin/secret-store-libsodium.test.ts+++ b/src/core/plugin/secret-store-libsodium.test.ts@@ -87,6 +87,20 @@ describe('LibsodiumSecretStore', () => {expect(recovered).toBe(plaintext)})+ it('decrypts tokens written before lazy initialization', async () => {+ const store = await LibsodiumSecretStore.create({+ userDataDir: tmpDir,+ envSeed: TEST_SEED,+ })+ // Fixed secretbox fixture: the existing 32-byte key, 24-byte nonce and+ // box: token format must survive the change in initialization timing.+ await expect(+ store.decrypt(+ 'box:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:02io/RDmzfFG2btAjFPmDMtgY7Q6HXgkp0yKYAJvg4vL'+ )+ ).resolves.toBe('legacy secret ✓')+ })+// Test 4: decrypt of malformed "box:" token rejects.it('decrypt of malformed box: token rejects', async () => {const store = await LibsodiumSecretStore.create({diff --git a/src/core/plugin/secret-store-libsodium.ts b/src/core/plugin/secret-store-libsodium.tsindex 92dd2814..86c081d9 100644--- a/src/core/plugin/secret-store-libsodium.ts+++ b/src/core/plugin/secret-store-libsodium.ts@@ -15,13 +15,14 @@// 3. If userDataDir is writable, generate and write a new lockbox (chmod 0600)// 4. Otherwise return FailingSecretStore (no encrypt/decrypt possible)//-// Must use async factory pattern because sodium.ready must be awaited before-// any crypto call. Never construct directly.+// Resolve the key at creation; load sodium only for the first encrypt/decrypt.+// The asynchronous factory remains shared by both runtime capability hosts.//// Used by:// - Task 18 factory: injected as the SecretStore impl in both runtimes// - Task 22 IPC handler: encrypts/decrypts secret config fields+import { randomBytes } from 'node:crypto'import { existsSync, readFileSync, writeFileSync } from 'node:fs'import path from 'node:path'import {@@ -29,7 +30,6 @@ import {type SecretStore,SecretStoreError,} from '@core/plugin/capabilities/secret-store'-import sodium from 'libsodium-wrappers'export type { FailingSecretStore }@@ -38,6 +38,19 @@ const NONCE_BYTES = 24const KEY_BYTES = 32const LOCKBOX_FILE = 'secrets.lockbox'+type Sodium = typeof import('libsodium-wrappers').default+let sodiumReady: Promise<Sodium> | undefined++function loadSodium(): Promise<Sodium> {+ sodiumReady ??= import('libsodium-wrappers').then(+ async ({ default: sodium }) => {+ await sodium.ready+ return sodium+ }+ )+ return sodiumReady+}+export interface LibsodiumSecretStoreOptions {userDataDir: string/** Shell-provided secret seed (64 hex chars); omitted to use the lockbox. */@@ -49,14 +62,12 @@ export class LibsodiumSecretStore implements SecretStore {/*** Async factory — must be used instead of new.- * Awaits sodium.ready and resolves a key via the priority chain.+ * Resolves a key via the priority chain without loading the WASM runtime.* Returns FailingSecretStore if no key source is available.*/static async create(opts: LibsodiumSecretStoreOptions): Promise<LibsodiumSecretStore | FailingSecretStore> {- await sodium.ready-const rawSeed = opts.envSeed// Priority 1: env seed (64 hex chars = 32 bytes)@@ -79,7 +90,7 @@ export class LibsodiumSecretStore implements SecretStore {// Priority 3: create new lockbox if userDataDir is writabletry {- const key = sodium.randombytes_buf(KEY_BYTES)+ const key = randomBytes(KEY_BYTES)// Create the lockbox atomically at 0o600 so the symmetric key is never// briefly group/world-readable in the window between create and chmod.// `wx` = exclusive create (O_CREAT|O_EXCL); `mode` is applied on creation@@ -97,7 +108,7 @@ export class LibsodiumSecretStore implements SecretStore {}async encrypt(plaintext: string): Promise<string> {- await sodium.ready+ const sodium = await loadSodium()const nonce = sodium.randombytes_buf(NONCE_BYTES)const ct = sodium.crypto_secretbox_easy(plaintext, nonce, this.key)const nonceb64 = Buffer.from(nonce).toString('base64')@@ -132,7 +143,6 @@ export class LibsodiumSecretStore implements SecretStore {)}- await sodium.readyconst nonce = new Uint8Array(Buffer.from(nonceb64, 'base64'))const ct = new Uint8Array(Buffer.from(ctb64, 'base64'))@@ -144,6 +154,7 @@ export class LibsodiumSecretStore implements SecretStore {}let plainBytes: Uint8Array+ const sodium = await loadSodium()try {plainBytes = sodium.crypto_secretbox_open_easy(ct, nonce, this.key)} catch {diff --git a/src/main/legacy-import/desktop-import.ts b/src/main/legacy-import/desktop-import.tsindex f39b603d..0b90544f 100644--- a/src/main/legacy-import/desktop-import.ts+++ b/src/main/legacy-import/desktop-import.ts@@ -18,6 +18,7 @@ import { Queries } from '@shared/protocol/queries'import {type LegacyImportNavigationState,legacyMetadataRequestSchema,+ legacyPreviewRequestSchema,legacyRunRequestSchema,legacyScanRequestSchema,legacyTaskMetadataSchema,@@ -207,6 +208,12 @@ export function registerLegacyImportIpc(deps: DesktopImportDeps): () => void {[Commands.CommitLegacyImport]: async (_event, input) => {return (await readyService()).commit(input)},+ [Commands.ReleaseLegacyImportPreview]: async (_event, input) => {+ service().releasePreview(+ legacyPreviewRequestSchema.parse(input).previewId+ )+ return { ok: true }+ },[Commands.CancelLegacyImport]: async (_event, input) =>service().cancel(legacyRunRequestSchema.parse(input).runId),[Commands.RetryLegacyImport]: async (_event, input) => {diff --git a/src/main/platform/tray-speedometer-lifecycle.test.ts b/src/main/platform/tray-speedometer-lifecycle.test.tsnew file mode 100644index 00000000..034b5963--- /dev/null+++ b/src/main/platform/tray-speedometer-lifecycle.test.ts@@ -0,0 +1,182 @@+import type { Tray } from 'electron'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ init: vi.fn(),+ construct: vi.fn(),+ render: vi.fn(),+ free: vi.fn(),+ imageFree: vi.fn(),+ asPng: vi.fn(),+ createImage: vi.fn(),+ warn: vi.fn(),+}))+vi.mock('node:fs', () => ({ readFileSync: () => Buffer.from([1, 2, 3]) }))+vi.mock('@core/logger', () => ({ getLogger: () => ({ warn: mocks.warn }) }))+vi.mock('electron', () => ({+ nativeImage: { createFromBuffer: mocks.createImage },+}))+vi.mock('@resvg/resvg-wasm', () => ({+ initWasm: mocks.init,+ Resvg: class {+ constructor(svg: string, options: unknown) {+ mocks.construct(svg, options)+ }+ render = mocks.render+ free = mocks.free+ },+}))++const handles: Array<{ destroy(): void }> = []+beforeEach(() => {+ vi.resetModules()+ vi.resetAllMocks()+ vi.useFakeTimers()+ mocks.init.mockResolvedValue(undefined)+ mocks.construct.mockImplementation(() => ({+ render: mocks.render,+ free: mocks.free,+ }))+ mocks.render.mockReturnValue({ asPng: mocks.asPng, free: mocks.imageFree })+ mocks.asPng.mockReturnValue(new Uint8Array([1, 2, 3]))+ mocks.createImage.mockReturnValue({ setTemplateImage: vi.fn() })+})+afterEach(() => {+ for (const handle of handles.splice(0)) handle.destroy()+ vi.useRealTimers()+})+async function fixture() {+ const { createSpeedometer } = await import('./tray-speedometer')+ const tray = { setImage: vi.fn() }+ let current: typeof tray | null = tray+ const handle = createSpeedometer(+ () => current as unknown as Tray | null,+ '<path/>',+ '/assets'+ )+ handles.push(handle)+ handle.setEnabled(true)+ return {+ handle,+ tray,+ replaceTray: () => {+ current = { setImage: vi.fn() }+ },+ }+}+async function tick() {+ await vi.advanceTimersByTimeAsync(500)+ await vi.dynamicImportSettled()+}++it('releases both WASM allocations before native image creation and copies their bytes', async () => {+ const { handle, tray } = await fixture()+ const bytes = new Uint8Array([1, 2, 3])+ mocks.asPng.mockReturnValue(bytes)+ mocks.imageFree.mockImplementation(() => {+ bytes.fill(0)+ })+ mocks.createImage.mockImplementation((png) => {+ expect([...png]).toEqual([1, 2, 3])+ expect(mocks.imageFree).toHaveBeenCalledOnce()+ expect(mocks.free).toHaveBeenCalledOnce()+ return { setTemplateImage: vi.fn() }+ })+ handle.onSpeedChange(0, 1000)+ await tick()+ expect(tray.setImage).toHaveBeenCalledOnce()+})++it.each(['render', 'encode', 'native', 'publish'] as const)(+ 'cleans up and retries after a %s failure',+ async (stage) => {+ const { handle, tray } = await fixture()+ const fail = () => {+ throw new Error('injected')+ }+ if (stage === 'render') mocks.render.mockImplementationOnce(fail)+ if (stage === 'encode') mocks.asPng.mockImplementationOnce(fail)+ if (stage === 'native') mocks.createImage.mockImplementationOnce(fail)+ if (stage === 'publish') tray.setImage.mockImplementationOnce(fail)+ handle.onSpeedChange(0, 1000)+ await tick()+ expect(mocks.free).toHaveBeenCalledOnce()+ expect(mocks.imageFree).toHaveBeenCalledTimes(stage === 'render' ? 0 : 1)+ handle.onSpeedChange(0, 1000)+ await tick()+ expect(mocks.free).toHaveBeenCalledTimes(2)+ expect(tray.setImage).toHaveBeenCalledTimes(stage === 'publish' ? 2 : 1)+ }+)++it.each(['destroy', 'disable', 'replace'] as const)(+ 'does not publish after %s during initialization',+ async (action) => {+ const { handle, tray, replaceTray } = await fixture()+ let ready!: () => void+ mocks.init.mockReturnValueOnce(+ new Promise<void>((resolve) => {+ ready = resolve+ })+ )+ handle.onSpeedChange(0, 1000)+ await tick()+ if (action === 'destroy') handle.destroy()+ if (action === 'disable') handle.setEnabled(false)+ if (action === 'replace') replaceTray()+ ready()+ await tick()+ expect(mocks.construct).not.toHaveBeenCalled()+ expect(tray.setImage).not.toHaveBeenCalled()+ }+)++it('shares initialization across handles and renders the latest unit after an invalidated frame', async () => {+ const { createSpeedometer } = await import('./tray-speedometer')+ let ready!: () => void+ mocks.init.mockReturnValueOnce(+ new Promise<void>((resolve) => {+ ready = resolve+ })+ )+ const a = createSpeedometer(+ () => ({ setImage() {} }) as unknown as Tray,+ '<path/>',+ '/assets'+ )+ handles.push(a)+ // A stable tray reference is required for the async identity guard.+ const tray = { setImage: vi.fn() }+ const b = createSpeedometer(+ () => tray as unknown as Tray,+ '<path/>',+ '/assets'+ )+ handles.push(b)+ for (const handle of [a, b]) {+ handle.setEnabled(true)+ handle.onSpeedChange(0, 1048576)+ }+ await tick()+ b.setUnitSystem('binary')+ ready()+ await tick()+ await tick()+ expect(mocks.init).toHaveBeenCalledOnce()+ expect(mocks.construct.mock.calls.at(-1)?.[0]).toContain('1.00 MiB/s')+ expect(tray.setImage).toHaveBeenCalledOnce()+})++it('skips equal displayed speeds and retries a failed initializer', async () => {+ const { handle } = await fixture()+ mocks.init.mockRejectedValueOnce(new Error('bad WASM'))+ handle.onSpeedChange(0, 1000)+ await tick()+ expect(mocks.construct).not.toHaveBeenCalled()+ handle.onSpeedChange(0, 1000)+ await tick()+ expect(mocks.init).toHaveBeenCalledTimes(2)+ handle.onSpeedChange(0, 1001)+ await tick()+ expect(mocks.construct).toHaveBeenCalledOnce()+})diff --git a/src/main/platform/tray-speedometer.ts b/src/main/platform/tray-speedometer.tsindex 47ee25ef..fafa3cbe 100644--- a/src/main/platform/tray-speedometer.ts+++ b/src/main/platform/tray-speedometer.ts@@ -1,5 +1,6 @@import { readFileSync } from 'node:fs'import path from 'node:path'+import { getLogger } from '@core/logger'import {type ByteUnitSystem,DEFAULT_BYTE_UNIT_SYSTEM,@@ -56,17 +57,24 @@ export interface SpeedometerHandle {destroy(): void}-type ResvgModule = {- Resvg: new (- svg: string,- opts: object- ) => { render(): { asPng(): Uint8Array } }- initWasm(): Promise<void>+type ResvgModule = typeof import('@resvg/resvg-wasm')+let resvgReady: Promise<ResvgModule> | undefined++function loadResvg(trayAssetDir: string): Promise<ResvgModule> {+ resvgReady ??= (async () => {+ const moduleName = '@resvg/resvg-wasm'+ const mod: ResvgModule = await import(/* @vite-ignore */ moduleName)+ await mod.initWasm(readFileSync(path.join(trayAssetDir, 'resvg.wasm')))+ return mod+ })().catch((error) => {+ resvgReady = undefined+ throw error+ })+ return resvgReady}-// SF Pro static (converted from variable SFNS.ttf) + Helvetica fallbackconst MACOS_FONT_PATHS = [- 'SFNS-Regular.ttf', // relative to trayAssetDir+ 'SFNS-Regular.ttf','/System/Library/Fonts/Helvetica.ttc',]@@ -77,107 +85,138 @@ export function createSpeedometer(): SpeedometerHandle {let unitSystem = DEFAULT_BYTE_UNIT_SYSTEMlet enabled = false- let lastUpload = -1- let lastDownload = -1+ let destroyed = false+ let revision = 0+ let request = 0+ let rendering = false+ let failureReported = false+ let lastSvg: string | null = nulllet throttleTimer: ReturnType<typeof setTimeout> | null = nulllet pendingUpload = 0let pendingDownload = 0- let resvgModule: ResvgModule | null = nulllet fontBuffers: Buffer[] | null = null- async function ensureResvg(): Promise<ResvgModule> {- if (resvgModule) return resvgModule- const resvgModuleName = '@resvg/resvg-wasm'- const mod = await import(/* @vite-ignore */ resvgModuleName)- try {- const wasmBinary = readFileSync(path.join(trayAssetDir, 'resvg.wasm'))- await mod.initWasm(wasmBinary)- } catch {- // Already initialized- }- resvgModule = mod as ResvgModule- return resvgModule- }-- async function render(upload: number, download: number) {- if (upload === lastUpload && download === lastDownload) return- lastUpload = upload- lastDownload = download-+ async function render(): Promise<void> {+ const currentRevision = revisionconst tray = trayRef()- if (!tray) return-- const svg = buildSpeedometerSvg(iconSvg, upload, download, unitSystem)- const { Resvg } = await ensureResvg()- // Load fonts once — resvg-wasm can't access filesystem for fonts+ if (!enabled || destroyed || !tray) return+ let svg = buildSpeedometerSvg(+ iconSvg,+ pendingUpload,+ pendingDownload,+ unitSystem+ )+ if (svg === lastSvg) return+ const { Resvg } = await loadResvg(trayAssetDir)+ if (+ !enabled ||+ destroyed ||+ revision !== currentRevision ||+ trayRef() !== tray+ )+ return+ svg = buildSpeedometerSvg(+ iconSvg,+ pendingUpload,+ pendingDownload,+ unitSystem+ )+ if (svg === lastSvg) returnif (!fontBuffers) {fontBuffers = []- for (const p of MACOS_FONT_PATHS) {+ for (const file of MACOS_FONT_PATHS) {try {- // First entry is relative to trayAssetDir, rest are absolute- const fullPath = path.isAbsolute(p) ? p : path.join(trayAssetDir, p)- fontBuffers.push(readFileSync(fullPath))+ fontBuffers.push(+ readFileSync(+ path.isAbsolute(file) ? file : path.join(trayAssetDir, file)+ )+ )} catch {- // Font not available+ /* Use whichever platform fonts are available. */}}}const resvg = new Resvg(svg, {fitTo: { mode: 'width', value: SVG_WIDTH },- font: {- fontBuffers,- defaultFontFamily: '.SF NS',- },+ font: { fontBuffers, defaultFontFamily: '.SF NS' },})- const png = resvg.render().asPng()- const image: NativeImage = nativeImage.createFromBuffer(Buffer.from(png), {+ let png: Buffer+ try {+ const rendered = resvg.render()+ try {+ // The native image must never borrow storage owned by a freed WASM object.+ png = Buffer.from(rendered.asPng())+ } finally {+ rendered.free()+ }+ } finally {+ resvg.free()+ }+ const image: NativeImage = nativeImage.createFromBuffer(png, {scaleFactor: 2,})image.setTemplateImage(true)tray.setImage(image)+ lastSvg = svg+ failureReported = false}- function scheduleRender() {- if (throttleTimer) return+ function scheduleRender(): void {+ if (!enabled || destroyed || throttleTimer || rendering) returnthrottleTimer = setTimeout(() => {throttleTimer = null- render(pendingUpload, pendingDownload)+ const startedRequest = request+ rendering = true+ void render()+ .catch((err) => {+ if (!destroyed && enabled && !failureReported) {+ failureReported = true+ getLogger('tray-speedometer').warn(+ { err },+ 'speedometer render failed'+ )+ }+ })+ .finally(() => {+ rendering = false+ if (request !== startedRequest) scheduleRender()+ })}, 500)}+ function invalidate(): void {+ revision+++ request+++ lastSvg = null+ if (throttleTimer) clearTimeout(throttleTimer)+ throttleTimer = null+ }+return {- onSpeedChange(uploadSpeed: number, downloadSpeed: number) {- if (!enabled) return+ onSpeedChange(uploadSpeed, downloadSpeed) {+ if (!enabled || destroyed) returnpendingUpload = uploadSpeedpendingDownload = downloadSpeed+ request++scheduleRender()},-- setUnitSystem(value: ByteUnitSystem) {- if (unitSystem === value) return+ setUnitSystem(value) {+ if (destroyed || unitSystem === value) returnunitSystem = value- lastUpload = -1- lastDownload = -1- if (enabled) scheduleRender()+ invalidate()+ scheduleRender()},-- setEnabled(value: boolean) {+ setEnabled(value) {+ if (destroyed || enabled === value) returnenabled = value- if (!enabled) {- lastUpload = -1- lastDownload = -1- if (throttleTimer) {- clearTimeout(throttleTimer)- throttleTimer = null- }- }+ invalidate()+ if (!enabled) fontBuffers = null},-destroy() {- if (throttleTimer) {- clearTimeout(throttleTimer)- throttleTimer = null- }+ destroyed = true+ enabled = false+ invalidate()+ fontBuffers = null},}}diff --git a/src/main/platform/tray.test.ts b/src/main/platform/tray.test.tsindex 5f6df5ff..eab0d652 100644--- a/src/main/platform/tray.test.ts+++ b/src/main/platform/tray.test.ts@@ -8,6 +8,7 @@ const {iconProvider,nativeThemeMock,speedometer,+ speedometerFactory,systemPreferencesMock,trayConstructor,trayInstance,@@ -38,6 +39,7 @@ const {setEnabled: vi.fn(),setUnitSystem: vi.fn(),},+ speedometerFactory: vi.fn(),systemPreferencesMock: {getUserDefault: vi.fn(),setUserDefault: vi.fn(),@@ -76,7 +78,7 @@ vi.mock('./tray-icon', () => ({}))vi.mock('./tray-speedometer', () => ({- createSpeedometer: () => speedometer,+ createSpeedometer: speedometerFactory,}))import { RunMode } from '@shared/constants'@@ -130,6 +132,7 @@ function getThemeUpdatedHandler(): () => Promise<void> {describe('setupTray', () => {beforeEach(() => {vi.resetAllMocks()+ speedometerFactory.mockReturnValue(speedometer)iconProviderFactory.mockReturnValue(iconProvider)iconProvider.getIcon.mockReturnValue(icon)iconProvider.init.mockResolvedValue(undefined)@@ -272,6 +275,7 @@ describe('setupTray', () => {expect(trayInstance.setImage).toHaveBeenCalledExactlyOnceWith(icon)}expect(speedometer.setEnabled).not.toHaveBeenCalled()+ expect(speedometerFactory).not.toHaveBeenCalled()handle.destroy()})diff --git a/src/main/plugin/capability-host.test.ts b/src/main/plugin/capability-host.test.tsindex 3bb3c795..9bdbb74b 100644--- a/src/main/plugin/capability-host.test.ts+++ b/src/main/plugin/capability-host.test.ts@@ -124,6 +124,8 @@ describe('createElectronCapabilityHost', () => {})expect(host.http).toBeInstanceOf(HttpCapabilityHost)+ expect(host.releaseLog).toBeTypeOf('function')+ expect(host.closeLogs).toBeTypeOf('function')})it('does not initialize native notification support while wiring capabilities', async () => {diff --git a/src/main/plugin/capability-host.ts b/src/main/plugin/capability-host.tsindex 6a34c9ed..8a8ae71d 100644--- a/src/main/plugin/capability-host.ts+++ b/src/main/plugin/capability-host.ts@@ -152,6 +152,8 @@ export async function createElectronCapabilityHost(setLocale: (locale) => i18nCap.setLanguage(locale),onLocaleChange: (h) => i18nCap.onChange(h),flush: () => log.flush(),+ releaseLog: (id) => log.release(id),+ closeLogs: () => log.close(),// ── Plan B ──────────────────────────────────────────────────────────────http,diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsxindex 0edb9537..99aa6664 100644--- a/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx+++ b/src/renderer/features/legacy-import/legacy-import-dialog.test.tsx@@ -6,6 +6,7 @@ import { transport } from '@renderer/lib/transport'import { Commands } from '@shared/protocol/commands'import { Queries } from '@shared/protocol/queries'import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { StrictMode } from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { LegacyImportDialog } from './legacy-import-dialog'import { useLegacyImportSidebar } from './sidebar-preference'@@ -97,6 +98,53 @@ describe('legacy import dialog', () => {})})+ it('keeps a current preview through StrictMode setup and releases it on unmount', async () => {+ const view = render(+ <StrictMode>+ <LegacyImportDialog open presentation="page" onClose={vi.fn()} />+ </StrictMode>+ )+ await continueFromSource()+ expect(transport.invoke).not.toHaveBeenCalledWith(+ Commands.ReleaseLegacyImportPreview,+ { previewId }+ )+ view.unmount()+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.ReleaseLegacyImportPreview,+ { previewId }+ )+ )+ })++ it('releases a scan result that arrives after the view has unmounted', async () => {+ const original = vi.mocked(transport.invoke).getMockImplementation()+ let resolve!: (value: typeof preview) => void+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) => {+ if (channel === Queries.ScanLegacyImport)+ return new Promise((done) => {+ resolve = done+ })+ return original!(channel, ...args)+ })+ const view = render(+ <LegacyImportDialog open presentation="page" onClose={vi.fn()} />+ )+ const button = await screen.findByRole('button', { name: 'Continue' })+ await waitFor(() => expect(button).toBeEnabled())+ fireEvent.click(button)+ await waitFor(() => expect(resolve).toBeTypeOf('function'))+ view.unmount()+ resolve(preview)+ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ Commands.ReleaseLegacyImportPreview,+ { previewId }+ )+ )+ })+it('selects HTTP records with saved request settings and explains verification and blocked options', async () => {const originalInvoke = vi.mocked(transport.invoke).getMockImplementation()vi.mocked(transport.invoke).mockImplementation(async (channel, payload) => {diff --git a/src/renderer/features/legacy-import/legacy-import-dialog.tsx b/src/renderer/features/legacy-import/legacy-import-dialog.tsxindex 1126778d..ed56df62 100644--- a/src/renderer/features/legacy-import/legacy-import-dialog.tsx+++ b/src/renderer/features/legacy-import/legacy-import-dialog.tsx@@ -99,6 +99,15 @@ class ImportErrorBoundary extends Component<}}+function releasePreview(preview: LegacyImportPreview | null): void {+ if (!preview) return+ void transport+ .invoke(Commands.ReleaseLegacyImportPreview, {+ previewId: preview.previewId,+ })+ .catch(() => {})+}+export function LegacyImportDialog(props: Props) {const { t } = useTranslation()return (@@ -218,6 +227,7 @@ function LegacyImportDialogContent({++sourceFeedbackEpoch.currentsourceHandleRef.current = source.sourceHandlesetSourceHandle(source.sourceHandle)+ releasePreview(previewRef.current)previewRef.current = nullsetPreview(null)setSelected(new Set())@@ -241,7 +251,12 @@ function LegacyImportDialogContent({sourceHandle: source.sourceHandle,}))- if (generation !== epoch.current) return+ if (generation !== epoch.current) {+ releasePreview(next)+ return+ }+ if (previewRef.current?.previewId !== next.previewId)+ releasePreview(previewRef.current)previewRef.current = nextsetPreview(next)setSelected(@@ -293,6 +308,8 @@ function LegacyImportDialogContent({return () => {epoch.current++busyRef.current = false+ releasePreview(previewRef.current)+ previewRef.current = null}}, [open, perform, discover])@@ -433,8 +450,14 @@ function LegacyImportDialogContent({Commands.PickLegacyTorrentMetadata,{ previewId: preview.previewId, itemId: item.itemId })- if (!result || generation !== epoch.current) return+ if (!result) returnconst next = legacyImportPreviewSchema.parse(result)+ if (generation !== epoch.current) {+ releasePreview(next)+ return+ }+ if (previewRef.current?.previewId !== next.previewId)+ releasePreview(previewRef.current)previewRef.current = nextsetPreview(next)setSelected(diff --git a/src/server/ipc/legacy-import.test.ts b/src/server/ipc/legacy-import.test.tsindex b44d86a1..e83e093c 100644--- a/src/server/ipc/legacy-import.test.ts+++ b/src/server/ipc/legacy-import.test.ts@@ -12,7 +12,7 @@ describe('server legacy import boundary', () => {...unsupportedLegacyImportCommands(),...unsupportedLegacyImportQueries(),}- expect(Object.keys(handlers)).toHaveLength(19)+ expect(Object.keys(handlers)).toHaveLength(20)await expect(handlers[Queries.GetLegacyImportNavigation]?.()).resolves.toEqual({ detected: false, invitationPending: false })diff --git a/src/server/ipc/legacy-import.ts b/src/server/ipc/legacy-import.tsindex c6a44dbf..5721e667 100644--- a/src/server/ipc/legacy-import.ts+++ b/src/server/ipc/legacy-import.ts@@ -23,6 +23,7 @@ export function unsupportedLegacyImportCommands(): CommandHandlerMap {[Commands.RevealLegacyImportSource]: desktopOnly,[Commands.PickLegacyTorrentMetadata]: desktopOnly,[Commands.CommitLegacyImport]: desktopOnly,+ [Commands.ReleaseLegacyImportPreview]: desktopOnly,[Commands.CancelLegacyImport]: desktopOnly,[Commands.RetryLegacyImport]: desktopOnly,[Commands.DismissLegacyImportInvitation]: desktopOnly,diff --git a/src/server/plugin/capability-host.test.ts b/src/server/plugin/capability-host.test.tsindex 4c364ac2..9403e803 100644--- a/src/server/plugin/capability-host.test.ts+++ b/src/server/plugin/capability-host.test.ts@@ -102,6 +102,8 @@ describe('createServerCapabilityHost', () => {})expect(host.http).toBeInstanceOf(HttpCapabilityHost)+ expect(host.releaseLog).toBeTypeOf('function')+ expect(host.closeLogs).toBeTypeOf('function')})it('notify.available is false (server runtime)', async () => {diff --git a/src/server/plugin/capability-host.ts b/src/server/plugin/capability-host.tsindex 1e63ba0d..ca1affb5 100644--- a/src/server/plugin/capability-host.ts+++ b/src/server/plugin/capability-host.ts@@ -141,6 +141,8 @@ export async function createServerCapabilityHost(setLocale: (locale) => i18nCap.setLanguage(locale),onLocaleChange: (h) => i18nCap.onChange(h),flush: () => log.flush(),+ releaseLog: (id) => log.release(id),+ closeLogs: () => log.close(),// ── Plan B ──────────────────────────────────────────────────────────────http,diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex 7d7b2cab..031b5bc0 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -24,6 +24,7 @@ export const Commands = {RevealLegacyImportSource: 'command:revealLegacyImportSource',PickLegacyTorrentMetadata: 'command:pickLegacyTorrentMetadata',CommitLegacyImport: 'command:commitLegacyImport',+ ReleaseLegacyImportPreview: 'command:releaseLegacyImportPreview',CancelLegacyImport: 'command:cancelLegacyImport',RetryLegacyImport: 'command:retryLegacyImport',DismissLegacyImportInvitation: 'command:dismissLegacyImportInvitation',diff --git a/src/shared/schemas/legacy-import.ts b/src/shared/schemas/legacy-import.tsindex 574de78e..d116cae7 100644--- a/src/shared/schemas/legacy-import.ts+++ b/src/shared/schemas/legacy-import.ts@@ -114,6 +114,9 @@ export type LegacyImportReport = z.infer<typeof legacyImportReportSchema>export const legacyScanRequestSchema = z.object({ sourceHandle: z.uuid() }).strict()+export const legacyPreviewRequestSchema = z+ .object({ previewId: z.uuid() })+ .strict()export const legacyMetadataRequestSchema = z.object({ previewId: z.uuid(), itemId: z.string().min(1).max(128) }).strict()diff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.tsindex 989c2104..e103401d 100644--- a/tests/scripts/production-build.test.ts+++ b/tests/scripts/production-build.test.ts@@ -5,8 +5,8 @@ import { beforeAll, describe, expect, it } from 'vitest'const MIB = 1024 * 1024const ROOT = path.resolve(import.meta.dirname, '../..')const TARGETS = [- // Plugin operations, renderer recovery and 26 catalogs bring main to ~5.28 MiB.- { name: 'main', initial: 2 * MIB, total: 5.5 * MIB },+ // Explicit resource lifetimes add ~6 KiB; retain the 2 MiB startup ceiling.+ { name: 'main', initial: 2 * MIB, total: 5.5 * MIB + 8 * 1024 },{ name: 'preload', initial: 80 * 1024, total: 80 * 1024 },{ name: 'worker', initial: 48 * 1024, total: 48 * 1024 },{ name: 'renderer', initial: 2.75 * MIB, total: 8 * MIB },