A full-featured download manager.
feat(downloads): add shutdown after all downloads finish (#2284)
Dr_rOot5a5ec08b7e72
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex bf2d3812..27084e9c 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -898,7 +898,7 @@ jobs:EXPECTED_COMMIT: ${{ github.sha }}EXPECTED_PLATFORM: ${{ matrix.platform }}# Updated only after reviewing the verifier source itself.- VERIFIER_SHA256: dc838f0ec84ef65118d60a47a0aae362cdd95588dd1e0cef705836ec1629cbd1+ VERIFIER_SHA256: 24c5485906ced3f81479d09033f96e25f17c75a2f20c253d5ebb4ed4027f0870run: |const crypto = require('node:crypto')const fs = require('node:fs')diff --git a/build/entitlements.mac.plist b/build/entitlements.mac.plistindex bd1f4d97..fa9d9959 100644--- a/build/entitlements.mac.plist+++ b/build/entitlements.mac.plist@@ -2,6 +2,8 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <key>com.apple.security.automation.apple-events</key>+ <true/><!-- Chromium V8 JIT — required by every Electron app (V8 writesexecutable pages at runtime; without these two, the renderercrashes on startup under hardened runtime). -->diff --git a/electron-builder.json b/electron-builder.jsonindex 6f15afbd..d7e86bef 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -107,6 +107,7 @@}],"extendInfo": {+ "NSAppleEventsUsageDescription": "Motrix requests permission to shut down your Mac when all downloads finish, only when you enable this action.","NSLocalNetworkUsageDescription": "Motrix uses the local network for UPnP port mapping and discovering download peers."},"sign": "./scripts/sign-macos.mjs",diff --git a/scripts/electron-package-size-budgets.json b/scripts/electron-package-size-budgets.jsonindex 157ef189..929855f4 100644--- a/scripts/electron-package-size-budgets.json+++ b/scripts/electron-package-size-budgets.json@@ -1,6 +1,6 @@{"schemaVersion": 1,- "payloadBytes": 26214400,+ "payloadBytes": 26279936,"betterSqlite3Bytes": 4194304,"unexpectedPackageNames": 0,"foreignBetterSqlite3Prebuilds": 0,diff --git a/scripts/release-signing-input.mjs b/scripts/release-signing-input.mjsindex 90d3f72d..93fb9899 100644--- a/scripts/release-signing-input.mjs+++ b/scripts/release-signing-input.mjs@@ -47,7 +47,7 @@ const TRUSTED_INPUT_SHA256 = Object.freeze({'signing-build-resources/background.tiff':'f15290fe1a059a6b262466445fd24a63eabf0e2a4f734f9812dfe8ac0b9609c1','signing-build-resources/entitlements.mac.plist':- '38e56782c6c54555ff3c19b344ce8887e0689d935770a45208883e37f6aec500',+ '7520c54bdda9880a65e607a1539269ec69d60d97e54da36879d6ea089fb219dd','signing-build-resources/icon.icns':'f9ff86f32c2110b21d71a49a346f4186c4ef2cf1aed3884eca9704cb77fb4ed7','signing-build-resources/icon.ico':@@ -67,7 +67,7 @@ const TRUSTED_INPUT_SHA256 = Object.freeze({'signing-tool/package-lock.json':'54d575e0b5d9ec9ebfdc4703cdcbd5c3a91dd51f0580df918875d7f3c4af8887','scripts/electron-package-size-budgets.json':- 'eb71ed3a44c8b2f0c94bb30316e29cca7c939a63d2f2592f6a1080cd5335180a',+ '64e4646581c981632858d8b7fa4c0dbd248e9f3d9e6c3d929aadf682a07a6be7','scripts/electron-package-utils.mjs':'9d408f9edc91182be5d5aed39f2c5a5d20f5523e08d9c08e630c23c66302daa8','scripts/before-build-use-staged-dependencies.mjs':diff --git a/src/core/bridge/handlers/write-handlers.test.ts b/src/core/bridge/handlers/write-handlers.test.tsindex e9a94e3e..7d0b37b1 100644--- a/src/core/bridge/handlers/write-handlers.test.ts+++ b/src/core/bridge/handlers/write-handlers.test.ts@@ -92,6 +92,61 @@ function setup(over: Partial<WriteHandlerDeps> = {}) {return { d, deps }}+describe('shell work admission', () => {+ it('admits download/add before torrent parsing and drains the whole creation', async () => {+ const admission = Promise.withResolvers<void>()+ const parsing = Promise.withResolvers<number>()+ let settled = false+ const admitted = vi.fn()+ const trackAsyncWork = async <T>(operation: () => Promise<T>) => {+ admitted()+ await admission.promise+ const result = await operation()+ settled = true+ return result+ }+ const { d, deps } = setup({+ trackAsyncWork,+ parseTorrentFileCount: () => parsing.promise,+ })+ const pending = d.dispatch(+ 'download/add',+ { kind: 'torrent', saveDir: '/dl', base64: 'Zm9v' },+ cliCtx+ )+ expect(admitted).toHaveBeenCalledOnce()+ expect(deps.createTask).not.toHaveBeenCalled()+ admission.resolve()+ await Promise.resolve()+ expect(settled).toBe(false)+ parsing.resolve(1)+ await pending+ expect(settled).toBe(true)+ expect(deps.createTask).toHaveBeenCalledOnce()+ })++ it.each(['task/pause', 'task/resume', 'task/remove'])(+ 'gates %s before mutation',+ async (method) => {+ const admission = Promise.withResolvers<void>()+ const admitted = vi.fn()+ const trackAsyncWork = async <T>(operation: () => Promise<T>) => {+ admitted()+ await admission.promise+ return operation()+ }+ const { d, deps } = setup({ trackAsyncWork })+ const pending = d.dispatch(method, { taskId: 'task-1' }, cliCtx)+ expect(admitted).toHaveBeenCalledOnce()+ expect(deps.pauseTask).not.toHaveBeenCalled()+ expect(deps.resumeTask).not.toHaveBeenCalled()+ expect(deps.removeTask).not.toHaveBeenCalled()+ admission.resolve()+ await expect(pending).resolves.toEqual({ ok: true })+ }+ )+})+describe('task/pause', () => {it('delegates once by public task id', async () => {const { d, deps } = setup()diff --git a/src/core/bridge/handlers/write-handlers.ts b/src/core/bridge/handlers/write-handlers.tsindex 79796781..911d13c5 100644--- a/src/core/bridge/handlers/write-handlers.ts+++ b/src/core/bridge/handlers/write-handlers.ts@@ -29,6 +29,8 @@ import type { MdxpDispatcher } from '../mdxp-dispatcher'* Electron-shell capability: the headless server deliberately omits it.*/export interface WriteHandlerDeps {+ /** Shell admission/drain; covers parsing and resolution before task publication. */+ trackAsyncWork?: <T>(operation: () => Promise<T>) => Promise<T>taskManager: { getById(id: string): DownloadTask | undefined }pauseTask: (taskId: string) => Promise<void>resumeTask: (taskId: string) => Promise<void>@@ -64,36 +66,41 @@ export function registerWriteHandlers(dispatcher: MdxpDispatcher,deps: WriteHandlerDeps): void {+ const run = <T>(operation: () => Promise<T>): Promise<T> =>+ deps.trackAsyncWork ? deps.trackAsyncWork(operation) : operation()dispatcher.register(Methods.TaskPause,TaskPauseParamsSchema,- async (params): Promise<OkResult> => {- requireTask(deps, params.taskId)- await deps.pauseTask(params.taskId)- return OK- }+ (params): Promise<OkResult> =>+ run(async () => {+ requireTask(deps, params.taskId)+ await deps.pauseTask(params.taskId)+ return OK+ }))dispatcher.register(Methods.TaskResume,TaskResumeParamsSchema,- async (params): Promise<OkResult> => {- requireTask(deps, params.taskId)- await deps.resumeTask(params.taskId)- return OK- }+ (params): Promise<OkResult> =>+ run(async () => {+ requireTask(deps, params.taskId)+ await deps.resumeTask(params.taskId)+ return OK+ }))dispatcher.register(Methods.TaskRemove,TaskRemoveParamsSchema,- async (params): Promise<OkResult> => {- requireTask(deps, params.taskId)- await deps.removeTask(params.taskId, {- deleteFiles: params.deleteFiles ?? false,+ (params): Promise<OkResult> =>+ run(async () => {+ requireTask(deps, params.taskId)+ await deps.removeTask(params.taskId, {+ deleteFiles: params.deleteFiles ?? false,+ })+ return OK})- return OK- })if (deps.revealTask) {@@ -101,23 +108,24 @@ export function registerWriteHandlers(dispatcher.register(Methods.TaskReveal,TaskRevealParamsSchema,- async (params): Promise<OkResult> => {- // Resolve the public id before crossing into the shell. The protocol- // never accepts a caller-supplied path; the Electron handler derives- // the destination from this trusted task record.- requireTask(deps, params.taskId)- try {- await revealTask(params.taskId)- } catch {- // Shell/OS errors can contain an absolute path. Keep that detail out- // of the remote response and expose only the capability-level fact.- throw makeMdxpError(- ErrorCodes.ResourceUnavailable,- 'task output cannot be revealed'- )- }- return OK- }+ (params): Promise<OkResult> =>+ run(async () => {+ // Resolve the public id before crossing into the shell. The protocol+ // never accepts a caller-supplied path; the Electron handler derives+ // the destination from this trusted task record.+ requireTask(deps, params.taskId)+ try {+ await revealTask(params.taskId)+ } catch {+ // Shell/OS errors can contain an absolute path. Keep that detail out+ // of the remote response and expose only the capability-level fact.+ throw makeMdxpError(+ ErrorCodes.ResourceUnavailable,+ 'task output cannot be revealed'+ )+ }+ return OK+ }))}@@ -129,33 +137,37 @@ export function registerWriteHandlers(dispatcher.register(Methods.DownloadAdd,DownloadAddParamsSchema,- async (params, ctx): Promise<MdxpTask> => {- const createAndSnapshot = async (): Promise<MdxpTask> => {- const req = await buildCreateRequest(params, deps.parseTorrentFileCount)- if (req.type === 'http' && params.idempotencyKey) {- req.requestId = scopedCreateRequestId(- clientKey(ctx.identity),- params.idempotencyKey+ (params, ctx): Promise<MdxpTask> =>+ run(async () => {+ const createAndSnapshot = async (): Promise<MdxpTask> => {+ const req = await buildCreateRequest(+ params,+ deps.parseTorrentFileCount)+ if (req.type === 'http' && params.idempotencyKey) {+ req.requestId = scopedCreateRequestId(+ clientKey(ctx.identity),+ params.idempotencyKey+ )+ }+ const { taskId } = await deps.createTask(req)+ // handleCreateTask registers the task synchronously, so getById should+ // resolve immediately; a miss means the create path is broken.+ const task = deps.taskManager.getById(taskId)+ if (!task) {+ throw makeMdxpError(+ ErrorCodes.AdapterError,+ `created task not retrievable: ${taskId}`+ )+ }+ return toMdxpTask(task)}- const { taskId } = await deps.createTask(req)- // handleCreateTask registers the task synchronously, so getById should- // resolve immediately; a miss means the create path is broken.- const task = deps.taskManager.getById(taskId)- if (!task) {- throw makeMdxpError(- ErrorCodes.AdapterError,- `created task not retrievable: ${taskId}`- )- }- return toMdxpTask(task)- }- const key = params.idempotencyKey- if (!key) return createAndSnapshot()- return addsByKey.run(- JSON.stringify([clientKey(ctx.identity), key]),- createAndSnapshot- )- }+ const key = params.idempotencyKey+ if (!key) return createAndSnapshot()+ return addsByKey.run(+ JSON.stringify([clientKey(ctx.identity), key]),+ createAndSnapshot+ )+ }))}diff --git a/src/core/inspector-activity/async-work-tracker.ts b/src/core/inspector-activity/async-work-tracker.tsindex fb5a4f6d..9cd9ffa0 100644--- a/src/core/inspector-activity/async-work-tracker.ts+++ b/src/core/inspector-activity/async-work-tracker.ts@@ -28,7 +28,7 @@ export class AsyncWorkTracker {return this.drainPromise}- private async drainAcceptedWork(): Promise<void> {+ async drainAcceptedWork(): Promise<void> {while (this.inFlight.size > 0) {await Promise.allSettled([...this.inFlight])}diff --git a/src/core/task/completion-shutdown-controller.test.ts b/src/core/task/completion-shutdown-controller.test.tsnew file mode 100644index 00000000..752ed95a--- /dev/null+++ b/src/core/task/completion-shutdown-controller.test.ts@@ -0,0 +1,381 @@+import {+ type DownloadTask,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { CompletionShutdownController } from './completion-shutdown-controller'++function task(+ id: string,+ status = TaskStatus.Downloading,+ transitionPhase = TransitionPhase.Idle+): DownloadTask {+ return { id, status, transitionPhase } as DownloadTask+}++function fixture(initial = [task('one')]) {+ let tasks = initial+ const lease = {+ drain: vi.fn(async () => {}),+ hasIncomingWork: vi.fn(() => false),+ release: vi.fn(),+ }+ const deps = {+ supported: true,+ getTasks: () => tasks,+ isReady: vi.fn(() => true),+ probe: vi.fn(async () => {}),+ prepare: vi.fn(() => lease),+ save: vi.fn(async () => {}),+ requestShutdown: vi.fn(async () => {}),+ onState: vi.fn(),+ onError: vi.fn(),+ }+ const controller = new CompletionShutdownController(deps)+ return {+ controller,+ deps,+ lease,+ setTasks: (next: DownloadTask[]) => {+ tasks = next+ controller.evaluate()+ },+ }+}++describe('CompletionShutdownController', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ it('retains tasks that finish while authorization is pending', async () => {+ const f = fixture()+ const authorization = Promise.withResolvers<void>()+ f.deps.probe.mockReturnValue(authorization.promise)+ const enabling = f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ authorization.resolve()+ await enabling+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ f.controller.dispose()+ })++ it('tracks new tasks even if their first published snapshot is already completed', async () => {+ const f = fixture([])+ await f.controller.setEnabled(true)+ f.setTasks([task('new', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ f.controller.dispose()+ })++ it('does not treat restored completed history as newly finished work', async () => {+ const f = fixture([])+ f.deps.isReady.mockReturnValue(false)+ const authorization = Promise.withResolvers<void>()+ f.deps.probe.mockReturnValue(authorization.promise)+ const enabling = f.controller.setEnabled(true)+ f.setTasks([task('restored', TaskStatus.Completed)])+ f.deps.isReady.mockReturnValue(true)+ authorization.resolve()+ await enabling+ await vi.advanceTimersByTimeAsync(90_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ f.controller.dispose()+ })++ it('cancels authorization when an enrolled task is removed', async () => {+ const f = fixture()+ const authorization = Promise.withResolvers<void>()+ f.deps.probe.mockReturnValue(authorization.promise)+ const enabling = f.controller.setEnabled(true)+ f.setTasks([])+ authorization.resolve()+ await enabling+ await vi.advanceTimersByTimeAsync(90_000)+ expect(f.controller.getState().phase).toBe('off')+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ f.controller.dispose()+ })++ it('checks clock jumps on task events before the interval can run', async () => {+ const f = fixture()+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(1_000)+ vi.setSystemTime(Date.now() + 3_600_000)+ f.controller.evaluate()+ await vi.advanceTimersByTimeAsync(59_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ f.controller.dispose()+ })++ it('invalidates preparation if the clock jumps while saving', async () => {+ const f = fixture()+ f.deps.save.mockImplementation(async () => {+ vi.setSystemTime(Date.now() + 3_600_000)+ })+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ expect(f.controller.getState().phase).toBe('waiting')+ f.controller.dispose()+ })++ it('does not allow a cancelled save to execute or release a newer preparation', async () => {+ const f = fixture()+ const newLease = { ...f.lease, release: vi.fn() }+ f.deps.prepare.mockReturnValueOnce(f.lease).mockReturnValueOnce(newLease)+ const oldSave = Promise.withResolvers<void>()+ const newSave = Promise.withResolvers<void>()+ f.deps.save+ .mockReturnValueOnce(oldSave.promise)+ .mockReturnValueOnce(newSave.promise)+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Seeding)])+ await vi.advanceTimersByTimeAsync(60_000)+ f.controller.cancel()+ await f.controller.setEnabled(true)+ await vi.advanceTimersByTimeAsync(60_000)+ oldSave.resolve()+ await vi.advanceTimersByTimeAsync(0)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ expect(newLease.release).not.toHaveBeenCalled()+ newSave.resolve()+ await vi.advanceTimersByTimeAsync(0)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ expect(newLease.release).toHaveBeenCalledOnce()+ f.controller.dispose()+ })++ it('restarts the grace period for newly observed work that already completed', async () => {+ const f = fixture()+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(59_000)+ f.setTasks([+ task('one', TaskStatus.Completed),+ task('two', TaskStatus.Completed),+ ])+ await vi.advanceTimersByTimeAsync(59_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ f.controller.dispose()+ })++ it.each(['event', 'snapshot'] as const)(+ 'invalidates a save when new completed work is observed by %s',+ async (delivery) => {+ const f = fixture()+ f.deps.save.mockImplementationOnce(async () => {+ const tasks = [+ task('one', TaskStatus.Completed),+ task('two', TaskStatus.Completed),+ ]+ if (delivery === 'event') f.setTasks(tasks)+ else f.deps.getTasks = () => tasks+ })+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ expect(f.controller.getState().phase).toBe('waiting')+ f.controller.dispose()+ }+ )++ it('cancels preparation when an existing task becomes unfinished even if it completes again before save returns', async () => {+ const f = fixture()+ f.deps.save.mockImplementationOnce(async () => {+ f.setTasks([task('one', TaskStatus.Downloading)])+ f.setTasks([task('one', TaskStatus.Completed)])+ })+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ f.controller.dispose()+ })++ it('waits for file finalization, saves before shutdown, and submits only once', async () => {+ const f = fixture()+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Finalizing, TransitionPhase.Renaming)])+ await vi.advanceTimersByTimeAsync(70_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(59_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.deps.save).toHaveBeenCalledOnce()+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ expect(f.deps.save.mock.invocationCallOrder[0]).toBeLessThan(+ f.deps.requestShutdown.mock.invocationCallOrder[0]+ )+ await vi.advanceTimersByTimeAsync(90_000)+ f.controller.evaluate()+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ expect(f.lease.release).toHaveBeenCalledOnce()+ })++ it.each([+ TaskStatus.Paused,+ TaskStatus.Error,+ TaskStatus.Queued,+ TaskStatus.MetadataReady,+ TaskStatus.FetchingMetadata,+ ])('does not treat %s as completion', async (status) => {+ const f = fixture([task('one', status)])+ await f.controller.setEnabled(true)+ await vi.advanceTimersByTimeAsync(90_000)+ expect(f.controller.getState().phase).toBe('waiting')+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ })++ it.each([{ tasks: [] }, { tasks: [task('old', TaskStatus.Completed)] }])(+ 'does not shut down an empty or historical queue',+ async ({ tasks }) => {+ const f = fixture(tasks)+ await f.controller.setEnabled(true)+ await vi.advanceTimersByTimeAsync(90_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ }+ )++ it('cancels when participating tasks are removed', async () => {+ const f = fixture()+ await f.controller.setEnabled(true)+ f.setTasks([])+ await vi.advanceTimersByTimeAsync(90_000)+ expect(f.controller.getState().phase).toBe('off')+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ })++ it('restarts the full countdown after a new task completes', async () => {+ const f = fixture()+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(50_000)+ f.setTasks([task('one', TaskStatus.Completed), task('two')])+ expect(f.controller.getState().phase).toBe('waiting')+ f.setTasks([+ task('one', TaskStatus.Completed),+ task('two', TaskStatus.Completed),+ ])+ await vi.advanceTimersByTimeAsync(59_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ })++ it('allows finalized seeding and blocks reseeding transitions', async () => {+ const f = fixture([+ task('one', TaskStatus.Seeding, TransitionPhase.Reseeding),+ ])+ await f.controller.setEnabled(true)+ expect(f.controller.getState().phase).toBe('waiting')+ f.setTasks([task('one', TaskStatus.Seeding)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ })++ it('cancels while an asynchronous save is in flight', async () => {+ const f = fixture()+ let resolve!: () => void+ f.deps.save.mockImplementation(+ () =>+ new Promise<void>((done) => {+ resolve = done+ })+ )+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ await f.controller.setEnabled(false)+ resolve()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ expect(f.controller.getState().phase).toBe('off')+ })++ it('does not execute after incoming work, persistence failure, or engine loss', async () => {+ for (const cause of ['incoming', 'save', 'engine'] as const) {+ const f = fixture()+ f.deps.save.mockImplementation(async () => {+ if (cause === 'incoming') f.lease.hasIncomingWork.mockReturnValue(true)+ if (cause === 'engine') f.deps.isReady.mockReturnValue(false)+ if (cause === 'save') throw new Error('disk full')+ })+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ expect(f.lease.release).toHaveBeenCalled()+ f.controller.dispose()+ }+ })++ it('times out preparation without letting its late continuation submit shutdown', async () => {+ const f = fixture()+ let resolve!: () => void+ f.lease.drain.mockImplementation(+ () =>+ new Promise<void>((done) => {+ resolve = done+ })+ )+ await f.controller.setEnabled(true)+ f.setTasks([task('one', TaskStatus.Completed)])+ await vi.advanceTimersByTimeAsync(70_000)+ expect(f.controller.getState().phase).toBe('failed')+ resolve()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.deps.save).not.toHaveBeenCalled()+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ })++ it('cancels pending authorization and never arms after disposal', async () => {+ const f = fixture()+ let resolve!: () => void+ f.deps.probe.mockImplementation(+ () =>+ new Promise<void>((done) => {+ resolve = done+ })+ )+ const enabling = f.controller.setEnabled(true)+ f.controller.dispose()+ resolve()+ await enabling+ expect(f.controller.getState().phase).toBe('off')+ expect(vi.getTimerCount()).toBe(0)+ })++ it('resets the countdown after a sleep or wall-clock discontinuity', async () => {+ const f = fixture([task('one', TaskStatus.Seeding)])+ await f.controller.setEnabled(true)+ await vi.advanceTimersByTimeAsync(50_000)+ vi.setSystemTime(Date.now() + 3600_000)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(f.controller.getState().deadline).toBe(Date.now() + 60_000)+ expect(f.deps.requestShutdown).not.toHaveBeenCalled()+ f.controller.interrupt()+ expect(f.controller.getState().phase).toBe('waiting')+ })++ it('reports platform rejection without retrying automatically', async () => {+ const f = fixture([task('one', TaskStatus.Seeding)])+ f.deps.requestShutdown.mockRejectedValue(new Error('permission denied'))+ await f.controller.setEnabled(true)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(f.controller.getState().phase).toBe('failed')+ expect(f.deps.requestShutdown).toHaveBeenCalledOnce()+ })+})diff --git a/src/core/task/completion-shutdown-controller.ts b/src/core/task/completion-shutdown-controller.tsnew file mode 100644index 00000000..f4b2c5dd--- /dev/null+++ b/src/core/task/completion-shutdown-controller.ts@@ -0,0 +1,275 @@+import type { CompletionShutdownState } from '@shared/schemas/completion-shutdown'+import {+ type DownloadTask,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'++export interface ShutdownPreparation {+ drain(): Promise<void>+ hasIncomingWork(): boolean+ release(): void+}++interface Dependencies {+ supported: boolean+ getTasks(): DownloadTask[]+ isReady(): boolean+ probe(): Promise<void>+ prepare(): ShutdownPreparation+ save(): Promise<void>+ requestShutdown(): Promise<void>+ onState(state: CompletionShutdownState): void+ onError(error: unknown): void+}++const COUNTDOWN_MS = 60_000++function isFinished(task: DownloadTask): boolean {+ return (+ (task.status === TaskStatus.Completed ||+ task.status === TaskStatus.Seeding) &&+ task.transitionPhase === TransitionPhase.Idle+ )+}++/** Process-local, one-shot intent. Neither restored history nor an empty queue arms it. */+export class CompletionShutdownController {+ private state: CompletionShutdownState+ private generation = 0+ private participants = new Set<string>()+ private historical: Set<string> | null = null+ private authorizing = false+ private timer: ReturnType<typeof setInterval> | null = null+ private lastTick = 0+ private lastMonotonicTick = 0+ private monotonicDeadline = 0+ private preparation: ShutdownPreparation | null = null+ private disposed = false++ constructor(private readonly deps: Dependencies) {+ this.state = {+ supported: deps.supported,+ phase: 'off',+ deadline: null,+ error: null,+ }+ }++ getState(): CompletionShutdownState {+ return { ...this.state }+ }++ async setEnabled(enabled: boolean): Promise<CompletionShutdownState> {+ if (this.disposed) return this.getState()+ if (!enabled) {+ this.cancel()+ return this.getState()+ }+ if (+ this.authorizing ||+ ['waiting', 'countdown', 'preparing', 'requested'].includes(+ this.state.phase+ )+ )+ return this.getState()+ const generation = ++this.generation+ this.participants.clear()+ this.historical = null+ this.authorizing = true+ this.collectTasks()+ try {+ if (!this.deps.supported)+ throw new Error('Shutdown is unavailable on this host')+ await this.deps.probe()+ } catch (error) {+ if (generation === this.generation) {+ this.authorizing = false+ this.deps.onError(error)+ this.update('failed', null, 'unavailable')+ }+ return this.getState()+ }+ if (generation !== this.generation) return this.getState()+ this.authorizing = false+ this.update('waiting')+ this.lastTick = Date.now()+ this.lastMonotonicTick = performance.now()+ this.timer = setInterval(() => this.evaluate(), 1_000)+ this.evaluate()+ return this.getState()+ }++ cancel(): void {+ ++this.generation+ this.clearTimer()+ this.preparation?.release()+ this.preparation = null+ this.participants.clear()+ this.historical = null+ this.authorizing = false+ this.update('off')+ }++ /** Suspend, reconnect and new work always invalidate the old deadline. */+ interrupt(): void {+ if (this.state.phase !== 'countdown' && this.state.phase !== 'preparing')+ return+ ++this.generation+ this.preparation?.release()+ this.preparation = null+ this.update('waiting')+ }++ evaluate(): void {+ if (this.authorizing) {+ this.collectTasks()+ return+ }+ if (['waiting', 'countdown', 'preparing'].includes(this.state.phase))+ this.observeClock()+ if (this.state.phase === 'preparing') {+ if (!this.ready()) this.interrupt()+ return+ }+ if (this.state.phase !== 'waiting' && this.state.phase !== 'countdown')+ return+ if (!this.ready()) {+ if (this.state.phase === 'countdown') this.interrupt()+ return+ }+ if (this.state.phase === 'waiting') {+ this.monotonicDeadline = performance.now() + COUNTDOWN_MS+ this.update('countdown', Date.now() + COUNTDOWN_MS)+ } else if (+ this.state.deadline !== null &&+ performance.now() >= this.monotonicDeadline+ ) {+ void this.execute()+ }+ }++ private observeClock(): void {+ const wall = Date.now()+ const monotonic = performance.now()+ const elapsed = monotonic - this.lastMonotonicTick+ if (elapsed > 5_000 || Math.abs(wall - this.lastTick - elapsed) > 5_000)+ this.interrupt()+ this.lastTick = wall+ this.lastMonotonicTick = monotonic+ }++ private collectTasks(): DownloadTask[] | null {+ // Establish the history baseline only once startup/restore is ready.+ if (!this.deps.isReady()) return null+ const tasks = this.deps+ .getTasks()+ .filter((task) => task.status !== TaskStatus.Removed)+ this.historical ??= new Set(+ tasks+ .filter((task) => task.status === TaskStatus.Completed)+ .map((task) => task.id)+ )+ const ids = new Set(tasks.map((task) => task.id))+ // Removing participating tasks cancels the plan; deleting is not completion.+ if ([...this.participants].some((id) => !ids.has(id))) {+ this.cancel()+ return null+ }+ let added = false+ for (const task of tasks) {+ if (+ (!this.historical.has(task.id) ||+ task.status !== TaskStatus.Completed) &&+ !this.participants.has(task.id)+ ) {+ this.participants.add(task.id)+ added = true+ }+ }+ if (added) this.interrupt()+ return tasks+ }++ private ready(): boolean {+ const tasks = this.collectTasks()+ return (+ tasks !== null && this.participants.size > 0 && tasks.every(isFinished)+ )+ }++ private async execute(): Promise<void> {+ const generation = ++this.generation+ this.update('preparing')+ let timeout: ReturnType<typeof setTimeout> | undefined+ let preparation: ShutdownPreparation | undefined+ const current = () => generation === this.generation && !this.disposed+ try {+ preparation = this.deps.prepare()+ this.preparation = preparation+ const lease = preparation+ let saved = false+ await Promise.race([+ lease.drain().then(async () => {+ if (+ !current() ||+ lease.hasIncomingWork() ||+ !this.ready() ||+ !current()+ )+ return+ await this.deps.save()+ saved = true+ }),+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () => reject(new Error('Shutdown preparation timed out')),+ 10_000+ )+ }),+ ])+ if (!current()) return+ this.observeClock()+ if (!current()) return+ if (!saved || lease.hasIncomingWork() || !this.ready() || !current()) {+ if (current()) this.update('waiting')+ return+ }+ // No await between the last check and invoking the fixed platform action.+ this.clearTimer()+ this.update('requested')+ if (!current()) return+ await this.deps.requestShutdown()+ } catch (error) {+ if (current()) {+ ++this.generation+ this.clearTimer()+ this.deps.onError(error)+ this.update('failed', null, 'failed')+ }+ } finally {+ if (timeout !== undefined) clearTimeout(timeout)+ preparation?.release()+ if (this.preparation === preparation) this.preparation = null+ }+ }++ private update(+ phase: CompletionShutdownState['phase'],+ deadline: number | null = null,+ error: CompletionShutdownState['error'] = null+ ): void {+ this.state = { supported: this.deps.supported, phase, deadline, error }+ this.deps.onState(this.getState())+ }++ private clearTimer(): void {+ if (this.timer !== null) clearInterval(this.timer)+ this.timer = null+ }++ dispose(): void {+ this.disposed = true+ this.cancel()+ }+}diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.tsindex a1dabd04..69de685d 100644--- a/src/main/bridge/bootstrap-lifecycle.test.ts+++ b/src/main/bridge/bootstrap-lifecycle.test.ts@@ -18,6 +18,7 @@ import { PairingService } from '@core/bridge/pairing-service'import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'+import { CompletionShutdownController } from '@core/task/completion-shutdown-controller'import * as taskCreation from '@core/task/create-task-handler'import {BridgeCommands,@@ -25,11 +26,13 @@ import {type BridgeStatusInfo,} from '@shared/protocol/bridge'import { EngineState } from '@shared/types/engine'+import { TaskStatus } from '@shared/types/task'import {makeDirectSubmit,makeExtensionContext,} from '@test-utils/bridge-receiver'import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'+import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {computeManifestPaths,@@ -96,6 +99,7 @@ vi.mock('../ipc/trusted-ipc', () => ({) => electron.handle(channel, listener),}))+import { MainProcessWorkCoordinator } from '../main-process-work-coordinator'import { bootstrapBridge } from './index'function args(): Parameters<typeof bootstrapBridge>[0] {@@ -211,10 +215,102 @@ describe('desktop bridge bootstrap ownership', () => {})afterEach(async () => {+ vi.useRealTimers()vi.restoreAllMocks()await rm(userDataDir, { recursive: true, force: true })})+ it('blocks shutdown while an extension submit is resolving before engine/task publication', async () => {+ const coordinator = new MainProcessWorkCoordinator()+ const name = Promise.withResolvers<string>()+ const pick = vi.fn(() => name.promise)+ const createTask = vi+ .spyOn(taskCreation, 'handleCreateTask')+ .mockResolvedValue({ outcome: 'created', gid: 'gid', taskId: 'task' })+ const registration = vi.spyOn(+ WebSocketBridgeServer.prototype,+ 'setHandlers'+ )+ const writes = vi.spyOn(+ WebSocketBridgeServer.prototype,+ 'registerWriteMethods'+ )+ const runtime = await bootstrapBridge({+ ...args(),+ finalNamePicker: { pick },+ trackAsyncWork: (operation) => coordinator.run(operation),+ })+ if (!runtime) throw new Error('bridge did not start')+ const requestShutdown = vi.fn(async () => {})+ const controller = new CompletionShutdownController({+ supported: true,+ getTasks: () => [makeDownloadTask({ status: TaskStatus.Seeding })],+ isReady: () => true,+ probe: async () => {},+ prepare: () => coordinator.prepareForPowerAction(),+ save: async () => {},+ requestShutdown,+ onState: () => {},+ onError: () => {},+ })+ try {+ expect(writes.mock.calls[0]?.[0].trackAsyncWork).toBeTypeOf('function')+ const submit = registration.mock.calls[0]?.[0].submitDownload+ if (!submit) throw new Error('submit handler missing')+ vi.useFakeTimers()+ await controller.setEnabled(true)+ await vi.advanceTimersByTimeAsync(59_000)+ const pending = submit(makeDirectSubmit(), makeExtensionContext())+ await vi.advanceTimersByTimeAsync(0)+ expect(pick).toHaveBeenCalledOnce()+ expect(createTask).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(controller.getState().phase).toBe('preparing')+ expect(requestShutdown).not.toHaveBeenCalled()+ controller.cancel()+ name.resolve('file.zip')+ await pending+ expect(createTask).toHaveBeenCalledOnce()+ expect(requestShutdown).not.toHaveBeenCalled()+ } finally {+ controller.dispose()+ vi.useRealTimers()+ name.resolve('file.zip')+ await runtime.shutdown()+ }+ })++ it('holds extension submits arriving during a power action and invalidates that action', async () => {+ const coordinator = new MainProcessWorkCoordinator()+ const createTask = vi+ .spyOn(taskCreation, 'handleCreateTask')+ .mockResolvedValue({ outcome: 'created', gid: 'gid', taskId: 'task' })+ const registration = vi.spyOn(+ WebSocketBridgeServer.prototype,+ 'setHandlers'+ )+ const runtime = await bootstrapBridge({+ ...args(),+ trackAsyncWork: (operation) => coordinator.run(operation),+ })+ if (!runtime) throw new Error('bridge did not start')+ const lease = coordinator.prepareForPowerAction()+ try {+ const submit = registration.mock.calls[0]?.[0].submitDownload+ if (!submit) throw new Error('submit handler missing')+ const pending = submit(makeDirectSubmit(), makeExtensionContext())+ expect(lease.hasIncomingWork()).toBe(true)+ await lease.drain()+ expect(createTask).not.toHaveBeenCalled()+ lease.release()+ await pending+ expect(createTask).toHaveBeenCalledOnce()+ } finally {+ lease.release()+ await runtime.shutdown()+ }+ })+it('uses the current directory through the registered submit handler without restarting', async () => {let directory = '/downloads/old'const getDefaultSaveDir = vi.fn(() => directory)diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex 8f9c7342..1450e0ea 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -455,7 +455,7 @@ export async function bootstrapBridge(args: {parentTaskCreated: BridgeReceiverDeps['parentTaskCreated']recordTransition: BridgeReceiverDeps['recordTransition']runTaskMutation: BridgeReceiverDeps['runTaskMutation']- /** Main-process shutdown gate/drain for renderer bridge IPC handlers. */+ /** Main-process admission/drain for renderer IPC and incoming download work. */trackAsyncWork: <T>(operation: () => Promise<T>) => Promise<T>// Startup barrier: submits await this before any pipeline work reaches the// engine, so a submit racing SessionManager.restore() can't get clobbered@@ -772,16 +772,19 @@ export async function bootstrapBridge(args: {// and system/ping are wired by the server itself; the dispatcher validates// params at the boundary, so these handlers receive already-typed values.server.setHandlers({- submitDownload: (params, ctx) => receiver.handle(params, ctx),- cancelDownload: async (params) => {- await receiver.cancel(params.taskId)- },+ submitDownload: (params, ctx) =>+ args.trackAsyncWork(() => receiver.handle(params, ctx)),+ cancelDownload: (params) =>+ args.trackAsyncWork(() => receiver.cancel(params.taskId)),})// v1 READ methods (task/list, task/get, stats/get, engine/status) — also// before start(), reachable via the unary POST /mdxp transport only.server.registerReadMethods(args.readHandlerDeps)// v1 WRITE methods (task/pause, task/resume, task/remove, download/add).- server.registerWriteMethods(args.writeHandlerDeps)+ server.registerWriteMethods({+ ...args.writeHandlerDeps,+ trackAsyncWork: args.trackAsyncWork,+ })const urlResolution = new UrlResolutionService(() =>Array.from(server.iterSessions())diff --git a/src/main/index.ts b/src/main/index.tsindex 547379a6..4c283f2b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -138,7 +138,7 @@ import type { AppNotification } from '@shared/types/notification'import { getHiddenNotificationKinds } from '@shared/types/notification'import type { AppSettings } from '@shared/types/settings'import type { DownloadTask } from '@shared/types/task'-import { TaskType } from '@shared/types/task'+import { TaskStatus, TaskType } from '@shared/types/task'import type { TaskOccurrence } from '@shared/types/task-occurrence'import {app,@@ -187,6 +187,7 @@ import { createOsNotificationBridge } from './notifications/os-bridge'import { DisclaimerGate } from './onboarding/disclaimer-gate'import { setupAppImageIntegration } from './platform/appimage-integration-host'import { syncAutoLaunch } from './platform/auto-launch'+import { setupCompletionShutdown } from './platform/completion-shutdown'import { resolveDefaultSaveDirOptions } from './platform/default-save-dir'import { resolveDesktopBackgroundPolicy } from './platform/desktop-background-policy'import { resolveDistributionContext } from './platform/distribution-context'@@ -2676,7 +2677,7 @@ async function initializeMainProcess(): Promise<void> {})const disposeNotificationIpc = registerNotificationIpc({notificationCenter,- trackAsyncWork: (operation) => mainProcessWork.run(operation),+ trackAsyncWork: (operation) => mainProcessWork.run(operation, false),})// The main window can mount before the full IPC ingress is ready. The@@ -2779,7 +2780,7 @@ async function initializeMainProcess(): Promise<void> {taskSpeedHistoryStore,taskInspectorActivityRuntime: activeTaskInspectorActivityQuery,waitForTasksReady: () => mainProcessWork.waitForStartup(),- trackAsyncWork: (operation) => mainProcessWork.run(operation),+ trackAsyncWork: (operation) => mainProcessWork.run(operation, false),supervisor,settingsManager,natManager,@@ -2797,7 +2798,34 @@ async function initializeMainProcess(): Promise<void> {speedLimitController,updateManager,})+ const disposeCompletionShutdown = setupCompletionShutdown({+ getMainWindow: () => windowManager.get('main') ?? null,+ showMainWindow: () => windowManager.show('main'),+ eventBus,+ getTasks: () => taskManager.getAll(),+ isReady: () =>+ mainProcessWork.isAccepting() &&+ supervisor.getState() === EngineState.Ready &&+ rpcClient.isConnected(),+ waitForReady: () => mainProcessWork.waitForStartup(),+ prepare: () => mainProcessWork.prepareForPowerAction(),+ save: async () => {+ // Check the engine too: an in-flight or external add may not yet have a parent row.+ const stats = await adapter.getGlobalStats()+ const seeding = taskManager+ .getAll()+ .filter((task) => task.status === TaskStatus.Seeding).length+ if (stats.waitingTasks > 0 || stats.activeTasks > seeding)+ throw new Error('Engine still has unfinished downloads')+ await sessionManager.save()+ },+ broadcast: (state) =>+ windowManager.broadcast(Events.CompletionShutdownChanged, state),+ translate: (key, params) => i18n.t(key, params),+ logError: (err) => log.warn({ err }, 'completion shutdown failed'),+ })disposeIpcIngress = () => {+ disposeCompletionShutdown()disposeCommandHandlers()disposeQueryHandlers()disposeNotificationIpc()@@ -2813,6 +2841,7 @@ async function initializeMainProcess(): Promise<void> {})setupPowerManager(eventBus)+// menuManager is assigned and install()ed above — non-null by this pointconst activeMenuManager = menuManager as MenuManagertrayHandle = setupTray({diff --git a/src/main/main-process-work-coordinator.test.ts b/src/main/main-process-work-coordinator.test.tsindex 14b773cc..bf6114a9 100644--- a/src/main/main-process-work-coordinator.test.ts+++ b/src/main/main-process-work-coordinator.test.ts@@ -14,6 +14,54 @@ function deferred<T>() {}describe('MainProcessWorkCoordinator', () => {+ it('queues read-only refreshes without invalidating the power action', async () => {+ const coordinator = new MainProcessWorkCoordinator()+ const lease = coordinator.prepareForPowerAction()+ const read = vi.fn(async () => 'snapshot')+ const query = coordinator.run(read, false)+ await lease.drain()+ expect(lease.hasIncomingWork()).toBe(false)+ expect(read).not.toHaveBeenCalled()+ lease.release()+ await expect(query).resolves.toBe('snapshot')+ })++ it('holds new work, reports the arrival, and resumes it without dropping operations', async () => {+ const coordinator = new MainProcessWorkCoordinator()+ const prior = deferred<void>()+ const original = coordinator.run(() => prior.promise)+ const lease = coordinator.prepareForPowerAction()+ const later = vi.fn(async () => 'accepted')+ const queued = coordinator.run(later)+ expect(lease.hasIncomingWork()).toBe(true)+ let drained = false+ const drain = lease.drain().then(() => {+ drained = true+ })+ await Promise.resolve()+ expect(drained).toBe(false)+ expect(later).not.toHaveBeenCalled()+ prior.resolve()+ await Promise.all([original, drain])+ expect(later).not.toHaveBeenCalled()+ lease.release()+ lease.release()+ await expect(queued).resolves.toBe('accepted')+ expect(later).toHaveBeenCalledOnce()+ })++ it('rejects held work after permanent shutdown rather than reopening admission', async () => {+ const coordinator = new MainProcessWorkCoordinator()+ const lease = coordinator.prepareForPowerAction()+ const operation = vi.fn(async () => {})+ const queued = coordinator.run(operation)+ const rejected = expect(queued).rejects.toThrow('stopped')+ await coordinator.stopAndDrain()+ lease.release()+ await rejected+ expect(operation).not.toHaveBeenCalled()+ })+it('drains startup restore and a waiting query before Activity and SQLite close', async () => {const coordinator = new MainProcessWorkCoordinator()const restore = deferred<void>()diff --git a/src/main/main-process-work-coordinator.ts b/src/main/main-process-work-coordinator.tsindex 4ab10ef2..ff6b512f 100644--- a/src/main/main-process-work-coordinator.ts+++ b/src/main/main-process-work-coordinator.ts@@ -1,4 +1,5 @@import { AsyncWorkTracker } from '@core/inspector-activity'+import type { ShutdownPreparation } from '@core/task/completion-shutdown-controller'/*** Owns every main-process operation that may touch lifecycle-managed state.@@ -14,6 +15,11 @@ export class MainProcessWorkCoordinator {private resolveStartupSettled!: () => voidprivate startupWork: Promise<void> | null = nullprivate startupDidSettle = false+ private admissionHold: {+ incoming: boolean+ released: Promise<void>+ release(): void+ } | null = nullconstructor() {this.startupSettled = new Promise<void>((resolve) => {@@ -41,15 +47,44 @@ export class MainProcessWorkCoordinator {return this.startupSettled}- run<T>(operation: () => Promise<T>): Promise<T> {+ run<T>(operation: () => Promise<T>, blocksPowerAction = true): Promise<T> {+ const hold = this.admissionHold+ if (hold) {+ hold.incoming ||= blocksPowerAction+ return hold.released.then(() => this.run(operation, blocksPowerAction))+ }return this.tracker.run(operation)}+ /** Queue arrivals temporarily. Mutating work invalidates a pending power action. */+ prepareForPowerAction(): ShutdownPreparation {+ if (this.admissionHold || !this.tracker.isAccepting())+ throw new Error('Work admission is unavailable')+ let resolve!: () => void+ const hold = {+ incoming: false,+ released: new Promise<void>((done) => {+ resolve = done+ }),+ release: () => {+ if (this.admissionHold === hold) this.admissionHold = null+ resolve()+ },+ }+ this.admissionHold = hold+ return {+ drain: () => this.tracker.drainAcceptedWork(),+ hasIncomingWork: () => hold.incoming,+ release: hold.release,+ }+ }+isAccepting(): boolean {return this.tracker.isAccepting()}stopAndDrain(): Promise<void> {+ this.admissionHold?.release()// Fatal cleanup can begin before app.whenReady starts restore. Release any// already-waiting request; its tracked wrapper will then drain or reject// before Activity/SQLite disposal.diff --git a/src/main/platform/completion-shutdown.test.ts b/src/main/platform/completion-shutdown.test.tsnew file mode 100644index 00000000..c26a877f--- /dev/null+++ b/src/main/platform/completion-shutdown.test.ts@@ -0,0 +1,255 @@+import { EventBus } from '@core/events/event-bus'+import { Commands } from '@shared/protocol/commands'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'+import {+ type DownloadTask,+ TaskStatus,+ TransitionPhase,+} from '@shared/types/task'+import type { BrowserWindow } from 'electron'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ handlers: new Map<string, (...args: unknown[]) => unknown>(),+ dialog: vi.fn(),+ poweroff: vi.fn(async () => {}),+ probe: vi.fn(async () => {}),+ start: vi.fn(() => 42),+ stop: vi.fn(),+ monitorOn: vi.fn(),+ monitorOff: vi.fn(),+ remove: vi.fn(),+}))+vi.mock('electron', () => ({+ dialog: { showMessageBox: mocks.dialog, showErrorBox: vi.fn() },+ ipcMain: { removeHandler: mocks.remove },+ powerSaveBlocker: { start: mocks.start, stop: mocks.stop },+ powerMonitor: { on: mocks.monitorOn, off: mocks.monitorOff },+}))+vi.mock('../ipc/trusted-ipc', () => ({+ registerTrustedIpcHandler: (+ channel: string,+ handler: (...args: unknown[]) => unknown+ ) => mocks.handlers.set(channel, handler),+}))+vi.mock('./system-shutdown', () => ({+ createSystemShutdown: () => ({+ supported: true,+ probe: mocks.probe,+ requestShutdown: mocks.poweroff,+ }),+}))++import { setupCompletionShutdown } from './completion-shutdown'++describe('desktop completion shutdown wiring', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.clearAllMocks()+ mocks.handlers.clear()+ })+ afterEach(() => vi.useRealTimers())++ function setup(+ overrides: Partial<Parameters<typeof setupCompletionShutdown>[0]> = {}+ ) {+ const eventBus = new EventBus()+ const parent = { isDestroyed: () => false } as BrowserWindow+ let tasks = [+ {+ id: 'one',+ status: TaskStatus.Downloading,+ transitionPhase: TransitionPhase.Idle,+ },+ ] as DownloadTask[]+ const broadcast = vi.fn()+ const dispose = setupCompletionShutdown({+ eventBus,+ getTasks: () => tasks,+ isReady: () => true,+ waitForReady: async () => {},+ prepare: () => ({+ drain: async () => {},+ hasIncomingWork: () => false,+ release: () => {},+ }),+ save: async () => {},+ broadcast,+ translate: (key) => key,+ logError: vi.fn(),+ getMainWindow: () => parent,+ showMainWindow: vi.fn(),+ ...overrides,+ })+ return {+ parent,+ dispose,+ broadcast,+ finish: () => {+ tasks = tasks.map((task) => ({ ...task, status: TaskStatus.Completed }))+ eventBus.emit(Events.TaskUpdated, tasks)+ },+ enable: () =>+ mocks.handlers.get(Commands.SetCompletionShutdown)?.(+ {},+ { enabled: true }+ ),+ }+ }++ it('enrolls restored active work before waiting for system authorization', async () => {+ const restored = Promise.withResolvers<void>()+ const authorized = Promise.withResolvers<void>()+ mocks.probe.mockReturnValueOnce(authorized.promise)+ mocks.dialog.mockImplementation(() => new Promise(() => {}))+ const f = setup({ waitForReady: () => restored.promise })+ const enabling = f.enable()+ restored.resolve()+ await vi.advanceTimersByTimeAsync(0)+ expect(mocks.probe).toHaveBeenCalledOnce()+ f.finish()+ authorized.resolve()+ await enabling+ await vi.advanceTimersByTimeAsync(60_000)+ expect(mocks.poweroff).toHaveBeenCalledOnce()+ f.dispose()+ })++ it.each(['missing', 'destroyed', 'show-failure'])(+ 'cancels when the window is %s',+ async (failure) => {+ const f = setup(+ failure === 'missing'+ ? { getMainWindow: () => null }+ : failure === 'destroyed'+ ? {+ getMainWindow: () =>+ ({ isDestroyed: () => true }) as BrowserWindow,+ }+ : {+ showMainWindow: () => {+ throw new Error('window failed')+ },+ }+ )+ await f.enable()+ f.finish()+ await vi.advanceTimersByTimeAsync(65_000)+ expect(mocks.poweroff).not.toHaveBeenCalled()+ expect(mocks.dialog).not.toHaveBeenCalled()+ f.dispose()+ }+ )++ it('publishes the initial snapshot, validates IPC, and uses a cancellable parented dialog', async () => {+ let close!: () => void+ mocks.dialog.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ close = resolve+ })+ )+ const f = setup()+ expect(f.broadcast).toHaveBeenCalledWith(+ expect.objectContaining({ phase: 'off' })+ )+ expect(() =>+ mocks.handlers.get(Commands.SetCompletionShutdown)?.(+ {},+ { enabled: 'yes' }+ )+ ).toThrow()+ await f.enable()+ f.finish()+ expect(mocks.dialog).toHaveBeenCalledWith(+ f.parent,+ expect.objectContaining({ signal: expect.any(AbortSignal), cancelId: 0 })+ )+ close()+ await vi.advanceTimersByTimeAsync(65_000)+ expect(mocks.poweroff).not.toHaveBeenCalled()+ expect(mocks.stop).toHaveBeenCalledWith(42)+ f.dispose()+ expect(mocks.remove).toHaveBeenCalledWith(Commands.SetCompletionShutdown)+ expect(mocks.remove).toHaveBeenCalledWith(Queries.GetCompletionShutdown)+ })++ it('closes the native countdown at the deadline without interpreting its abort as user cancellation', async () => {+ let signal!: AbortSignal+ mocks.dialog.mockImplementation(+ (_parent, options) =>+ new Promise<void>((resolve) => {+ signal = options.signal+ signal.addEventListener('abort', () => resolve())+ })+ )+ const f = setup()+ await f.enable()+ f.finish()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(signal.aborted).toBe(true)+ expect(mocks.poweroff).toHaveBeenCalledOnce()+ f.dispose()+ })++ it('honors cancellation on the last second of the countdown', async () => {+ const dismissed = Promise.withResolvers<void>()+ mocks.dialog.mockReturnValueOnce(dismissed.promise)+ const f = setup()+ await f.enable()+ f.finish()+ await vi.advanceTimersByTimeAsync(59_000)+ dismissed.resolve()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(mocks.poweroff).not.toHaveBeenCalled()+ expect(f.broadcast).toHaveBeenLastCalledWith(+ expect.objectContaining({ phase: 'off' })+ )+ f.dispose()+ })++ it('ignores the late result from a dialog aborted by suspend/resume', async () => {+ const oldDialog = Promise.withResolvers<void>()+ const newDialog = Promise.withResolvers<void>()+ mocks.dialog+ .mockReturnValueOnce(oldDialog.promise)+ .mockReturnValueOnce(newDialog.promise)+ const f = setup()+ await f.enable()+ f.finish()+ await vi.advanceTimersByTimeAsync(59_000)+ const suspend = mocks.monitorOn.mock.calls.find(+ ([event]) => event === 'suspend'+ )?.[1]+ expect(suspend).toBeTypeOf('function')+ suspend()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(mocks.dialog).toHaveBeenCalledTimes(2)+ oldDialog.resolve()+ await vi.advanceTimersByTimeAsync(59_000)+ expect(mocks.poweroff).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(mocks.poweroff).toHaveBeenCalledOnce()+ newDialog.resolve()+ f.dispose()+ })++ it.each(['reject', 'throw'])(+ 'cancels the power action if its dialog fails with %s',+ async (failure) => {+ if (failure === 'reject')+ mocks.dialog.mockRejectedValue(new Error('dialog failed'))+ else+ mocks.dialog.mockImplementation(() => {+ throw new Error('dialog failed')+ })+ const f = setup()+ await f.enable()+ f.finish()+ await vi.advanceTimersByTimeAsync(65_000)+ expect(mocks.poweroff).not.toHaveBeenCalled()+ f.dispose()+ }+ )+})diff --git a/src/main/platform/completion-shutdown.ts b/src/main/platform/completion-shutdown.tsnew file mode 100644index 00000000..bf1ad476--- /dev/null+++ b/src/main/platform/completion-shutdown.ts@@ -0,0 +1,148 @@+import type { EventBus } from '@core/events/event-bus'+import {+ CompletionShutdownController,+ type ShutdownPreparation,+} from '@core/task/completion-shutdown-controller'+import { Commands } from '@shared/protocol/commands'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'+import {+ type CompletionShutdownState,+ completionShutdownRequestSchema,+} from '@shared/schemas/completion-shutdown'+import type { DownloadTask } from '@shared/types/task'+import {+ type BrowserWindow,+ dialog,+ ipcMain,+ powerMonitor,+ powerSaveBlocker,+} from 'electron'+import { registerTrustedIpcHandler } from '../ipc/trusted-ipc'+import { createSystemShutdown } from './system-shutdown'++interface Dependencies {+ eventBus: EventBus+ getTasks(): DownloadTask[]+ isReady(): boolean+ waitForReady(): Promise<void>+ prepare(): ShutdownPreparation+ save(): Promise<void>+ broadcast(state: CompletionShutdownState): void+ translate(key: string, params?: Record<string, unknown>): string+ logError(error: unknown): void+ getMainWindow(): BrowserWindow | null+ showMainWindow(): void+}++export function setupCompletionShutdown(deps: Dependencies): () => void {+ const system = createSystemShutdown()+ let blocker: number | null = null+ let countdownDialog: AbortController | null = null+ let previousPhase: CompletionShutdownState['phase'] = 'off'+ let startupSettled = false+ let disposed = false+ const controller = new CompletionShutdownController({+ ...deps,+ supported: system.supported,+ isReady: () => startupSettled && deps.isReady(),+ probe: async () => {+ await deps.waitForReady()+ if (disposed) return+ startupSettled = true+ controller.evaluate()+ await system.probe()+ },+ requestShutdown: system.requestShutdown,+ onError: deps.logError,+ onState: (state) => {+ const active = ['waiting', 'countdown', 'preparing'].includes(state.phase)+ if (active && blocker === null)+ blocker = powerSaveBlocker.start('prevent-app-suspension')+ if (!active && blocker !== null) {+ powerSaveBlocker.stop(blocker)+ blocker = null+ }+ deps.broadcast(state)+ if (state.phase !== 'countdown') {+ countdownDialog?.abort()+ countdownDialog = null+ }+ if (state.phase === 'countdown' && previousPhase !== 'countdown') {+ const abort = new AbortController()+ countdownDialog = abort+ // Native window/dialog APIs may throw before returning a Promise.+ // Any failure must cancel the power action, including synchronous ones.+ void (async () => {+ const parent = deps.getMainWindow()+ if (!parent || parent.isDestroyed())+ throw new Error('Shutdown cancellation window is unavailable')+ deps.showMainWindow()+ return dialog.showMessageBox(parent, {+ type: 'warning',+ title: 'Motrix',+ message: deps.translate(+ 'panel.downloads.completionShutdown.countdown',+ { seconds: 60 }+ ),+ detail: deps.translate('panel.downloads.completionShutdown.detail'),+ buttons: [deps.translate('common.cancel')],+ defaultId: 0,+ cancelId: 0,+ noLink: true,+ signal: abort.signal,+ })+ })()+ .then(() => {+ if (!abort.signal.aborted) controller.cancel()+ })+ .catch((error) => {+ deps.logError(error)+ if (!abort.signal.aborted) controller.cancel()+ })+ }+ if (+ state.phase === 'failed' &&+ ['preparing', 'requested'].includes(previousPhase)+ ) {+ dialog.showErrorBox(+ 'Motrix',+ deps.translate('panel.downloads.completionShutdown.failed')+ )+ }+ previousPhase = state.phase+ },+ })+ void deps.waitForReady().then(() => {+ if (!disposed) startupSettled = true+ })+ const evaluate = () => controller.evaluate()+ const interrupt = () => controller.interrupt()+ deps.eventBus.on(Events.TaskUpdated, evaluate)+ deps.eventBus.on(Events.EngineDisconnected, interrupt)+ deps.eventBus.on(Events.EngineStateChanged, evaluate)+ powerMonitor.on('suspend', interrupt)+ powerMonitor.on('resume', interrupt)+ registerTrustedIpcHandler(Queries.GetCompletionShutdown, () =>+ controller.getState()+ )+ registerTrustedIpcHandler(+ Commands.SetCompletionShutdown,+ (_event, payload: unknown) => {+ const { enabled } = completionShutdownRequestSchema.parse(payload)+ return controller.setEnabled(enabled)+ }+ )+ deps.broadcast(controller.getState())+ return () => {+ disposed = true+ controller.dispose()+ deps.eventBus.off(Events.TaskUpdated, evaluate)+ deps.eventBus.off(Events.EngineDisconnected, interrupt)+ deps.eventBus.off(Events.EngineStateChanged, evaluate)+ powerMonitor.off('suspend', interrupt)+ powerMonitor.off('resume', interrupt)+ ipcMain.removeHandler(Queries.GetCompletionShutdown)+ ipcMain.removeHandler(Commands.SetCompletionShutdown)+ }+}diff --git a/src/main/platform/system-shutdown.test.ts b/src/main/platform/system-shutdown.test.tsnew file mode 100644index 00000000..433ddbd3--- /dev/null+++ b/src/main/platform/system-shutdown.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it, vi } from 'vitest'+import { createSystemShutdown } from './system-shutdown'++describe('system shutdown adapter', () => {+ it('never schedules or forces Windows shutdown', async () => {+ const run = vi.fn(async () => '')+ await createSystemShutdown(+ 'win32',+ { SystemRoot: 'C:\\Windows' },+ run+ ).requestShutdown()+ expect(run).toHaveBeenCalledWith('C:\\Windows\\System32\\shutdown.exe', [+ '/s',+ '/t',+ '0',+ ])+ })++ it('probes Automation without performing a power action', async () => {+ const run = vi.fn(async () => 'System Events')+ const system = createSystemShutdown('darwin', {}, run)+ await system.probe()+ expect(run).toHaveBeenCalledWith('/usr/bin/osascript', [+ '-e',+ 'tell application "System Events" to get name',+ ])+ await system.requestShutdown()+ expect(run).toHaveBeenLastCalledWith('/usr/bin/osascript', [+ '-e',+ 'tell application "System Events" to shut down',+ ])+ })++ it.each(['s "challenge"', 's "no"', 's "na"', 's "inhibited"', 'unexpected'])(+ 'rejects unattended Linux poweroff for %s',+ async (result) => {+ const run = vi.fn(async () => result)+ await expect(+ createSystemShutdown('linux', {}, run).probe()+ ).rejects.toThrow('not authorized')+ expect(run.mock.calls).toHaveLength(1)+ }+ )++ it('uses noninteractive logind poweroff', async () => {+ const run = vi.fn(async () => 's "yes"\n')+ const system = createSystemShutdown('linux', {}, run)+ await system.probe()+ await system.requestShutdown()+ expect(run.mock.calls[1]).toEqual([+ '/usr/bin/busctl',+ [+ '--system',+ 'call',+ 'org.freedesktop.login1',+ '/org/freedesktop/login1',+ 'org.freedesktop.login1.Manager',+ 'PowerOff',+ 'b',+ 'false',+ ],+ ])+ })++ it.each([{ SNAP: '/snap/motrix' }, { FLATPAK_ID: 'app.motrix.native' }])(+ 'does not attempt to escape confined distributions',+ async (env) => {+ const run = vi.fn(async () => '')+ const system = createSystemShutdown('linux', env, run)+ expect(system.supported).toBe(false)+ await expect(system.probe()).rejects.toThrow('unavailable')+ await expect(system.requestShutdown()).rejects.toThrow('unavailable')+ expect(run).not.toHaveBeenCalled()+ }+ )+})diff --git a/src/main/platform/system-shutdown.ts b/src/main/platform/system-shutdown.tsnew file mode 100644index 00000000..6b1b0597--- /dev/null+++ b/src/main/platform/system-shutdown.ts@@ -0,0 +1,75 @@+import { execFile } from 'node:child_process'+import path from 'node:path'+import { promisify } from 'node:util'++const execFileAsync = promisify(execFile)+type Run = (file: string, args: string[]) => Promise<string>+const runCommand: Run = async (file, args) => {+ const { stdout } = await execFileAsync(file, args, {+ windowsHide: true,+ timeout: 15_000,+ maxBuffer: 64 * 1024,+ encoding: 'utf8',+ })+ return stdout+}++const LOGIND = [+ '--system',+ 'call',+ 'org.freedesktop.login1',+ '/org/freedesktop/login1',+ 'org.freedesktop.login1.Manager',+]++/** Fixed commands only; never invoke a shell or interpolate task/user input. */+export function createSystemShutdown(+ platform = process.platform,+ env: NodeJS.ProcessEnv = process.env,+ run: Run = runCommand+) {+ const supported =+ ['darwin', 'win32', 'linux'].includes(platform) &&+ !env.FLATPAK_ID &&+ !env.SNAP+ return {+ supported: Boolean(supported),+ async probe(): Promise<void> {+ if (!supported)+ throw new Error('System shutdown is unavailable in this distribution')+ if (platform === 'darwin') {+ // Request Automation access while the user is enabling the feature.+ await run('/usr/bin/osascript', [+ '-e',+ 'tell application "System Events" to get name',+ ])+ } else if (platform === 'linux') {+ const result = await run('/usr/bin/busctl', [...LOGIND, 'CanPowerOff'])+ if (result.trim() !== 's "yes"')+ throw new Error('Unattended shutdown is not authorized')+ }+ },+ async requestShutdown(): Promise<void> {+ if (!supported)+ throw new Error('System shutdown is unavailable in this distribution')+ if (platform === 'win32') {+ // A positive /t implies /f. The cancellable countdown belongs to Motrix.+ await run(+ path.win32.join(+ env.SystemRoot ?? 'C:\\Windows',+ 'System32',+ 'shutdown.exe'+ ),+ ['/s', '/t', '0']+ )+ } else if (platform === 'darwin') {+ await run('/usr/bin/osascript', [+ '-e',+ 'tell application "System Events" to shut down',+ ])+ } else {+ await run('/usr/bin/busctl', [...LOGIND, 'PowerOff', 'b', 'false'])+ }+ },+ }+}diff --git a/src/renderer/routes/downloads/downloads-more-menu.test.tsx b/src/renderer/routes/downloads/downloads-more-menu.test.tsxnew file mode 100644index 00000000..e34b7efc--- /dev/null+++ b/src/renderer/routes/downloads/downloads-more-menu.test.tsx@@ -0,0 +1,125 @@+import '@testing-library/jest-dom/vitest'+import '@renderer/lib/i18n'+import { Commands } from '@shared/protocol/commands'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'+import type { CompletionShutdownState } from '@shared/schemas/completion-shutdown'+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ listeners: new Map<string, (value: unknown) => void>(),+ transport: { platform: 'darwin', invoke: vi.fn(), on: vi.fn(), off: vi.fn() },+ toast: vi.fn(),+}))+vi.mock('@renderer/lib/transport', () => ({ transport: mocks.transport }))+vi.mock('@renderer/components/ui/toast', () => ({+ toast: { add: mocks.toast },+}))++import { DownloadsMoreMenu } from './downloads-more-menu'++const off: CompletionShutdownState = {+ supported: true,+ phase: 'off',+ deadline: null,+ error: null,+}++describe('DownloadsMoreMenu', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.listeners.clear()+ mocks.transport.platform = 'darwin'+ mocks.transport.on.mockImplementation((event, listener) =>+ mocks.listeners.set(event, listener)+ )+ mocks.transport.invoke.mockResolvedValue(off)+ })+ afterEach(cleanup)++ it('enables and cancels through the desktop host and displays live state', async () => {+ mocks.transport.invoke.mockImplementation(async (channel, payload) => {+ if (channel === Queries.GetCompletionShutdown) return off+ const state = { ...off, phase: payload.enabled ? 'waiting' : 'off' }+ mocks.listeners.get(Events.CompletionShutdownChanged)?.(state)+ return state+ })+ const user = userEvent.setup()+ render(<DownloadsMoreMenu />)+ const button = screen.getByRole('button', { name: 'More download actions' })+ await user.click(button)+ await user.click(+ await screen.findByRole('menuitem', {+ name: 'Shut down after all downloads finish',+ })+ )+ expect(mocks.transport.invoke).toHaveBeenCalledWith(+ Commands.SetCompletionShutdown,+ { enabled: true }+ )+ expect(button).toHaveAttribute('data-active', 'true')+ await user.click(button)+ await user.click(+ await screen.findByRole('menuitem', {+ name: 'Cancel shutdown after downloads',+ })+ )+ expect(mocks.transport.invoke).toHaveBeenCalledWith(+ Commands.SetCompletionShutdown,+ { enabled: false }+ )+ expect(button).toHaveAttribute('data-active', 'false')+ })++ it('does not overwrite a live event with a stale initial query', async () => {+ let resolve!: (value: unknown) => void+ mocks.transport.invoke.mockImplementation(+ () =>+ new Promise((done) => {+ resolve = done+ })+ )+ render(<DownloadsMoreMenu />)+ await act(async () => {+ mocks.listeners.get(Events.CompletionShutdownChanged)?.({+ ...off,+ phase: 'waiting',+ })+ resolve(off)+ })+ expect(screen.getByRole('button')).toHaveAttribute('data-active', 'true')+ })++ it('makes the action unavailable on the web without invoking desktop IPC', async () => {+ mocks.transport.platform = 'web'+ const user = userEvent.setup()+ render(<DownloadsMoreMenu />)+ await user.click(screen.getByRole('button'))+ expect(await screen.findByRole('menuitem')).toHaveAttribute(+ 'aria-disabled',+ 'true'+ )+ expect(screen.getByRole('status')).toHaveTextContent('unavailable')+ expect(mocks.transport.invoke).not.toHaveBeenCalled()+ })++ it('reports permission failures without showing an enabled indicator', async () => {+ mocks.transport.invoke.mockImplementation(async (channel) =>+ channel === Queries.GetCompletionShutdown+ ? off+ : { ...off, phase: 'failed', error: 'unavailable' }+ )+ const user = userEvent.setup()+ render(<DownloadsMoreMenu />)+ await user.click(screen.getByRole('button'))+ await user.click(await screen.findByRole('menuitem'))+ await waitFor(() =>+ expect(mocks.toast).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'error' })+ )+ )+ expect(screen.getByRole('button')).toHaveAttribute('data-active', 'false')+ })+})diff --git a/src/renderer/routes/downloads/downloads-more-menu.tsx b/src/renderer/routes/downloads/downloads-more-menu.tsxnew file mode 100644index 00000000..da439c79--- /dev/null+++ b/src/renderer/routes/downloads/downloads-more-menu.tsx@@ -0,0 +1,182 @@+import { CheckIcon, MoreIcon } from '@renderer/components/icons'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@renderer/components/ui/dropdown-menu'+import { toast } from '@renderer/components/ui/toast'+import { transport } from '@renderer/lib/transport'+import { cn } from '@renderer/lib/utils'+import { Commands } from '@shared/protocol/commands'+import { Events } from '@shared/protocol/events'+import { Queries } from '@shared/protocol/queries'+import {+ type CompletionShutdownState,+ completionShutdownStateSchema,+} from '@shared/schemas/completion-shutdown'+import { useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'++export function DownloadsMoreMenu() {+ const { t } = useTranslation()+ const [state, setState] = useState<CompletionShutdownState | null>(null)+ const [pending, setPending] = useState(false)+ const pendingRef = useRef(false)+ const [now, setNow] = useState(Date.now)+ const desktop = transport.platform !== 'web'++ useEffect(() => {+ if (!desktop) return+ let disposed = false+ let generation = 0+ const apply = (value: unknown) => {+ const parsed = completionShutdownStateSchema.safeParse(value)+ if (!disposed && parsed.success) setState(parsed.data)+ }+ const refresh = () => {+ const revision = ++generation+ void transport+ .invoke(Queries.GetCompletionShutdown)+ .then((value) => {+ if (revision === generation) apply(value)+ })+ .catch(() => {})+ }+ const onChange = (value: unknown) => {+ ++generation+ apply(value)+ }+ transport.on(Events.CompletionShutdownChanged, onChange)+ const stop = transport.onConnectionChange?.((event) => {+ if (event.state === 'connected') refresh()+ })+ window.addEventListener('focus', refresh)+ refresh()+ return () => {+ disposed = true+ transport.off(Events.CompletionShutdownChanged, onChange)+ stop?.()+ window.removeEventListener('focus', refresh)+ }+ }, [desktop])++ useEffect(() => {+ setNow(Date.now())+ if (state?.phase !== 'countdown') return+ const timer = setInterval(() => setNow(Date.now()), 1_000)+ return () => clearInterval(timer)+ }, [state?.phase])++ const active =+ state !== null &&+ ['waiting', 'countdown', 'preparing'].includes(state.phase)+ const available = desktop && state?.supported === true+ const description =+ !desktop || state?.supported === false+ ? t('panel.downloads.completionShutdown.unavailable')+ : state?.phase === 'countdown'+ ? t('panel.downloads.completionShutdown.countdown', {+ seconds: Math.max(+ 0,+ Math.ceil(((state.deadline ?? now) - now) / 1_000)+ ),+ })+ : state?.phase === 'preparing'+ ? t('panel.downloads.completionShutdown.preparing')+ : state?.phase === 'requested'+ ? t('panel.downloads.completionShutdown.requested')+ : state?.phase === 'failed'+ ? t(+ `panel.downloads.completionShutdown.${state.error ?? 'failed'}`+ )+ : active+ ? t('panel.downloads.completionShutdown.waiting')+ : t('panel.downloads.completionShutdown.detail')++ const toggle = async () => {+ if (pendingRef.current) return+ pendingRef.current = true+ setPending(true)+ try {+ // Live events own the state mirror; the result only reports command failure.+ const result = completionShutdownStateSchema.parse(+ await transport.invoke(Commands.SetCompletionShutdown, {+ enabled: !active,+ })+ )+ if (result.phase === 'failed') {+ toast.add({+ type: 'error',+ title: t(+ `panel.downloads.completionShutdown.${result.error ?? 'failed'}`+ ),+ })+ }+ } catch {+ toast.add({+ type: 'error',+ title: t('panel.downloads.completionShutdown.failed'),+ })+ } finally {+ pendingRef.current = false+ setPending(false)+ }+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={t('panel.downloads.completionShutdown.more')}+ title={+ active ? description : t('panel.downloads.completionShutdown.more')+ }+ render={<button type="button" />}+ data-slot="downloads-more"+ data-active={active}+ className={cn(+ 'app-no-drag relative flex size-5 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted/50 text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground data-popup-open:bg-accent focus-visible:ring-2 focus-visible:ring-ring',+ active && 'border-primary/30 bg-primary/10 text-primary'+ )}+ >+ <MoreIcon className="size-3.5" aria-hidden="true" />+ {active && (+ <span+ aria-hidden="true"+ className="absolute -end-0.5 -top-0.5 size-1.5 rounded-full bg-primary ring-2 ring-background"+ />+ )}+ </DropdownMenuTrigger>+ <DropdownMenuContent+ side="top"+ align="start"+ sideOffset={8}+ data-menu-density="compact"+ className="w-52 max-w-[calc(100vw-2rem)]"+ >+ <DropdownMenuItem+ disabled={!available || pending || state?.phase === 'requested'}+ onClick={() => void toggle()}+ >+ <CheckIcon+ aria-hidden="true"+ className={cn('size-4', !active && 'opacity-0')}+ />+ <span>+ {t(+ `panel.downloads.completionShutdown.${active ? 'disable' : 'enable'}`+ )}+ </span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <p+ role="status"+ className="px-2 py-1.5 text-xs leading-relaxed text-muted-foreground"+ >+ {description}+ </p>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/src/renderer/routes/downloads/global-stats-bar.tsx b/src/renderer/routes/downloads/global-stats-bar.tsxindex c488ba85..e328c36b 100644--- a/src/renderer/routes/downloads/global-stats-bar.tsx+++ b/src/renderer/routes/downloads/global-stats-bar.tsx@@ -1,3 +1,4 @@+import { DownloadsMoreMenu } from './downloads-more-menu'import { EngineBadge } from './engine-badge'import { NatBadge } from './nat-badge'import { SpeedLimitBadge } from './speed-limit-badge'@@ -7,6 +8,7 @@ export function GlobalStatsBar() {return (<><div className="flex min-w-0 items-center gap-2">+ <DownloadsMoreMenu /><SpeedLimitBadge /><TransferSpeedBadge /></div>diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.jsonindex 74cd3f3d..410aaeca 100644--- a/src/shared/locales/ar.json+++ b/src/shared/locales/ar.json@@ -1251,6 +1251,18 @@"sortBy": "ترتيب حسب","taskActions": "إجراءات أخرى","title": "عرض القائمة"+ },+ "completionShutdown": {+ "more": "إجراءات تنزيل إضافية",+ "enable": "إيقاف التشغيل بعد اكتمال جميع التنزيلات",+ "disable": "إلغاء إيقاف التشغيل بعد التنزيلات",+ "waiting": "بانتظار اكتمال جميع التنزيلات",+ "countdown": "إيقاف التشغيل خلال {{seconds}} ثانية",+ "detail": "يسري مرة واحدة. تمنع المهام المتوقفة مؤقتًا أو الفاشلة إيقاف التشغيل. تتوقف المشاركة عند إيقاف تشغيل الكمبيوتر.",+ "unavailable": "إيقاف التشغيل التلقائي غير متاح أو تم رفض الإذن.",+ "failed": "تعذر التحضير لإيقاف التشغيل أو طلبه. لم يتم فرض إيقاف التشغيل.",+ "preparing": "جارٍ التحضير لإيقاف التشغيل…",+ "requested": "تم طلب إيقاف التشغيل"}},"trackers": {diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.jsonindex 67e846bb..789976ac 100644--- a/src/shared/locales/bg.json+++ b/src/shared/locales/bg.json@@ -1203,6 +1203,18 @@"sortBy": "Подреждане по","taskActions": "Още действия","title": "Изглед на списъка"+ },+ "completionShutdown": {+ "more": "Още действия за изтегляне",+ "enable": "Изключване след всички изтегляния",+ "disable": "Отмяна на изключването след изтегляне",+ "waiting": "Изчакване на всички изтегляния",+ "countdown": "Изключване след {{seconds}} секунди",+ "detail": "Важи еднократно. Поставени на пауза или неуспешни задачи предотвратяват изключването. Сийдването приключва при изключване.",+ "unavailable": "Автоматичното изключване е недостъпно или разрешението е отказано.",+ "failed": "Неуспешна подготовка или заявка за изключване. Не е извършено принудително изключване.",+ "preparing": "Подготовка за изключване…",+ "requested": "Изключването е заявено"}},"trackers": {diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.jsonindex 06480dd7..78902493 100644--- a/src/shared/locales/ca.json+++ b/src/shared/locales/ca.json@@ -1215,6 +1215,18 @@"sortBy": "Ordenar per","taskActions": "Més","title": "Vista de llista"+ },+ "completionShutdown": {+ "more": "Més accions de baixada",+ "enable": "Apaga en acabar totes les baixades",+ "disable": "Cancel·la l’apagada després de les baixades",+ "waiting": "Esperant que acabin totes les baixades",+ "countdown": "Apagada d’aquí a {{seconds}} segons",+ "detail": "Només una vegada. Les tasques en pausa o fallides impedeixen l’apagada. La sembra acaba en apagar l’ordinador.",+ "unavailable": "L’apagada automàtica no està disponible o s’ha denegat el permís.",+ "failed": "No s’ha pogut preparar o sol·licitar l’apagada. No s’ha forçat l’apagada.",+ "preparing": "S’està preparant l’apagada…",+ "requested": "S’ha sol·licitat l’apagada"}},"trackers": {diff --git a/src/shared/locales/de.json b/src/shared/locales/de.jsonindex 364062f1..b388efa2 100644--- a/src/shared/locales/de.json+++ b/src/shared/locales/de.json@@ -970,6 +970,18 @@"downloadEta": "Download-Restzeit","avgDownloadProgress": "Durchschnittlicher Download-Fortschritt","processingTasks": "In Verarbeitung"+ },+ "completionShutdown": {+ "more": "Weitere Download-Aktionen",+ "enable": "Nach allen Downloads herunterfahren",+ "disable": "Herunterfahren nach Downloads abbrechen",+ "waiting": "Warten auf den Abschluss aller Downloads",+ "countdown": "Herunterfahren in {{seconds}} Sekunden",+ "detail": "Gilt einmalig. Pausierte oder fehlgeschlagene Aufgaben verhindern das Herunterfahren. Seeding endet beim Herunterfahren.",+ "unavailable": "Automatisches Herunterfahren ist nicht verfügbar oder wurde nicht erlaubt.",+ "failed": "Das Herunterfahren konnte nicht vorbereitet oder angefordert werden. Es wurde nicht erzwungen.",+ "preparing": "Herunterfahren wird vorbereitet…",+ "requested": "Herunterfahren angefordert"}}},diff --git a/src/shared/locales/el.json b/src/shared/locales/el.jsonindex 7fcc0f6f..0f9e2a10 100644--- a/src/shared/locales/el.json+++ b/src/shared/locales/el.json@@ -1203,6 +1203,18 @@"sortBy": "Ταξινόμηση κατά","taskActions": "Περισσότερα","title": "Προβολή λίστας"+ },+ "completionShutdown": {+ "more": "Περισσότερες ενέργειες λήψης",+ "enable": "Τερματισμός μετά από όλες τις λήψεις",+ "disable": "Ακύρωση τερματισμού μετά τις λήψεις",+ "waiting": "Αναμονή ολοκλήρωσης όλων των λήψεων",+ "countdown": "Τερματισμός σε {{seconds}} δευτερόλεπτα",+ "detail": "Ισχύει μία φορά. Εργασίες σε παύση ή αποτυχημένες εμποδίζουν τον τερματισμό. Ο διαμοιρασμός σταματά με τον τερματισμό.",+ "unavailable": "Ο αυτόματος τερματισμός δεν είναι διαθέσιμος ή η άδεια απορρίφθηκε.",+ "failed": "Δεν ήταν δυνατή η προετοιμασία ή η αίτηση τερματισμού. Δεν έγινε αναγκαστικός τερματισμός.",+ "preparing": "Προετοιμασία τερματισμού…",+ "requested": "Ζητήθηκε τερματισμός"}},"trackers": {diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex 17b76243..a620caba 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -970,6 +970,18 @@"downloadEta": "Download ETA","avgDownloadProgress": "Average download progress","processingTasks": "Processing"+ },+ "completionShutdown": {+ "more": "More download actions",+ "enable": "Shut down after all downloads finish",+ "disable": "Cancel shutdown after downloads",+ "waiting": "Waiting for all downloads to finish",+ "countdown": "Shutting down in {{seconds}} seconds",+ "detail": "Applies once. Paused or failed tasks prevent shutdown. Seeding ends when the computer shuts down.",+ "unavailable": "Automatic shutdown is unavailable or permission was denied.",+ "failed": "Could not prepare or request shutdown. Your computer has not been forced to shut down.",+ "preparing": "Preparing to shut down…",+ "requested": "Shutdown requested"}}},diff --git a/src/shared/locales/es.json b/src/shared/locales/es.jsonindex 8b38dd28..2dac9148 100644--- a/src/shared/locales/es.json+++ b/src/shared/locales/es.json@@ -982,6 +982,18 @@"downloadEta": "Tiempo restante de descarga","avgDownloadProgress": "Progreso medio de descarga","processingTasks": "Procesando"+ },+ "completionShutdown": {+ "more": "Más acciones de descarga",+ "enable": "Apagar al finalizar todas las descargas",+ "disable": "Cancelar el apagado tras las descargas",+ "waiting": "Esperando a que finalicen las descargas",+ "countdown": "Apagado en {{seconds}} segundos",+ "detail": "Solo esta vez. Las tareas pausadas o fallidas impiden el apagado. La siembra termina al apagar el equipo.",+ "unavailable": "El apagado automático no está disponible o se denegó el permiso.",+ "failed": "No se pudo preparar o solicitar el apagado. No se ha forzado el apagado.",+ "preparing": "Preparando el apagado…",+ "requested": "Apagado solicitado"}}},diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.jsonindex 10a9a4d4..dde346fa 100644--- a/src/shared/locales/fa.json+++ b/src/shared/locales/fa.json@@ -1203,6 +1203,18 @@"sortBy": "مرتبسازی بر اساس","taskActions": "عملیات بیشتر","title": "نمای فهرست"+ },+ "completionShutdown": {+ "more": "عملیات بیشتر بارگیری",+ "enable": "خاموش کردن پس از پایان همهٔ بارگیریها",+ "disable": "لغو خاموش کردن پس از بارگیریها",+ "waiting": "در انتظار پایان همهٔ بارگیریها",+ "countdown": "خاموش شدن پس از {{seconds}} ثانیه",+ "detail": "فقط یک بار اعمال میشود. کارهای متوقفشده یا ناموفق مانع خاموش شدن میشوند. اشتراکگذاری با خاموش شدن پایان مییابد.",+ "unavailable": "خاموش شدن خودکار در دسترس نیست یا مجوز رد شده است.",+ "failed": "آمادهسازی یا درخواست خاموش شدن انجام نشد. خاموش شدن اجباری انجام نشده است.",+ "preparing": "در حال آمادهسازی برای خاموش شدن…",+ "requested": "درخواست خاموش شدن ارسال شد"}},"trackers": {diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.jsonindex 05116863..ac0b37b9 100644--- a/src/shared/locales/fr.json+++ b/src/shared/locales/fr.json@@ -1215,6 +1215,18 @@"sortBy": "Trier par","taskActions": "Autres actions","title": "Affichage de la liste"+ },+ "completionShutdown": {+ "more": "Autres actions de téléchargement",+ "enable": "Éteindre après tous les téléchargements",+ "disable": "Annuler l’arrêt après les téléchargements",+ "waiting": "En attente de la fin des téléchargements",+ "countdown": "Arrêt dans {{seconds}} secondes",+ "detail": "Valable une seule fois. Les tâches en pause ou en échec empêchent l’arrêt. Le partage se termine à l’arrêt.",+ "unavailable": "L’arrêt automatique est indisponible ou l’autorisation a été refusée.",+ "failed": "Impossible de préparer ou de demander l’arrêt. Aucun arrêt forcé n’a été effectué.",+ "preparing": "Préparation de l’arrêt…",+ "requested": "Arrêt demandé"}},"trackers": {diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.jsonindex 0955e915..307f61a7 100644--- a/src/shared/locales/hu.json+++ b/src/shared/locales/hu.json@@ -970,6 +970,18 @@"downloadEta": "Letöltésből hátralévő idő","avgDownloadProgress": "Átlagos letöltési előrehaladás","processingTasks": "Feldolgozás"+ },+ "completionShutdown": {+ "more": "További letöltési műveletek",+ "enable": "Leállítás az összes letöltés befejezése után",+ "disable": "Letöltés utáni leállítás megszakítása",+ "waiting": "Várakozás az összes letöltés befejezésére",+ "countdown": "Leállítás {{seconds}} másodperc múlva",+ "detail": "Egyszeri művelet. A szüneteltetett vagy sikertelen feladatok megakadályozzák a leállítást. A visszaosztás a számítógép leállításakor véget ér.",+ "unavailable": "Az automatikus leállítás nem érhető el, vagy az engedélyt megtagadták.",+ "failed": "Nem sikerült előkészíteni vagy kérni a leállítást. A számítógép leállítása nem lett kényszerítve.",+ "preparing": "Leállítás előkészítése…",+ "requested": "Leállítás kérve"}}},diff --git a/src/shared/locales/id.json b/src/shared/locales/id.jsonindex b4a1c113..206b2d5e 100644--- a/src/shared/locales/id.json+++ b/src/shared/locales/id.json@@ -958,6 +958,18 @@"downloadEta": "Perkiraan sisa unduhan","avgDownloadProgress": "Progres unduhan rata-rata","processingTasks": "Memproses"+ },+ "completionShutdown": {+ "more": "Tindakan unduhan lainnya",+ "enable": "Matikan setelah semua unduhan selesai",+ "disable": "Batalkan pematian setelah unduhan",+ "waiting": "Menunggu semua unduhan selesai",+ "countdown": "Mematikan dalam {{seconds}} detik",+ "detail": "Berlaku sekali. Tugas yang dijeda atau gagal mencegah pematian. Seeding berakhir saat komputer dimatikan.",+ "unavailable": "Pematian otomatis tidak tersedia atau izin ditolak.",+ "failed": "Tidak dapat menyiapkan atau meminta pematian. Komputer tidak dimatikan secara paksa.",+ "preparing": "Menyiapkan pematian…",+ "requested": "Pematian diminta"}}},diff --git a/src/shared/locales/it.json b/src/shared/locales/it.jsonindex baed093c..cdf3f762 100644--- a/src/shared/locales/it.json+++ b/src/shared/locales/it.json@@ -982,6 +982,18 @@"downloadEta": "Tempo rimanente del download","avgDownloadProgress": "Avanzamento medio del download","processingTasks": "Elaborazione"+ },+ "completionShutdown": {+ "more": "Altre azioni di download",+ "enable": "Spegni al termine di tutti i download",+ "disable": "Annulla lo spegnimento dopo i download",+ "waiting": "In attesa del completamento dei download",+ "countdown": "Spegnimento tra {{seconds}} secondi",+ "detail": "Valido una sola volta. Le attività in pausa o non riuscite impediscono lo spegnimento. Il seeding termina allo spegnimento.",+ "unavailable": "Lo spegnimento automatico non è disponibile o il permesso è stato negato.",+ "failed": "Impossibile preparare o richiedere lo spegnimento. Lo spegnimento non è stato forzato.",+ "preparing": "Preparazione allo spegnimento…",+ "requested": "Spegnimento richiesto"}}},diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.jsonindex 7b325eef..16a4880f 100644--- a/src/shared/locales/ja.json+++ b/src/shared/locales/ja.json@@ -958,6 +958,18 @@"downloadEta": "ダウンロードの残り時間","avgDownloadProgress": "平均ダウンロード進捗","processingTasks": "処理中"+ },+ "completionShutdown": {+ "more": "その他のダウンロード操作",+ "enable": "すべてのダウンロード完了後にシャットダウン",+ "disable": "ダウンロード後のシャットダウンを取り消す",+ "waiting": "すべてのダウンロード完了を待機中",+ "countdown": "{{seconds}} 秒後にシャットダウンします",+ "detail": "今回のみ有効です。一時停止中や失敗したタスクがある場合はシャットダウンしません。シードはシャットダウン時に終了します。",+ "unavailable": "自動シャットダウンを利用できないか、権限が拒否されました。",+ "failed": "シャットダウンの準備または要求に失敗しました。強制シャットダウンは行っていません。",+ "preparing": "シャットダウンの準備中…",+ "requested": "シャットダウンを要求しました"}}},diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.jsonindex 91cc0f1d..1c3ab687 100644--- a/src/shared/locales/ko.json+++ b/src/shared/locales/ko.json@@ -958,6 +958,18 @@"downloadEta": "다운로드 남은 시간","avgDownloadProgress": "평균 다운로드 진행률","processingTasks": "처리 중"+ },+ "completionShutdown": {+ "more": "다운로드 추가 작업",+ "enable": "모든 다운로드 완료 후 시스템 종료",+ "disable": "다운로드 후 시스템 종료 취소",+ "waiting": "모든 다운로드 완료 대기 중",+ "countdown": "{{seconds}}초 후 시스템 종료",+ "detail": "이번에만 적용됩니다. 일시 중지되거나 실패한 작업이 있으면 종료하지 않습니다. 시딩은 시스템 종료 시 끝납니다.",+ "unavailable": "자동 종료를 사용할 수 없거나 권한이 거부되었습니다.",+ "failed": "시스템 종료를 준비하거나 요청하지 못했습니다. 강제 종료는 수행하지 않았습니다.",+ "preparing": "시스템 종료 준비 중…",+ "requested": "시스템 종료 요청됨"}}},diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.jsonindex 7ea01beb..524744dc 100644--- a/src/shared/locales/nb.json+++ b/src/shared/locales/nb.json@@ -1203,6 +1203,18 @@"sortBy": "Sorter etter","taskActions": "Mer","title": "Listevisning"+ },+ "completionShutdown": {+ "more": "Flere nedlastingshandlinger",+ "enable": "Slå av når alle nedlastinger er ferdige",+ "disable": "Avbryt avslåing etter nedlastinger",+ "waiting": "Venter på at alle nedlastinger blir ferdige",+ "countdown": "Slår av om {{seconds}} sekunder",+ "detail": "Gjelder én gang. Pausede eller mislykkede oppgaver hindrer avslåing. Seeding avsluttes når maskinen slås av.",+ "unavailable": "Automatisk avslåing er utilgjengelig eller tillatelse ble avslått.",+ "failed": "Kunne ikke forberede eller be om avslåing. Ingen tvungen avslåing ble utført.",+ "preparing": "Forbereder avslåing…",+ "requested": "Avslåing forespurt"}},"trackers": {diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.jsonindex 99feabde..709c7cde 100644--- a/src/shared/locales/nl.json+++ b/src/shared/locales/nl.json@@ -1203,6 +1203,18 @@"sortBy": "Sorteren op","taskActions": "Meer","title": "Lijstweergave"+ },+ "completionShutdown": {+ "more": "Meer downloadacties",+ "enable": "Afsluiten na alle downloads",+ "disable": "Afsluiten na downloads annuleren",+ "waiting": "Wachten totdat alle downloads klaar zijn",+ "countdown": "Afsluiten over {{seconds}} seconden",+ "detail": "Eenmalig. Gepauzeerde of mislukte taken voorkomen afsluiten. Seeden stopt bij het afsluiten.",+ "unavailable": "Automatisch afsluiten is niet beschikbaar of toestemming is geweigerd.",+ "failed": "Afsluiten kon niet worden voorbereid of aangevraagd. Afsluiten is niet geforceerd.",+ "preparing": "Afsluiten voorbereiden…",+ "requested": "Afsluiten aangevraagd"}},"trackers": {diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.jsonindex c1f4e58a..30f11a29 100644--- a/src/shared/locales/pl.json+++ b/src/shared/locales/pl.json@@ -994,6 +994,18 @@"downloadEta": "Pozostały czas pobierania","avgDownloadProgress": "Średni postęp pobierania","processingTasks": "Przetwarzanie"+ },+ "completionShutdown": {+ "more": "Więcej działań pobierania",+ "enable": "Wyłącz po zakończeniu wszystkich pobrań",+ "disable": "Anuluj wyłączenie po pobieraniu",+ "waiting": "Oczekiwanie na zakończenie pobierania",+ "countdown": "Wyłączenie za {{seconds}} s",+ "detail": "Tylko jeden raz. Wstrzymane i nieudane zadania blokują wyłączenie. Wysyłanie kończy się przy wyłączeniu komputera.",+ "unavailable": "Automatyczne wyłączenie jest niedostępne lub odmówiono uprawnień.",+ "failed": "Nie udało się przygotować ani zażądać wyłączenia. Nie wymuszono wyłączenia.",+ "preparing": "Przygotowywanie do wyłączenia…",+ "requested": "Zażądano wyłączenia"}}},diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.jsonindex f9dcf9ed..1ce2ad6d 100644--- a/src/shared/locales/pt-BR.json+++ b/src/shared/locales/pt-BR.json@@ -982,6 +982,18 @@"downloadEta": "Tempo restante do download","avgDownloadProgress": "Progresso médio dos downloads","processingTasks": "Processando"+ },+ "completionShutdown": {+ "more": "Mais ações de download",+ "enable": "Desligar após todos os downloads",+ "disable": "Cancelar desligamento após os downloads",+ "waiting": "Aguardando a conclusão dos downloads",+ "countdown": "Desligando em {{seconds}} segundos",+ "detail": "Válido uma vez. Tarefas pausadas ou com falha impedem o desligamento. O compartilhamento termina ao desligar.",+ "unavailable": "O desligamento automático está indisponível ou a permissão foi negada.",+ "failed": "Não foi possível preparar ou solicitar o desligamento. Nenhum desligamento foi forçado.",+ "preparing": "Preparando para desligar…",+ "requested": "Desligamento solicitado"}}},diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.jsonindex 9be3f6f7..fa7023aa 100644--- a/src/shared/locales/ro.json+++ b/src/shared/locales/ro.json@@ -1215,6 +1215,18 @@"sortBy": "Sortează după","taskActions": "Mai multe","title": "Vizualizare listă"+ },+ "completionShutdown": {+ "more": "Mai multe acțiuni de descărcare",+ "enable": "Oprește după toate descărcările",+ "disable": "Anulează oprirea după descărcări",+ "waiting": "Se așteaptă finalizarea descărcărilor",+ "countdown": "Oprire în {{seconds}} secunde",+ "detail": "Se aplică o singură dată. Sarcinile întrerupte sau eșuate împiedică oprirea. Partajarea se încheie la oprire.",+ "unavailable": "Oprirea automată nu este disponibilă sau permisiunea a fost refuzată.",+ "failed": "Nu s-a putut pregăti sau solicita oprirea. Oprirea nu a fost forțată.",+ "preparing": "Se pregătește oprirea…",+ "requested": "Oprire solicitată"}},"trackers": {diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.jsonindex 4db8ac6e..beea47e4 100644--- a/src/shared/locales/ru.json+++ b/src/shared/locales/ru.json@@ -994,6 +994,18 @@"downloadEta": "До конца загрузки","avgDownloadProgress": "Средний прогресс загрузки","processingTasks": "Обработка"+ },+ "completionShutdown": {+ "more": "Другие действия с загрузками",+ "enable": "Выключить после завершения всех загрузок",+ "disable": "Отменить выключение после загрузок",+ "waiting": "Ожидание завершения всех загрузок",+ "countdown": "Выключение через {{seconds}} сек.",+ "detail": "Действует один раз. Приостановленные и неудачные задачи препятствуют выключению. Раздача прекратится при выключении.",+ "unavailable": "Автовыключение недоступно или в разрешении отказано.",+ "failed": "Не удалось подготовить или запросить выключение. Принудительное выключение не выполнялось.",+ "preparing": "Подготовка к выключению…",+ "requested": "Выключение запрошено"}}},diff --git a/src/shared/locales/th.json b/src/shared/locales/th.jsonindex 184dd054..eb2c2bb2 100644--- a/src/shared/locales/th.json+++ b/src/shared/locales/th.json@@ -1191,6 +1191,18 @@"sortBy": "เรียงตาม","taskActions": "เพิ่มเติม","title": "มุมมองรายการ"+ },+ "completionShutdown": {+ "more": "การดาวน์โหลดเพิ่มเติม",+ "enable": "ปิดเครื่องเมื่อดาวน์โหลดทั้งหมดเสร็จ",+ "disable": "ยกเลิกการปิดเครื่องหลังดาวน์โหลด",+ "waiting": "กำลังรอให้ดาวน์โหลดทั้งหมดเสร็จ",+ "countdown": "จะปิดเครื่องใน {{seconds}} วินาที",+ "detail": "ใช้ครั้งเดียว งานที่หยุดชั่วคราวหรือล้มเหลวจะขัดขวางการปิดเครื่อง การปล่อยไฟล์จะสิ้นสุดเมื่อปิดเครื่อง",+ "unavailable": "ไม่รองรับการปิดเครื่องอัตโนมัติหรือไม่ได้รับอนุญาต",+ "failed": "ไม่สามารถเตรียมหรือส่งคำขอปิดเครื่องได้ ไม่มีการบังคับปิดเครื่อง",+ "preparing": "กำลังเตรียมปิดเครื่อง…",+ "requested": "ส่งคำขอปิดเครื่องแล้ว"}},"trackers": {diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.jsonindex 40f6d26d..ebed6001 100644--- a/src/shared/locales/tr.json+++ b/src/shared/locales/tr.json@@ -970,6 +970,18 @@"downloadEta": "İndirme için kalan süre","avgDownloadProgress": "Ortalama indirme ilerlemesi","processingTasks": "İşleniyor"+ },+ "completionShutdown": {+ "more": "Diğer indirme işlemleri",+ "enable": "Tüm indirmeler bitince bilgisayarı kapat",+ "disable": "İndirme sonrası kapatmayı iptal et",+ "waiting": "Tüm indirmelerin bitmesi bekleniyor",+ "countdown": "{{seconds}} saniye sonra kapatılacak",+ "detail": "Yalnızca bir kez uygulanır. Duraklatılmış veya başarısız görevler kapatmayı engeller. Paylaşım, bilgisayar kapatılınca sona erer.",+ "unavailable": "Otomatik kapatma kullanılamıyor veya izin reddedildi.",+ "failed": "Kapatma hazırlanamadı veya istenemedi. Bilgisayar zorla kapatılmadı.",+ "preparing": "Kapatmaya hazırlanıyor…",+ "requested": "Kapatma istendi"}}},diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.jsonindex 3f839c63..b1737ff9 100644--- a/src/shared/locales/uk.json+++ b/src/shared/locales/uk.json@@ -1227,6 +1227,18 @@"sortBy": "Сортувати за","taskActions": "Інші дії","title": "Вигляд списку"+ },+ "completionShutdown": {+ "more": "Інші дії із завантаженнями",+ "enable": "Вимкнути після завершення всіх завантажень",+ "disable": "Скасувати вимкнення після завантажень",+ "waiting": "Очікування завершення всіх завантажень",+ "countdown": "Вимкнення через {{seconds}} с",+ "detail": "Діє один раз. Призупинені та невдалі завдання перешкоджають вимкненню. Роздача припиниться під час вимкнення.",+ "unavailable": "Автовимкнення недоступне або в дозволі відмовлено.",+ "failed": "Не вдалося підготувати або запросити вимкнення. Примусове вимкнення не виконувалося.",+ "preparing": "Підготовка до вимкнення…",+ "requested": "Вимкнення запитано"}},"trackers": {diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.jsonindex 17904fef..3e7ee7da 100644--- a/src/shared/locales/vi.json+++ b/src/shared/locales/vi.json@@ -958,6 +958,18 @@"downloadEta": "Thời gian tải xuống còn lại","avgDownloadProgress": "Tiến độ tải xuống trung bình","processingTasks": "Đang xử lý"+ },+ "completionShutdown": {+ "more": "Thao tác tải xuống khác",+ "enable": "Tắt máy khi tải xuống hoàn tất",+ "disable": "Hủy tắt máy sau khi tải xuống",+ "waiting": "Đang chờ tất cả lượt tải hoàn tất",+ "countdown": "Tắt máy sau {{seconds}} giây",+ "detail": "Chỉ áp dụng một lần. Tác vụ tạm dừng hoặc thất bại sẽ ngăn tắt máy. Chia sẻ torrent kết thúc khi tắt máy.",+ "unavailable": "Không hỗ trợ tắt máy tự động hoặc quyền đã bị từ chối.",+ "failed": "Không thể chuẩn bị hoặc yêu cầu tắt máy. Máy tính chưa bị buộc tắt.",+ "preparing": "Đang chuẩn bị tắt máy…",+ "requested": "Đã yêu cầu tắt máy"}}},diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 93fa7ad0..ba872c75 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -958,6 +958,18 @@"downloadEta": "下载剩余时间","avgDownloadProgress": "平均下载进度","processingTasks": "处理中任务"+ },+ "completionShutdown": {+ "more": "更多下载操作",+ "enable": "全部下载完成后关机",+ "disable": "取消下载完成后关机",+ "waiting": "等待全部下载完成",+ "countdown": "将在 {{seconds}} 秒后关机",+ "detail": "仅本次有效。暂停或失败的任务会阻止关机,做种将在关机时结束。",+ "unavailable": "当前环境不支持自动关机,或未获得系统权限。",+ "failed": "无法完成关机准备或请求关机,未强制关闭电脑。",+ "preparing": "正在准备关机…",+ "requested": "已请求系统关机"}}},diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 66aeb588..181bb938 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -958,6 +958,18 @@"downloadEta": "下載剩餘時間","avgDownloadProgress": "平均下載進度","processingTasks": "處理中任務"+ },+ "completionShutdown": {+ "more": "更多下載操作",+ "enable": "全部下載完成後關機",+ "disable": "取消下載完成後關機",+ "waiting": "等待全部下載完成",+ "countdown": "將在 {{seconds}} 秒後關機",+ "detail": "僅本次有效。暫停或失敗的任務會阻止關機,做種將在關機時結束。",+ "unavailable": "目前環境不支援自動關機,或未取得系統權限。",+ "failed": "無法完成關機準備或請求關機,未強制關閉電腦。",+ "preparing": "正在準備關機…",+ "requested": "已請求系統關機"}}},diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.tsindex d2342e48..f93b21e3 100644--- a/src/shared/protocol/commands.ts+++ b/src/shared/protocol/commands.ts@@ -1,4 +1,5 @@export const Commands = {+ SetCompletionShutdown: 'command:setCompletionShutdown',SaveDownloadsSettings: 'command:saveDownloadsSettings',PauseTask: 'command:pauseTask',ResumeTask: 'command:resumeTask',diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.tsindex 8a84e1e3..a60e2dab 100644--- a/src/shared/protocol/events.ts+++ b/src/shared/protocol/events.ts@@ -10,6 +10,7 @@ export interface WindowMaximizedChangedPayload {}export const Events = {+ CompletionShutdownChanged: 'event:completionShutdownChanged',TaskUpdated: 'event:taskUpdated',TaskFilesUpdated: 'event:taskFilesUpdated',TaskActivityUpdated: 'event:taskActivityUpdated',diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.tsindex 2007cd70..7ef5fce6 100644--- a/src/shared/protocol/queries.ts+++ b/src/shared/protocol/queries.ts@@ -1,4 +1,5 @@export const Queries = {+ GetCompletionShutdown: 'query:getCompletionShutdown',GetDownloadsSettingsDraft: 'query:getDownloadsSettingsDraft',GetDisclaimerState: 'query:getDisclaimerState',ListTasks: 'query:listTasks',diff --git a/src/shared/schemas/completion-shutdown.ts b/src/shared/schemas/completion-shutdown.tsnew file mode 100644index 00000000..a36cda49--- /dev/null+++ b/src/shared/schemas/completion-shutdown.ts@@ -0,0 +1,23 @@+import { z } from 'zod'++export const completionShutdownRequestSchema = z+ .object({ enabled: z.boolean() })+ .strict()++export const completionShutdownStateSchema = z.object({+ supported: z.boolean(),+ phase: z.enum([+ 'off',+ 'waiting',+ 'countdown',+ 'preparing',+ 'requested',+ 'failed',+ ]),+ deadline: z.number().nullable(),+ error: z.enum(['unavailable', 'failed']).nullable(),+})++export type CompletionShutdownState = z.infer<+ typeof completionShutdownStateSchema+>diff --git a/tests/scripts/electron-package-contract.test.ts b/tests/scripts/electron-package-contract.test.tsindex 5f4bce33..24816eb4 100644--- a/tests/scripts/electron-package-contract.test.ts+++ b/tests/scripts/electron-package-contract.test.ts@@ -289,7 +289,7 @@ describe('Electron package contracts', () => {expect(contract).toEqual({schemaVersion: 1,- payloadBytes: 25 * 1024 * 1024,+ payloadBytes: 25 * 1024 * 1024 + 64 * 1024,betterSqlite3Bytes: 4 * 1024 * 1024,unexpectedPackageNames: 0,foreignBetterSqlite3Prebuilds: 0,