Skip to content

A full-featured download manager.

feat(windows): isolate packaged profiles and application updates (#2242)

Dr_rOot4d0866e16df6
diff --git a/src/main/bridge/snap-environment.test.ts b/src/main/bridge/snap-environment.test.ts
index 760b7c0f..a82bf0f2 100644
--- a/src/main/bridge/snap-environment.test.ts
+++ b/src/main/bridge/snap-environment.test.ts
@@ -1,7 +1,6 @@
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import {
- isElectronSelfUpdateSupported,
isLegacySnapDefaultSaveDir,
resolveBridgeDataDir,
resolvePackagedLinuxSnapEnvironment,
@@ -158,39 +157,6 @@ describe('resolvePackagedLinuxSnapEnvironment', () => {
})
})
-describe('isElectronSelfUpdateSupported', () => {
- it('keeps snapd as the only application update authority', () => {
- expect(
- isElectronSelfUpdateSupported({
- hasUpdateMetadata: true,
- isPackaged: true,
- snapEnvironment: {
- installRoot: '/snap/motrix/current',
- instanceName: 'motrix',
- realHome: '/home/user',
- },
- })
- ).toBe(false)
- })
-
- it('preserves self-updates for packaged non-Snap distributions', () => {
- expect(
- isElectronSelfUpdateSupported({
- hasUpdateMetadata: true,
- isPackaged: true,
- snapEnvironment: null,
- })
- ).toBe(true)
- expect(
- isElectronSelfUpdateSupported({
- hasUpdateMetadata: false,
- isPackaged: true,
- snapEnvironment: null,
- })
- ).toBe(false)
- })
-})
-
describe('isLegacySnapDefaultSaveDir', () => {
const snap = {
instanceName: 'motrix',
diff --git a/src/main/bridge/snap-environment.ts b/src/main/bridge/snap-environment.ts
index 96305b3e..164cfdc4 100644
--- a/src/main/bridge/snap-environment.ts
+++ b/src/main/bridge/snap-environment.ts
@@ -14,12 +14,6 @@ export interface SnapEnvironmentOptions {
env: Readonly<Record<string, string | undefined>>
}
-export interface ElectronSelfUpdateOptions {
- hasUpdateMetadata: boolean
- isPackaged: boolean
- snapEnvironment: PackagedLinuxSnapEnvironment | null
-}
-
const SNAP_NAME = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
const SNAP_INSTANCE_NAME =
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:_[a-z0-9]{1,10})?$/
@@ -28,21 +22,6 @@ export function isValidSnapInstanceName(value: string): boolean {
return SNAP_INSTANCE_NAME.test(value)
}
-/**
- * Store-managed packages must not compete with electron-updater. Even if an
- * app-update.yml file is accidentally staged, snapd remains the only
- * application update authority for a packaged Snap.
- */
-export function isElectronSelfUpdateSupported(
- options: ElectronSelfUpdateOptions
-): boolean {
- return (
- options.isPackaged &&
- options.snapEnvironment === null &&
- options.hasUpdateMetadata
- )
-}
-
function canonicalAbsoluteDirectory(value: string, label: string): string {
if (
value.length === 0 ||
diff --git a/src/main/commands/definitions/app.commands.test.ts b/src/main/commands/definitions/app.commands.test.ts
index a55ff634..122a0c54 100644
--- a/src/main/commands/definitions/app.commands.test.ts
+++ b/src/main/commands/definitions/app.commands.test.ts
@@ -39,29 +39,32 @@ describe('app commands', () => {
)
})
- it('still opens About but skips the check when updates are unsupported', async () => {
- const registry = new CommandRegistry()
- registerAppCommands(registry, {} as CommandDeps)
- const show = vi.fn()
- const emit = vi.fn()
- const check = vi.fn().mockResolvedValue(undefined)
- const deps = {
- windowManager: { show },
- eventBus: { emit },
- updateManager: {
- check,
- getState: () => ({ phase: 'unsupported', currentVersion: '2.0.0' }),
- },
- log: { error: vi.fn() },
- } as unknown as CommandDeps
+ it.each(['unsupported', 'managed'])(
+ 'still opens About but skips the check when updates are %s',
+ async (phase) => {
+ const registry = new CommandRegistry()
+ registerAppCommands(registry, {} as CommandDeps)
+ const show = vi.fn()
+ const emit = vi.fn()
+ const check = vi.fn().mockResolvedValue(undefined)
+ const deps = {
+ windowManager: { show },
+ eventBus: { emit },
+ updateManager: {
+ check,
+ getState: () => ({ phase, currentVersion: '2.0.0' }),
+ },
+ log: { error: vi.fn() },
+ } as unknown as CommandDeps
- await registry.execute(CommandIds.AppCheckForUpdates, undefined, {
- menuContext: DEFAULT_MENU_CONTEXT,
- deps,
- })
+ await registry.execute(CommandIds.AppCheckForUpdates, undefined, {
+ menuContext: DEFAULT_MENU_CONTEXT,
+ deps,
+ })
- expect(show).toHaveBeenCalledWith('main')
- expect(emit).toHaveBeenCalledWith(Events.NavigateTo, '/settings/about')
- expect(check).not.toHaveBeenCalled()
- })
+ expect(show).toHaveBeenCalledWith('main')
+ expect(emit).toHaveBeenCalledWith(Events.NavigateTo, '/settings/about')
+ expect(check).not.toHaveBeenCalled()
+ }
+ )
})
diff --git a/src/main/commands/definitions/app.commands.ts b/src/main/commands/definitions/app.commands.ts
index 21bd98fe..af8ebfc9 100644
--- a/src/main/commands/definitions/app.commands.ts
+++ b/src/main/commands/definitions/app.commands.ts
@@ -33,7 +33,12 @@ export function registerAppCommands(
deps.eventBus.emit(Events.NavigateTo, '/settings/about')
// The About page already explains why updates are unavailable;
// checking anyway would only log a rejected command.
- if (deps.updateManager.getState().phase !== 'unsupported') {
+ const state = deps.updateManager.getState()
+ if (
+ state.phase !== 'unsupported' &&
+ state.phase !== 'managed' &&
+ state.updateAuthority !== 'system'
+ ) {
await deps.updateManager.check()
}
},
diff --git a/src/main/commands/types.ts b/src/main/commands/types.ts
index df352564..06a0f69a 100644
--- a/src/main/commands/types.ts
+++ b/src/main/commands/types.ts
@@ -14,7 +14,7 @@ import type { TaskManager } from '@core/task/task-manager'
import type { TorrentMetaStore } from '@core/task/torrent-meta-store'
import type { MagnetTracker } from '@core/torrent/magnet-tracker'
import type { MenuContext } from '@shared/types/menu-context'
-import type { UpdateManager } from '../core/update-manager'
+import type { AppUpdateService } from '../core/app-update-service'
import type { createProtocolManager } from '../platform/protocol-manager'
import type { WindowManager } from '../window/window-manager'
import type { WhenExpr } from './when'
@@ -26,7 +26,7 @@ export interface CommandDeps {
windowManager: WindowManager
eventBus: EventBus
log: Logger
- updateManager: UpdateManager
+ updateManager: AppUpdateService
protocolManager: ReturnType<typeof createProtocolManager>
fileCleanupService: FileCleanupService
torrentMetaStore: TorrentMetaStore
diff --git a/src/main/core/app-update-service.test.ts b/src/main/core/app-update-service.test.ts
new file mode 100644
index 00000000..23101e76
--- /dev/null
+++ b/src/main/core/app-update-service.test.ts
@@ -0,0 +1,111 @@
+import { EventBus } from '@core/events/event-bus'
+import { ErrorCode } from '@shared/errors'
+import { describe, expect, it, vi } from 'vitest'
+import { createFakeUpdater } from './__fixtures__/fake-updater'
+import { createAppUpdateService } from './app-update-service'
+
+describe('createAppUpdateService', () => {
+ it.each([false, true])(
+ 'keeps Windows packages inert even when update support is %s',
+ async (supported) => {
+ const loadUpdater = vi.fn(async () => {
+ throw new Error('Windows package must not load electron-updater')
+ })
+ const service = await createAppUpdateService({
+ eventBus: new EventBus(),
+ currentVersion: '2.0.0',
+ channel: 'stable',
+ isWindowsPackage: true,
+ supported,
+ loadUpdater,
+ getManagedMessage: () => 'Updates come from the installation source',
+ })
+
+ await expect(service.check()).rejects.toMatchObject({
+ code: ErrorCode.AppUpdateManaged,
+ })
+ await expect(service.download()).rejects.toMatchObject({
+ code: ErrorCode.AppUpdateManaged,
+ })
+ expect(() => service.install()).toThrow(
+ expect.objectContaining({ code: ErrorCode.AppUpdateManaged })
+ )
+ service.setChannel('beta')
+ await expect(service.check()).rejects.toMatchObject({
+ code: ErrorCode.AppUpdateManaged,
+ })
+
+ expect(loadUpdater).not.toHaveBeenCalled()
+ expect(service.getChannel()).toBe('beta')
+ expect(service.getState()).toEqual({
+ phase: 'managed',
+ currentVersion: '2.0.0',
+ updateAuthority: 'system',
+ })
+ }
+ )
+
+ it('localizes each managed error without changing the managed snapshot', async () => {
+ let message = 'Updates come from the installation source'
+ const service = await createAppUpdateService({
+ eventBus: new EventBus(),
+ currentVersion: '2.0.0-beta.41',
+ channel: 'beta',
+ isWindowsPackage: true,
+ supported: false,
+ loadUpdater: vi.fn(),
+ getManagedMessage: () => message,
+ })
+
+ await expect(service.check()).rejects.toThrow(message)
+ message = 'Use the original installation source to update'
+ await expect(service.download()).rejects.toThrow(message)
+ service.getState().phase = 'available'
+ expect(service.getState().phase).toBe('managed')
+ })
+
+ it('retains the direct-build update lifecycle and channel handling', async () => {
+ const updater = createFakeUpdater()
+ const loadUpdater = vi.fn(async () => updater)
+ const service = await createAppUpdateService({
+ eventBus: new EventBus(),
+ currentVersion: '2.0.0',
+ channel: 'stable',
+ isWindowsPackage: false,
+ supported: true,
+ loadUpdater,
+ getManagedMessage: vi.fn(),
+ })
+
+ await service.check()
+ updater.fire('update-available', { version: '2.0.1' })
+ await service.download()
+ updater.fire('update-downloaded', { version: '2.0.1' })
+ service.install()
+ service.setChannel('beta')
+
+ expect(loadUpdater).toHaveBeenCalledOnce()
+ expect(updater.checkForUpdates).toHaveBeenCalledOnce()
+ expect(updater.downloadUpdate).toHaveBeenCalledOnce()
+ expect(updater.quitAndInstall).toHaveBeenCalledOnce()
+ expect(updater.channel).toBe('beta')
+ })
+
+ it('preserves unsupported direct builds', async () => {
+ const updater = createFakeUpdater()
+ const service = await createAppUpdateService({
+ eventBus: new EventBus(),
+ currentVersion: '2.0.0',
+ channel: 'stable',
+ isWindowsPackage: false,
+ supported: false,
+ loadUpdater: async () => updater,
+ getManagedMessage: vi.fn(),
+ })
+
+ expect(service.getState().phase).toBe('unsupported')
+ updater.fire('update-downloaded', { version: '2.0.1' })
+ expect(() => service.install()).toThrow()
+ expect(updater.quitAndInstall).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/core/app-update-service.ts b/src/main/core/app-update-service.ts
new file mode 100644
index 00000000..16838683
--- /dev/null
+++ b/src/main/core/app-update-service.ts
@@ -0,0 +1,86 @@
+import type { EventBus } from '@core/events/event-bus'
+import { AppError, ErrorCode } from '@shared/errors'
+import type { AppUpdateState } from '@shared/types/app-update'
+import type { AppUpdateChannel } from '@shared/types/settings'
+import { UpdateManager, type Updater } from './update-manager'
+
+export interface AppUpdateService {
+ getState(): AppUpdateState
+ getChannel(): AppUpdateChannel
+ setChannel(channel: AppUpdateChannel): void
+ check(): Promise<unknown>
+ download(): Promise<unknown>
+ install(): void
+}
+
+interface CreateAppUpdateServiceOptions {
+ eventBus: EventBus
+ currentVersion: string
+ channel: AppUpdateChannel
+ isWindowsPackage: boolean
+ supported: boolean
+ loadUpdater: () => Promise<Updater>
+ getManagedMessage: () => string
+}
+
+/** Windows packages never load the application updater, including sideloaded tests. */
+export async function createAppUpdateService(
+ options: CreateAppUpdateServiceOptions
+): Promise<AppUpdateService> {
+ if (options.isWindowsPackage) {
+ return new ManagedUpdateService(
+ options.currentVersion,
+ options.channel,
+ options.getManagedMessage
+ )
+ }
+
+ return new UpdateManager({
+ eventBus: options.eventBus,
+ currentVersion: options.currentVersion,
+ channel: options.channel,
+ updater: await options.loadUpdater(),
+ supported: options.supported,
+ })
+}
+
+class ManagedUpdateService implements AppUpdateService {
+ constructor(
+ private readonly currentVersion: string,
+ private channel: AppUpdateChannel,
+ private readonly getManagedMessage: () => string
+ ) {}
+
+ getState(): AppUpdateState {
+ return {
+ phase: 'managed',
+ currentVersion: this.currentVersion,
+ updateAuthority: 'system',
+ }
+ }
+
+ getChannel(): AppUpdateChannel {
+ return this.channel
+ }
+
+ setChannel(channel: AppUpdateChannel): void {
+ // Retain the preference for callers without creating a package update channel.
+ this.channel = channel
+ }
+
+ check(): Promise<never> {
+ return Promise.reject(this.managedError())
+ }
+
+ download(): Promise<never> {
+ return Promise.reject(this.managedError())
+ }
+
+ install(): never {
+ throw this.managedError()
+ }
+
+ private managedError(): AppError {
+ return new AppError(ErrorCode.AppUpdateManaged, this.getManagedMessage())
+ }
+}
diff --git a/src/main/core/update-manager.test.ts b/src/main/core/update-manager.test.ts
index d32c8889..3d98d144 100644
--- a/src/main/core/update-manager.test.ts
+++ b/src/main/core/update-manager.test.ts
@@ -311,6 +311,8 @@ describe('UpdateManager', () => {
let unsupported: UpdateManager
beforeEach(() => {
+ eventBus = new EventBus()
+ updater = createFakeUpdater()
unsupported = new UpdateManager({
eventBus,
updater,
@@ -339,6 +341,67 @@ describe('UpdateManager', () => {
await expect(unsupported.download()).rejects.toThrow()
expect(updater.downloadUpdate).not.toHaveBeenCalled()
})
+
+ it('cannot download or install after backend events', async () => {
+ updater.fire('update-available', { version: '2.0.1' })
+
+ await expect(unsupported.download()).rejects.toThrow(
+ 'Automatic updates are not supported in this build'
+ )
+ updater.fire('update-downloaded', { version: '2.0.1' })
+ expect(() => unsupported.install()).toThrow(
+ 'Automatic updates are not supported in this build'
+ )
+ expect(updater.downloadUpdate).not.toHaveBeenCalled()
+ expect(updater.quitAndInstall).not.toHaveBeenCalled()
+ expect(unsupported.getState().phase).toBe('unsupported')
+ })
+
+ it.each([
+ 'checking-for-update',
+ 'update-available',
+ 'update-not-available',
+ 'download-progress',
+ 'update-downloaded',
+ 'update-cancelled',
+ 'error',
+ ])('ignores the backend %s event', (event) => {
+ const emit = vi.spyOn(eventBus, 'emit')
+
+ updater.fire(event, { version: '2.0.1', percent: 50 })
+
+ expect(unsupported.getState()).toEqual({
+ phase: 'unsupported',
+ currentVersion: '2.0.0',
+ })
+ expect(emit).not.toHaveBeenCalled()
+ })
+
+ it('never accesses the backend when created or changing channels', () => {
+ const inaccessibleUpdater = new Proxy(createFakeUpdater(), {
+ get() {
+ throw new Error('Unexpected updater access')
+ },
+ set() {
+ throw new Error('Unexpected updater mutation')
+ },
+ })
+ const isolated = new UpdateManager({
+ eventBus,
+ updater: inaccessibleUpdater,
+ currentVersion: '2.0.0',
+ channel: 'stable',
+ supported: false,
+ })
+
+ isolated.setChannel('beta')
+
+ expect(isolated.getChannel()).toBe('beta')
+ expect(isolated.getState()).toEqual({
+ phase: 'unsupported',
+ currentVersion: '2.0.0',
+ })
+ })
})
describe('constructor configuration', () => {
diff --git a/src/main/core/update-manager.ts b/src/main/core/update-manager.ts
index fc7304b0..48963837 100644
--- a/src/main/core/update-manager.ts
+++ b/src/main/core/update-manager.ts
@@ -67,6 +67,10 @@ export class UpdateManager {
currentVersion: options.currentVersion,
}
+ // Unsupported builds must remain inert even if the shared updater emits
+ // stale events. Do not configure or subscribe to that backend.
+ if (!this.supported) return
+
// We never auto-download or auto-install. The renderer drives the
// user experience: check → ask → download → ask → install, and can
// recover the latest snapshot whenever the About dialog is reopened.
@@ -104,7 +108,7 @@ export class UpdateManager {
setChannel(channel: AppUpdateChannel): void {
if (channel === this.channel) return
this.channel = channel
- this.configureUpdaterChannel()
+ if (this.supported) this.configureUpdaterChannel()
this.transition({
phase: this.supported ? 'idle' : 'unsupported',
currentVersion: this.state.currentVersion,
@@ -146,6 +150,11 @@ export class UpdateManager {
}
download(): Promise<unknown> {
+ if (!this.supported) {
+ return Promise.reject(
+ new Error('Automatic updates are not supported in this build')
+ )
+ }
if (this.downloadPromise) return this.downloadPromise
const canDownload =
this.state.phase === 'available' ||
@@ -179,6 +188,9 @@ export class UpdateManager {
}
install(): void {
+ if (!this.supported) {
+ throw new Error('Automatic updates are not supported in this build')
+ }
if (this.state.phase !== 'downloaded') {
throw new Error('Update is not ready to install')
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 4bd72ed9..82806234 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -147,14 +147,10 @@ import {
shell,
systemPreferences,
} from 'electron'
-import { autoUpdater } from 'electron-updater'
import { bootstrapBridge, createNativeMessagingInstaller } from './bridge'
import { BridgeManager } from './bridge/bridge-manager'
import { isPackagedLinuxFlatpak } from './bridge/flatpak-environment'
-import {
- isElectronSelfUpdateSupported,
- resolvePackagedLinuxSnapEnvironment,
-} from './bridge/snap-environment'
+import { resolvePackagedLinuxSnapEnvironment } from './bridge/snap-environment'
import { CliToolService } from './cli/cli-tool-service'
import { resolveExecutable } from './cli/shell-environment'
import { CommandRegistry } from './commands/command-registry'
@@ -162,11 +158,11 @@ import { ContextStore } from './commands/context-store'
import { registerAllCommands } from './commands/definitions'
import { KeybindingRegistry } from './commands/keybindings/keybinding-registry'
import type { CommandDeps } from './commands/types'
+import { createAppUpdateService } from './core/app-update-service'
import {
DevelopmentUpdateSimulator,
shouldUseDevelopmentUpdateSimulator,
} from './core/development-update-simulator'
-import { UpdateManager } from './core/update-manager'
import { registerUpdateQuitPreparation } from './core/update-quit-preparation'
import { setupExceptionHandler } from './exception-handler'
import { registerApplicationMenuIpc } from './ipc/application-menu'
@@ -191,10 +187,12 @@ import { setupAppImageIntegration } from './platform/appimage-integration-host'
import { syncAutoLaunch } from './platform/auto-launch'
import { resolveDefaultSaveDirOptions } from './platform/default-save-dir'
import { resolveDesktopBackgroundPolicy } from './platform/desktop-background-policy'
+import { resolveDistributionContext } from './platform/distribution-context'
import { removePathRecursive, renameAtomic } from './platform/fs-helpers'
import { setupNativeThemeSync } from './platform/native-theme-sync'
import { setupPowerManager } from './platform/power-manager'
import { createProtocolManager } from './platform/protocol-manager'
+import { isElectronSelfUpdateSupported } from './platform/self-update-policy'
import { createElectronPlatformServices } from './platform/services'
import { setupSystemAccentColorSync } from './platform/system-accent-color'
import { removeTaskPath } from './platform/task-file-remover'
@@ -225,7 +223,13 @@ import { resolveMainWindowStartupPlan } from './window/window-startup-plan'
suppressMacOSAutomaticFullscreenMenuItem(process.platform, systemPreferences)
-if (process.platform === 'win32') {
+const distributionContext = resolveDistributionContext({
+ platform: process.platform,
+ isPackaged: app.isPackaged,
+ windowsStore: process.windowsStore,
+})
+
+if (process.platform === 'win32' && !distributionContext.isWindowsPackage) {
app.setAppUserModelId(APP_ID)
}
@@ -246,7 +250,7 @@ if (process.platform === 'linux') {
app.commandLine.appendSwitch('password-store', 'basic')
}
-const platform = createElectronPlatformServices()
+const platform = createElectronPlatformServices(distributionContext)
const rendererUrlPolicy = initializeRendererUrlPolicy({
isPackaged: app.isPackaged,
appPath: app.getAppPath(),
@@ -2173,14 +2177,15 @@ async function initializeMainProcess(): Promise<void> {
onQuitAndInstall: () => app.quit(),
})
: null
- const updateBackend = developmentUpdateSimulator ?? autoUpdater
const updatesSupported =
- updateSimulatorEnabled ||
- isElectronSelfUpdateSupported({
- hasUpdateMetadata,
- isPackaged: app.isPackaged,
- snapEnvironment: settingsSnapEnvironment,
- })
+ !distributionContext.isWindowsPackage &&
+ (updateSimulatorEnabled ||
+ isElectronSelfUpdateSupported({
+ hasUpdateMetadata,
+ isPackaged: app.isPackaged,
+ isWindowsPackage: distributionContext.isWindowsPackage,
+ isSnap: settingsSnapEnvironment !== null,
+ }))
if (developmentUpdateSimulator) {
log.info('development update simulator enabled')
registerUpdateQuitPreparation({
@@ -2190,13 +2195,18 @@ async function initializeMainProcess(): Promise<void> {
})
}
if (!mainProcessWork.isAccepting()) return
- const updateManager = new UpdateManager({
+ const updateManager = await createAppUpdateService({
eventBus,
- updater: updateBackend,
currentVersion: app.getVersion(),
channel: settingsManager.getApp().updateChannel,
+ isWindowsPackage: distributionContext.isWindowsPackage,
supported: updatesSupported,
+ loadUpdater: async () =>
+ developmentUpdateSimulator ??
+ (await import('electron-updater')).default.autoUpdater,
+ getManagedMessage: () => i18n.t('settings.about.update.managedDescription'),
})
+ if (!mainProcessWork.isAccepting()) return
const trackerStorePath = path.join(platform.userDataDir, 'tracker.json')
const trackerStore = new TrackerStore(trackerStorePath)
@@ -2916,11 +2926,13 @@ const quitController = new QuitController({
beginShutdown,
})
-registerUpdateQuitPreparation({
- updater: nativeAutoUpdater,
- markForceQuit: () => quitController.markForceQuit(),
- setWillQuit: (value) => windowManager?.setWillQuit(value),
-})
+if (!distributionContext.isWindowsPackage) {
+ registerUpdateQuitPreparation({
+ updater: nativeAutoUpdater,
+ markForceQuit: () => quitController.markForceQuit(),
+ setWillQuit: (value) => windowManager?.setWillQuit(value),
+ })
+}
const requestForcedQuit = (reason: string) => {
log.info({ reason }, 'received forced quit request')
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index ca5236c2..2f7912e9 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -3,8 +3,10 @@ import { tmpdir } from 'node:os'
import path from 'node:path'
import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'
import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'
+import { EventBus } from '@core/events/event-bus'
import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
import { SettingsManager } from '@core/settings/settings-manager'
+import { ErrorCode } from '@shared/errors'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
@@ -20,6 +22,7 @@ import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'
import { makeDownloadTask } from '@test-utils/task'
import { directTaskUpdatePublication } from '@test-utils/task-update'
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createAppUpdateService } from '../core/app-update-service'
import { MainProcessWorkCoordinator } from '../main-process-work-coordinator'
import { WINDOWS_DEFAULT_APPS_SETTINGS_URL } from '../platform/windows-default-apps'
import type { CommandContext } from './commands'
@@ -908,6 +911,37 @@ describe('buildCommandHandlers', () => {
})
})
+ it('rejects direct update IPC for a Windows package without loading its updater', async () => {
+ const loadUpdater = vi.fn(async () => {
+ throw new Error('Application updater must stay unloaded')
+ })
+ const updateManager = await createAppUpdateService({
+ eventBus: new EventBus(),
+ currentVersion: '2.0.0',
+ channel: 'stable',
+ isWindowsPackage: true,
+ supported: true,
+ loadUpdater,
+ getManagedMessage: () => 'Updates come from the installation source',
+ })
+ const handlers = buildCommandHandlers({
+ ...fakeCtx(),
+ updateManager,
+ } as unknown as CommandContext)
+
+ for (const command of [
+ Commands.CheckForUpdates,
+ Commands.DownloadUpdate,
+ Commands.InstallUpdate,
+ ]) {
+ await expect(handlers[command]?.()).rejects.toMatchObject({
+ code: ErrorCode.AppUpdateManaged,
+ })
+ }
+ expect(loadUpdater).not.toHaveBeenCalled()
+ expect(updateManager.getState().phase).toBe('managed')
+ })
+
it.each([0, 1, 2])(
'applies App batch options and records history only for accepted tasks (%s failures)',
async (failures) => {
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index e2a1a3d3..31128596 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -138,7 +138,7 @@ import type { BridgeManager } from '../bridge/bridge-manager'
import type { CliToolService } from '../cli/cli-tool-service'
import { MenuContextPatchSchema } from '../commands/context-schema'
import type { ContextStore } from '../commands/context-store'
-import type { UpdateManager } from '../core/update-manager'
+import type { AppUpdateService } from '../core/app-update-service'
import { i18n } from '../lib/i18n'
import {
enableAppImageIntegrationFromSettings,
@@ -183,7 +183,7 @@ export interface CommandContext {
torrentParser: TorrentParser
adapter: EngineAdapter
taskManager: TaskManager
- updateManager: UpdateManager
+ updateManager: AppUpdateService
/**
* Startup barrier: resolves once engine start + session restore have
* settled (success or failure). createTask awaits it (after engine-ready)
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 91a8cc19..6ead7707 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -50,7 +50,7 @@ import type { GetTaskActivityParams } from '@shared/types/task-activity'
import { ipcMain, session } from 'electron'
import { getAppImageNativeHost } from '../bridge/appimage-native-host-electron'
import type { CliToolService } from '../cli/cli-tool-service'
-import type { UpdateManager } from '../core/update-manager'
+import type { AppUpdateService } from '../core/app-update-service'
import { getAppImageIntegrationView } from '../platform/appimage-integration-host'
import { getLinuxDefaultAssociations } from '../platform/linux-default-apps'
import { getSystemAccentColor } from '../platform/system-accent-color'
@@ -94,7 +94,7 @@ export interface QueryContext {
hostVersion: string
userDataDir: string
speedLimitController: SpeedLimitController
- updateManager: UpdateManager
+ updateManager: AppUpdateService
}
export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
diff --git a/src/main/platform/distribution-context.test.ts b/src/main/platform/distribution-context.test.ts
new file mode 100644
index 00000000..c85f4b15
--- /dev/null
+++ b/src/main/platform/distribution-context.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it, vi } from 'vitest'
+import { resolveDistributionContext } from './distribution-context'
+
+describe('resolveDistributionContext', () => {
+ it('classifies a packaged Windows app without claiming Store provenance', () => {
+ expect(
+ resolveDistributionContext({
+ platform: 'win32',
+ isPackaged: true,
+ windowsStore: true,
+ })
+ ).toEqual({ distribution: 'windows-package', isWindowsPackage: true })
+ })
+
+ it.each([true, false, undefined])(
+ 'keeps an unpackaged Windows app in development when windowsStore is %s',
+ (windowsStore) => {
+ expect(
+ resolveDistributionContext({
+ platform: 'win32',
+ isPackaged: false,
+ windowsStore,
+ })
+ ).toEqual({ distribution: 'development', isWindowsPackage: false })
+ }
+ )
+
+ it.each([false, undefined])(
+ 'preserves direct Windows installations when windowsStore is %s',
+ (windowsStore) => {
+ expect(
+ resolveDistributionContext({
+ platform: 'win32',
+ isPackaged: true,
+ windowsStore,
+ })
+ ).toEqual({ distribution: 'direct', isWindowsPackage: false })
+ }
+ )
+
+ it.each(['darwin', 'linux'] as const)(
+ 'does not classify %s as a Windows package even when the flag is set',
+ (platform) => {
+ expect(
+ resolveDistributionContext({
+ platform,
+ isPackaged: true,
+ windowsStore: true,
+ })
+ ).toEqual({ distribution: 'direct', isWindowsPackage: false })
+ }
+ )
+
+ it('does not treat an environment variable as a package identity signal', () => {
+ vi.stubEnv('MOTRIX_DISTRIBUTION', 'microsoft-store')
+ try {
+ expect(
+ resolveDistributionContext({ platform: 'win32', isPackaged: true })
+ ).toEqual({ distribution: 'direct', isWindowsPackage: false })
+ } finally {
+ vi.unstubAllEnvs()
+ }
+ })
+})
diff --git a/src/main/platform/distribution-context.ts b/src/main/platform/distribution-context.ts
new file mode 100644
index 00000000..8cc313e2
--- /dev/null
+++ b/src/main/platform/distribution-context.ts
@@ -0,0 +1,30 @@
+export interface DistributionContextInput {
+ platform: NodeJS.Platform
+ isPackaged: boolean
+ windowsStore?: boolean
+}
+
+export interface DistributionContext {
+ readonly distribution: 'development' | 'direct' | 'windows-package'
+ readonly isWindowsPackage: boolean
+}
+
+/**
+ * Electron's windowsStore flag identifies MSIX/AppX packaging, including
+ * sideloaded test packages. It does not verify a Store publisher or package
+ * family. Exact package identity validation would require a separate native
+ * identity query; no such validation is performed here.
+ */
+export function resolveDistributionContext({
+ platform,
+ isPackaged,
+ windowsStore,
+}: DistributionContextInput): DistributionContext {
+ if (!isPackaged) {
+ return { distribution: 'development', isWindowsPackage: false }
+ }
+ if (platform === 'win32' && windowsStore === true) {
+ return { distribution: 'windows-package', isWindowsPackage: true }
+ }
+ return { distribution: 'direct', isWindowsPackage: false }
+}
diff --git a/src/main/platform/self-update-policy.test.ts b/src/main/platform/self-update-policy.test.ts
new file mode 100644
index 00000000..f5c61f98
--- /dev/null
+++ b/src/main/platform/self-update-policy.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest'
+import { isElectronSelfUpdateSupported } from './self-update-policy'
+
+describe('Electron self-update policy', () => {
+ it.each([
+ [true, true],
+ [true, false],
+ [false, true],
+ [false, false],
+ ])(
+ 'rejects Windows package and Snap updates with packaged=%s, metadata=%s',
+ (isPackaged, hasUpdateMetadata) => {
+ expect(
+ isElectronSelfUpdateSupported({
+ isPackaged,
+ hasUpdateMetadata,
+ isWindowsPackage: true,
+ isSnap: false,
+ })
+ ).toBe(false)
+ expect(
+ isElectronSelfUpdateSupported({
+ isPackaged,
+ hasUpdateMetadata,
+ isWindowsPackage: false,
+ isSnap: true,
+ })
+ ).toBe(false)
+ }
+ )
+
+ it.each([
+ [true, true, true],
+ [true, false, false],
+ [false, true, false],
+ [false, false, false],
+ ])(
+ 'requires packaged=%s and metadata=%s for direct-build support=%s',
+ (isPackaged, hasUpdateMetadata, supported) => {
+ expect(
+ isElectronSelfUpdateSupported({
+ isPackaged,
+ hasUpdateMetadata,
+ isWindowsPackage: false,
+ isSnap: false,
+ })
+ ).toBe(supported)
+ }
+ )
+})
diff --git a/src/main/platform/self-update-policy.ts b/src/main/platform/self-update-policy.ts
new file mode 100644
index 00000000..66c0dcbe
--- /dev/null
+++ b/src/main/platform/self-update-policy.ts
@@ -0,0 +1,18 @@
+export interface ElectronSelfUpdateOptions {
+ hasUpdateMetadata: boolean
+ isPackaged: boolean
+ isWindowsPackage: boolean
+ isSnap: boolean
+}
+
+/** System-managed packages cannot opt into EXE updates by carrying a feed. */
+export function isElectronSelfUpdateSupported(
+ options: ElectronSelfUpdateOptions
+): boolean {
+ return (
+ options.isPackaged &&
+ !options.isWindowsPackage &&
+ !options.isSnap &&
+ options.hasUpdateMetadata
+ )
+}
diff --git a/src/main/platform/services.test.ts b/src/main/platform/services.test.ts
index 63c5f3a1..f147803f 100644
--- a/src/main/platform/services.test.ts
+++ b/src/main/platform/services.test.ts
@@ -5,6 +5,11 @@ const originalResourcesPath = Object.getOwnPropertyDescriptor(
process,
'resourcesPath'
)
+const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
+const originalWindowsStore = Object.getOwnPropertyDescriptor(
+ process,
+ 'windowsStore'
+)
const mocks = vi.hoisted(() => {
const state = {
@@ -53,16 +58,28 @@ describe('createElectronPlatformServices', () => {
configurable: true,
value: '/fake/resources',
})
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: false,
+ })
delete process.env.MOTRIX_USER_DATA
+ vi.stubEnv('MOTRIX_BRIDGE_DATA_DIR', undefined)
})
afterEach(() => {
delete process.env.MOTRIX_USER_DATA
+ vi.unstubAllEnvs()
if (originalResourcesPath) {
Object.defineProperty(process, 'resourcesPath', originalResourcesPath)
} else {
Reflect.deleteProperty(process, 'resourcesPath')
}
+ Object.defineProperty(process, 'platform', originalPlatform)
+ if (originalWindowsStore) {
+ Object.defineProperty(process, 'windowsStore', originalWindowsStore)
+ } else {
+ Reflect.deleteProperty(process, 'windowsStore')
+ }
})
it('uses a sibling development profile by default', () => {
@@ -71,7 +88,11 @@ describe('createElectronPlatformServices', () => {
expect(svc.host).toBe(RunHost.Electron)
expect(svc.userDataDir).toBe('/fake/Motrix-dev')
expect(svc.isDev).toBe(true)
- expect(svc.aria2BinaryPath.endsWith('aria2c')).toBe(true)
+ expect(
+ svc.aria2BinaryPath.endsWith(
+ process.platform === 'win32' ? 'aria2c.exe' : 'aria2c'
+ )
+ ).toBe(true)
expect(svc.extraResourceDir).toMatch(/extra$/)
})
@@ -124,6 +145,25 @@ describe('createElectronPlatformServices', () => {
)
})
+ it.each([false, true])(
+ 'preserves bridge directory overrides outside Windows packages (packaged=%s)',
+ (isPackaged) => {
+ mocks.state.isPackaged = isPackaged
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: 'win32',
+ })
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: !isPackaged,
+ })
+ process.env.MOTRIX_BRIDGE_DATA_DIR = '/tmp/shared-bridge'
+
+ expect(() => createElectronPlatformServices()).not.toThrow()
+ expect(process.env.MOTRIX_BRIDGE_DATA_DIR).toBe('/tmp/shared-bridge')
+ }
+ )
+
it('rejects a relative MOTRIX_USER_DATA before creating it', () => {
process.env.MOTRIX_USER_DATA = 'relative/profile'
@@ -156,4 +196,187 @@ describe('createElectronPlatformServices', () => {
'setPath:sessionData:/fake/Motrix-dev',
])
})
+
+ describe('Windows package profile', () => {
+ const appData = 'C:\\Users\\Test User\\AppData\\Roaming'
+ const storeProfile = `${appData}\\Motrix-Store`
+
+ beforeEach(() => {
+ mocks.state.isPackaged = true
+ mocks.state.paths = {
+ appData,
+ userData: `${appData}\\Motrix`,
+ sessionData: `${appData}\\Motrix`,
+ }
+ Object.defineProperty(process, 'platform', {
+ configurable: true,
+ value: 'win32',
+ })
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: true,
+ })
+ })
+
+ it('selects a separate root without reading the direct-install profile', () => {
+ const svc = createElectronPlatformServices()
+
+ expect(svc.userDataDir).toBe(storeProfile)
+ expect(svc.isDev).toBe(false)
+ expect(mocks.getPath.mock.calls).toEqual([['appData']])
+ expect(mocks.state.paths.userData).toBe(storeProfile)
+ expect(mocks.state.paths.sessionData).toBe(storeProfile)
+ })
+
+ it('sets both paths before returning services to persistent consumers', () => {
+ const svc = createElectronPlatformServices()
+ mocks.state.operations.push(`persistent-service:${svc.userDataDir}`)
+
+ expect(mocks.state.operations).toEqual([
+ `mkdir:${storeProfile}`,
+ `setPath:userData:${storeProfile}`,
+ `setPath:sessionData:${storeProfile}`,
+ `persistent-service:${storeProfile}`,
+ ])
+ })
+
+ it.each([
+ 'C:\\Users\\Test User\\AppData\\Roaming\\Motrix',
+ 'C:\\isolated-but-unverified',
+ 'relative/profile',
+ ' ',
+ ])('rejects nonempty overrides before any path access: %s', (override) => {
+ process.env.MOTRIX_USER_DATA = override
+
+ expect(() => createElectronPlatformServices()).toThrow(
+ 'MOTRIX_USER_DATA is unsupported for Windows packages'
+ )
+ expect(mocks.getPath).not.toHaveBeenCalled()
+ expect(mocks.mkdirSync).not.toHaveBeenCalled()
+ expect(mocks.setPath).not.toHaveBeenCalled()
+ })
+
+ it('treats an empty override as absent and still isolates the profile', () => {
+ process.env.MOTRIX_USER_DATA = ''
+
+ expect(createElectronPlatformServices().userDataDir).toBe(storeProfile)
+ })
+
+ it.each([
+ 'C:\\Users\\Test User\\AppData\\Roaming\\Motrix\\bridge',
+ 'C:\\isolated-but-unverified\\bridge',
+ 'relative/bridge',
+ ' ',
+ ])(
+ 'rejects nonempty bridge overrides before path access: %s',
+ (override) => {
+ process.env.MOTRIX_BRIDGE_DATA_DIR = override
+
+ expect(() => createElectronPlatformServices()).toThrow(
+ 'MOTRIX_BRIDGE_DATA_DIR is unsupported for Windows packages'
+ )
+ expect(mocks.getPath).not.toHaveBeenCalled()
+ expect(mocks.mkdirSync).not.toHaveBeenCalled()
+ expect(mocks.setPath).not.toHaveBeenCalled()
+ }
+ )
+
+ it('ignores an empty bridge override and keeps the isolated profile', () => {
+ process.env.MOTRIX_BRIDGE_DATA_DIR = ''
+
+ expect(createElectronPlatformServices().userDataDir).toBe(storeProfile)
+ })
+
+ it.each([
+ [
+ 'C:\\Users\\测试 用户\\AppData\\Roaming',
+ 'C:\\Users\\测试 用户\\AppData\\Roaming\\Motrix-Store',
+ ],
+ [
+ '\\\\server\\profiles\\tester',
+ '\\\\server\\profiles\\tester\\Motrix-Store',
+ ],
+ ])(
+ 'preserves the AppData root selected by Electron: %s',
+ (base, expected) => {
+ mocks.state.paths.appData = base
+
+ expect(createElectronPlatformServices().userDataDir).toBe(expected)
+ }
+ )
+
+ it('rejects a relative AppData root before changing paths', () => {
+ mocks.state.paths.appData = 'relative/appdata'
+
+ expect(() => createElectronPlatformServices()).toThrow(
+ 'Windows package AppData must be an absolute path'
+ )
+ expect(mocks.mkdirSync).not.toHaveBeenCalled()
+ expect(mocks.setPath).not.toHaveBeenCalled()
+ })
+
+ it('does not fall back to a direct profile when directory creation fails', () => {
+ mocks.mkdirSync.mockImplementationOnce(() => {
+ throw new Error('access denied')
+ })
+
+ expect(() => createElectronPlatformServices()).toThrow('access denied')
+ expect(mocks.getPath.mock.calls).toEqual([['appData']])
+ expect(mocks.setPath).not.toHaveBeenCalled()
+ })
+
+ it('accepts the same resolved context used by main startup', () => {
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: false,
+ })
+
+ expect(
+ createElectronPlatformServices({
+ distribution: 'windows-package',
+ isWindowsPackage: true,
+ }).userDataDir
+ ).toBe(storeProfile)
+ })
+
+ it('preserves the direct Windows profile when the package flag is absent', () => {
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: undefined,
+ })
+
+ expect(createElectronPlatformServices().userDataDir).toBe(
+ `${appData}\\Motrix`
+ )
+ expect(mocks.getPath.mock.calls).toEqual([['userData']])
+ expect(mocks.setPath).not.toHaveBeenCalled()
+ })
+
+ it('honors direct Windows absolute overrides without package isolation', () => {
+ Object.defineProperty(process, 'windowsStore', {
+ configurable: true,
+ value: false,
+ })
+ process.env.MOTRIX_USER_DATA = 'D:\\test-profile'
+
+ expect(createElectronPlatformServices().userDataDir).toBe(
+ 'D:\\test-profile'
+ )
+ expect(mocks.setPath).toHaveBeenCalledWith(
+ 'sessionData',
+ 'D:\\test-profile'
+ )
+ })
+
+ it('uses the existing development override even if windowsStore is true', () => {
+ mocks.state.isPackaged = false
+ process.env.MOTRIX_USER_DATA = 'D:\\development-profile'
+
+ const svc = createElectronPlatformServices()
+
+ expect(svc.isDev).toBe(true)
+ expect(svc.userDataDir).toBe('D:\\development-profile')
+ expect(mocks.getPath.mock.calls).toEqual([['userData']])
+ })
+ })
})
diff --git a/src/main/platform/services.ts b/src/main/platform/services.ts
index 91f240d3..1595848a 100644
--- a/src/main/platform/services.ts
+++ b/src/main/platform/services.ts
@@ -3,20 +3,54 @@ import path from 'node:path'
import { aria2BinaryName } from '@shared/platform/aria2'
import { type PlatformServices, RunHost } from '@shared/platform/services'
import { app } from 'electron'
+import {
+ type DistributionContext,
+ resolveDistributionContext,
+} from './distribution-context'
-export function createElectronPlatformServices(): PlatformServices {
+export function createElectronPlatformServices(
+ distributionContext: DistributionContext = resolveDistributionContext({
+ platform: process.platform,
+ isPackaged: app.isPackaged,
+ windowsStore: process.windowsStore,
+ })
+): PlatformServices {
const isDev = !app.isPackaged
const userDataOverride = process.env.MOTRIX_USER_DATA
- const defaultUserDataDir = app.getPath('userData')
- const userDataDir =
- userDataOverride ||
- (isDev ? `${defaultUserDataDir}-dev` : defaultUserDataDir)
+ const { isWindowsPackage } = distributionContext
+ const dataPaths = process.platform === 'win32' ? path.win32 : path
+ if (isWindowsPackage && userDataOverride) {
+ throw new Error('MOTRIX_USER_DATA is unsupported for Windows packages')
+ }
+ if (isWindowsPackage && process.env.MOTRIX_BRIDGE_DATA_DIR) {
+ // Bridge credentials and discovery state must share the isolated profile.
+ // Reject this before any persistent consumer can reopen a direct profile.
+ throw new Error(
+ 'MOTRIX_BRIDGE_DATA_DIR is unsupported for Windows packages'
+ )
+ }
+
+ let userDataDir: string
+ if (isWindowsPackage) {
+ // Never consult or migrate the direct-install profile in package mode.
+ // Resolve AppData through Electron so Windows controls its package mapping.
+ userDataDir = dataPaths.join(app.getPath('appData'), 'Motrix-Store')
+ } else {
+ const defaultUserDataDir = app.getPath('userData')
+ userDataDir =
+ userDataOverride ||
+ (isDev ? `${defaultUserDataDir}-dev` : defaultUserDataDir)
+ }
// Resolve this before any persistent service or the single-instance lock.
// Electron requires an existing absolute directory for app.setPath().
- if (userDataOverride || isDev) {
- if (!path.isAbsolute(userDataDir)) {
- throw new Error('MOTRIX_USER_DATA must be an absolute path')
+ if (isWindowsPackage || userDataOverride || isDev) {
+ if (!dataPaths.isAbsolute(userDataDir)) {
+ throw new Error(
+ isWindowsPackage
+ ? 'Windows package AppData must be an absolute path'
+ : 'MOTRIX_USER_DATA must be an absolute path'
+ )
}
mkdirSync(userDataDir, { recursive: true })
app.setPath('userData', userDataDir)
diff --git a/src/renderer/routes/settings/cards/about-dialog.test.tsx b/src/renderer/routes/settings/cards/about-dialog.test.tsx
index c3d21f6a..fcf90330 100644
--- a/src/renderer/routes/settings/cards/about-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.test.tsx
@@ -12,7 +12,7 @@ import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import packageJson from '../../../../../package.json'
import { AboutDialog } from './about-dialog'
-import { shouldShowAppUpdate } from './app-update-section'
+import * as appUpdateSection from './app-update-section'
vi.mock('@renderer/lib/transport', () => ({
transport: {
@@ -175,6 +175,163 @@ describe('<AboutDialog>', () => {
expect(transport.invoke).toHaveBeenCalledWith(Commands.CheckForUpdates)
})
+ it('keeps update controls hidden until the initial state is known', async () => {
+ let resolveSnapshot!: (state: AppUpdateState) => void
+ vi.mocked(transport.invoke).mockImplementation((channel) => {
+ if (channel === Queries.GetUpdateState) {
+ return new Promise((resolve) => {
+ resolveSnapshot = resolve
+ })
+ }
+ return Promise.resolve({ ok: true })
+ })
+ renderDialog()
+
+ expect(screen.getByText('Loading...')).toBeInTheDocument()
+ expectNoUpdateControls()
+ expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetSettings)
+ expect(vi.mocked(transport.on).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(transport.invoke).mock.invocationCallOrder[0] ?? 0
+ )
+
+ await act(async () => {
+ resolveSnapshot({
+ phase: 'managed',
+ currentVersion: packageJson.version,
+ updateAuthority: 'system',
+ })
+ })
+ expectNoUpdateControls()
+ })
+
+ it('keeps controls hidden when update capability cannot be loaded', async () => {
+ vi.mocked(transport.invoke).mockRejectedValue(
+ new Error('service unavailable')
+ )
+ renderDialog()
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Update failed: service unavailable'
+ )
+ expectNoUpdateControls()
+ expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetSettings)
+ })
+
+ it.each<AppUpdateState>([
+ {
+ phase: 'managed',
+ currentVersion: packageJson.version,
+ updateAuthority: 'system',
+ },
+ { phase: 'managed', currentVersion: packageJson.version },
+ {
+ phase: 'error',
+ currentVersion: packageJson.version,
+ updateAuthority: 'system',
+ error: { message: 'backend failed' },
+ },
+ ])(
+ 'explains externally managed updates for $phase without app controls',
+ async (state) => {
+ vi.mocked(transport.invoke).mockResolvedValue(state)
+ renderDialog()
+
+ expect(
+ await screen.findByText('Updates from your installation source')
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText(
+ 'This packaged Windows edition is updated through its original installation source. In-app updates are unavailable.'
+ )
+ ).toBeInTheDocument()
+ expectNoUpdateControls()
+ expect(screen.queryByText('Motrix is up to date')).not.toBeInTheDocument()
+ expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetSettings)
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.CheckForUpdates
+ )
+ }
+ )
+
+ it('retains system update authority through late backend events', async () => {
+ renderDialog()
+ await emitState({
+ phase: 'managed',
+ currentVersion: packageJson.version,
+ updateAuthority: 'system',
+ })
+
+ for (const phase of ['error', 'available', 'downloaded', 'idle'] as const) {
+ await emitState({
+ phase,
+ currentVersion: packageJson.version,
+ availableVersion: '2.0.1',
+ error: { message: 'stale backend event' },
+ })
+ expectNoUpdateControls()
+ expect(
+ screen.getByText('Updates from your installation source')
+ ).toBeInTheDocument()
+ }
+ })
+
+ it('retains system update authority when an earlier command rejects', async () => {
+ let rejectCheck!: (error: Error) => void
+ vi.mocked(transport.invoke).mockImplementation((channel) => {
+ if (channel === Queries.GetUpdateState) return Promise.resolve(idleState)
+ if (channel === Queries.GetSettings)
+ return Promise.resolve({
+ app: { checkForUpdatesOnLaunch: true, updateChannel: 'stable' },
+ })
+ if (channel === Commands.CheckForUpdates)
+ return new Promise((_, reject) => {
+ rejectCheck = reject
+ })
+ return Promise.resolve({ ok: true })
+ })
+ renderDialog()
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Check for updates' })
+ )
+ await emitState({
+ phase: 'managed',
+ currentVersion: packageJson.version,
+ updateAuthority: 'system',
+ })
+ await act(async () => {
+ rejectCheck(new Error('late check failure'))
+ })
+
+ expectNoUpdateControls()
+ expect(
+ screen.getByText('Updates from your installation source')
+ ).toBeInTheDocument()
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ })
+
+ it('shares one snapshot and subscription while supporting an older host', async () => {
+ renderDialog()
+ expect(
+ await screen.findByRole('button', { name: 'Check for updates' })
+ ).toBeEnabled()
+ expect(
+ await screen.findByRole('switch', { name: 'Check automatically' })
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('combobox', { name: 'Update channel' })
+ ).toBeInTheDocument()
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(([channel]) => channel === Queries.GetUpdateState)
+ ).toHaveLength(1)
+ expect(
+ vi
+ .mocked(transport.on)
+ .mock.calls.filter(([channel]) => channel === Events.UpdateStateChanged)
+ ).toHaveLength(1)
+ })
+
it('offers download when a newer version becomes available', async () => {
renderDialog()
await emitState({
@@ -466,9 +623,31 @@ describe('<AboutDialog>', () => {
)
})
+ it('renders the web note without querying or subscribing to app updates', () => {
+ const showUpdates = vi
+ .spyOn(appUpdateSection, 'shouldShowAppUpdate')
+ .mockReturnValue(false)
+ try {
+ renderDialog()
+ expect(
+ screen.getByText(
+ 'This web edition is updated by its deployment administrator.'
+ )
+ ).toBeInTheDocument()
+ expectNoUpdateControls()
+ expect(transport.invoke).not.toHaveBeenCalledWith(Queries.GetUpdateState)
+ expect(transport.on).not.toHaveBeenCalledWith(
+ Events.UpdateStateChanged,
+ expect.any(Function)
+ )
+ } finally {
+ showUpdates.mockRestore()
+ }
+ })
+
it('does not expose app updates to the web target', () => {
- expect(shouldShowAppUpdate('web')).toBe(false)
- expect(shouldShowAppUpdate('electron')).toBe(true)
+ expect(appUpdateSection.shouldShowAppUpdate('web')).toBe(false)
+ expect(appUpdateSection.shouldShowAppUpdate('electron')).toBe(true)
})
})
@@ -486,3 +665,17 @@ async function emitState(state: AppUpdateState) {
call?.[1](state)
})
}
+
+function expectNoUpdateControls() {
+ expect(
+ screen.queryByRole('button', {
+ name: /^(Check for updates|Download update|Restart and install|Retry)$/,
+ })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('combobox', { name: 'Update channel' })
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('switch', { name: 'Check automatically' })
+ ).not.toBeInTheDocument()
+}
diff --git a/src/renderer/routes/settings/cards/about-dialog.tsx b/src/renderer/routes/settings/cards/about-dialog.tsx
index 35e3f210..51371ead 100644
--- a/src/renderer/routes/settings/cards/about-dialog.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.tsx
@@ -19,6 +19,7 @@ import { useTranslation } from 'react-i18next'
import { AppUpdateSection, shouldShowAppUpdate } from './app-update-section'
import { AutomaticUpdateSetting } from './automatic-update-setting'
import type { SettingsCardDialogProps } from './card-types'
+import { useAppUpdate } from './use-app-update'
const appIconUrl = `${import.meta.env.BASE_URL}app-icon.png`
@@ -50,6 +51,7 @@ export function AboutDialog({
const heading = useRef<HTMLHeadingElement>(null)
const metadata = __MOTRIX_APP_METADATA__
const showUpdates = shouldShowAppUpdate(__MOTRIX_TARGET__)
+ const update = useAppUpdate(showUpdates && open)
return (
<Dialog open={open} onOpenChange={(value) => !value && onClose()}>
@@ -157,7 +159,7 @@ export function AboutDialog({
>
<ScrollAreaContent style={{ minWidth: '100%' }}>
{showUpdates ? (
- <AppUpdateSection />
+ <AppUpdateSection update={update} />
) : (
<p className="px-6 py-5 text-xs text-muted-foreground">
{t('settings.about.webVersionNote')}
@@ -169,7 +171,7 @@ export function AboutDialog({
</ScrollArea>
<DialogFooter className="shrink-0 flex-row items-center justify-between gap-4 border-t border-border/70 bg-background/85 px-6 py-3.5 backdrop-blur-xl sm:justify-between">
- {showUpdates ? <AutomaticUpdateSetting /> : <span />}
+ {update.showControls ? <AutomaticUpdateSetting /> : <span />}
<Button onClick={onClose} size="sm" className="min-w-20">
{t('common.close')}
</Button>
diff --git a/src/renderer/routes/settings/cards/app-update-section.tsx b/src/renderer/routes/settings/cards/app-update-section.tsx
index 13bb024a..75b07779 100644
--- a/src/renderer/routes/settings/cards/app-update-section.tsx
+++ b/src/renderer/routes/settings/cards/app-update-section.tsx
@@ -13,11 +13,11 @@ import type { ReactNode } from 'react'
import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { UpdateChannelSetting } from './update-channel-setting'
-import { useAppUpdate } from './use-app-update'
+import type { AppUpdateController } from './use-app-update'
-export function AppUpdateSection() {
+export function AppUpdateSection({ update }: { update: AppUpdateController }) {
const { t } = useTranslation()
- const { state, check, download, install } = useAppUpdate()
+ const { state, loading, showControls, check, download, install } = update
const betaWarningId = useId()
const [channel, setChannel] = useState<AppUpdateChannel>('stable')
@@ -37,33 +37,37 @@ export function AppUpdateSection() {
id="app-update-title"
className="text-base leading-5 font-semibold tracking-[-0.01em]"
>
- {statusTitle(state, t)}
+ {loading ? t('common.loading') : statusTitle(state, t)}
</h3>
- <p className="mt-1 text-xs leading-normal text-muted-foreground">
- {statusDescription(state, t)}
- </p>
+ {!loading && (
+ <p className="mt-1 text-xs leading-normal text-muted-foreground">
+ {statusDescription(state, t)}
+ </p>
+ )}
</div>
- <UpdateChannelSetting
- warningId={betaWarningId}
- onChannelChanged={setChannel}
- disabled={
- state.phase === 'unsupported' ||
- state.phase === 'checking' ||
- state.phase === 'downloading' ||
- state.phase === 'downloaded'
- }
- >
- <UpdateActionButton
- state={state}
- check={check}
- download={download}
- install={install}
- />
- </UpdateChannelSetting>
+ {showControls && (
+ <UpdateChannelSetting
+ warningId={betaWarningId}
+ onChannelChanged={setChannel}
+ disabled={
+ state.phase === 'unsupported' ||
+ state.phase === 'checking' ||
+ state.phase === 'downloading' ||
+ state.phase === 'downloaded'
+ }
+ >
+ <UpdateActionButton
+ state={state}
+ check={check}
+ download={download}
+ install={install}
+ />
+ </UpdateChannelSetting>
+ )}
</div>
- {channel === 'beta' && (
+ {showControls && channel === 'beta' && (
<Alert
id={betaWarningId}
className="mt-2 border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] leading-4 text-amber-900 dark:text-amber-200"
@@ -153,6 +157,8 @@ function updateAction(
t: ReturnType<typeof useTranslation>['t']
): UpdateAction | null {
switch (state.phase) {
+ case 'managed':
+ return null
case 'unsupported':
return {
label: t('settings.about.update.checkAction'),
@@ -214,6 +220,8 @@ function statusTitle(
t: ReturnType<typeof useTranslation>['t']
): string {
switch (state.phase) {
+ case 'managed':
+ return t('settings.about.update.managedTitle')
case 'unsupported':
return t('settings.about.update.unsupportedTitle')
case 'checking':
@@ -244,6 +252,8 @@ function statusDescription(
t: ReturnType<typeof useTranslation>['t']
): string {
switch (state.phase) {
+ case 'managed':
+ return t('settings.about.update.managedDescription')
case 'unsupported':
return t('settings.about.update.unsupported')
case 'checking':
diff --git a/src/renderer/routes/settings/cards/use-app-update.ts b/src/renderer/routes/settings/cards/use-app-update.ts
index 69c59e2b..b9f7e14a 100644
--- a/src/renderer/routes/settings/cards/use-app-update.ts
+++ b/src/renderer/routes/settings/cards/use-app-update.ts
@@ -3,69 +3,130 @@ import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
import type { AppUpdateState } from '@shared/types/app-update'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
const initialState: AppUpdateState = {
phase: 'idle',
currentVersion: __MOTRIX_APP_METADATA__.version,
}
-export function useAppUpdate() {
+export function useAppUpdate(enabled = true) {
const [state, setState] = useState<AppUpdateState>(initialState)
+ const [hasState, setHasState] = useState(false)
+ const [loading, setLoading] = useState(true)
+ const systemManaged = useRef(false)
useEffect(() => {
+ if (!enabled) return
let active = true
- let receivedEvent = false
+ let revision = 0
+ let snapshotRequest = 0
+ setLoading(true)
+
+ const applyState = (value: unknown) => {
+ const next = value as AppUpdateState
+ // Update authority is fixed for this host. A late event from an older
+ // backend must not restore app-managed actions after a managed snapshot.
+ systemManaged.current ||= isSystemManaged(next)
+ setState(
+ systemManaged.current
+ ? { ...next, phase: 'managed', updateAuthority: 'system' }
+ : next
+ )
+ setHasState(true)
+ setLoading(false)
+ }
+ const refresh = () => {
+ const request = ++snapshotRequest
+ const startedAtRevision = revision
+ void transport
+ .invoke(Queries.GetUpdateState)
+ .then((value) => {
+ if (
+ active &&
+ request === snapshotRequest &&
+ revision === startedAtRevision
+ ) {
+ applyState(value)
+ }
+ })
+ .catch((error: unknown) => {
+ if (
+ !active ||
+ request !== snapshotRequest ||
+ revision !== startedAtRevision
+ ) {
+ return
+ }
+ setLoading(false)
+ setState((current) =>
+ systemManaged.current
+ ? current
+ : {
+ ...current,
+ phase: 'error',
+ error: { message: toMessage(error) },
+ }
+ )
+ })
+ }
const onStateChanged = (value: unknown) => {
- receivedEvent = true
- if (active) setState(value as AppUpdateState)
+ if (!active) return
+ revision += 1
+ applyState(value)
}
transport.on(Events.UpdateStateChanged, onStateChanged)
- void transport
- .invoke(Queries.GetUpdateState)
- .then((value) => {
- if (active && !receivedEvent) setState(value as AppUpdateState)
- })
- .catch((error: unknown) => {
- if (!active || receivedEvent) return
- setState({
- ...initialState,
- phase: 'error',
- error: { message: toMessage(error) },
- })
- })
+ const stopConnectionListener = transport.onConnectionChange?.((event) => {
+ if (event.state === 'connected') refresh()
+ })
+ refresh()
return () => {
active = false
transport.off(Events.UpdateStateChanged, onStateChanged)
+ stopConnectionListener?.()
}
- }, [])
+ }, [enabled])
+ const showControls = enabled && hasState && !isSystemManaged(state)
const invoke = useCallback(
async (command: (typeof Commands)[keyof typeof Commands]) => {
+ if (!showControls || systemManaged.current) return
try {
await transport.invoke(command)
} catch (error) {
- setState((current) => ({
- ...current,
- phase: 'error',
- progress: undefined,
- error: { message: toMessage(error) },
- }))
+ setState((current) =>
+ systemManaged.current
+ ? current
+ : {
+ ...current,
+ phase: 'error',
+ progress: undefined,
+ error: { message: toMessage(error) },
+ }
+ )
}
},
- []
+ [showControls]
)
return {
state,
+ loading,
+ showControls,
check: () => invoke(Commands.CheckForUpdates),
download: () => invoke(Commands.DownloadUpdate),
install: () => invoke(Commands.InstallUpdate),
}
}
+export type AppUpdateController = ReturnType<typeof useAppUpdate>
+
+function isSystemManaged(state: AppUpdateState): boolean {
+ return state.updateAuthority === 'system' || state.phase === 'managed'
+}
+
function toMessage(error: unknown): string {
return error instanceof Error && error.message
? error.message
diff --git a/src/shared/errors.ts b/src/shared/errors.ts
index 4e5871d9..242089b3 100644
--- a/src/shared/errors.ts
+++ b/src/shared/errors.ts
@@ -1,4 +1,5 @@
export enum ErrorCode {
+ AppUpdateManaged = 'APP_UPDATE_MANAGED',
EngineStartFailed = 'ENGINE_START_FAILED',
EngineConnectionLost = 'ENGINE_CONNECTION_LOST',
EngineTimeout = 'ENGINE_TIMEOUT',
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 4c06129f..f1785af1 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -1749,6 +1749,8 @@
"retry": "إعادة المحاولة",
"title": "تحديثات التطبيق",
"unsupported": "لا يمكن تحديث هذا الإصدار تلقائيًا. نزّل أحدث إصدار من الموقع الرسمي.",
+ "managedTitle": "التحديثات عبر مصدر التثبيت",
+ "managedDescription": "يُحدَّث إصدار Windows المعبّأ هذا عبر مصدر تثبيته الأصلي. التحديث من داخل التطبيق غير متاح.",
"unsupportedTitle": "التحديثات التلقائية غير متاحة",
"upToDate": "الإصدار {{version}} هو أحدث إصدار متاح.",
"upToDateTitle": "لديك أحدث إصدار من Motrix"
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index 5a476a47..040aef63 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -1673,6 +1673,8 @@
"retry": "Повторен опит",
"title": "Актуализации на приложението",
"unsupported": "Тази версия не може да се обновява автоматично. Изтеглете най-новата версия от официалния уебсайт.",
+ "managedTitle": "Актуализации от източника на инсталиране",
+ "managedDescription": "Това пакетирано издание за Windows се актуализира чрез първоначалния източник на инсталиране. Актуализациите в приложението не са налични.",
"unsupportedTitle": "Автоматичните актуализации са недостъпни",
"upToDate": "Версия {{version}} е най-новото налично издание.",
"upToDateTitle": "Motrix е с най-новата версия"
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 5bbd4538..31e1f7d3 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -1692,6 +1692,8 @@
"retry": "Tornar-ho a provar",
"title": "Actualitzacions de l'aplicació",
"unsupported": "Aquesta versió no es pot actualitzar automàticament. Baixeu l'última versió del lloc web oficial.",
+ "managedTitle": "Actualitzacions des de la font d’instal·lació",
+ "managedDescription": "Aquesta edició empaquetada per a Windows s’actualitza des de la font d’instal·lació original. Les actualitzacions des de l’aplicació no estan disponibles.",
"unsupportedTitle": "Actualitzacions automàtiques no disponibles",
"upToDate": "La versió {{version}} és l'última disponible.",
"upToDateTitle": "El Motrix està actualitzat"
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index ff4e4b1d..5942550c 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1324,6 +1324,8 @@
"currentVersion": "Aktuelle Version {{version}}",
"idleTitle": "Motrix aktuell halten",
"idle": "Version {{version}} ist installiert. Suchen Sie jetzt nach Updates oder lassen Sie Motrix beim Start danach suchen.",
+ "managedTitle": "Updates über die Installationsquelle",
+ "managedDescription": "Diese paketierte Windows-Version wird über ihre ursprüngliche Installationsquelle aktualisiert. Updates innerhalb der App sind nicht verfügbar.",
"unsupportedTitle": "Automatische Updates nicht verfügbar",
"unsupported": "Diese Version kann nicht automatisch aktualisiert werden. Laden Sie die neueste Version von der offiziellen Website herunter.",
"check": "Nach Updates suchen",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 546018ff..65a38dcd 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -1673,6 +1673,8 @@
"retry": "Επανάληψη",
"title": "Ενημερώσεις εφαρμογής",
"unsupported": "Αυτή η έκδοση δεν μπορεί να ενημερωθεί αυτόματα. Κατεβάστε την τελευταία έκδοση από τον επίσημο ιστότοπο.",
+ "managedTitle": "Ενημερώσεις από την πηγή εγκατάστασης",
+ "managedDescription": "Αυτή η έκδοση πακέτου για Windows ενημερώνεται μέσω της αρχικής πηγής εγκατάστασης. Οι ενημερώσεις μέσα από την εφαρμογή δεν είναι διαθέσιμες.",
"unsupportedTitle": "Οι αυτόματες ενημερώσεις δεν είναι διαθέσιμες",
"upToDate": "Η έκδοση {{version}} είναι η πιο πρόσφατη διαθέσιμη έκδοση.",
"upToDateTitle": "Το Motrix είναι ενημερωμένο"
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index e8115f37..4677a47d 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1324,6 +1324,8 @@
"currentVersion": "Current version {{version}}",
"idleTitle": "Keep Motrix up to date",
"idle": "Version {{version}} is installed. Check now, or let Motrix check when it opens.",
+ "managedTitle": "Updates from your installation source",
+ "managedDescription": "This packaged Windows edition is updated through its original installation source. In-app updates are unavailable.",
"unsupportedTitle": "Automatic updates unavailable",
"unsupported": "This version cannot update automatically. Download the latest version from the official website.",
"check": "Check for updates",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 01b585da..f91fa56c 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1338,6 +1338,8 @@
"currentVersion": "Versión actual: {{version}}",
"idleTitle": "Mantén Motrix actualizado",
"idle": "La versión {{version}} está instalada. Busca actualizaciones ahora o deja que Motrix lo haga al abrirse.",
+ "managedTitle": "Actualizaciones desde la fuente de instalación",
+ "managedDescription": "Esta edición empaquetada para Windows se actualiza desde su fuente de instalación original. Las actualizaciones desde la aplicación no están disponibles.",
"unsupportedTitle": "Actualizaciones automáticas no disponibles",
"unsupported": "Esta versión no se puede actualizar automáticamente. Descarga la versión más reciente desde el sitio web oficial.",
"check": "Buscar actualizaciones",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 9c83ff68..d9f87fb8 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -1673,6 +1673,8 @@
"retry": "تلاش دوباره",
"title": "به‌روزرسانی‌های برنامه",
"unsupported": "این نسخه خودکار به‌روز نمی‌شود. آخرین نسخه را از وب‌سایت رسمی دانلود کنید.",
+ "managedTitle": "به‌روزرسانی از منبع نصب",
+ "managedDescription": "این نسخهٔ بسته‌بندی‌شدهٔ ویندوز از طریق منبع اصلی نصب به‌روزرسانی می‌شود. به‌روزرسانی درون برنامه در دسترس نیست.",
"unsupportedTitle": "به‌روزرسانی خودکار در دسترس نیست",
"upToDate": "نسخهٔ {{version}} آخرین نسخهٔ موجود است.",
"upToDateTitle": "Motrix به‌روز است"
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 21d41005..3b0a845a 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -1692,6 +1692,8 @@
"retry": "Réessayer",
"title": "Mises à jour de l’application",
"unsupported": "Cette version ne peut pas se mettre à jour automatiquement. Téléchargez la dernière version sur le site officiel.",
+ "managedTitle": "Mises à jour via la source d’installation",
+ "managedDescription": "Cette édition Windows empaquetée se met à jour via sa source d’installation d’origine. Les mises à jour depuis l’application ne sont pas disponibles.",
"unsupportedTitle": "Mises à jour automatiques indisponibles",
"upToDate": "La version {{version}} est la dernière version disponible.",
"upToDateTitle": "Motrix est à jour"
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index ee354faf..8fc03596 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1310,6 +1310,8 @@
"currentVersion": "Versi saat ini {{version}}",
"idleTitle": "Pastikan Motrix selalu terbaru",
"idle": "Versi {{version}} terpasang. Periksa sekarang atau izinkan Motrix memeriksa saat dibuka.",
+ "managedTitle": "Pembaruan melalui sumber instalasi",
+ "managedDescription": "Edisi Windows dalam paket ini diperbarui melalui sumber instalasi aslinya. Pembaruan di dalam aplikasi tidak tersedia.",
"unsupportedTitle": "Pembaruan otomatis tidak tersedia",
"unsupported": "Versi ini tidak dapat diperbarui secara otomatis. Unduh versi terbaru dari situs resmi.",
"check": "Periksa pembaruan",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index 29a23c6e..39eff41c 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1338,6 +1338,8 @@
"currentVersion": "Versione attuale {{version}}",
"idleTitle": "Mantieni Motrix aggiornato",
"idle": "È installata la versione {{version}}. Cerca ora gli aggiornamenti oppure lascia che Motrix li cerchi all’avvio.",
+ "managedTitle": "Aggiornamenti dalla fonte di installazione",
+ "managedDescription": "Questa edizione Windows in pacchetto viene aggiornata tramite la fonte di installazione originale. Gli aggiornamenti dall’app non sono disponibili.",
"unsupportedTitle": "Aggiornamenti automatici non disponibili",
"unsupported": "Questa versione non può aggiornarsi automaticamente. Scarica l’ultima versione dal sito ufficiale.",
"check": "Cerca aggiornamenti",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index bf21cc16..2a34a5f0 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1310,6 +1310,8 @@
"currentVersion": "現在のバージョン {{version}}",
"idleTitle": "Motrix を最新の状態に保ちましょう",
"idle": "バージョン {{version}} がインストールされています。今すぐ確認するか、Motrix の起動時に自動で確認できます。",
+ "managedTitle": "インストール元から更新",
+ "managedDescription": "この Windows パッケージ版は、元のインストール元から更新します。アプリ内での更新は利用できません。",
"unsupportedTitle": "自動アップデートは利用できません",
"unsupported": "このバージョンは自動でアップデートできません。公式サイトから最新版をダウンロードしてください。",
"check": "アップデートを確認",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 4ab6dd20..33a35258 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1310,6 +1310,8 @@
"currentVersion": "현재 버전 {{version}}",
"idleTitle": "Motrix를 최신 상태로 유지하세요",
"idle": "현재 설치된 버전은 {{version}}입니다. 지금 업데이트를 확인하거나 Motrix를 열 때 확인하도록 설정하세요.",
+ "managedTitle": "설치 출처를 통한 업데이트",
+ "managedDescription": "이 Windows 패키지 버전은 원래 설치 출처를 통해 업데이트됩니다. 앱 내 업데이트는 사용할 수 없습니다.",
"unsupportedTitle": "자동 업데이트를 사용할 수 없음",
"unsupported": "이 버전은 자동으로 업데이트할 수 없습니다. 공식 웹사이트에서 최신 버전을 다운로드하세요.",
"check": "업데이트 확인",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 7ed28de5..e961cb22 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -1673,6 +1673,8 @@
"retry": "Prøv igjen",
"title": "Appoppdateringer",
"unsupported": "Denne versjonen kan ikke oppdateres automatisk. Last ned den nyeste versjonen fra det offisielle nettstedet.",
+ "managedTitle": "Oppdateringer fra installasjonskilden",
+ "managedDescription": "Denne pakkede Windows-utgaven oppdateres via den opprinnelige installasjonskilden. Oppdatering fra appen er ikke tilgjengelig.",
"unsupportedTitle": "Automatiske oppdateringer er utilgjengelige",
"upToDate": "Versjon {{version}} er den nyeste tilgjengelige utgaven.",
"upToDateTitle": "Motrix er oppdatert"
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 451331fd..4628207d 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -1673,6 +1673,8 @@
"retry": "Opnieuw proberen",
"title": "Appupdates",
"unsupported": "Deze versie kan niet automatisch worden bijgewerkt. Download de nieuwste versie van de officiële website.",
+ "managedTitle": "Updates via de installatiebron",
+ "managedDescription": "Deze verpakte Windows-editie wordt bijgewerkt via de oorspronkelijke installatiebron. Updates vanuit de app zijn niet beschikbaar.",
"unsupportedTitle": "Automatische updates niet beschikbaar",
"upToDate": "Versie {{version}} is de nieuwste beschikbare versie.",
"upToDateTitle": "Motrix is up-to-date"
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index c03483df..c03a94c9 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1352,6 +1352,8 @@
"currentVersion": "Bieżąca wersja {{version}}",
"idleTitle": "Dbaj o aktualność Motrix",
"idle": "Zainstalowano wersję {{version}}. Sprawdź aktualizacje teraz lub pozwól Motrix sprawdzać je przy uruchamianiu.",
+ "managedTitle": "Aktualizacje ze źródła instalacji",
+ "managedDescription": "Ta spakowana wersja dla Windows jest aktualizowana za pośrednictwem pierwotnego źródła instalacji. Aktualizacje z poziomu aplikacji są niedostępne.",
"unsupportedTitle": "Automatyczne aktualizacje niedostępne",
"unsupported": "Ta wersja nie może aktualizować się automatycznie. Pobierz najnowszą wersję z oficjalnej witryny.",
"check": "Sprawdź aktualizacje",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 776dd49f..95753825 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1338,6 +1338,8 @@
"currentVersion": "Versão atual: {{version}}",
"idleTitle": "Mantenha o Motrix atualizado",
"idle": "A versão {{version}} está instalada. Verifique agora ou deixe o Motrix verificar ao abrir.",
+ "managedTitle": "Atualizações pela fonte de instalação",
+ "managedDescription": "Esta edição empacotada para Windows é atualizada pela fonte de instalação original. As atualizações pelo aplicativo não estão disponíveis.",
"unsupportedTitle": "Atualizações automáticas indisponíveis",
"unsupported": "Esta versão não pode ser atualizada automaticamente. Baixe a versão mais recente no site oficial.",
"check": "Verificar atualizações",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 4046b1aa..12c1bd27 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -1692,6 +1692,8 @@
"retry": "Încearcă din nou",
"title": "Actualizările aplicației",
"unsupported": "Această versiune nu se poate actualiza automat. Descarcă cea mai nouă versiune de pe site-ul oficial.",
+ "managedTitle": "Actualizări din sursa de instalare",
+ "managedDescription": "Această ediție Windows împachetată se actualizează prin sursa de instalare originală. Actualizările din aplicație nu sunt disponibile.",
"unsupportedTitle": "Actualizările automate nu sunt disponibile",
"upToDate": "Versiunea {{version}} este cea mai nouă versiune disponibilă.",
"upToDateTitle": "Motrix este la zi"
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 1b78cb56..67adb0f9 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1352,6 +1352,8 @@
"currentVersion": "Текущая версия {{version}}",
"idleTitle": "Поддерживайте Motrix в актуальном состоянии",
"idle": "Установлена версия {{version}}. Проверьте обновления сейчас или разрешите Motrix проверять их при запуске.",
+ "managedTitle": "Обновления из источника установки",
+ "managedDescription": "Эта пакетная версия для Windows обновляется через исходный источник установки. Обновления внутри приложения недоступны.",
"unsupportedTitle": "Автоматическое обновление недоступно",
"unsupported": "Эта версия не поддерживает автоматическое обновление. Скачайте последнюю версию с официального сайта.",
"check": "Проверить обновления",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 0afefb4f..c00fbafb 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -1654,6 +1654,8 @@
"retry": "ลองอีกครั้ง",
"title": "การอัปเดตแอป",
"unsupported": "รุ่นนี้อัปเดตอัตโนมัติไม่ได้ ดาวน์โหลดรุ่นล่าสุดจากเว็บไซต์ทางการ",
+ "managedTitle": "อัปเดตผ่านแหล่งติดตั้งเดิม",
+ "managedDescription": "Windows รุ่นแพ็กเกจนี้อัปเดตผ่านแหล่งติดตั้งเดิม ไม่สามารถอัปเดตภายในแอปได้",
"unsupportedTitle": "การอัปเดตอัตโนมัติไม่พร้อมใช้งาน",
"upToDate": "เวอร์ชัน {{version}} เป็นรุ่นล่าสุดที่มีให้ใช้งาน",
"upToDateTitle": "Motrix เป็นรุ่นล่าสุดแล้ว"
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 8213340c..548cd059 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1324,6 +1324,8 @@
"currentVersion": "Geçerli sürüm {{version}}",
"idleTitle": "Motrix’i güncel tutun",
"idle": "{{version}} sürümü yüklü. Şimdi denetleyin veya Motrix açıldığında denetlemesine izin verin.",
+ "managedTitle": "Yükleme kaynağından güncellemeler",
+ "managedDescription": "Bu paketlenmiş Windows sürümü, ilk yükleme kaynağı üzerinden güncellenir. Uygulama içi güncellemeler kullanılamaz.",
"unsupportedTitle": "Otomatik güncellemeler kullanılamıyor",
"unsupported": "Bu sürüm otomatik olarak güncellenemez. En son sürümü resmî web sitesinden indirin.",
"check": "Güncellemeleri denetle",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 31e55936..233c4115 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -1711,6 +1711,8 @@
"retry": "Спробувати ще раз",
"title": "Оновлення програми",
"unsupported": "Ця версія не підтримує автоматичне оновлення. Завантажте останню версію з офіційного сайту.",
+ "managedTitle": "Оновлення з джерела встановлення",
+ "managedDescription": "Ця пакетна версія для Windows оновлюється через початкове джерело встановлення. Оновлення всередині застосунку недоступні.",
"unsupportedTitle": "Автоматичні оновлення недоступні",
"upToDate": "Версія {{version}} — найновіший доступний випуск.",
"upToDateTitle": "Встановлено найновішу версію Motrix"
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index bc67bdd2..9bd643ea 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1310,6 +1310,8 @@
"currentVersion": "Phiên bản hiện tại {{version}}",
"idleTitle": "Luôn cập nhật Motrix",
"idle": "Đã cài đặt phiên bản {{version}}. Kiểm tra ngay hoặc để Motrix kiểm tra khi mở ứng dụng.",
+ "managedTitle": "Cập nhật qua nguồn cài đặt",
+ "managedDescription": "Phiên bản Windows đóng gói này được cập nhật qua nguồn cài đặt ban đầu. Không thể cập nhật trong ứng dụng.",
"unsupportedTitle": "Không thể cập nhật tự động",
"unsupported": "Phiên bản này không thể tự động cập nhật. Hãy tải phiên bản mới nhất từ trang web chính thức.",
"check": "Kiểm tra bản cập nhật",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 0ca6b480..4ea47475 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1284,6 +1284,8 @@
"currentVersion": "当前版本 {{version}}",
"idleTitle": "让 Motrix 保持最新",
"idle": "当前安装的是版本 {{version}}。立即检查,或让 Motrix 在启动时自动检查。",
+ "managedTitle": "通过原安装来源更新",
+ "managedDescription": "此 Windows 打包版通过原安装来源更新,应用内更新不可用。",
"unsupportedTitle": "自动更新不可用",
"unsupported": "当前版本不支持自动更新,请到官网下载最新版。",
"check": "检查更新",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 1a67266d..515e49fa 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1310,6 +1310,8 @@
"currentVersion": "目前版本 {{version}}",
"idleTitle": "讓 Motrix 保持最新",
"idle": "已安裝版本 {{version}}。現在檢查,或讓 Motrix 在開啟時檢查。",
+ "managedTitle": "透過原安裝來源更新",
+ "managedDescription": "此 Windows 封裝版透過原安裝來源更新,無法在應用程式內更新。",
"unsupportedTitle": "無法自動更新",
"unsupported": "目前版本不支援自動更新,請至官網下載最新版。",
"check": "檢查更新",
diff --git a/src/shared/types/app-update.ts b/src/shared/types/app-update.ts
index 1eb2dd87..5c7f56da 100644
--- a/src/shared/types/app-update.ts
+++ b/src/shared/types/app-update.ts
@@ -1,5 +1,6 @@
export type AppUpdatePhase =
| 'idle'
+ | 'managed'
| 'unsupported'
| 'checking'
| 'up-to-date'
@@ -24,6 +25,8 @@ export interface AppUpdateError {
export interface AppUpdateState {
phase: AppUpdatePhase
currentVersion: string
+ /** Absent on older hosts that predate externally managed updates. */
+ updateAuthority?: 'application' | 'system'
availableVersion?: string
releaseName?: string
progress?: AppUpdateProgress