Skip to content

A full-featured download manager.

fix(desktop): recover after repeated graphics crashes (#2429)

Dr_rOotbc63c9cb44a3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4e828a1a..cc18a307 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -56,6 +56,17 @@ jobs:
- name: i18n catalog and translation contract
run: pnpm run check:i18n
+ - name: Desktop graphics recovery contracts
+ run: >-
+ pnpm exec vitest run
+ src/main/platform/graphics-recovery.test.ts
+ src/main/platform/graphics-recovery-runtime.test.ts
+ src/renderer/hooks/use-graphics-recovery-toast.test.tsx
+ src/renderer/routes/settings/cards/appearance-dialog.test.tsx
+ src/core/settings/settings-manager.test.ts
+ src/shared/schemas/app-settings.test.ts
+ src/renderer/lib/settings-save.test.tsx
+
- name: Locale runtime contracts
run: >-
pnpm exec vitest run
diff --git a/e2e/graphics-recovery.spec.ts b/e2e/graphics-recovery.spec.ts
new file mode 100644
index 00000000..a0696555
--- /dev/null
+++ b/e2e/graphics-recovery.spec.ts
@@ -0,0 +1,150 @@
+import { readFile, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { CURRENT_SETTINGS_VERSION } from '../src/core/settings/migrations'
+import { Queries } from '../src/shared/protocol/queries'
+import {
+ expect,
+ launchMotrix,
+ test,
+ waitForEngineReady,
+} from './fixtures/electron-app'
+
+test('graphics failures recover on the next launch and acceleration stays off until the user enables it', async ({
+ userDataDir,
+ rpcPort,
+}, testInfo) => {
+ test.setTimeout(90_000)
+ const settingsPath = path.join(userDataDir, 'settings.json')
+ const recoveryPath = path.join(userDataDir, 'graphics-recovery.json')
+ const readSettings = async () =>
+ JSON.parse(await readFile(settingsPath, 'utf8'))
+ await writeFile(
+ settingsPath,
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: { language: 'zh-CN', autofillClipboardLinks: false },
+ tracker: { autoSync: false },
+ nat: { enabled: false },
+ onboarding: { disclaimerAccepted: true },
+ })
+ )
+ let electron = await launchMotrix({ userDataDir, rpcPort })
+ try {
+ let page = await electron.firstWindow()
+ await waitForEngineReady(page)
+ const initialAcceleration = await electron.evaluate(({ app }) =>
+ app.isHardwareAccelerationEnabled()
+ )
+ expect((await readSettings()).app.hardwareAcceleration).toBe(true)
+
+ // Inject Electron's documented process-failure event, not a synthetic
+ // settings file. This tests production listeners and persistence without
+ // requiring a defective GPU driver on the test machine.
+ await electron.evaluate(({ app }) => {
+ for (let i = 0; i < 3; i++) {
+ app.emit(
+ 'child-process-gone',
+ {},
+ { type: 'GPU', reason: 'crashed', exitCode: 139 }
+ )
+ }
+ })
+ expect(
+ JSON.parse(await readFile(recoveryPath, 'utf8')).recoveryPending
+ ).toBe(true)
+ expect((await readSettings()).app.hardwareAcceleration).toBe(true)
+ expect(
+ await electron.evaluate(({ app }) => app.isHardwareAccelerationEnabled())
+ ).toBe(initialAcceleration)
+ expect(
+ await page.evaluate(
+ (query) => window.motrix.invoke(query),
+ Queries.GetGraphicsRecoveryNotice
+ )
+ ).toBeNull()
+ await electron.close()
+
+ electron = await launchMotrix({ userDataDir, rpcPort })
+ page = await electron.firstWindow()
+ await waitForEngineReady(page)
+ expect((await readSettings()).app.hardwareAcceleration).toBe(false)
+ expect(
+ await electron.evaluate(({ app }) => app.isHardwareAccelerationEnabled())
+ ).toBe(false)
+ const title = page.getByText('已关闭硬件加速', { exact: true })
+ await expect(title).toBeVisible()
+ await expect(
+ page.getByText(
+ '由于画面显示连续出错,Motrix 已关闭硬件加速,避免再次闪退。你可以在“设置 → 外观”中重新开启,重启后生效。',
+ { exact: true }
+ )
+ ).toBeVisible()
+ await page.screenshot({
+ path: testInfo.outputPath('graphics-recovery-toast.png'),
+ })
+ // Base UI announces high-priority toasts in a separate live region and
+ // keeps their visible dialog aria-hidden until focused.
+ await page
+ .locator('[role="dialog"], [role="alertdialog"]')
+ .filter({ has: title })
+ .getByRole('button', { name: '关闭', exact: true, includeHidden: true })
+ .click()
+ await expect
+ .poll(() =>
+ page.evaluate(
+ (query) => window.motrix.invoke(query),
+ Queries.GetGraphicsRecoveryNotice
+ )
+ )
+ .toBeNull()
+ await page.reload({ waitUntil: 'domcontentloaded' })
+ await waitForEngineReady(page)
+ await expect(page.getByText('已关闭硬件加速', { exact: true })).toHaveCount(
+ 0
+ )
+ await electron.close()
+
+ // A later ordinary launch keeps software mode after the notice was read.
+ electron = await launchMotrix({ userDataDir, rpcPort })
+ page = await electron.firstWindow()
+ await waitForEngineReady(page)
+ expect(
+ await electron.evaluate(({ app }) => app.isHardwareAccelerationEnabled())
+ ).toBe(false)
+ await page.evaluate(() => {
+ location.hash = '/settings'
+ })
+ await page.getByText('外观', { exact: true }).click()
+ const control = page.getByRole('switch', { name: '硬件加速', exact: true })
+ await expect(control).not.toBeChecked()
+ await control.click()
+ expect((await readSettings()).app.hardwareAcceleration).toBe(false)
+ await page.screenshot({
+ path: testInfo.outputPath('graphics-settings.png'),
+ })
+ await page.getByRole('button', { name: '保存', exact: true }).click()
+ await expect
+ .poll(async () => (await readSettings()).app.hardwareAcceleration)
+ .toBe(true)
+ expect(
+ await electron.evaluate(({ app }) => app.isHardwareAccelerationEnabled())
+ ).toBe(false)
+ await electron.close()
+
+ electron = await launchMotrix({ userDataDir, rpcPort })
+ page = await electron.firstWindow()
+ await waitForEngineReady(page)
+ expect((await readSettings()).app.hardwareAcceleration).toBe(true)
+ expect(
+ await electron.evaluate(({ app }) => app.isHardwareAccelerationEnabled())
+ ).toBe(initialAcceleration)
+ expect(
+ await page.evaluate(
+ (query) => window.motrix.invoke(query),
+ Queries.GetGraphicsRecoveryNotice
+ )
+ ).toBeNull()
+ } finally {
+ await electron.close().catch(() => {})
+ }
+})
diff --git a/scripts/measure-production-bundles.mjs b/scripts/measure-production-bundles.mjs
index f0f00f2c..becf1ec2 100644
--- a/scripts/measure-production-bundles.mjs
+++ b/scripts/measure-production-bundles.mjs
@@ -102,6 +102,9 @@ export async function measureProductionBundles() {
.length,
initialLocales: locales(startupModules),
bundledLocales: locales(allModules),
+ bundledOperatorAdmin: chunks.some((chunk) =>
+ /\boperatorAdmin\s*[:=]/.test(chunk.code)
+ ),
initialElk: startupModules.some((id) => id.includes('/elkjs/')),
bundledElk: allModules.some((id) => id.includes('/elkjs/')),
}
diff --git a/scripts/vite-desktop-locales.ts b/scripts/vite-desktop-locales.ts
new file mode 100644
index 00000000..17b6e9cc
--- /dev/null
+++ b/scripts/vite-desktop-locales.ts
@@ -0,0 +1,18 @@
+import type { Plugin } from 'vite'
+
+/** The operator-admin CLI is a separate Server entrypoint. Keep its catalog
+ * out of the desktop main bundle while preserving all desktop translations. */
+export function desktopLocaleProjection(localeDirectory: string): Plugin {
+ const prefix = `${localeDirectory.replaceAll('\\', '/')}/`
+ return {
+ name: 'desktop-locale-projection',
+ enforce: 'pre',
+ transform(source, id) {
+ const file = id.split('?')[0]?.replaceAll('\\', '/')
+ if (!file?.startsWith(prefix) || !file.endsWith('.json')) return null
+ const catalog = JSON.parse(source) as Record<string, unknown>
+ delete catalog.operatorAdmin
+ return { code: JSON.stringify(catalog), map: null }
+ },
+ }
+}
diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.ts
index 840f0295..b270788f 100644
--- a/src/core/settings/settings-manager.test.ts
+++ b/src/core/settings/settings-manager.test.ts
@@ -109,6 +109,31 @@ describe('SettingsManager', () => {
})
})
+ it('persists acceleration changes and requests a full app restart only for a changed value', async () => {
+ expect(
+ await manager.update({ app: { hardwareAcceleration: false } })
+ ).toMatchObject({
+ requiresAppRestart: true,
+ changedAppRestartKeys: ['hardwareAcceleration'],
+ requiresRestart: false,
+ })
+ const saved = mockWriteFileAtomic.mock.lastCall![1]
+ mockReadFile.mockResolvedValue(saved)
+ const reloaded = new SettingsManager(TEST_PATH)
+ await reloaded.load()
+ expect(reloaded.getApp().hardwareAcceleration).toBe(false)
+ expect(
+ await reloaded.update({ app: { hardwareAcceleration: false } })
+ ).toMatchObject({
+ requiresAppRestart: false,
+ })
+ expect(
+ await reloaded.update({ app: { hardwareAcceleration: true } })
+ ).toMatchObject({
+ requiresAppRestart: true,
+ })
+ })
+
describe('directory preferences', () => {
beforeEach(() => {
mockWriteFileAtomic.mockResolvedValue(undefined)
diff --git a/src/main/index.ts b/src/main/index.ts
index fa9ae5b6..592f6167 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -207,6 +207,7 @@ 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 { setupGraphicsRecovery } from './platform/graphics-recovery-runtime'
import { setupNativeThemeSync } from './platform/native-theme-sync'
import { setupPowerManager } from './platform/power-manager'
import { createProtocolManager } from './platform/protocol-manager'
@@ -308,6 +309,7 @@ const speedHistoryStore = new SpeedHistoryStore()
const taskSpeedHistoryStore = new TaskSpeedHistoryStore()
const torrentParser = new TorrentParser()
let windowManager: WindowManager
+let graphicsRuntime: ReturnType<typeof setupGraphicsRecovery> | undefined
let rendererRecovery:
| ReturnType<typeof createRendererRecoveryRuntime>
| undefined
@@ -372,6 +374,11 @@ const settingsManager = new SettingsManager(settingsPath, {
}),
...defaultSaveDirOptions,
onChange: (old, updated) => {
+ if (old.app.hardwareAcceleration !== updated.app.hardwareAcceleration) {
+ graphicsRuntime?.recovery.preferenceChanged(
+ updated.app.hardwareAcceleration
+ )
+ }
eventBus.emit(Events.SettingsChanged, { old, updated })
if (
old.app.notifyInAppOnComplete !== updated.app.notifyInAppOnComplete ||
@@ -821,6 +828,13 @@ const launcher = setupLauncher({
},
})
+// Run synchronously before ready, after the launcher owns this profile.
+// SettingsManager loads asynchronously after ready, which is too late for
+// Electron's hardware acceleration switch.
+if (app.hasSingleInstanceLock()) {
+ graphicsRuntime = setupGraphicsRecovery(platform.userDataDir, settingsPath)
+}
+
function runShellAsyncWork(
label: string,
operation: () => Promise<void>
@@ -1593,6 +1607,10 @@ async function initializeMainProcess(): Promise<void> {
// settings (for window bounds/run mode) and WindowManager.
await settingsManager.load()
+ if (graphicsRuntime?.recovery.recoveredAtStartup) {
+ await settingsManager.update({ app: { hardwareAcceleration: false } })
+ graphicsRuntime.recovery.completeRecovery()
+ }
pluginHttpClient = new PluginHttpClient(() => settingsManager.getProxy())
if (!mainProcessWork.isAccepting()) return
@@ -3178,6 +3196,7 @@ async function showQuitConfirmation(activeCount: number): Promise<{
}
function beginShutdown(): void {
+ graphicsRuntime?.stop()
// quitController.phase is already 'shutting-down' (set synchronously before
// this call). app.quit() below re-fires before-quit synchronously; the guard
// there relies on the phase already being terminal.
diff --git a/src/main/platform/graphics-recovery-runtime.test.ts b/src/main/platform/graphics-recovery-runtime.test.ts
new file mode 100644
index 00000000..7dce5f37
--- /dev/null
+++ b/src/main/platform/graphics-recovery-runtime.test.ts
@@ -0,0 +1,150 @@
+// @vitest-environment node
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { handlers, ipc, mockApp } = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: unknown[]) => void>(),
+ ipc: new Map<string, (...args: unknown[]) => Promise<unknown>>(),
+ mockApp: {
+ on: vi.fn(),
+ off: vi.fn(),
+ once: vi.fn(),
+ disableHardwareAcceleration: vi.fn(),
+ getGPUFeatureStatus: vi.fn(),
+ isHardwareAccelerationEnabled: vi.fn(),
+ getGPUInfo: vi.fn(),
+ },
+}))
+vi.mock('electron', () => ({ app: mockApp }))
+vi.mock('@core/logger', () => ({
+ getLogger: () => ({ info: vi.fn(), warn: vi.fn() }),
+}))
+vi.mock('../ipc/trusted-ipc', () => ({
+ registerTrustedIpcHandler: (
+ channel: string,
+ handler: (...args: unknown[]) => Promise<unknown>
+ ) => ipc.set(channel, handler),
+}))
+
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { GPU_HEALTHY_INTERVAL_MS, GraphicsRecovery } from './graphics-recovery'
+import { setupGraphicsRecovery } from './graphics-recovery-runtime'
+
+describe('desktop graphics lifecycle wiring', () => {
+ let directory: string
+ let runtime: ReturnType<typeof setupGraphicsRecovery> | undefined
+ const failure = { type: 'GPU', reason: 'crashed', exitCode: 139 }
+ const emit = (name: string, ...args: unknown[]) =>
+ handlers.get(name)?.(...args)
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.clearAllMocks()
+ handlers.clear()
+ ipc.clear()
+ directory = mkdtempSync(path.join(tmpdir(), 'motrix-graphics-runtime-'))
+ mockApp.on.mockImplementation((name, handler) =>
+ handlers.set(name, handler)
+ )
+ mockApp.getGPUFeatureStatus.mockReturnValue({ gpu_compositing: 'enabled' })
+ mockApp.isHardwareAccelerationEnabled.mockReturnValue(true)
+ mockApp.getGPUInfo.mockResolvedValue({ gpuDevice: [] })
+ })
+ afterEach(() => {
+ runtime?.stop()
+ runtime = undefined
+ vi.useRealTimers()
+ rmSync(directory, { recursive: true, force: true })
+ })
+
+ const start = (enabled?: boolean) => {
+ const settingsPath = path.join(directory, 'settings.json')
+ if (enabled !== undefined)
+ writeFileSync(
+ settingsPath,
+ JSON.stringify({ app: { hardwareAcceleration: enabled } })
+ )
+ runtime = setupGraphicsRecovery(directory, settingsPath)
+ return runtime
+ }
+
+ it('applies a saved disabled switch synchronously before GPU initialization', () => {
+ start(false)
+ expect(mockApp.disableHardwareAcceleration).toHaveBeenCalledTimes(1)
+ expect(mockApp.getGPUFeatureStatus).not.toHaveBeenCalled()
+ expect(handlers.has('child-process-gone')).toBe(true)
+ })
+
+ it('records only GPU exits and never changes acceleration during this launch', () => {
+ const { recovery } = start()
+ for (let i = 0; i < 3; i++)
+ emit('child-process-gone', {}, { ...failure, type: 'Utility' })
+ expect(
+ new GraphicsRecovery({
+ statePath: path.join(directory, 'graphics-recovery.json'),
+ hardwareAcceleration: true,
+ warn: vi.fn(),
+ }).recoveredAtStartup
+ ).toBe(false)
+ for (let i = 0; i < 3; i++) emit('child-process-gone', {}, failure)
+ expect(recovery.getNotice()).toBeNull()
+ expect(mockApp.disableHardwareAcceleration).not.toHaveBeenCalled()
+ runtime!.stop()
+ start()
+ expect(mockApp.disableHardwareAcceleration).toHaveBeenCalledTimes(1)
+ })
+
+ it('counts recovery across a fresh runtime and only acknowledges a matching notice', async () => {
+ start()
+ for (let i = 0; i < 3; i++) emit('child-process-gone', {}, failure)
+ runtime!.stop()
+ start()
+ const notice = await ipc.get(Queries.GetGraphicsRecoveryNotice)!()
+ expect(notice).toEqual({ id: expect.any(String) })
+ await expect(
+ ipc.get(Commands.AcknowledgeGraphicsRecoveryNotice)!(
+ {},
+ { id: 'invalid' }
+ )
+ ).rejects.toThrow()
+ expect(await ipc.get(Queries.GetGraphicsRecoveryNotice)!()).toEqual(notice)
+ await ipc.get(Commands.AcknowledgeGraphicsRecoveryNotice)!({}, notice)
+ expect(await ipc.get(Queries.GetGraphicsRecoveryNotice)!()).toBeNull()
+ })
+
+ it('requires a continuous healthy accelerated interval before resetting failures', () => {
+ const { recovery } = start()
+ const healthy = vi.spyOn(recovery, 'markHealthy')
+ emit('gpu-info-update')
+ vi.advanceTimersByTime(GPU_HEALTHY_INTERVAL_MS - 1)
+ emit('child-process-gone', {}, failure)
+ vi.advanceTimersByTime(1)
+ expect(healthy).not.toHaveBeenCalled()
+ emit('gpu-info-update')
+ vi.advanceTimersByTime(GPU_HEALTHY_INTERVAL_MS)
+ expect(healthy).toHaveBeenCalledTimes(1)
+ expect(mockApp.getGPUInfo).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not treat software rendering as healthy hardware or count shutdown failures', () => {
+ const { recovery } = start()
+ const healthy = vi.spyOn(recovery, 'markHealthy')
+ const record = vi.spyOn(recovery, 'recordFailure')
+ mockApp.getGPUFeatureStatus.mockReturnValue({
+ gpu_compositing: 'unavailable_software',
+ })
+ emit('gpu-info-update')
+ vi.advanceTimersByTime(GPU_HEALTHY_INTERVAL_MS)
+ expect(healthy).not.toHaveBeenCalled()
+ runtime!.stop()
+ emit('child-process-gone', {}, failure)
+ expect(record).not.toHaveBeenCalled()
+ expect(mockApp.off).toHaveBeenCalledWith(
+ 'child-process-gone',
+ expect.any(Function)
+ )
+ })
+})
diff --git a/src/main/platform/graphics-recovery-runtime.ts b/src/main/platform/graphics-recovery-runtime.ts
new file mode 100644
index 00000000..7293e6dc
--- /dev/null
+++ b/src/main/platform/graphics-recovery-runtime.ts
@@ -0,0 +1,118 @@
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import { getLogger } from '@core/logger'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { appSettingsSchema } from '@shared/schemas/app-settings'
+import { graphicsRecoveryNoticeSchema } from '@shared/schemas/graphics-recovery'
+import { app } from 'electron'
+import { z } from 'zod'
+import { registerTrustedIpcHandler } from '../ipc/trusted-ipc'
+import { GPU_HEALTHY_INTERVAL_MS, GraphicsRecovery } from './graphics-recovery'
+
+const earlySettingsSchema = z.object({
+ app: z.object({
+ hardwareAcceleration: appSettingsSchema.shape.hardwareAcceleration,
+ }),
+})
+
+export function setupGraphicsRecovery(
+ userDataDir: string,
+ settingsPath: string
+) {
+ const log = getLogger('graphics')
+ let hardwareAcceleration = true
+ try {
+ hardwareAcceleration = earlySettingsSchema.parse(
+ JSON.parse(readFileSync(settingsPath, 'utf8'))
+ ).app.hardwareAcceleration
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ log.warn({ err: error }, 'Unable to read early graphics preference')
+ }
+ }
+ const recovery = new GraphicsRecovery({
+ statePath: path.join(userDataDir, 'graphics-recovery.json'),
+ hardwareAcceleration,
+ warn: (err, message) => log.warn({ err }, message),
+ })
+ if (!recovery.hardwareAcceleration) app.disableHardwareAcceleration()
+ log.info(
+ {
+ hardwareAcceleration: recovery.hardwareAcceleration,
+ recoveredAtStartup: recovery.recoveredAtStartup,
+ },
+ 'Applied startup graphics mode'
+ )
+
+ let stopped = false
+ let loggedDevice = false
+ let healthyTimer: ReturnType<typeof setTimeout> | undefined
+ const clearHealthyTimer = () => {
+ clearTimeout(healthyTimer)
+ healthyTimer = undefined
+ }
+ const gpuInfoUpdated = () => {
+ if (stopped) return
+ const features = app.getGPUFeatureStatus()
+ log.info(
+ { features, enabled: app.isHardwareAccelerationEnabled() },
+ 'GPU features updated'
+ )
+ if (
+ recovery.hardwareAcceleration &&
+ app.isHardwareAccelerationEnabled() &&
+ features.gpu_compositing?.startsWith('enabled')
+ ) {
+ if (healthyTimer === undefined) {
+ healthyTimer = setTimeout(() => {
+ healthyTimer = undefined
+ recovery.markHealthy()
+ }, GPU_HEALTHY_INTERVAL_MS)
+ healthyTimer.unref()
+ }
+ } else clearHealthyTimer()
+ if (!loggedDevice) {
+ loggedDevice = true
+ void app
+ .getGPUInfo('basic')
+ .then((info) => {
+ log.info({ info }, 'GPU device information')
+ })
+ .catch((err) =>
+ log.warn({ err }, 'Unable to read GPU device information')
+ )
+ }
+ }
+ const childGone = (_event: unknown, details: Electron.Details) => {
+ if (stopped || details.type !== 'GPU') return
+ clearHealthyTimer()
+ log.warn(
+ { reason: details.reason, exitCode: details.exitCode },
+ 'GPU process exited'
+ )
+ recovery.recordFailure({
+ reason: details.reason,
+ exitCode: details.exitCode,
+ })
+ }
+ app.on('gpu-info-update', gpuInfoUpdated)
+ app.on('child-process-gone', childGone)
+ registerTrustedIpcHandler(Queries.GetGraphicsRecoveryNotice, async () =>
+ recovery.getNotice()
+ )
+ registerTrustedIpcHandler(
+ Commands.AcknowledgeGraphicsRecoveryNotice,
+ async (_event, payload: unknown) => {
+ recovery.acknowledgeNotice(graphicsRecoveryNoticeSchema.parse(payload).id)
+ }
+ )
+ const stop = () => {
+ stopped = true
+ clearHealthyTimer()
+ app.off('gpu-info-update', gpuInfoUpdated)
+ app.off('child-process-gone', childGone)
+ }
+ app.once('will-quit', stop)
+ return { recovery, stop }
+}
diff --git a/src/main/platform/graphics-recovery.test.ts b/src/main/platform/graphics-recovery.test.ts
new file mode 100644
index 00000000..911c68a8
--- /dev/null
+++ b/src/main/platform/graphics-recovery.test.ts
@@ -0,0 +1,155 @@
+// @vitest-environment node
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { GPU_FAILURE_WINDOW_MS, GraphicsRecovery } from './graphics-recovery'
+
+describe('durable graphics recovery', () => {
+ let directory: string
+ let statePath: string
+ let now: number
+ const warn = vi.fn()
+ const crash = { reason: 'crashed', exitCode: 139 }
+ const open = (hardwareAcceleration = true) =>
+ new GraphicsRecovery({
+ statePath,
+ hardwareAcceleration,
+ warn,
+ now: () => now,
+ })
+
+ beforeEach(() => {
+ directory = mkdtempSync(path.join(tmpdir(), 'motrix-graphics-'))
+ statePath = path.join(directory, 'graphics-recovery.json')
+ now = 10_000
+ warn.mockReset()
+ })
+ afterEach(() => rmSync(directory, { recursive: true, force: true }))
+
+ it('preserves explicit software mode without inventing a recovery notice', () => {
+ expect(open().hardwareAcceleration).toBe(true)
+ const software = open(false)
+ expect(software.hardwareAcceleration).toBe(false)
+ expect(software.recoveredAtStartup).toBe(false)
+ expect(software.getNotice()).toBeNull()
+ expect(warn).not.toHaveBeenCalled()
+ })
+
+ it('persists consecutive GPU failures across hosts and disables only on the next startup', () => {
+ open().recordFailure(crash)
+ now += 1_000
+ open().recordFailure({ reason: 'launch-failed', exitCode: 1002 })
+ const current = open()
+ expect(current.hardwareAcceleration).toBe(true)
+ current.recordFailure(crash)
+ expect(current.hardwareAcceleration).toBe(true)
+ expect(current.getNotice()).toBeNull()
+ current.markHealthy()
+
+ const recovered = open()
+ expect(recovered.hardwareAcceleration).toBe(false)
+ expect(recovered.recoveredAtStartup).toBe(true)
+ const notice = recovered.getNotice()
+ expect(notice).toEqual({ id: expect.any(String) })
+ // If startup dies before settings can be saved, keep recovery latched.
+ expect(open().getNotice()).toEqual(notice)
+ // Simulate successful persistence through SettingsManager.
+ recovered.preferenceChanged(false)
+ recovered.completeRecovery()
+ expect(open(false).getNotice()).toEqual(notice)
+ expect(open(false).recoveredAtStartup).toBe(false)
+ })
+
+ it('keeps software mode until the user explicitly enables acceleration again', () => {
+ const current = open()
+ for (let i = 0; i < 3; i++) current.recordFailure(crash)
+ const recovered = open()
+ recovered.completeRecovery()
+ expect(open(false).hardwareAcceleration).toBe(false)
+ recovered.preferenceChanged(true)
+ // A settings change cannot change the already-running graphics mode.
+ expect(recovered.hardwareAcceleration).toBe(false)
+ expect(open(true).hardwareAcceleration).toBe(true)
+ expect(open(true).getNotice()).toBeNull()
+ open(true).recordFailure(crash)
+ expect(open(true).hardwareAcceleration).toBe(true)
+ })
+
+ it('resets a partial streak after healthy operation', () => {
+ const current = open()
+ current.recordFailure(crash)
+ current.recordFailure(crash)
+ current.markHealthy()
+ current.recordFailure(crash)
+ expect(open().hardwareAcceleration).toBe(true)
+ })
+
+ it('does not accumulate failures separated by a long gap or clock rollback', () => {
+ const current = open()
+ current.recordFailure(crash)
+ current.recordFailure(crash)
+ now += GPU_FAILURE_WINDOW_MS + 1
+ current.recordFailure(crash)
+ expect(open().hardwareAcceleration).toBe(true)
+ now = 1
+ current.recordFailure(crash)
+ expect(open().hardwareAcceleration).toBe(true)
+ })
+
+ it('records other exit reasons without attributing them to acceleration', () => {
+ const current = open()
+ for (const reason of [
+ 'clean-exit',
+ 'killed',
+ 'oom',
+ 'memory-eviction',
+ 'integrity-failure',
+ ]) {
+ current.recordFailure({ reason, exitCode: 0 })
+ }
+ current.recordFailure(crash)
+ expect(open().hardwareAcceleration).toBe(true)
+ const software = open(false)
+ for (let i = 0; i < 20; i++) software.recordFailure(crash)
+ const persisted = JSON.parse(readFileSync(statePath, 'utf8'))
+ expect(persisted.failures).toHaveLength(10)
+ expect(persisted.recoveryPending).toBe(false)
+ })
+
+ it('keeps the notice durable until its exact id is acknowledged', () => {
+ const current = open()
+ for (let i = 0; i < 3; i++) current.recordFailure(crash)
+ const recovered = open()
+ recovered.completeRecovery()
+ const notice = recovered.getNotice()!
+ recovered.acknowledgeNotice('different-notice')
+ expect(open(false).getNotice()).toEqual(notice)
+ recovered.acknowledgeNotice(notice.id)
+ expect(open(false).getNotice()).toBeNull()
+ })
+
+ it('honors a manual disable before a scheduled recovery', () => {
+ const current = open()
+ for (let i = 0; i < 3; i++) current.recordFailure(crash)
+ current.preferenceChanged(false)
+ expect(open(false).recoveredAtStartup).toBe(false)
+ expect(open(false).getNotice()).toBeNull()
+ })
+
+ it('recovers malformed state without crashing or overriding an explicit disable', () => {
+ writeFileSync(statePath, '{ broken')
+ expect(open(false).hardwareAcceleration).toBe(false)
+ expect(warn).toHaveBeenCalledTimes(1)
+ })
+
+ it('reports a failed durable write without throwing from the GPU event', () => {
+ const recovery = new GraphicsRecovery({
+ statePath: path.join(directory, 'missing', 'state.json'),
+ hardwareAcceleration: true,
+ warn,
+ })
+ expect(() => recovery.recordFailure(crash)).not.toThrow()
+ expect(warn).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/main/platform/graphics-recovery.ts b/src/main/platform/graphics-recovery.ts
new file mode 100644
index 00000000..5ad6840c
--- /dev/null
+++ b/src/main/platform/graphics-recovery.ts
@@ -0,0 +1,151 @@
+import { randomUUID } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import type { GraphicsRecoveryNotice } from '@shared/schemas/graphics-recovery'
+import writeFileAtomic from 'write-file-atomic'
+import { z } from 'zod'
+
+export const GPU_FAILURE_LIMIT = 3
+export const GPU_FAILURE_WINDOW_MS = 5 * 60_000
+export const GPU_HEALTHY_INTERVAL_MS = 60_000
+
+const failureSchema = z.object({
+ at: z.number().int().nonnegative(),
+ reason: z.string().max(100),
+ exitCode: z.number().int(),
+})
+const recoveryStateSchema = z.object({
+ version: z.literal(1),
+ consecutiveFailures: z.number().int().min(0).max(GPU_FAILURE_LIMIT),
+ lastFailureAt: z.number().int().nonnegative().nullable(),
+ recoveryPending: z.boolean(),
+ noticeId: z.uuid().nullable(),
+ failures: z.array(failureSchema).max(10),
+})
+type RecoveryState = z.infer<typeof recoveryStateSchema>
+
+export interface GraphicsRecoveryOptions {
+ statePath: string
+ hardwareAcceleration: boolean
+ warn: (error: unknown, message: string) => void
+ now?: () => number
+}
+
+/** Durable desktop-only policy; writes are synchronous because Chromium can
+ * terminate the host immediately after another GPU process failure. */
+export class GraphicsRecovery {
+ private state: RecoveryState = {
+ version: 1,
+ consecutiveFailures: 0,
+ lastFailureAt: null,
+ recoveryPending: false,
+ noticeId: null,
+ failures: [],
+ }
+ private preferenceEnabled: boolean
+ private readonly now: () => number
+ readonly hardwareAcceleration: boolean
+ readonly recoveredAtStartup: boolean
+
+ constructor(private readonly options: GraphicsRecoveryOptions) {
+ this.now = options.now ?? Date.now
+ this.preferenceEnabled = options.hardwareAcceleration
+ try {
+ this.state = recoveryStateSchema.parse(
+ JSON.parse(readFileSync(options.statePath, 'utf8'))
+ )
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ options.warn(error, 'Unable to read graphics recovery state')
+ }
+ }
+ this.recoveredAtStartup = this.state.recoveryPending
+ this.hardwareAcceleration =
+ options.hardwareAcceleration && !this.recoveredAtStartup
+ if (this.recoveredAtStartup && this.state.noticeId === null) {
+ this.state.noticeId = randomUUID()
+ this.persist()
+ }
+ }
+
+ recordFailure(details: { reason: string; exitCode: number }): void {
+ const at = this.now()
+ this.state.failures = [...this.state.failures, { at, ...details }].slice(
+ -10
+ )
+ // Log every GPU exit, but only explicit crashes/start failures count.
+ // Explicit software mode cannot establish a hardware/driver failure.
+ // When acceleration is allowed, repeated GPU failures still trigger
+ // conservative recovery even if Chromium has already fallen back.
+ if (
+ this.hardwareAcceleration &&
+ this.preferenceEnabled &&
+ ['crashed', 'abnormal-exit', 'launch-failed'].includes(details.reason)
+ ) {
+ const previous = this.state.lastFailureAt
+ const consecutive =
+ previous !== null &&
+ at >= previous &&
+ at - previous <= GPU_FAILURE_WINDOW_MS
+ this.state.consecutiveFailures = Math.min(
+ GPU_FAILURE_LIMIT,
+ consecutive ? this.state.consecutiveFailures + 1 : 1
+ )
+ this.state.lastFailureAt = at
+ if (this.state.consecutiveFailures === GPU_FAILURE_LIMIT) {
+ this.state.recoveryPending = true
+ }
+ }
+ this.persist()
+ }
+
+ markHealthy(): void {
+ // Once repeated failures schedule recovery, a later Chromium fallback
+ // must not silently cancel it before the next launch.
+ if (this.state.recoveryPending || this.state.consecutiveFailures === 0)
+ return
+ this.state.consecutiveFailures = 0
+ this.state.lastFailureAt = null
+ this.persist()
+ }
+
+ preferenceChanged(enabled: boolean): void {
+ this.preferenceEnabled = enabled
+ this.state.consecutiveFailures = 0
+ this.state.lastFailureAt = null
+ this.state.recoveryPending = false
+ if (enabled) this.state.noticeId = null
+ this.persist()
+ }
+
+ /** Called only after SettingsManager durably stores the disabled switch. */
+ completeRecovery(): void {
+ if (!this.recoveredAtStartup) return
+ this.preferenceEnabled = false
+ this.state.recoveryPending = false
+ this.state.consecutiveFailures = 0
+ this.state.lastFailureAt = null
+ this.persist()
+ }
+
+ getNotice(): GraphicsRecoveryNotice | null {
+ return !this.hardwareAcceleration && this.state.noticeId
+ ? { id: this.state.noticeId }
+ : null
+ }
+
+ acknowledgeNotice(id: string): void {
+ if (id !== this.state.noticeId) return
+ this.state.noticeId = null
+ this.persist()
+ }
+
+ private persist(): void {
+ try {
+ writeFileAtomic.sync(this.options.statePath, JSON.stringify(this.state), {
+ mode: 0o600,
+ })
+ } catch (error) {
+ this.options.warn(error, 'Unable to persist graphics recovery state')
+ }
+ }
+}
diff --git a/src/renderer/hooks/use-graphics-recovery-toast.test.tsx b/src/renderer/hooks/use-graphics-recovery-toast.test.tsx
new file mode 100644
index 00000000..5be44c53
--- /dev/null
+++ b/src/renderer/hooks/use-graphics-recovery-toast.test.tsx
@@ -0,0 +1,110 @@
+import '@renderer/lib/i18n'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { add, close, invoke, transportMock } = vi.hoisted(() => {
+ const invoke = vi.fn()
+ return {
+ add: vi.fn(),
+ close: vi.fn(),
+ invoke,
+ transportMock: { platform: 'darwin', invoke },
+ }
+})
+vi.mock('@renderer/components/ui/toast', () => ({ toast: { add, close } }))
+vi.mock('@renderer/lib/transport', () => ({ transport: transportMock }))
+
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { useGraphicsRecoveryToast } from './use-graphics-recovery-toast'
+
+const notice = { id: '6acb7e2d-1982-4a14-aea1-773001123456' }
+
+describe('graphics recovery toast', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ transportMock.platform = 'darwin'
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible')
+ invoke.mockResolvedValue(notice)
+ })
+ afterEach(() => vi.restoreAllMocks())
+
+ it('shows a durable explanation and acknowledges only when dismissed', async () => {
+ renderHook(() => useGraphicsRecoveryToast())
+ await waitFor(() => expect(add).toHaveBeenCalledTimes(1))
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'Hardware acceleration was turned off',
+ description: expect.stringContaining('Settings → Appearance'),
+ timeout: 0,
+ })
+ )
+ expect(invoke).toHaveBeenCalledExactlyOnceWith(
+ Queries.GetGraphicsRecoveryNotice
+ )
+ act(() => add.mock.calls[0]![0].onClose())
+ expect(invoke).toHaveBeenLastCalledWith(
+ Commands.AcknowledgeGraphicsRecoveryNotice,
+ notice
+ )
+ })
+
+ it('waits for a hidden window to become visible and does not duplicate the notice', async () => {
+ const visibility = vi
+ .spyOn(document, 'visibilityState', 'get')
+ .mockReturnValue('hidden')
+ renderHook(() => useGraphicsRecoveryToast())
+ expect(invoke).not.toHaveBeenCalled()
+ visibility.mockReturnValue('visible')
+ act(() => document.dispatchEvent(new Event('visibilitychange')))
+ await waitFor(() => expect(add).toHaveBeenCalledTimes(1))
+ act(() => document.dispatchEvent(new Event('visibilitychange')))
+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(2))
+ expect(add).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves an unseen notice pending when a renderer closes during the query', async () => {
+ let resolve!: (value: unknown) => void
+ invoke.mockReturnValue(
+ new Promise((done) => {
+ resolve = done
+ })
+ )
+ const hook = renderHook(() => useGraphicsRecoveryToast())
+ hook.unmount()
+ await act(async () => resolve(notice))
+ expect(add).not.toHaveBeenCalled()
+ expect(invoke).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not acknowledge an existing notice when the renderer unmounts', async () => {
+ const hook = renderHook(() => useGraphicsRecoveryToast())
+ await waitFor(() => expect(add).toHaveBeenCalledTimes(1))
+ close.mockImplementation(() => add.mock.calls[0]![0].onClose())
+ hook.unmount()
+ expect(invoke).toHaveBeenCalledTimes(1)
+ })
+
+ it('retries a query that races IPC startup', async () => {
+ invoke
+ .mockRejectedValueOnce(new Error('not ready'))
+ .mockResolvedValue(notice)
+ renderHook(() => useGraphicsRecoveryToast())
+ await waitFor(() => expect(add).toHaveBeenCalledTimes(1), {
+ timeout: 2_000,
+ })
+ })
+
+ it('does not request desktop recovery in a web browser', () => {
+ transportMock.platform = 'web'
+ renderHook(() => useGraphicsRecoveryToast())
+ expect(invoke).not.toHaveBeenCalled()
+ })
+
+ it('does not show a toast for a normal startup', async () => {
+ invoke.mockResolvedValue(null)
+ renderHook(() => useGraphicsRecoveryToast())
+ await act(async () => {})
+ expect(add).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/hooks/use-graphics-recovery-toast.ts b/src/renderer/hooks/use-graphics-recovery-toast.ts
new file mode 100644
index 00000000..62082b38
--- /dev/null
+++ b/src/renderer/hooks/use-graphics-recovery-toast.ts
@@ -0,0 +1,76 @@
+import { toast } from '@renderer/components/ui/toast'
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { graphicsRecoveryNoticeSchema } from '@shared/schemas/graphics-recovery'
+import { useEffect, useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export const GRAPHICS_RECOVERY_TOAST_ID = 'graphics-recovery'
+
+/** Read the durable notice after the main UI mounts; startup events can precede
+ * the renderer, and a hidden login window must not consume the explanation. */
+export function useGraphicsRecoveryToast(): void {
+ const { t } = useTranslation()
+ const tRef = useRef(t)
+ tRef.current = t
+ useEffect(() => {
+ if (transport.platform === 'web') return
+ let disposed = false
+ let pending = false
+ let shownId: string | null = null
+ let retries = 0
+ let retryTimer: ReturnType<typeof setTimeout> | undefined
+ const check = async () => {
+ if (disposed || pending || document.visibilityState !== 'visible') return
+ pending = true
+ try {
+ const notice = graphicsRecoveryNoticeSchema
+ .nullable()
+ .parse(await transport.invoke(Queries.GetGraphicsRecoveryNotice))
+ if (
+ disposed ||
+ document.visibilityState !== 'visible' ||
+ !notice ||
+ shownId === notice.id
+ )
+ return
+ shownId = notice.id
+ toast.add({
+ id: GRAPHICS_RECOVERY_TOAST_ID,
+ type: 'warning',
+ title: tRef.current(
+ 'settings.appearance.hardwareAccelerationRecoveryTitle'
+ ),
+ description: tRef.current(
+ 'settings.appearance.hardwareAccelerationRecoveryBody'
+ ),
+ timeout: 0,
+ onClose: () => {
+ if (disposed) return
+ // Keep the durable notice until the user dismisses it. If this
+ // write fails, a future renderer/launch can deliver it again.
+ void transport
+ .invoke(Commands.AcknowledgeGraphicsRecoveryNotice, notice)
+ .catch(() => {})
+ },
+ })
+ } catch {
+ if (!disposed && retries++ < 3) {
+ retryTimer = setTimeout(() => void check(), 1_000)
+ }
+ } finally {
+ pending = false
+ }
+ }
+ const onVisible = () => void check()
+ document.addEventListener('visibilitychange', onVisible)
+ void check()
+ return () => {
+ disposed = true
+ clearTimeout(retryTimer)
+ document.removeEventListener('visibilitychange', onVisible)
+ if (shownId) toast.close(GRAPHICS_RECOVERY_TOAST_ID)
+ }
+ }, [])
+}
diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsx
index 8a896eb0..ec2e3bb9 100644
--- a/src/renderer/layouts/app-layout.tsx
+++ b/src/renderer/layouts/app-layout.tsx
@@ -16,6 +16,7 @@ import { MenuNavigationFocus } from '@renderer/features/application-menu/navigat
import { EngineDiagnosticsDialogHost } from '@renderer/features/engine-diagnostics/engine-diagnostics-dialog'
import { OperationDialogHost } from '@renderer/features/plugin-operations/operation-dialog'
import { useEngineRestartRequiredToast } from '@renderer/hooks/use-engine-restart-required-toast'
+import { useGraphicsRecoveryToast } from '@renderer/hooks/use-graphics-recovery-toast'
import { useIpcEvent } from '@renderer/hooks/use-ipc-event'
import { useMenuContextSync } from '@renderer/hooks/use-menu-context-sync'
import { useNotificationToasts } from '@renderer/hooks/use-notification-toasts'
@@ -58,6 +59,7 @@ export function AppLayout() {
useToastEvents()
usePairRequestPrompts()
useEngineRestartRequiredToast()
+ useGraphicsRecoveryToast()
useNotificationToasts()
const navigate = useNavigate()
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
index 4c02e1e7..90bf9c9c 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.test.tsx
@@ -71,6 +71,54 @@ beforeEach(async () => {
})
describe('<AppearanceDialog>', () => {
+ it('keeps acceleration changes in the draft until Save', async () => {
+ render(
+ <AppearanceDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.appearance.title"
+ descKey="settings.cards.appearance.desc"
+ />
+ )
+ const user = userEvent.setup({ pointerEventsCheck: 0 })
+ const control = await screen.findByRole('switch', {
+ name: 'Hardware acceleration',
+ })
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ )
+ expect(control).toBeChecked()
+ await user.click(control)
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ Commands.UpdateSettings,
+ expect.anything()
+ )
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: { hardwareAcceleration: false },
+ })
+ })
+
+ it('hides the hardware acceleration switch in the web UI', async () => {
+ Object.defineProperty(transport, 'platform', {
+ configurable: true,
+ value: 'web',
+ })
+ render(
+ <AppearanceDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.appearance.title"
+ descKey="settings.cards.appearance.desc"
+ />
+ )
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ )
+ expect(
+ screen.queryByRole('switch', { name: 'Hardware acceleration' })
+ ).not.toBeInTheDocument()
+ })
it('pins Follow system first and saves the preference only after confirmation', async () => {
render(
<AppearanceDialog
diff --git a/src/renderer/routes/settings/cards/appearance-dialog.tsx b/src/renderer/routes/settings/cards/appearance-dialog.tsx
index 32b45cd1..986eb595 100644
--- a/src/renderer/routes/settings/cards/appearance-dialog.tsx
+++ b/src/renderer/routes/settings/cards/appearance-dialog.tsx
@@ -62,6 +62,7 @@ type AppearanceFields = Pick<
| 'theme'
| 'sidebarColor'
| 'reduceMotion'
+ | 'hardwareAcceleration'
| 'language'
| 'byteUnitSystem'
| 'traySpeedometer'
@@ -76,6 +77,7 @@ const DEFAULTS: AppearanceFields = {
theme: DEFAULT_APP_SETTINGS.theme,
sidebarColor: DEFAULT_APP_SETTINGS.sidebarColor,
reduceMotion: DEFAULT_APP_SETTINGS.reduceMotion,
+ hardwareAcceleration: DEFAULT_APP_SETTINGS.hardwareAcceleration,
language: DEFAULT_APP_SETTINGS.language,
byteUnitSystem: DEFAULT_APP_SETTINGS.byteUnitSystem,
traySpeedometer: DEFAULT_APP_SETTINGS.traySpeedometer,
@@ -110,6 +112,8 @@ export function AppearanceDialog({
theme: all.app.theme,
sidebarColor: all.app.sidebarColor ?? DEFAULTS.sidebarColor,
reduceMotion: all.app.reduceMotion ?? DEFAULTS.reduceMotion,
+ hardwareAcceleration:
+ all.app.hardwareAcceleration ?? DEFAULTS.hardwareAcceleration,
language: all.app.language,
byteUnitSystem: all.app.byteUnitSystem ?? DEFAULTS.byteUnitSystem,
traySpeedometer: all.app.traySpeedometer,
@@ -348,6 +352,32 @@ export function AppearanceDialog({
</SettingsFormRow>
)}
/>
+ {transport.platform !== 'web' && (
+ <FormField
+ control={form.control}
+ name="hardwareAcceleration"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.appearance.hardwareAcceleration')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t(
+ 'settings.appearance.hardwareAccelerationDesc'
+ )}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ )}
<Separator className="my-4" />
<h3 className="text-sm font-semibold">
{t('settings.appearance.languageAndDisplay')}
diff --git a/src/renderer/routes/settings/cards/settings-form-schemas.ts b/src/renderer/routes/settings/cards/settings-form-schemas.ts
index db53b1cc..8a3d5572 100644
--- a/src/renderer/routes/settings/cards/settings-form-schemas.ts
+++ b/src/renderer/routes/settings/cards/settings-form-schemas.ts
@@ -24,6 +24,7 @@ export const appearanceFormSchema = appSettingsInputSchema.pick({
theme: true,
sidebarColor: true,
reduceMotion: true,
+ hardwareAcceleration: true,
language: true,
byteUnitSystem: true,
traySpeedometer: true,
diff --git a/src/shared/constants/restart-keys.ts b/src/shared/constants/restart-keys.ts
index c2e92233..6a2f8330 100644
--- a/src/shared/constants/restart-keys.ts
+++ b/src/shared/constants/restart-keys.ts
@@ -29,4 +29,5 @@ export const APP_RESTART_REQUIRED_KEYS: ReadonlySet<keyof MotrixAppSettings> =
new Set<keyof MotrixAppSettings>([
'mainWindowMinWidth',
'mainWindowMinHeight',
+ 'hardwareAcceleration',
])
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index eed6968c..0ac5c0ae 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -1952,6 +1952,10 @@
"menuBar": "شريط القوائم",
"reduceMotion": "تقليل الحركة",
"reduceMotionDesc": "استخدام رسوم متحركة أقل في التطبيق.",
+ "hardwareAcceleration": "تسريع الأجهزة",
+ "hardwareAccelerationDesc": "يستخدم بطاقة الرسومات لعرض أكثر سلاسة. أوقفه إذا كانت النافذة تومض أو يتعطل Motrix. تسري التغييرات بعد إعادة تشغيل Motrix.",
+ "hardwareAccelerationRecoveryTitle": "تم إيقاف تسريع الأجهزة",
+ "hardwareAccelerationRecoveryBody": "أوقف Motrix تسريع الأجهزة بعد أعطال متكررة في العرض. يمكنك تفعيله مجددًا من الإعدادات → المظهر، ثم إعادة تشغيل Motrix.",
"runMode": "إظهار التطبيق في",
"runModeHideTray": "Dock فقط",
"runModeLaunch": "عند فتح Motrix",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index b07e189b..32fcd77f 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -1876,6 +1876,10 @@
"menuBar": "Лента с менюта",
"reduceMotion": "Намаляване на движението",
"reduceMotionDesc": "Използва по-малко анимации в приложението.",
+ "hardwareAcceleration": "Хардуерно ускорение",
+ "hardwareAccelerationDesc": "Използва видеокартата за по-плавно показване. Изключете, ако прозорецът мига или Motrix се срива. Промените влизат в сила след рестартиране на Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Хардуерното ускорение е изключено",
+ "hardwareAccelerationRecoveryBody": "Motrix изключи хардуерното ускорение след повтарящи се сривове при показване. Можете да го включите отново в Настройки → Външен вид и да рестартирате Motrix.",
"runMode": "Показване на приложението в",
"runModeHideTray": "Само Dock",
"runModeLaunch": "При отваряне на Motrix",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 267afc74..892b7f0f 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -1895,6 +1895,10 @@
"menuBar": "Barra de menús",
"reduceMotion": "Reduir el moviment",
"reduceMotionDesc": "Utilitza menys animacions a tota l'aplicació.",
+ "hardwareAcceleration": "Acceleració per maquinari",
+ "hardwareAccelerationDesc": "Utilitza la targeta gràfica per mostrar la interfície amb més fluïdesa. Desactiva-la si la finestra parpelleja o el Motrix es tanca inesperadament. Els canvis s’apliquen en reiniciar el Motrix.",
+ "hardwareAccelerationRecoveryTitle": "S’ha desactivat l’acceleració per maquinari",
+ "hardwareAccelerationRecoveryBody": "El Motrix ha desactivat l’acceleració per maquinari després de diversos errors de visualització. Pots tornar-la a activar a Configuració → Aparença i reiniciar el Motrix.",
"runMode": "Mostrar l'aplicació a",
"runModeHideTray": "Només al Dock",
"runModeLaunch": "En obrir el Motrix",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index bd336d37..c6ee76de 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1316,6 +1316,10 @@
"trayIconColorDark": "Dunkles Symbol (helle Leiste)",
"reduceMotion": "Bewegung reduzieren",
"reduceMotionDesc": "Weniger Animationen in der gesamten Anwendung verwenden.",
+ "hardwareAcceleration": "Hardwarebeschleunigung",
+ "hardwareAccelerationDesc": "Nutzt die Grafikkarte für eine flüssigere Anzeige. Bei Flackern oder Abstürzen ausschalten. Änderungen gelten nach einem Neustart von Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Hardwarebeschleunigung wurde ausgeschaltet",
+ "hardwareAccelerationRecoveryBody": "Motrix hat die Hardwarebeschleunigung nach wiederholten Abstürzen der Grafikanzeige ausgeschaltet. Unter Einstellungen → Darstellung können Sie sie wieder einschalten und Motrix neu starten.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Der Download-Werkzeugleiste einen durchscheinenden Glaseffekt verleihen.",
"liquidGlassEffectMacDesc": "Gilt ab macOS 26 auch für das Fenster. Nach einer Änderung wird das Fenster erneut geöffnet.",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 8a473059..93d71ac9 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -1876,6 +1876,10 @@
"menuBar": "Γραμμή μενού",
"reduceMotion": "Μείωση κίνησης",
"reduceMotionDesc": "Χρησιμοποιεί λιγότερα εφέ κίνησης σε όλη την εφαρμογή.",
+ "hardwareAcceleration": "Επιτάχυνση υλικού",
+ "hardwareAccelerationDesc": "Χρησιμοποιεί την κάρτα γραφικών για ομαλότερη εμφάνιση. Απενεργοποιήστε την αν το παράθυρο τρεμοπαίζει ή το Motrix καταρρέει. Οι αλλαγές ισχύουν μετά την επανεκκίνηση του Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Η επιτάχυνση υλικού απενεργοποιήθηκε",
+ "hardwareAccelerationRecoveryBody": "Το Motrix απενεργοποίησε την επιτάχυνση υλικού μετά από επανειλημμένες καταρρεύσεις της εμφάνισης. Μπορείτε να την ενεργοποιήσετε στις Ρυθμίσεις → Εμφάνιση και να επανεκκινήσετε το Motrix.",
"runMode": "Εμφάνιση εφαρμογής σε",
"runModeHideTray": "Μόνο στο Dock",
"runModeLaunch": "Κατά το άνοιγμα του Motrix",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 124ee0b6..7f412c79 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1316,6 +1316,10 @@
"trayIconColorDark": "Dark icon (light panel)",
"reduceMotion": "Reduce motion",
"reduceMotionDesc": "Use fewer animations throughout the app.",
+ "hardwareAcceleration": "Hardware acceleration",
+ "hardwareAccelerationDesc": "Use your graphics card for smoother visuals. Turn this off if the window flickers or Motrix crashes. Changes take effect after restarting Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Hardware acceleration was turned off",
+ "hardwareAccelerationRecoveryBody": "Motrix turned off hardware acceleration after repeated display crashes. You can turn it back on in Settings → Appearance, then restart Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Give the download toolbar a translucent glass effect.",
"liquidGlassEffectMacDesc": "Also applies to the window on macOS 26+. The window reopens when changed.",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 9fa8ef8b..f47f9cbc 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1330,6 +1330,10 @@
"trayIconColorDark": "Icono oscuro (panel claro)",
"reduceMotion": "Reducir movimiento",
"reduceMotionDesc": "Usa menos animaciones en toda la aplicación.",
+ "hardwareAcceleration": "Aceleración por hardware",
+ "hardwareAccelerationDesc": "Usa la tarjeta gráfica para mostrar la interfaz con mayor fluidez. Desactívala si la ventana parpadea o Motrix se cierra inesperadamente. Los cambios se aplican al reiniciar Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Se desactivó la aceleración por hardware",
+ "hardwareAccelerationRecoveryBody": "Motrix desactivó la aceleración por hardware tras varios fallos de visualización. Puedes volver a activarla en Ajustes → Apariencia y reiniciar Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Aplica un efecto de cristal translúcido a la barra de herramientas de descargas.",
"liquidGlassEffectMacDesc": "También se aplica a la ventana en macOS 26 o posterior. La ventana vuelve a abrirse al cambiarlo.",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index d1f7409c..3922c025 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -1876,6 +1876,10 @@
"menuBar": "نوار منو",
"reduceMotion": "کاهش حرکت",
"reduceMotionDesc": "از پویانمایی‌های کمتری در برنامه استفاده شود.",
+ "hardwareAcceleration": "شتاب‌دهی سخت‌افزاری",
+ "hardwareAccelerationDesc": "برای نمایش روان‌تر از کارت گرافیک استفاده می‌کند. اگر پنجره چشمک می‌زند یا Motrix از کار می‌افتد، آن را خاموش کنید. تغییرات پس از راه‌اندازی مجدد Motrix اعمال می‌شوند.",
+ "hardwareAccelerationRecoveryTitle": "شتاب‌دهی سخت‌افزاری خاموش شد",
+ "hardwareAccelerationRecoveryBody": "Motrix پس از خرابی‌های پی‌درپی نمایش، شتاب‌دهی سخت‌افزاری را خاموش کرد. می‌توانید آن را در تنظیمات → ظاهر دوباره روشن کنید و Motrix را راه‌اندازی مجدد کنید.",
"runMode": "نمایش برنامه در",
"runModeHideTray": "فقط Dock",
"runModeLaunch": "هنگام باز کردن Motrix",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 4b0ddaf8..b08aed44 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -1894,6 +1894,10 @@
"menuBar": "Barre des menus",
"reduceMotion": "Réduire les animations",
"reduceMotionDesc": "Limiter les animations dans toute l’application.",
+ "hardwareAcceleration": "Accélération matérielle",
+ "hardwareAccelerationDesc": "Utilise la carte graphique pour un affichage plus fluide. Désactivez cette option en cas de scintillement ou de plantage. Les modifications prennent effet après le redémarrage de Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Accélération matérielle désactivée",
+ "hardwareAccelerationRecoveryBody": "Motrix a désactivé l’accélération matérielle après plusieurs plantages de l’affichage. Vous pouvez la réactiver dans Paramètres → Apparence, puis redémarrer Motrix.",
"runMode": "Afficher l’application dans",
"runModeHideTray": "Dock uniquement",
"runModeLaunch": "À l’ouverture de Motrix",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 1885ef93..3c316752 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1316,6 +1316,10 @@
"trayIconColorDark": "Sötét ikon (világos panel)",
"reduceMotion": "Mozgás csökkentése",
"reduceMotionDesc": "Kevesebb animáció használata az alkalmazásban.",
+ "hardwareAcceleration": "Hardveres gyorsítás",
+ "hardwareAccelerationDesc": "A videokártyát használja a simább megjelenítéshez. Kapcsolja ki, ha az ablak villog vagy a Motrix összeomlik. A módosítás a Motrix újraindítása után lép életbe.",
+ "hardwareAccelerationRecoveryTitle": "A hardveres gyorsítás kikapcsolva",
+ "hardwareAccelerationRecoveryBody": "A Motrix ismétlődő megjelenítési összeomlások miatt kikapcsolta a hardveres gyorsítást. A Beállítások → Megjelenés menüben visszakapcsolhatja, majd újraindíthatja a Motrixot.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Áttetsző üveghatás a letöltési eszköztáron.",
"liquidGlassEffectMacDesc": "macOS 26 vagy újabb rendszeren az ablakra is érvényes. Módosításkor az ablak újra megnyílik.",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index b63b6579..4f874d93 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1302,6 +1302,10 @@
"trayIconColorDark": "Ikon gelap (panel terang)",
"reduceMotion": "Kurangi gerakan",
"reduceMotionDesc": "Gunakan lebih sedikit animasi dalam aplikasi.",
+ "hardwareAcceleration": "Akselerasi perangkat keras",
+ "hardwareAccelerationDesc": "Menggunakan kartu grafis agar tampilan lebih lancar. Matikan jika jendela berkedip atau Motrix berhenti mendadak. Perubahan berlaku setelah Motrix dimulai ulang.",
+ "hardwareAccelerationRecoveryTitle": "Akselerasi perangkat keras dimatikan",
+ "hardwareAccelerationRecoveryBody": "Motrix mematikan akselerasi perangkat keras setelah tampilan berulang kali mengalami gangguan. Anda dapat mengaktifkannya kembali di Pengaturan → Tampilan, lalu memulai ulang Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Terapkan efek kaca semitransparan pada bilah alat unduhan.",
"liquidGlassEffectMacDesc": "Juga diterapkan pada jendela di macOS 26 ke atas. Jendela akan dibuka ulang saat opsi ini diubah.",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index c3482904..ba5b01d4 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1330,6 +1330,10 @@
"trayIconColorDark": "Icona scura (pannello chiaro)",
"reduceMotion": "Riduci movimento",
"reduceMotionDesc": "Usa meno animazioni nell’app.",
+ "hardwareAcceleration": "Accelerazione hardware",
+ "hardwareAccelerationDesc": "Usa la scheda grafica per una visualizzazione più fluida. Disattivala se la finestra sfarfalla o Motrix si arresta. Le modifiche si applicano dopo il riavvio di Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Accelerazione hardware disattivata",
+ "hardwareAccelerationRecoveryBody": "Motrix ha disattivato l’accelerazione hardware dopo ripetuti arresti della visualizzazione. Puoi riattivarla in Impostazioni → Aspetto, quindi riavviare Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Applica un effetto vetro traslucido alla barra degli strumenti dei download.",
"liquidGlassEffectMacDesc": "Si applica anche alla finestra su macOS 26 e versioni successive. La finestra viene riaperta quando cambi questa impostazione.",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index a9ee9ff8..866f17fe 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1302,6 +1302,10 @@
"trayIconColorDark": "暗いアイコン(明るいパネル向け)",
"reduceMotion": "視差効果を減らす",
"reduceMotionDesc": "アプリ全体のアニメーションを減らします。",
+ "hardwareAcceleration": "ハードウェアアクセラレーション",
+ "hardwareAccelerationDesc": "グラフィックスカードを使って画面を滑らかに表示します。画面のちらつきやクラッシュが起きる場合はオフにしてください。変更は Motrix の再起動後に反映されます。",
+ "hardwareAccelerationRecoveryTitle": "ハードウェアアクセラレーションをオフにしました",
+ "hardwareAccelerationRecoveryBody": "画面表示のクラッシュが続いたため、Motrix はハードウェアアクセラレーションをオフにしました。「設定 → 外観」で再びオンにし、Motrix を再起動できます。",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "ダウンロードのツールバーに半透明のガラス効果を適用します。",
"liquidGlassEffectMacDesc": "macOS 26 以降ではウインドウにも適用します。変更するとウインドウが開き直されます。",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 2240d2f3..41a5ebcf 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1302,6 +1302,10 @@
"trayIconColorDark": "어두운 아이콘(밝은 패널용)",
"reduceMotion": "동작 줄이기",
"reduceMotionDesc": "앱 전체에서 애니메이션 사용을 줄입니다.",
+ "hardwareAcceleration": "하드웨어 가속",
+ "hardwareAccelerationDesc": "그래픽 카드를 사용해 화면을 더 부드럽게 표시합니다. 화면이 깜박이거나 Motrix가 종료되면 꺼 보세요. 변경 사항은 Motrix를 다시 시작한 후 적용됩니다.",
+ "hardwareAccelerationRecoveryTitle": "하드웨어 가속이 꺼졌습니다",
+ "hardwareAccelerationRecoveryBody": "화면 표시 오류가 반복되어 Motrix가 하드웨어 가속을 껐습니다. 설정 → 모양에서 다시 켠 후 Motrix를 다시 시작할 수 있습니다.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "다운로드 도구 막대에 반투명 유리 효과를 적용합니다.",
"liquidGlassEffectMacDesc": "macOS 26 이상에서는 창에도 적용됩니다. 변경하면 창이 다시 열립니다.",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 73553762..5cdfd00b 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -1876,6 +1876,10 @@
"menuBar": "Menylinje",
"reduceMotion": "Reduser bevegelse",
"reduceMotionDesc": "Bruk færre animasjoner i hele appen.",
+ "hardwareAcceleration": "Maskinvareakselerasjon",
+ "hardwareAccelerationDesc": "Bruker grafikkortet for jevnere visning. Slå av hvis vinduet flimrer eller Motrix krasjer. Endringer trer i kraft når Motrix startes på nytt.",
+ "hardwareAccelerationRecoveryTitle": "Maskinvareakselerasjon er slått av",
+ "hardwareAccelerationRecoveryBody": "Motrix slo av maskinvareakselerasjon etter gjentatte skjermkrasj. Du kan slå den på igjen i Innstillinger → Utseende og starte Motrix på nytt.",
"runMode": "Vis appen i",
"runModeHideTray": "Bare Dock",
"runModeLaunch": "Når Motrix åpnes",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 444cfe66..5e707850 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -1876,6 +1876,10 @@
"menuBar": "Menubalk",
"reduceMotion": "Beweging verminderen",
"reduceMotionDesc": "Minder animaties in de hele app gebruiken.",
+ "hardwareAcceleration": "Hardwareversnelling",
+ "hardwareAccelerationDesc": "Gebruikt de grafische kaart voor een vloeiendere weergave. Schakel dit uit als het venster flikkert of Motrix vastloopt. Wijzigingen gelden na het herstarten van Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Hardwareversnelling is uitgeschakeld",
+ "hardwareAccelerationRecoveryBody": "Motrix heeft hardwareversnelling uitgeschakeld na herhaalde weergavecrashes. Je kunt dit weer inschakelen via Instellingen → Weergave en Motrix herstarten.",
"runMode": "App tonen in",
"runModeHideTray": "Alleen Dock",
"runModeLaunch": "Bij het openen van Motrix",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index e008298d..4e94a90e 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1344,6 +1344,10 @@
"trayIconColorDark": "Ciemna ikona (jasny panel)",
"reduceMotion": "Ogranicz ruch",
"reduceMotionDesc": "Używaj mniej animacji w aplikacji.",
+ "hardwareAcceleration": "Przyspieszenie sprzętowe",
+ "hardwareAccelerationDesc": "Używa karty graficznej do płynniejszego wyświetlania. Wyłącz, jeśli okno migocze lub Motrix się zawiesza. Zmiany zaczną działać po ponownym uruchomieniu Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Przyspieszenie sprzętowe zostało wyłączone",
+ "hardwareAccelerationRecoveryBody": "Motrix wyłączył przyspieszenie sprzętowe po powtarzających się awariach wyświetlania. Możesz je ponownie włączyć w Ustawienia → Wygląd, a następnie uruchomić Motrix ponownie.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Nadaj paskowi narzędzi pobierania efekt półprzezroczystego szkła.",
"liquidGlassEffectMacDesc": "Dotyczy także okna w macOS 26 i nowszych. Po zmianie okno otwiera się ponownie.",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index f1a0d8a3..e3ca234f 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1330,6 +1330,10 @@
"trayIconColorDark": "Ícone escuro (painel claro)",
"reduceMotion": "Reduzir movimento",
"reduceMotionDesc": "Usa menos animações no aplicativo.",
+ "hardwareAcceleration": "Aceleração de hardware",
+ "hardwareAccelerationDesc": "Usa a placa de vídeo para uma interface mais fluida. Desative se a janela piscar ou o Motrix fechar inesperadamente. As alterações entram em vigor após reiniciar o Motrix.",
+ "hardwareAccelerationRecoveryTitle": "A aceleração de hardware foi desativada",
+ "hardwareAccelerationRecoveryBody": "O Motrix desativou a aceleração de hardware após falhas repetidas de exibição. Você pode reativá-la em Configurações → Aparência e reiniciar o Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Aplica um efeito de vidro translúcido à barra de ferramentas de downloads.",
"liquidGlassEffectMacDesc": "Também se aplica à janela no macOS 26 ou posterior. A janela é reaberta quando esta opção é alterada.",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index d9a51803..f64bbe2e 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -1895,6 +1895,10 @@
"menuBar": "Bara de meniu",
"reduceMotion": "Redu mișcarea",
"reduceMotionDesc": "Folosește mai puține animații în aplicație.",
+ "hardwareAcceleration": "Accelerare hardware",
+ "hardwareAccelerationDesc": "Folosește placa video pentru o afișare mai fluidă. Dezactivează dacă fereastra pâlpâie sau Motrix se închide neașteptat. Modificările se aplică după repornirea Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Accelerarea hardware a fost dezactivată",
+ "hardwareAccelerationRecoveryBody": "Motrix a dezactivat accelerarea hardware după erori repetate de afișare. O poți reactiva în Setări → Aspect, apoi poți reporni Motrix.",
"runMode": "Arată aplicația în",
"runModeHideTray": "Doar Dock",
"runModeLaunch": "La deschiderea Motrix",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 4dbe355f..484095b5 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1344,6 +1344,10 @@
"trayIconColorDark": "Тёмный значок (светлая панель)",
"reduceMotion": "Уменьшить движение",
"reduceMotionDesc": "Использовать меньше анимации в приложении.",
+ "hardwareAcceleration": "Аппаратное ускорение",
+ "hardwareAccelerationDesc": "Использует видеокарту для более плавного отображения. Отключите, если окно мерцает или Motrix аварийно закрывается. Изменения вступят в силу после перезапуска Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Аппаратное ускорение отключено",
+ "hardwareAccelerationRecoveryBody": "Motrix отключил аппаратное ускорение после повторных сбоев отображения. Его можно снова включить в разделе Настройки → Внешний вид, а затем перезапустить Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Добавить полупрозрачный стеклянный эффект панели инструментов загрузок.",
"liquidGlassEffectMacDesc": "Также применяется к окну в macOS 26 и новее. При изменении окно открывается заново.",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 40ff55d6..965e3b9c 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -1857,6 +1857,10 @@
"menuBar": "แถบเมนู",
"reduceMotion": "ลดการเคลื่อนไหว",
"reduceMotionDesc": "ลดภาพเคลื่อนไหวทั่วทั้งแอป",
+ "hardwareAcceleration": "การเร่งด้วยฮาร์ดแวร์",
+ "hardwareAccelerationDesc": "ใช้การ์ดจอเพื่อให้แสดงผลลื่นไหลขึ้น หากหน้าต่างกะพริบหรือ Motrix ปิดตัวเอง ให้ลองปิดตัวเลือกนี้ การเปลี่ยนแปลงมีผลหลังเริ่ม Motrix ใหม่",
+ "hardwareAccelerationRecoveryTitle": "ปิดการเร่งด้วยฮาร์ดแวร์แล้ว",
+ "hardwareAccelerationRecoveryBody": "Motrix ปิดการเร่งด้วยฮาร์ดแวร์หลังเกิดข้อผิดพลาดในการแสดงผลซ้ำหลายครั้ง คุณเปิดอีกครั้งได้ที่ การตั้งค่า → รูปลักษณ์ แล้วเริ่ม Motrix ใหม่",
"runMode": "แสดงแอปใน",
"runModeHideTray": "Dock เท่านั้น",
"runModeLaunch": "เมื่อเปิด Motrix",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 7b5d95b1..2ae1c0ed 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1316,6 +1316,10 @@
"trayIconColorDark": "Koyu simge (açık panel)",
"reduceMotion": "Hareketi azalt",
"reduceMotionDesc": "Uygulama genelinde daha az animasyon kullanın.",
+ "hardwareAcceleration": "Donanım hızlandırma",
+ "hardwareAccelerationDesc": "Daha akıcı görüntü için ekran kartını kullanır. Pencere titriyorsa veya Motrix çöküyorsa kapatın. Değişiklikler Motrix yeniden başlatılınca uygulanır.",
+ "hardwareAccelerationRecoveryTitle": "Donanım hızlandırma kapatıldı",
+ "hardwareAccelerationRecoveryBody": "Tekrarlanan görüntü çökmeleri nedeniyle Motrix donanım hızlandırmayı kapattı. Ayarlar → Görünüm bölümünden yeniden açıp Motrix’i yeniden başlatabilirsiniz.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "İndirme araç çubuğuna yarı saydam cam efekti uygulayın.",
"liquidGlassEffectMacDesc": "macOS 26 ve üzeri sürümlerde pencereye de uygulanır. Bu ayar değiştiğinde pencere yeniden açılır.",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index b4b1344f..db38c4d2 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -1914,6 +1914,10 @@
"menuBar": "Смуга меню",
"reduceMotion": "Зменшити рух",
"reduceMotionDesc": "Використовувати менше анімацій у застосунку.",
+ "hardwareAcceleration": "Апаратне прискорення",
+ "hardwareAccelerationDesc": "Використовує відеокарту для плавнішого відображення. Вимкніть, якщо вікно мерехтить або Motrix аварійно закривається. Зміни діють після перезапуску Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Апаратне прискорення вимкнено",
+ "hardwareAccelerationRecoveryBody": "Motrix вимкнув апаратне прискорення після повторних збоїв відображення. Його можна знову ввімкнути в розділі Налаштування → Вигляд, а потім перезапустити Motrix.",
"runMode": "Показувати застосунок у",
"runModeHideTray": "Лише Dock",
"runModeLaunch": "Під час відкриття Motrix",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 8be9b097..9b3549f8 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1302,6 +1302,10 @@
"trayIconColorDark": "Biểu tượng tối (nền sáng)",
"reduceMotion": "Giảm chuyển động",
"reduceMotionDesc": "Giảm hiệu ứng chuyển động trong toàn bộ ứng dụng.",
+ "hardwareAcceleration": "Tăng tốc phần cứng",
+ "hardwareAccelerationDesc": "Dùng card đồ họa để hiển thị mượt hơn. Tắt nếu cửa sổ nhấp nháy hoặc Motrix bị đóng đột ngột. Thay đổi có hiệu lực sau khi khởi động lại Motrix.",
+ "hardwareAccelerationRecoveryTitle": "Đã tắt tăng tốc phần cứng",
+ "hardwareAccelerationRecoveryBody": "Motrix đã tắt tăng tốc phần cứng sau nhiều lần gặp sự cố hiển thị. Bạn có thể bật lại trong Cài đặt → Giao diện, rồi khởi động lại Motrix.",
"liquidGlassEffect": "Liquid Glass",
"liquidGlassEffectDesc": "Thêm hiệu ứng kính trong mờ cho thanh công cụ tải xuống.",
"liquidGlassEffectMacDesc": "Cũng áp dụng cho cửa sổ trên macOS 26 trở lên. Cửa sổ sẽ mở lại khi thay đổi.",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index beae5744..3a1d2993 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1302,6 +1302,10 @@
"trayIconColorDark": "深色图标(浅色面板)",
"reduceMotion": "减少动画",
"reduceMotionDesc": "减少界面中的动态效果。",
+ "hardwareAcceleration": "硬件加速",
+ "hardwareAccelerationDesc": "使用显卡让界面显示更流畅。如果出现闪屏或闪退,可以尝试关闭。修改后需重启 Motrix 才会生效。",
+ "hardwareAccelerationRecoveryTitle": "已关闭硬件加速",
+ "hardwareAccelerationRecoveryBody": "由于画面显示连续出错,Motrix 已关闭硬件加速,避免再次闪退。你可以在“设置 → 外观”中重新开启,重启后生效。",
"liquidGlassEffect": "液态玻璃",
"liquidGlassEffectDesc": "让下载工具栏呈现半透明玻璃效果。",
"liquidGlassEffectMacDesc": "macOS 26 及以上也会应用到窗口;更改后窗口会重新打开。",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index b2e280fb..1efa998a 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1302,6 +1302,10 @@
"trayIconColorDark": "深色圖示(淺色面板)",
"reduceMotion": "減少動畫",
"reduceMotionDesc": "減少介面中的動態效果。",
+ "hardwareAcceleration": "硬體加速",
+ "hardwareAccelerationDesc": "使用顯示卡讓介面顯示更流暢。如果出現閃爍或閃退,可以嘗試關閉。變更後需重新啟動 Motrix 才會生效。",
+ "hardwareAccelerationRecoveryTitle": "已關閉硬體加速",
+ "hardwareAccelerationRecoveryBody": "由於畫面顯示連續出錯,Motrix 已關閉硬體加速,避免再次閃退。你可以在「設定 → 外觀」中重新開啟,重新啟動後生效。",
"liquidGlassEffect": "液態玻璃",
"liquidGlassEffectDesc": "讓下載工具列呈現半透明玻璃效果。",
"liquidGlassEffectMacDesc": "macOS 26 及以上也會套用至視窗;變更後視窗會重新開啟。",
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 031b5bc0..b52fd83c 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -1,4 +1,6 @@
export const Commands = {
+ AcknowledgeGraphicsRecoveryNotice:
+ 'command:acknowledgeGraphicsRecoveryNotice',
ExecuteRendererSubmission: 'command:executeRendererSubmission',
AcknowledgeRendererIntent: 'command:acknowledgeRendererIntent',
ReportRendererSurface: 'command:reportRendererSurface',
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index c98ada95..b56020b6 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -1,4 +1,5 @@
export const Queries = {
+ GetGraphicsRecoveryNotice: 'query:getGraphicsRecoveryNotice',
GetRendererSession: 'query:getRendererSession',
GetLegacyImportNavigation: 'query:getLegacyImportNavigation',
GetLegacyBtActivationAvailability: 'query:getLegacyBtActivationAvailability',
diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.ts
index b02ad944..cf176e31 100644
--- a/src/shared/schemas/app-settings.test.ts
+++ b/src/shared/schemas/app-settings.test.ts
@@ -6,6 +6,18 @@ import {
} from './app-settings'
describe('appSettingsSchema', () => {
+ it('defaults acceleration on for existing profiles and strictly validates changes', () => {
+ expect(DEFAULT_APP_SETTINGS.hardwareAcceleration).toBe(true)
+ expect(
+ appSettingsSchema.parse({ hardwareAcceleration: false })
+ .hardwareAcceleration
+ ).toBe(false)
+ expect(
+ appSettingsInputSchema
+ .partial()
+ .safeParse({ hardwareAcceleration: 'false' }).success
+ ).toBe(false)
+ })
it('recovers missing or damaged speed limit units without losing valid choices', () => {
expect(appSettingsSchema.parse({}).speedLimitUnits).toEqual({
baseUpload: 'kilo',
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index 91e923e7..a462f1da 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -40,6 +40,7 @@ export const appSettingsSchema = z.object({
theme: z.enum(['system', 'light', 'dark']).catch('system'),
sidebarColor: sidebarColorSchema.catch('cyan'),
reduceMotion: z.boolean().catch(false),
+ hardwareAcceleration: z.boolean().catch(true),
language: languagePreferenceSchema.catch('system'),
byteUnitSystem: byteUnitSystemSchema.catch(DEFAULT_BYTE_UNIT_PREFERENCE),
speedLimitUnits: speedLimitUnitsSchema.catch(speedLimitUnitsSchema.parse({})),
diff --git a/src/shared/schemas/graphics-recovery.ts b/src/shared/schemas/graphics-recovery.ts
new file mode 100644
index 00000000..38951d6a
--- /dev/null
+++ b/src/shared/schemas/graphics-recovery.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod'
+
+export const graphicsRecoveryNoticeSchema = z.object({
+ id: z.uuid(),
+})
+
+export type GraphicsRecoveryNotice = z.infer<
+ typeof graphicsRecoveryNoticeSchema
+>
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index b7071567..ef9d3545 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -231,6 +231,7 @@ export interface MotrixAppSettings {
theme: 'system' | 'light' | 'dark'
sidebarColor: SidebarColor
reduceMotion: boolean
+ hardwareAcceleration: boolean
byteUnitSystem: ByteUnitPreference
speedLimitUnits: SpeedLimitUnits
language: LanguagePreference
diff --git a/tests/scripts/production-build.test.ts b/tests/scripts/production-build.test.ts
index e103401d..d6468661 100644
--- a/tests/scripts/production-build.test.ts
+++ b/tests/scripts/production-build.test.ts
@@ -23,6 +23,7 @@ interface BundleMetrics {
sourceMaps: number
initialLocales: string[]
bundledLocales: string[]
+ bundledOperatorAdmin: boolean
initialElk: boolean
bundledElk: boolean
javascriptAssetBytes: number
@@ -58,6 +59,8 @@ describe('production bundle loading and size contracts', () => {
expect(result.initialBytes).toBeLessThanOrEqual(target.initial)
expect(result.totalBytes).toBeLessThanOrEqual(target.total)
expect(result.sourceMaps).toBe(0)
+ if (target.name === 'main')
+ expect(result.bundledOperatorAdmin).toBe(false)
if (
['main', 'server', 'renderer', 'renderer.web'].includes(target.name)
) {
diff --git a/tests/scripts/vite-desktop-locales.test.ts b/tests/scripts/vite-desktop-locales.test.ts
new file mode 100644
index 00000000..6c604446
--- /dev/null
+++ b/tests/scripts/vite-desktop-locales.test.ts
@@ -0,0 +1,49 @@
+import { readdirSync, readFileSync } from 'node:fs'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { desktopLocaleProjection } from '../../scripts/vite-desktop-locales'
+
+describe('desktop main locale projection', () => {
+ const root = path.resolve(import.meta.dirname, '../../src/shared/locales')
+ const plugin = desktopLocaleProjection(root)
+ const transform = plugin.transform as (
+ source: string,
+ id: string
+ ) => { code: string } | null
+
+ it('removes only the Server CLI catalog from every locale', () => {
+ for (const file of readdirSync(root).filter((name) =>
+ name.endsWith('.json')
+ )) {
+ const source = readFileSync(path.join(root, file), 'utf8')
+ const original = JSON.parse(source)
+ expect(original.operatorAdmin).toBeDefined()
+ const result = JSON.parse(transform(source, path.join(root, file))!.code)
+ expect(result.operatorAdmin).toBeUndefined()
+ delete original.operatorAdmin
+ expect(result).toEqual(original)
+ }
+ })
+
+ it('leaves unrelated JSON and scripts unchanged', () => {
+ expect(transform('{}', path.join(root, '../schemas/test.json'))).toBeNull()
+ expect(
+ transform('export default {}', path.join(root, 'test.ts'))
+ ).toBeNull()
+ })
+
+ it('recognizes Windows module paths with Vite query suffixes', () => {
+ const windowsPlugin = desktopLocaleProjection(
+ 'C:\\app\\src\\shared\\locales'
+ )
+ const windowsTransform = windowsPlugin.transform as typeof transform
+ expect(
+ JSON.parse(
+ windowsTransform(
+ '{"operatorAdmin":{},"settings":{"x":"y"}}',
+ 'C:\\app\\src\\shared\\locales\\en-US.json?import'
+ )!.code
+ )
+ ).toEqual({ settings: { x: 'y' } })
+ })
+})
diff --git a/vite.main.config.ts b/vite.main.config.ts
index 731c814e..3d8fe598 100644
--- a/vite.main.config.ts
+++ b/vite.main.config.ts
@@ -1,6 +1,7 @@
import { builtinModules, createRequire } from 'node:module'
import path from 'node:path'
import { defineConfig } from 'vite'
+import { desktopLocaleProjection } from './scripts/vite-desktop-locales'
import { PRODUCTION_OUTPUT } from './scripts/vite-production-output'
const require = createRequire(import.meta.url)
@@ -54,6 +55,11 @@ function isExternal(id: string): boolean {
export default defineConfig({
publicDir: false,
+ plugins: [
+ desktopLocaleProjection(
+ path.resolve(import.meta.dirname, 'src/shared/locales')
+ ),
+ ],
build: {
outDir: 'dist/main',
emptyOutDir: true,