Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(gpu): stop 1.8.3's GPU regression — Vulkan iGPU default, off-PATH nvidia-smi, silent pack deletion (#1606) (#1609)

Joshua251e1ad0fc8f
diff --git a/main.js b/main.js
index 41030422a..a34cfaab0 100644
--- a/main.js
+++ b/main.js
@@ -429,7 +429,16 @@ function initializeCoreManagers() {
// Heal installs from before GPU packs got per-pack directories; must run
// before startup pre-warm resolves any GPU binary path.
const LlamaVulkanManager = require("./src/helpers/llamaVulkanManager");
- migrateLegacyBinDir([whisperCudaManager, whisperVulkanManager, new LlamaVulkanManager()]);
+ const clearedPacks = migrateLegacyBinDir([
+ whisperCudaManager,
+ whisperVulkanManager,
+ new LlamaVulkanManager(),
+ ]);
+ if (clearedPacks.length > 0) {
+ // No window exists yet — persist the notice; a control panel window
+ // shows it as a toast and clears it. See #1606.
+ require("./src/helpers/gpuPackMigrationNotice").record(clearedPacks);
+ }
// Lets every server start resolve its GPU backend from installed packs
whisperManager.setGpuBinaryManagers({ cuda: whisperCudaManager, vulkan: whisperVulkanManager });
}
diff --git a/preload.js b/preload.js
index ca4a18a48..d19a60e1c 100644
--- a/preload.js
+++ b/preload.js
@@ -363,6 +363,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
(callback) => () => callback()
),
+ // One-time "GPU pack needs re-downloading" notice from the legacy-layout migration
+ getGpuPackMigrationNotice: () => ipcRenderer.invoke("get-gpu-pack-migration-notice"),
+ dismissGpuPackMigrationNotice: () => ipcRenderer.invoke("dismiss-gpu-pack-migration-notice"),
+
// Local Parakeet (NVIDIA) functions
transcribeLocalParakeet: (audioBlob, options) =>
ipcRenderer.invoke("transcribe-local-parakeet", audioBlob, options),
diff --git a/src/components/GpuPackMigrationToastListener.tsx b/src/components/GpuPackMigrationToastListener.tsx
new file mode 100644
index 000000000..ae386cc38
--- /dev/null
+++ b/src/components/GpuPackMigrationToastListener.tsx
@@ -0,0 +1,38 @@
+import { useEffect } from "react";
+import { useTranslation } from "react-i18next";
+import { useToast } from "./ui/useToast";
+import { isDictationPanelWindow } from "../utils/windowContext";
+
+/**
+ * One-time notice that the legacy-layout migration cleared a GPU pack, which
+ * otherwise degrades to a silent CPU fallback. The notice is persisted by the
+ * main process (it happens before any window exists) and cleared once shown.
+ * See #1606.
+ */
+export default function GpuPackMigrationToastListener() {
+ const { t } = useTranslation();
+ const { toast } = useToast();
+
+ useEffect(() => {
+ // Only the control panel shows it — the dictation panel is transient and
+ // would burn the one-time notice where it's least likely to be read.
+ if (isDictationPanelWindow()) return;
+ let cancelled = false;
+ window.electronAPI?.getGpuPackMigrationNotice?.().then((notice) => {
+ if (cancelled || !notice) return;
+ toast({
+ title: t("app.toasts.gpuPackMigration.title"),
+ description: t("app.toasts.gpuPackMigration.description", {
+ packs: notice.packs.join(", "),
+ }),
+ duration: 15000,
+ });
+ window.electronAPI?.dismissGpuPackMigrationNotice?.();
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [toast, t]);
+
+ return null;
+}
diff --git a/src/helpers/environment.js b/src/helpers/environment.js
index 91eafb87a..8e1a37e59 100644
--- a/src/helpers/environment.js
+++ b/src/helpers/environment.js
@@ -47,6 +47,7 @@ const PERSISTED_KEYS = [
"UI_LANGUAGE",
"WHISPER_CUDA_ENABLED",
"WHISPER_VULKAN_ENABLED",
+ "WHISPER_VULKAN_DEVICE",
"WHISPER_GPU_FAILED",
"WHISPER_THREADS",
"TRANSCRIPTION_GPU_UUID",
diff --git a/src/helpers/gpuBinaryManager.js b/src/helpers/gpuBinaryManager.js
index 39a13e8b9..a562accc3 100644
--- a/src/helpers/gpuBinaryManager.js
+++ b/src/helpers/gpuBinaryManager.js
@@ -268,15 +268,18 @@ class GpuBinaryManager {
// A pack with libs can't tell which of the surviving DLLs are its own (the
// clobbering destroyed that), so its files are removed and the pack shows as
// not installed until re-downloaded from Settings. Synchronous so it completes
-// before startup pre-warm reads any binary path.
+// before startup pre-warm reads any binary path. Returns the names of the
+// packs that were cleared so the caller can tell the user to re-download
+// them instead of leaving a silent CPU fallback (#1606).
function migrateLegacyBinDir(managers) {
+ const clearedPacks = [];
const packs = managers
.map((m) => ({ manager: m, assetConfig: m._getAssetConfig() }))
.filter((p) => p.assetConfig);
- if (packs.length === 0) return;
+ if (packs.length === 0) return clearedPacks;
const binRoot = packs[0].manager.binRoot;
- if (!fs.existsSync(binRoot)) return;
+ if (!fs.existsSync(binRoot)) return clearedPacks;
for (const { manager, assetConfig } of packs) {
const legacyBinary = path.join(binRoot, assetConfig.outputName);
@@ -284,6 +287,7 @@ function migrateLegacyBinDir(managers) {
if (!fs.existsSync(legacyBinary)) continue;
if (assetConfig.libPattern) {
fs.unlinkSync(legacyBinary);
+ clearedPacks.push(manager.config.name);
debugLogger.info(`${manager.config.name} legacy install removed (needs re-download)`);
} else if (manager.isDownloaded()) {
fs.unlinkSync(legacyBinary);
@@ -299,7 +303,7 @@ function migrateLegacyBinDir(managers) {
// The lib-carrying packs' orphaned companion libs (ownership is unknowable)
const libPatterns = packs.map((p) => p.assetConfig.libPattern).filter(Boolean);
- if (libPatterns.length === 0) return;
+ if (libPatterns.length === 0) return clearedPacks;
try {
for (const entry of fs.readdirSync(binRoot, { withFileTypes: true })) {
if (!entry.isFile() || !libPatterns.some((pattern) => pattern.test(entry.name))) continue;
@@ -308,6 +312,7 @@ function migrateLegacyBinDir(managers) {
} catch {}
}
} catch {}
+ return clearedPacks;
}
module.exports = GpuBinaryManager;
diff --git a/src/helpers/gpuPackMigrationNotice.js b/src/helpers/gpuPackMigrationNotice.js
new file mode 100644
index 000000000..851e11a62
--- /dev/null
+++ b/src/helpers/gpuPackMigrationNotice.js
@@ -0,0 +1,42 @@
+const fs = require("fs");
+const path = require("path");
+const { app } = require("electron");
+
+// The legacy-layout migration (migrateLegacyBinDir) runs before any window
+// exists and can clear a GPU pack the user relied on. This sentinel carries
+// the "re-download your GPU pack" notice across launches until a control
+// panel window has actually shown it — a broadcast at window creation would
+// be lost if the user quit first. See #1606.
+const SENTINEL_FILENAME = ".gpu-pack-migration-notice";
+
+function getSentinelPath() {
+ return path.join(app.getPath("userData"), SENTINEL_FILENAME);
+}
+
+function record(packNames) {
+ if (!packNames || packNames.length === 0) return;
+ const existing = read();
+ const packs = [...new Set([...(existing ? existing.packs : []), ...packNames])];
+ try {
+ fs.writeFileSync(getSentinelPath(), JSON.stringify({ packs, ts: new Date().toISOString() }));
+ } catch {
+ // Best-effort: without the sentinel the user just isn't notified.
+ }
+}
+
+function read() {
+ try {
+ const { packs } = JSON.parse(fs.readFileSync(getSentinelPath(), "utf8"));
+ return Array.isArray(packs) && packs.length > 0 ? { packs } : null;
+ } catch {
+ return null;
+ }
+}
+
+function clear() {
+ try {
+ fs.unlinkSync(getSentinelPath());
+ } catch {}
+}
+
+module.exports = { record, read, clear };
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 0ea358b38..fd502e44a 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -607,6 +607,14 @@ class IPCHandlers {
this._recordWhisperGpuFailure("vulkan");
broadcastToWindows("gpu-fallback-notification", {});
});
+ // Persist the discrete-GPU pin so later launches spawn pinned directly
+ // instead of paying a second Vulkan cold start. See #1606.
+ this.whisperManager.serverManager.on("vulkan-device-pinned", ({ index }) => {
+ this._syncStartupEnv({ WHISPER_VULKAN_DEVICE: String(index) });
+ });
+ this.whisperManager.serverManager.on("vulkan-device-pin-cleared", () => {
+ this._syncStartupEnv({}, ["WHISPER_VULKAN_DEVICE"]);
+ });
}
}
@@ -2839,12 +2847,23 @@ class IPCHandlers {
// Stop the server first so the running binary can be deleted on Windows
await this.whisperManager.stopServer().catch(() => {});
const { deletedCount } = await this.whisperVulkanManager.delete();
- this._syncStartupEnv({}, ["WHISPER_VULKAN_ENABLED"]);
+ this._syncStartupEnv({}, ["WHISPER_VULKAN_ENABLED", "WHISPER_VULKAN_DEVICE"]);
this._clearWhisperGpuFailure("vulkan");
this._applyWhisperGpuPreference(reloadModel);
return { success: true, deletedCount };
});
+ // One-time "GPU pack needs re-downloading" notice recorded by the
+ // legacy-layout migration before any window existed. See #1606.
+ ipcMain.handle("get-gpu-pack-migration-notice", () => {
+ return require("./gpuPackMigrationNotice").read();
+ });
+
+ ipcMain.handle("dismiss-gpu-pack-migration-notice", () => {
+ require("./gpuPackMigrationNotice").clear();
+ return { success: true };
+ });
+
// Clears the remembered GPU failure and reloads the server with the GPU
// backend re-enabled (Retry on the "GPU could not be activated" state)
ipcMain.handle("whisper-gpu-retry", async () => {
diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.js
index 78d7948cb..ca8e8746f 100644
--- a/src/helpers/whisperServer.js
+++ b/src/helpers/whisperServer.js
@@ -136,11 +136,21 @@ function buildWhisperServerArgs({
vadEnabled = false,
vadModelPath = null,
vadConfig,
+ gpuDeviceIndex = null,
}) {
const args = ["--model", modelPath, "--host", "127.0.0.1", "--port", String(port)];
if (threads) args.push("--threads", String(threads));
+ // --device counts the logical GPU devices ggml registers, i.e. exactly the
+ // indices whisper-server prints as "ggml_vulkan: N = ...". Do NOT use
+ // GGML_VK_VISIBLE_DEVICES here: it takes raw physical enumeration indices,
+ // which diverge from the printed ones whenever a device is filtered out
+ // (lavapipe, dual-driver dedupe).
+ if (Number.isInteger(gpuDeviceIndex) && gpuDeviceIndex >= 0) {
+ args.push("--device", String(gpuDeviceIndex));
+ }
+
// whisper.cpp defaults to English when --language is omitted;
// explicitly pass "auto" to enable language auto-detection
args.push("--language", language || "auto");
@@ -176,6 +186,43 @@ function buildWhisperServerArgs({
return args;
}
+// ggml-vulkan prints one line per usable device on startup, e.g.
+// "ggml_vulkan: 0 = Intel(R) UHD Graphics 770 (Intel Corporation) | uma: 1 | fp16: 1 | ..."
+// The leading number is the logical index --device selects; uma: 1 marks an
+// integrated (host-memory) device. Format verified against the pinned
+// OpenWhispr/whisper.cpp tag (ggml-vulkan.cpp, ggml_vk_print_gpu_info).
+const VULKAN_DEVICE_LINE = /^ggml_vulkan: (\d+) = (.+?) \((.+?)\) \| uma: ([01]) \|/gm;
+
+function parseVulkanDevices(stderr) {
+ const devices = [];
+ for (const match of String(stderr || "").matchAll(VULKAN_DEVICE_LINE)) {
+ devices.push({
+ index: parseInt(match[1], 10),
+ name: match[2],
+ driver: match[3],
+ uma: parseInt(match[4], 10),
+ });
+ }
+ return devices;
+}
+
+function resolveVulkanPinAction({ devices, appliedPin }) {
+ if (appliedPin != null) {
+ // A persisted pin that no longer resolves to a device (hardware change)
+ // must be dropped, or ggml silently runs on CPU forever.
+ if (devices.length > 0 && appliedPin >= devices.length) return { action: "clear" };
+ return { action: "none" };
+ }
+
+ // ggml defaults to device 0; only intervene when that default is an iGPU
+ // and a discrete device is available. See #1606.
+ if (devices.length >= 2 && devices[0].uma === 1) {
+ const discrete = devices.find((d) => d.uma === 0);
+ if (discrete) return { action: "pin", index: discrete.index };
+ }
+ return { action: "none" };
+}
+
function shouldFallbackToCpuAfterRequestError({
isConnectionError,
useGpu,
@@ -478,6 +525,19 @@ class WhisperServerManager extends EventEmitter {
this.useCuda = usingCuda;
this.useVulkan = usingVulkan;
+ // Pin Vulkan to a specific device: an explicit option wins (set by the
+ // one-shot restart below; -1 means "explicitly unpinned", so the stale env
+ // value must not resurface), else the persisted choice from a prior run.
+ let vulkanDeviceIndex = null;
+ if (usingVulkan) {
+ if (Number.isInteger(options.vulkanDeviceIndex)) {
+ vulkanDeviceIndex = options.vulkanDeviceIndex;
+ } else {
+ const persisted = parseInt(process.env.WHISPER_VULKAN_DEVICE, 10);
+ if (Number.isInteger(persisted) && persisted >= 0) vulkanDeviceIndex = persisted;
+ }
+ }
+
// Check for FFmpeg first - only use --convert flag if FFmpeg is available
const ffmpegPath = this.getFFmpegPath();
const spawnEnv = { ...process.env };
@@ -509,6 +569,7 @@ class WhisperServerManager extends EventEmitter {
vadEnabled: options.vadEnabled === true,
vadModelPath: options.vadModelPath || null,
vadConfig: options.vadConfig,
+ gpuDeviceIndex: vulkanDeviceIndex,
});
// FFmpeg is required for pre-converting audio to 16kHz mono WAV
@@ -527,6 +588,7 @@ class WhisperServerManager extends EventEmitter {
cwd: serverBinaryDir,
cuda: usingCuda,
vulkan: usingVulkan,
+ vulkanDeviceIndex,
threads: threadResolution,
});
@@ -613,6 +675,42 @@ class WhisperServerManager extends EventEmitter {
throw err;
}
+ // One-shot after the server is up: if ggml defaulted to an integrated GPU
+ // while a discrete one is available, restart pinned to the discrete device
+ // (and drop a persisted pin that no longer resolves). vulkanPinChecked
+ // bounds this to a single extra start; if the pinned restart fails, the
+ // catch above falls back to CPU as usual. See #1606.
+ if (usingVulkan && !options.vulkanPinChecked) {
+ const pinAction = resolveVulkanPinAction({
+ devices: parseVulkanDevices(stderrBuffer),
+ appliedPin: vulkanDeviceIndex,
+ });
+ if (pinAction.action === "pin") {
+ debugLogger.info("Vulkan device 0 is integrated; restarting pinned to discrete GPU", {
+ index: pinAction.index,
+ });
+ this.emit("vulkan-device-pinned", { index: pinAction.index });
+ await this.stop();
+ return this._doStart(modelPath, {
+ ...options,
+ vulkanDeviceIndex: pinAction.index,
+ vulkanPinChecked: true,
+ });
+ }
+ if (pinAction.action === "clear") {
+ debugLogger.warn("Persisted Vulkan device pin is out of range; clearing it", {
+ appliedPin: vulkanDeviceIndex,
+ });
+ this.emit("vulkan-device-pin-cleared");
+ await this.stop();
+ return this._doStart(modelPath, {
+ ...options,
+ vulkanDeviceIndex: -1,
+ vulkanPinChecked: true,
+ });
+ }
+ }
+
this.startHealthCheck();
debugLogger.info("whisper-server started successfully", {
@@ -1020,6 +1118,8 @@ class WhisperServerManager extends EventEmitter {
module.exports = WhisperServerManager;
module.exports.buildWhisperServerArgs = buildWhisperServerArgs;
+module.exports.parseVulkanDevices = parseVulkanDevices;
+module.exports.resolveVulkanPinAction = resolveVulkanPinAction;
module.exports.getVadSignature = getVadSignature;
module.exports.resolveWhisperThreads = resolveWhisperThreads;
module.exports.shouldFallbackToCpuAfterRequestError = shouldFallbackToCpuAfterRequestError;
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 4c21c02f5..036fb3356 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -3112,6 +3112,10 @@
"title": "GPU-Beschleunigung nicht verfügbar",
"description": "Die Transkription verwendet stattdessen die CPU. Du kannst die GPU-Beschleunigung in den Einstellungen deaktivieren."
},
+ "gpuPackMigration": {
+ "title": "GPU-Paket muss erneut heruntergeladen werden",
+ "description": "Ein Update hat eine veraltete GPU-Paket-Installation entfernt ({{packs}}). Lade es in den Einstellungen erneut herunter, um die GPU-Beschleunigung wiederherzustellen."
+ },
"cleanupFailed": {
"title": "Bereinigung fehlgeschlagen",
"description": "Dein Diktat wurde ohne KI-Bereinigung eingefügt."
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index c04b7c337..21ffd9cbf 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -3112,6 +3112,10 @@
"title": "GPU acceleration unavailable",
"description": "Transcription is using the CPU instead. You can disable GPU acceleration in Settings."
},
+ "gpuPackMigration": {
+ "title": "GPU pack needs re-downloading",
+ "description": "An update removed an outdated GPU pack installation ({{packs}}). Re-download it in Settings to restore GPU acceleration."
+ },
"cleanupFailed": {
"title": "Cleanup failed",
"description": "Your dictation was pasted without AI cleanup."
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 730048fbb..ae6e8a9e3 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2995,6 +2995,10 @@
"title": "Aceleración GPU no disponible",
"description": "La transcripción está usando la CPU. Puedes desactivar la aceleración GPU en Configuración."
},
+ "gpuPackMigration": {
+ "title": "Es necesario volver a descargar el paquete GPU",
+ "description": "Una actualización eliminó una instalación obsoleta del paquete GPU ({{packs}}). Vuelve a descargarlo en Configuración para restaurar la aceleración GPU."
+ },
"cleanupFailed": {
"title": "Limpieza fallida",
"description": "Tu dictado se pegó sin limpieza con IA."
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 5d8fcaef4..573db0af9 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -3112,6 +3112,10 @@
"title": "Accélération GPU indisponible",
"description": "La transcription utilise le CPU à la place. Vous pouvez désactiver l'accélération GPU dans les paramètres."
},
+ "gpuPackMigration": {
+ "title": "Le pack GPU doit être retéléchargé",
+ "description": "Une mise à jour a supprimé une installation obsolète du pack GPU ({{packs}}). Retéléchargez-le dans les paramètres pour rétablir l'accélération GPU."
+ },
"cleanupFailed": {
"title": "Échec du nettoyage",
"description": "Votre dictée a été collée sans nettoyage par IA."
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 78e5159b1..1b14debb0 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2947,6 +2947,10 @@
"title": "Accelerazione GPU non disponibile",
"description": "La trascrizione sta usando la CPU. Puoi disattivare l'accelerazione GPU nelle Impostazioni."
},
+ "gpuPackMigration": {
+ "title": "Il pacchetto GPU deve essere scaricato di nuovo",
+ "description": "Un aggiornamento ha rimosso un'installazione obsoleta del pacchetto GPU ({{packs}}). Scaricalo di nuovo nelle Impostazioni per ripristinare l'accelerazione GPU."
+ },
"cleanupFailed": {
"title": "Pulizia non riuscita",
"description": "La dettatura è stata incollata senza pulizia IA."
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index da7ec3118..f0787750f 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2947,6 +2947,10 @@
"title": "GPU アクセラレーションを利用できません",
"description": "文字起こしは代わりに CPU を使用しています。設定で GPU アクセラレーションを無効にできます。"
},
+ "gpuPackMigration": {
+ "title": "GPU パックの再ダウンロードが必要です",
+ "description": "アップデートにより古い GPU パックのインストール({{packs}})が削除されました。設定から再ダウンロードすると GPU アクセラレーションが復元されます。"
+ },
"cleanupFailed": {
"title": "クリーンアップに失敗しました",
"description": "ディクテーションは AI クリーンアップなしで貼り付けられました。"
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 9aebae2b5..2b3cd837d 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2947,6 +2947,10 @@
"title": "Aceleração GPU indisponível",
"description": "A transcrição está usando a CPU. Você pode desativar a aceleração GPU nas Configurações."
},
+ "gpuPackMigration": {
+ "title": "O pacote GPU precisa ser baixado novamente",
+ "description": "Uma atualização removeu uma instalação desatualizada do pacote GPU ({{packs}}). Baixe-o novamente nas Configurações para restaurar a aceleração GPU."
+ },
"cleanupFailed": {
"title": "Falha na limpeza",
"description": "Seu ditado foi colado sem limpeza por IA."
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 5495cac81..36b7ada89 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2975,6 +2975,10 @@
"title": "Ускорение GPU недоступно",
"description": "Транскрипция выполняется на CPU. Вы можете отключить ускорение GPU в настройках."
},
+ "gpuPackMigration": {
+ "title": "Требуется повторная загрузка GPU-пакета",
+ "description": "Обновление удалило устаревшую установку GPU-пакета ({{packs}}). Загрузите его заново в настройках, чтобы восстановить ускорение GPU."
+ },
"cleanupFailed": {
"title": "Не удалось выполнить очистку",
"description": "Диктовка вставлена без ИИ-очистки."
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index a5becd859..603487f18 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2947,6 +2947,10 @@
"title": "GPU 加速不可用",
"description": "转录正在使用 CPU。你可以在设置中关闭 GPU 加速。"
},
+ "gpuPackMigration": {
+ "title": "需要重新下载 GPU 加速包",
+ "description": "更新移除了过时的 GPU 加速包安装({{packs}})。请在设置中重新下载以恢复 GPU 加速。"
+ },
"cleanupFailed": {
"title": "清理失败",
"description": "你的听写已直接粘贴,未经 AI 清理。"
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 7627c5577..435b44462 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2947,6 +2947,10 @@
"title": "GPU 加速無法使用",
"description": "轉錄正在使用 CPU。你可以在設定中關閉 GPU 加速。"
},
+ "gpuPackMigration": {
+ "title": "需要重新下載 GPU 加速包",
+ "description": "更新移除了過時的 GPU 加速包安裝({{packs}})。請在設定中重新下載以恢復 GPU 加速。"
+ },
"cleanupFailed": {
"title": "清理失敗",
"description": "你的聽寫已直接貼上,未經 AI 清理。"
diff --git a/src/main.jsx b/src/main.jsx
index e74c492ea..3f4b14187 100644
--- a/src/main.jsx
+++ b/src/main.jsx
@@ -5,6 +5,7 @@ import AppRouter from "./AppRouter.jsx";
import ErrorBoundary from "./components/ErrorBoundary.tsx";
import CleanupFailureToastListener from "./components/CleanupFailureToastListener.tsx";
import TinfoilModelSwitchToastListener from "./components/TinfoilModelSwitchToastListener.tsx";
+import GpuPackMigrationToastListener from "./components/GpuPackMigrationToastListener.tsx";
import { ToastProvider } from "./components/ui/Toast.tsx";
import { SettingsProvider } from "./hooks/useSettings";
@@ -20,6 +21,7 @@ root.render(
<ToastProvider>
<TinfoilModelSwitchToastListener />
<CleanupFailureToastListener />
+ <GpuPackMigrationToastListener />
<AppRouter />
</ToastProvider>
</SettingsProvider>
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 20e5061c4..887815c7a 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1342,6 +1342,10 @@ declare global {
) => () => void;
onGpuFallbackNotification: (callback: () => void) => () => void;
+ // One-time "GPU pack needs re-downloading" notice from the legacy-layout migration
+ getGpuPackMigrationNotice: () => Promise<{ packs: string[] } | null>;
+ dismissGpuPackMigrationNotice: () => Promise<{ success: boolean }>;
+
// Parakeet operations (NVIDIA via sherpa-onnx)
transcribeLocalParakeet: (
audioBlob: ArrayBuffer,
diff --git a/src/utils/gpuDetection.js b/src/utils/gpuDetection.js
index 22ffeb873..00cccf0c8 100644
--- a/src/utils/gpuDetection.js
+++ b/src/utils/gpuDetection.js
@@ -1,4 +1,7 @@
const { execFile } = require("child_process");
+const fs = require("fs");
+const path = require("path");
+const debugLogger = require("../helpers/debugLogger");
// The shipped CUDA whisper build (release 0.0.9) carries kernels for Pascal
// (compute capability 6.1) and newer; 6.1's embedded PTX also covers Volta via
@@ -10,18 +13,73 @@ const { execFile } = require("child_process");
const MIN_CUDA_COMPUTE_CAP = 6.1;
let cachedGpuInfo = null;
+let cachedGpuList = null;
+let cachedSmiPath; // undefined = unresolved, null = no nvidia-smi anywhere
+
+function clearCache() {
+ cachedGpuInfo = null;
+ cachedGpuList = null;
+ cachedSmiPath = undefined;
+}
-function queryNvidiaSmi(fields) {
+function runNvidiaSmi(smiPath, fields, execFileImpl) {
return new Promise((resolve) => {
- execFile(
- "nvidia-smi",
+ execFileImpl(
+ smiPath,
["--query-gpu=" + fields, "--format=csv,noheader,nounits"],
{ timeout: 5000, windowsHide: true },
- (error, stdout) => resolve(error || !stdout ? null : stdout)
+ (error, stdout) => resolve({ error, stdout: stdout || "" })
);
});
}
+// DCH/Windows-Update driver installs don't reliably put nvidia-smi on PATH —
+// some ship it only in System32, some only inside the DriverStore, and nothing
+// a user runs day-to-day (games, CUDA apps) ever needs it, so only detection
+// notices. Climb the ladder once and cache the answer. See #1606.
+async function resolveNvidiaSmiPath({ execFileImpl = execFile, fsImpl = fs } = {}) {
+ if (cachedSmiPath !== undefined) return cachedSmiPath;
+
+ // A probe error other than ENOENT (timeout, driver refusing the query)
+ // still proves the binary exists, so the rung is kept.
+ const probe = await runNvidiaSmi("nvidia-smi", "name", execFileImpl);
+ if (probe.error?.code !== "ENOENT") {
+ cachedSmiPath = { smiPath: "nvidia-smi", source: "path" };
+ return cachedSmiPath;
+ }
+
+ if (process.platform === "win32") {
+ debugLogger.debug("nvidia-smi not on PATH, trying System32", { error: probe.error.message });
+ const system32 = path.join(process.env.SystemRoot || "C:\\Windows", "System32");
+ const system32Smi = path.join(system32, "nvidia-smi.exe");
+ if (fsImpl.existsSync(system32Smi)) {
+ cachedSmiPath = { smiPath: system32Smi, source: "system32" };
+ return cachedSmiPath;
+ }
+
+ try {
+ const repository = path.join(system32, "DriverStore", "FileRepository");
+ const candidates = fsImpl
+ .readdirSync(repository)
+ .filter((dir) => /^nv/i.test(dir))
+ .map((dir) => path.join(repository, dir, "nvidia-smi.exe"))
+ .filter((candidate) => fsImpl.existsSync(candidate));
+ if (candidates.length > 0) {
+ // Several driver generations can coexist; the newest copy is the
+ // one belonging to the currently installed driver.
+ candidates.sort((a, b) => fsImpl.statSync(b).mtimeMs - fsImpl.statSync(a).mtimeMs);
+ cachedSmiPath = { smiPath: candidates[0], source: "driverstore" };
+ return cachedSmiPath;
+ }
+ } catch (error) {
+ debugLogger.debug("DriverStore scan for nvidia-smi failed", { error: error.message });
+ }
+ }
+
+ cachedSmiPath = null;
+ return cachedSmiPath;
+}
+
function parseNvidiaSmiGpuInfo(stdout) {
const parts = stdout
.trim()
@@ -41,7 +99,45 @@ function parseNvidiaSmiGpuInfo(stdout) {
};
}
-async function detectNvidiaGpu() {
+function parseWmiVideoControllers(stdout) {
+ return (
+ String(stdout || "")
+ .split("\n")
+ .map((line) => line.trim())
+ .find((line) => /NVIDIA|GeForce|Quadro|Tesla/i.test(line)) || null
+ );
+}
+
+// WMI gives a name but no compute capability, so gate the CUDA pack on
+// families that provably sit at or above MIN_CUDA_COMPUTE_CAP: RTX-branded
+// cards (Turing+), GTX 10xx (Pascal, the exact floor), GTX 16xx (Turing),
+// and the post-Maxwell TITANs. A false negative just gets the Vulkan pack;
+// a false positive would crash every transcription at the first kernel
+// launch, so anything unproven stays out.
+function isCudaCapableGpuName(name) {
+ return /\bRTX\b|\bGTX 10\d\d\b|\bGTX 16\d\d\b|\bTITAN (Xp|V|RTX)\b/i.test(String(name || ""));
+}
+
+// Last resort when no nvidia-smi exists at all: ask WMI for the display
+// adapters. Works with zero NVIDIA tooling installed. wmic is gone from
+// Windows 11, so go through PowerShell's CIM cmdlet.
+function queryWmiVideoControllers(execFileImpl) {
+ return new Promise((resolve) => {
+ execFileImpl(
+ "powershell.exe",
+ [
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "Get-CimInstance Win32_VideoController | Select-Object -ExpandProperty Name",
+ ],
+ { timeout: 15000, windowsHide: true },
+ (error, stdout) => resolve({ error, stdout: stdout || "" })
+ );
+ });
+}
+
+async function detectNvidiaGpu(deps = {}) {
if (cachedGpuInfo) return cachedGpuInfo;
if (process.platform === "darwin") {
@@ -49,58 +145,115 @@ async function detectNvidiaGpu() {
return cachedGpuInfo;
}
- let stdout = await queryNvidiaSmi("name,driver_version,memory.total,compute_cap");
- if (stdout === null) {
- // Drivers too old to answer the compute_cap query (pre-R470) also predate
- // the CUDA 12 runtime the pack ships with, so cudaSupported stays false.
- stdout = await queryNvidiaSmi("name,driver_version,memory.total");
+ const execFileImpl = deps.execFileImpl || execFile;
+ const resolved = await resolveNvidiaSmiPath(deps);
+ if (resolved) {
+ let { error, stdout } = await runNvidiaSmi(
+ resolved.smiPath,
+ "name,driver_version,memory.total,compute_cap",
+ execFileImpl
+ );
+ if (error || !stdout) {
+ // Drivers too old to answer the compute_cap query (pre-R470) also predate
+ // the CUDA 12 runtime the pack ships with, so cudaSupported stays false.
+ ({ error, stdout } = await runNvidiaSmi(
+ resolved.smiPath,
+ "name,driver_version,memory.total",
+ execFileImpl
+ ));
+ }
+ if (!error && stdout) {
+ cachedGpuInfo = parseNvidiaSmiGpuInfo(stdout);
+ debugLogger.info("NVIDIA GPU detection via nvidia-smi", {
+ source: resolved.source,
+ hasNvidiaGpu: cachedGpuInfo.hasNvidiaGpu,
+ cudaSupported: cachedGpuInfo.cudaSupported,
+ });
+ return cachedGpuInfo;
+ }
+ debugLogger.warn("nvidia-smi found but its queries failed", {
+ source: resolved.source,
+ error: error ? error.message : "empty output",
+ });
}
- cachedGpuInfo = stdout === null ? { hasNvidiaGpu: false } : parseNvidiaSmiGpuInfo(stdout);
+ if (process.platform === "win32") {
+ const wmi = await queryWmiVideoControllers(execFileImpl);
+ const gpuName = wmi.error ? null : parseWmiVideoControllers(wmi.stdout);
+ if (gpuName) {
+ cachedGpuInfo = {
+ hasNvidiaGpu: true,
+ gpuName,
+ cudaSupported: isCudaCapableGpuName(gpuName),
+ detectionSource: "wmi",
+ };
+ debugLogger.info("NVIDIA GPU detected via WMI (no nvidia-smi available)", cachedGpuInfo);
+ return cachedGpuInfo;
+ }
+ if (wmi.error) {
+ debugLogger.warn("WMI video controller query failed", { error: wmi.error.message });
+ }
+ }
+
+ cachedGpuInfo = { hasNvidiaGpu: false };
return cachedGpuInfo;
}
-let cachedGpuList = null;
-
-function listNvidiaGpus() {
- if (cachedGpuList) return Promise.resolve(cachedGpuList);
+async function listNvidiaGpus(deps = {}) {
+ if (cachedGpuList) return cachedGpuList;
if (process.platform === "darwin") {
cachedGpuList = [];
- return Promise.resolve(cachedGpuList);
+ return cachedGpuList;
}
- return new Promise((resolve) => {
- execFile(
- "nvidia-smi",
- ["--query-gpu=index,uuid,name,memory.total", "--format=csv,noheader,nounits"],
- { timeout: 5000, windowsHide: true },
- (error, stdout) => {
- if (error || !stdout) {
- cachedGpuList = [];
- resolve(cachedGpuList);
- return;
- }
-
- const gpus = stdout
- .trim()
- .split("\n")
- .map((line) => {
- const parts = line.split(",").map((s) => s.trim());
- return {
- index: parseInt(parts[0], 10),
- uuid: parts[1] || "",
- name: parts[2] || "Unknown GPU",
- vramMb: parseInt(parts[3], 10) || 0,
- };
- })
- .filter((g) => !isNaN(g.index));
-
- if (gpus.length > 0) cachedGpuList = gpus;
- resolve(gpus);
- }
- );
- });
+ // WMI can't supply UUIDs, so on machines where the whole nvidia-smi ladder
+ // misses the per-GPU picker simply has no choices to offer.
+ const resolved = await resolveNvidiaSmiPath(deps);
+ if (!resolved) {
+ cachedGpuList = [];
+ return cachedGpuList;
+ }
+
+ const { error, stdout } = await runNvidiaSmi(
+ resolved.smiPath,
+ "index,uuid,name,memory.total",
+ deps.execFileImpl || execFile
+ );
+ if (error || !stdout) {
+ debugLogger.debug("nvidia-smi GPU list query failed", {
+ source: resolved.source,
+ error: error ? error.message : "empty output",
+ });
+ cachedGpuList = [];
+ return cachedGpuList;
+ }
+
+ const gpus = stdout
+ .trim()
+ .split("\n")
+ .map((line) => {
+ const parts = line.split(",").map((s) => s.trim());
+ return {
+ index: parseInt(parts[0], 10),
+ uuid: parts[1] || "",
+ name: parts[2] || "Unknown GPU",
+ vramMb: parseInt(parts[3], 10) || 0,
+ };
+ })
+ .filter((g) => !isNaN(g.index));
+
+ if (gpus.length > 0) cachedGpuList = gpus;
+ return gpus;
}
-module.exports = { detectNvidiaGpu, listNvidiaGpus, parseNvidiaSmiGpuInfo, MIN_CUDA_COMPUTE_CAP };
+module.exports = {
+ detectNvidiaGpu,
+ listNvidiaGpus,
+ resolveNvidiaSmiPath,
+ parseNvidiaSmiGpuInfo,
+ parseWmiVideoControllers,
+ isCudaCapableGpuName,
+ clearCache,
+ MIN_CUDA_COMPUTE_CAP,
+};
diff --git a/test/helpers/gpuBinaryManager.test.js b/test/helpers/gpuBinaryManager.test.js
index 6267fc257..f869da76c 100644
--- a/test/helpers/gpuBinaryManager.test.js
+++ b/test/helpers/gpuBinaryManager.test.js
@@ -406,7 +406,7 @@ test("legacy migration: lib-free pack is moved, lib-carrying packs are cleared f
const cuda = new WhisperCudaManager();
const vulkan = new WhisperVulkanManager();
const llama = new LlamaVulkanManager();
- migrateLegacyBinDir([cuda, vulkan, llama]);
+ const clearedPacks = migrateLegacyBinDir([cuda, vulkan, llama]);
assert.equal(vulkan.isDownloaded(), true, "statically-linked pack migrated in place");
assert.ok(fs.existsSync(path.join(binRoot, "whisper-vulkan", "whisper-server-linux-x64-vulkan")));
@@ -417,9 +417,14 @@ test("legacy migration: lib-free pack is moved, lib-carrying packs are cleared f
["whisper-vulkan"],
"legacy binaries and orphaned libs removed"
);
+ assert.deepEqual(
+ clearedPacks,
+ ["CUDA whisper", "Vulkan llama"],
+ "cleared (not migrated) packs are reported for the re-download notice"
+ );
- // Idempotent on the healed layout
- migrateLegacyBinDir([cuda, vulkan, llama]);
+ // Idempotent on the healed layout — and nothing left to report
+ assert.deepEqual(migrateLegacyBinDir([cuda, vulkan, llama]), []);
assert.equal(vulkan.isDownloaded(), true);
});
diff --git a/test/helpers/gpuDetection.test.js b/test/helpers/gpuDetection.test.js
index 284c9d8e6..92df13d3b 100644
--- a/test/helpers/gpuDetection.test.js
+++ b/test/helpers/gpuDetection.test.js
@@ -1,7 +1,12 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const { parseNvidiaSmiGpuInfo, MIN_CUDA_COMPUTE_CAP } = require("../../src/utils/gpuDetection.js");
+const {
+ parseNvidiaSmiGpuInfo,
+ parseWmiVideoControllers,
+ isCudaCapableGpuName,
+ MIN_CUDA_COMPUTE_CAP,
+} = require("../../src/utils/gpuDetection.js");
// The CUDA pack must only be offered to cards its build actually carries
// kernels for. A Pascal card passing this gate cost two days of debugging
@@ -62,3 +67,45 @@ test("multi-GPU output uses the primary card", () => {
test("garbage output is not an NVIDIA GPU", () => {
assert.deepEqual(parseNvidiaSmiGpuInfo("command not found"), { hasNvidiaGpu: false });
});
+
+test("parseWmiVideoControllers picks the NVIDIA adapter out of a multi-GPU list", () => {
+ // The #1606 reporter's three adapters, as PowerShell prints them
+ const stdout = "AMD Radeon RX 7900 XTX\r\nNVIDIA GeForce RTX 4060 Ti\r\nIntel(R) UHD Graphics 770\r\n";
+ assert.equal(parseWmiVideoControllers(stdout), "NVIDIA GeForce RTX 4060 Ti");
+});
+
+test("parseWmiVideoControllers returns null when no NVIDIA adapter is present", () => {
+ assert.equal(parseWmiVideoControllers("AMD Radeon RX 7900 XTX\r\nIntel(R) UHD Graphics 770\r\n"), null);
+ assert.equal(parseWmiVideoControllers(""), null);
+});
+
+// The WMI rung has no compute capability to gate on, so only names that
+// provably sit at or above the kernel floor may pass.
+test("isCudaCapableGpuName accepts families provably at or above the floor", () => {
+ for (const name of [
+ "NVIDIA GeForce RTX 4060 Ti",
+ "Quadro RTX 4000",
+ "NVIDIA TITAN RTX",
+ "NVIDIA GeForce GTX 1080 Ti",
+ "NVIDIA GeForce GTX 1660 SUPER",
+ "NVIDIA TITAN Xp",
+ "NVIDIA TITAN V",
+ ]) {
+ assert.equal(isCudaCapableGpuName(name), true, name);
+ }
+});
+
+test("isCudaCapableGpuName rejects unproven and non-NVIDIA names", () => {
+ for (const name of [
+ "NVIDIA GeForce GTX 970",
+ "NVIDIA GeForce GTX 980 Ti",
+ "NVIDIA TITAN X", // Maxwell — not the Pascal "TITAN Xp"
+ "Quadro M4000",
+ "AMD Radeon RX 7900 XTX",
+ "Intel(R) UHD Graphics 770",
+ "",
+ null,
+ ]) {
+ assert.equal(isCudaCapableGpuName(name), false, String(name));
+ }
+});
diff --git a/test/helpers/gpuPackMigrationNotice.test.js b/test/helpers/gpuPackMigrationNotice.test.js
new file mode 100644
index 000000000..52ecd91dc
--- /dev/null
+++ b/test/helpers/gpuPackMigrationNotice.test.js
@@ -0,0 +1,47 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("fs");
+const os = require("os");
+const path = require("path");
+
+// Runs outside Electron: stub the app userData path before loading the module.
+let userDataDir = null;
+
+require.cache[require.resolve("electron")] = {
+ exports: { app: { getPath: () => userDataDir } },
+};
+
+const notice = require("../../src/helpers/gpuPackMigrationNotice.js");
+
+test.beforeEach(() => {
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "gpu-notice-test-"));
+});
+
+test.afterEach(() => {
+ fs.rmSync(userDataDir, { recursive: true, force: true });
+});
+
+test("record/read/clear round-trip", () => {
+ assert.equal(notice.read(), null);
+
+ notice.record(["CUDA whisper", "Vulkan llama"]);
+ assert.deepEqual(notice.read(), { packs: ["CUDA whisper", "Vulkan llama"] });
+
+ notice.clear();
+ assert.equal(notice.read(), null);
+});
+
+test("recording again merges and dedupes instead of overwriting", () => {
+ notice.record(["CUDA whisper"]);
+ notice.record(["CUDA whisper", "Vulkan llama"]);
+
+ assert.deepEqual(notice.read(), { packs: ["CUDA whisper", "Vulkan llama"] });
+});
+
+test("empty recordings and corrupt sentinels read as no notice", () => {
+ notice.record([]);
+ assert.equal(notice.read(), null);
+
+ fs.writeFileSync(path.join(userDataDir, ".gpu-pack-migration-notice"), "not json");
+ assert.equal(notice.read(), null);
+});
diff --git a/test/helpers/whisperServerVadArgs.test.js b/test/helpers/whisperServerVadArgs.test.js
index 35b6fd4b6..3843048d9 100644
--- a/test/helpers/whisperServerVadArgs.test.js
+++ b/test/helpers/whisperServerVadArgs.test.js
@@ -91,6 +91,30 @@ test("buildWhisperServerArgs includes thread count when provided", () => {
]);
});
+test("buildWhisperServerArgs pins the GPU device when an index is given", () => {
+ const args = WhisperServerManager.buildWhisperServerArgs({
+ modelPath: "/tmp/model.bin",
+ port: 8180,
+ language: "auto",
+ gpuDeviceIndex: 1,
+ });
+
+ assert.deepEqual(args.slice(6, 8), ["--device", "1"]);
+});
+
+test("buildWhisperServerArgs omits --device by default and for unpinned sentinels", () => {
+ for (const gpuDeviceIndex of [undefined, null, -1]) {
+ const args = WhisperServerManager.buildWhisperServerArgs({
+ modelPath: "/tmp/model.bin",
+ port: 8180,
+ language: "auto",
+ gpuDeviceIndex,
+ });
+
+ assert.equal(args.includes("--device"), false);
+ }
+});
+
test("resolveWhisperThreads keeps whisper.cpp default on small machines", () => {
const result = WhisperServerManager.resolveWhisperThreads(
{},
diff --git a/test/helpers/whisperVulkanDevicePin.test.js b/test/helpers/whisperVulkanDevicePin.test.js
new file mode 100644
index 000000000..62cc4eba6
--- /dev/null
+++ b/test/helpers/whisperVulkanDevicePin.test.js
@@ -0,0 +1,79 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ parseVulkanDevices,
+ resolveVulkanPinAction,
+} = require("../../src/helpers/whisperServer");
+
+// Shape taken from the reporter's 1.8.3 debug log on issue #1606 (whisper.cpp
+// GPU pack 0.0.9), with surrounding server noise included on purpose.
+const IGPU_FIRST_STDERR = [
+ "whisper_init_from_file_with_params_no_state: loading model from '/tmp/ggml-base.bin'",
+ "ggml_vulkan: Found 3 Vulkan devices:",
+ "ggml_vulkan: 0 = Intel(R) UHD Graphics 770 (Intel Corporation) | uma: 1 | fp16: 1 | bf16: 0 | warp size: 32 | shared memory: 32768 | int dot: 1 | matrix cores: none",
+ "ggml_vulkan: 1 = NVIDIA GeForce RTX 4060 Ti (NVIDIA) | uma: 0 | fp16: 1 | bf16: 0 | warp size: 32 | shared memory: 49152 | int dot: 1 | matrix cores: KHR_coopmat",
+ "ggml_vulkan: 2 = AMD Radeon RX 7900 XTX (AMD proprietary driver) | uma: 0 | fp16: 1 | bf16: 0 | warp size: 64 | shared memory: 32768 | int dot: 1 | matrix cores: KHR_coopmat",
+ "whisper_backend_init_gpu: using Vulkan0 backend",
+].join("\n");
+
+test("parseVulkanDevices reads index, name, driver, and uma from device lines", () => {
+ const devices = parseVulkanDevices(IGPU_FIRST_STDERR);
+
+ assert.deepEqual(devices, [
+ { index: 0, name: "Intel(R) UHD Graphics 770", driver: "Intel Corporation", uma: 1 },
+ { index: 1, name: "NVIDIA GeForce RTX 4060 Ti", driver: "NVIDIA", uma: 0 },
+ { index: 2, name: "AMD Radeon RX 7900 XTX", driver: "AMD proprietary driver", uma: 0 },
+ ]);
+});
+
+test("parseVulkanDevices returns [] on CUDA/CPU stderr or an empty buffer", () => {
+ assert.deepEqual(parseVulkanDevices("whisper_init: using CUDA0 backend"), []);
+ assert.deepEqual(parseVulkanDevices(""), []);
+ assert.deepEqual(parseVulkanDevices(undefined), []);
+});
+
+test("resolveVulkanPinAction pins the first discrete device when an iGPU is device 0", () => {
+ const devices = parseVulkanDevices(IGPU_FIRST_STDERR);
+
+ assert.deepEqual(resolveVulkanPinAction({ devices, appliedPin: null }), {
+ action: "pin",
+ index: 1,
+ });
+});
+
+test("resolveVulkanPinAction leaves discrete-first, single-device, and all-UMA setups alone", () => {
+ const discreteFirst = [
+ { index: 0, name: "RTX 4090", driver: "NVIDIA", uma: 0 },
+ { index: 1, name: "Intel UHD", driver: "Intel", uma: 1 },
+ ];
+ const single = [{ index: 0, name: "Intel UHD", driver: "Intel", uma: 1 }];
+ const allUma = [
+ { index: 0, name: "Intel UHD", driver: "Intel", uma: 1 },
+ { index: 1, name: "AMD Radeon 780M", driver: "AMD", uma: 1 },
+ ];
+
+ for (const devices of [discreteFirst, single, allUma, []]) {
+ assert.deepEqual(resolveVulkanPinAction({ devices, appliedPin: null }), { action: "none" });
+ }
+});
+
+test("resolveVulkanPinAction clears a persisted pin that no longer resolves", () => {
+ const devices = [
+ { index: 0, name: "Intel UHD", driver: "Intel", uma: 1 },
+ { index: 1, name: "RTX 4060 Ti", driver: "NVIDIA", uma: 0 },
+ ];
+
+ assert.deepEqual(resolveVulkanPinAction({ devices, appliedPin: 5 }), { action: "clear" });
+});
+
+test("resolveVulkanPinAction keeps a valid applied pin, even on unparseable stderr", () => {
+ const devices = [
+ { index: 0, name: "Intel UHD", driver: "Intel", uma: 1 },
+ { index: 1, name: "RTX 4060 Ti", driver: "NVIDIA", uma: 0 },
+ ];
+
+ assert.deepEqual(resolveVulkanPinAction({ devices, appliedPin: 1 }), { action: "none" });
+ // Format drift → no devices parsed → never clear a working pin blindly
+ assert.deepEqual(resolveVulkanPinAction({ devices: [], appliedPin: 1 }), { action: "none" });
+});
diff --git a/test/utils/gpuDetectionLadder.test.js b/test/utils/gpuDetectionLadder.test.js
new file mode 100644
index 000000000..b5e2a3ad9
--- /dev/null
+++ b/test/utils/gpuDetectionLadder.test.js
@@ -0,0 +1,150 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const path = require("path");
+
+const {
+ detectNvidiaGpu,
+ listNvidiaGpus,
+ resolveNvidiaSmiPath,
+ clearCache,
+} = require("../../src/utils/gpuDetection.js");
+
+// The ladder's System32/DriverStore/WMI rungs are win32-only; pin the platform
+// the way gpuBinaryManager.test.js does. Each test file runs in its own
+// process, but restore anyway.
+const realPlatform = process.platform;
+Object.defineProperty(process, "platform", { value: "win32" });
+test.after(() => Object.defineProperty(process, "platform", { value: realPlatform }));
+test.beforeEach(() => clearCache());
+
+const SYSTEM32 = path.join(process.env.SystemRoot || "C:\\Windows", "System32");
+const SYSTEM32_SMI = path.join(SYSTEM32, "nvidia-smi.exe");
+const REPOSITORY = path.join(SYSTEM32, "DriverStore", "FileRepository");
+
+const RTX_ROW = "NVIDIA GeForce RTX 4060 Ti, 555.85, 16380, 8.9\n";
+
+function enoent(command) {
+ const error = new Error(`spawn ${command} ENOENT`);
+ error.code = "ENOENT";
+ return error;
+}
+
+// handlers: (file, args) => { error?, stdout? }; every call is recorded
+function fakeExecFile(handlers, calls = []) {
+ const impl = (file, args, options, callback) => {
+ calls.push({ file, args, options });
+ const result = handlers(file, args) || {};
+ process.nextTick(() => callback(result.error || null, result.stdout || ""));
+ };
+ impl.calls = calls;
+ return impl;
+}
+
+function fakeFs({ existing = [], driverStoreDirs = null, mtimes = {} } = {}) {
+ return {
+ existsSync: (p) => existing.includes(p),
+ readdirSync: (p) => {
+ if (p === REPOSITORY && driverStoreDirs) return driverStoreDirs;
+ throw enoent(p);
+ },
+ statSync: (p) => ({ mtimeMs: mtimes[p] || 0 }),
+ };
+}
+
+test("nvidia-smi on PATH wins the ladder and answers detection", async () => {
+ const execFileImpl = fakeExecFile((file) => {
+ assert.equal(file, "nvidia-smi");
+ return { stdout: RTX_ROW };
+ });
+
+ const info = await detectNvidiaGpu({ execFileImpl, fsImpl: fakeFs() });
+ assert.equal(info.hasNvidiaGpu, true);
+ assert.equal(info.cudaSupported, true);
+ assert.equal(info.gpuName, "NVIDIA GeForce RTX 4060 Ti");
+});
+
+test("PATH miss falls back to the System32 copy", async () => {
+ const execFileImpl = fakeExecFile((file) =>
+ file === "nvidia-smi" ? { error: enoent("nvidia-smi") } : { stdout: RTX_ROW }
+ );
+
+ const resolved = await resolveNvidiaSmiPath({
+ execFileImpl,
+ fsImpl: fakeFs({ existing: [SYSTEM32_SMI] }),
+ });
+ assert.deepEqual(resolved, { smiPath: SYSTEM32_SMI, source: "system32" });
+});
+
+test("System32 miss falls back to the newest DriverStore copy", async () => {
+ const older = path.join(REPOSITORY, "nvmdi.inf_amd64_111", "nvidia-smi.exe");
+ const newer = path.join(REPOSITORY, "nvmdi.inf_amd64_222", "nvidia-smi.exe");
+ const execFileImpl = fakeExecFile((file) =>
+ file === "nvidia-smi" ? { error: enoent("nvidia-smi") } : { stdout: RTX_ROW }
+ );
+
+ const resolved = await resolveNvidiaSmiPath({
+ execFileImpl,
+ fsImpl: fakeFs({
+ existing: [older, newer],
+ driverStoreDirs: ["nvmdi.inf_amd64_111", "nvmdi.inf_amd64_222", "intelgpu.inf_amd64_1"],
+ mtimes: { [older]: 1000, [newer]: 2000 },
+ }),
+ });
+ assert.deepEqual(resolved, { smiPath: newer, source: "driverstore" });
+});
+
+test("with no nvidia-smi anywhere, WMI still detects the NVIDIA GPU", async () => {
+ const execFileImpl = fakeExecFile((file) => {
+ if (file === "nvidia-smi") return { error: enoent("nvidia-smi") };
+ assert.equal(file, "powershell.exe");
+ return { stdout: "AMD Radeon RX 7900 XTX\r\nNVIDIA GeForce RTX 4060 Ti\r\nIntel(R) UHD Graphics 770\r\n" };
+ });
+
+ const info = await detectNvidiaGpu({ execFileImpl, fsImpl: fakeFs() });
+ assert.deepEqual(info, {
+ hasNvidiaGpu: true,
+ gpuName: "NVIDIA GeForce RTX 4060 Ti",
+ cudaSupported: true,
+ detectionSource: "wmi",
+ });
+});
+
+test("when every rung misses there is no NVIDIA GPU", async () => {
+ const execFileImpl = fakeExecFile((file) =>
+ file === "nvidia-smi"
+ ? { error: enoent("nvidia-smi") }
+ : { stdout: "Intel(R) UHD Graphics 770\r\n" }
+ );
+
+ const info = await detectNvidiaGpu({ execFileImpl, fsImpl: fakeFs() });
+ assert.deepEqual(info, { hasNvidiaGpu: false });
+});
+
+test("detection results and the resolved path are cached", async () => {
+ const execFileImpl = fakeExecFile(() => ({ stdout: RTX_ROW }));
+
+ await detectNvidiaGpu({ execFileImpl, fsImpl: fakeFs() });
+ const callsAfterFirst = execFileImpl.calls.length;
+ const again = await detectNvidiaGpu({ execFileImpl, fsImpl: fakeFs() });
+
+ assert.equal(again.hasNvidiaGpu, true);
+ assert.equal(execFileImpl.calls.length, callsAfterFirst);
+});
+
+test("listNvidiaGpus uses the resolved path and stays empty on WMI-only machines", async () => {
+ const withSmi = fakeExecFile((file) =>
+ file === "nvidia-smi"
+ ? { stdout: "0, GPU-abc123, NVIDIA GeForce RTX 4060 Ti, 16380\n" }
+ : {}
+ );
+ const gpus = await listNvidiaGpus({ execFileImpl: withSmi, fsImpl: fakeFs() });
+ assert.deepEqual(gpus, [
+ { index: 0, uuid: "GPU-abc123", name: "NVIDIA GeForce RTX 4060 Ti", vramMb: 16380 },
+ ]);
+
+ clearCache();
+ const withoutSmi = fakeExecFile((file) =>
+ file === "nvidia-smi" ? { error: enoent("nvidia-smi") } : { stdout: "NVIDIA GeForce RTX 4060 Ti\r\n" }
+ );
+ assert.deepEqual(await listNvidiaGpus({ execFileImpl: withoutSmi, fsImpl: fakeFs() }), []);
+});
diff --git a/test/utils/gpuDetectionWindowsHide.test.js b/test/utils/gpuDetectionWindowsHide.test.js
index 1169bbbb0..9b848e165 100644
--- a/test/utils/gpuDetectionWindowsHide.test.js
+++ b/test/utils/gpuDetectionWindowsHide.test.js
@@ -3,8 +3,14 @@ const assert = require("node:assert/strict");
const fs = require("fs");
const path = require("path");
-test("nvidia-smi GPU probes set windowsHide", () => {
+// Every child process gpuDetection spawns (nvidia-smi rungs, the PowerShell
+// WMI fallback) must set windowsHide, or a console window flashes on Windows.
+// All spawns go through the injectable execFileImpl, so the invariant is:
+// each execFileImpl call site carries windowsHide: true in its options.
+test("every GPU probe spawn sets windowsHide", () => {
const src = fs.readFileSync(path.join(__dirname, "../../src/utils/gpuDetection.js"), "utf8");
- const hidden = src.match(/execFile\(\s*"nvidia-smi"[^{}]*\{[^{}]*windowsHide: true/g) || [];
- assert.equal(hidden.length, 2);
+ const spawnSites = src.match(/execFileImpl\(/g) || [];
+ const hidden = src.match(/windowsHide: true/g) || [];
+ assert.ok(spawnSites.length > 0, "expected execFileImpl call sites in gpuDetection.js");
+ assert.equal(hidden.length, spawnSites.length);
});