Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat: CUDA GPU acceleration for local Whisper transcription (#314)
Gabriel Steind108e00592be
diff --git a/main.js b/main.jsindex 917ee200b..1481d86c7 100644--- a/main.js+++ b/main.js@@ -160,6 +160,7 @@ const UpdateManager = require("./src/updater");const GlobeKeyManager = require("./src/helpers/globeKeyManager");const DevServerManager = require("./src/helpers/devServerManager");const WindowsKeyManager = require("./src/helpers/windowsKeyManager");+const WhisperCudaManager = require("./src/helpers/whisperCudaManager");const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");// Manager instances - initialized after app.whenReady()@@ -175,6 +176,7 @@ let trayManager = null;let updateManager = null;let globeKeyManager = null;let windowsKeyManager = null;+let whisperCudaManager = null;let globeKeyAlertShown = false;let authBridgeServer = null;@@ -233,6 +235,9 @@ function initializeCoreManagers() {databaseManager = new DatabaseManager();clipboardManager = new ClipboardManager();whisperManager = new WhisperManager();+ if (process.platform !== "darwin") {+ whisperCudaManager = new WhisperCudaManager();+ }parakeetManager = new ParakeetManager();updateManager = new UpdateManager();windowsKeyManager = new WindowsKeyManager();@@ -247,6 +252,7 @@ function initializeCoreManagers() {windowManager,updateManager,windowsKeyManager,+ whisperCudaManager,getTrayManager: () => trayManager,});}@@ -327,7 +333,6 @@ function navigateControlPanelWithVerifier(verifier) {windowManager.controlPanelWindow.focus();}-function handleOAuthDeepLink(deepLinkUrl) {try {const parsed = new URL(deepLinkUrl);@@ -484,6 +489,7 @@ async function startApp() {const whisperSettings = {localTranscriptionProvider: process.env.LOCAL_TRANSCRIPTION_PROVIDER || "",whisperModel: process.env.LOCAL_WHISPER_MODEL,+ useCuda: process.env.WHISPER_CUDA_ENABLED === "true" && whisperCudaManager?.isDownloaded(),};whisperManager.initializeAtStartup(whisperSettings).catch((err) => {debugLogger.debug("Whisper startup init error (non-fatal)", { error: err.message });diff --git a/preload.js b/preload.jsindex 9bb9caf5b..aa002f517 100644--- a/preload.js+++ b/preload.js@@ -41,9 +41,18 @@ contextBridge.exposeInMainWorld("electronAPI", {// Note functionssaveNote: (title, content, noteType, sourceFile, audioDuration, folderId) =>- ipcRenderer.invoke("db-save-note", title, content, noteType, sourceFile, audioDuration, folderId),+ ipcRenderer.invoke(+ "db-save-note",+ title,+ content,+ noteType,+ sourceFile,+ audioDuration,+ folderId+ ),getNote: (id) => ipcRenderer.invoke("db-get-note", id),- getNotes: (noteType, limit, folderId) => ipcRenderer.invoke("db-get-notes", noteType, limit, folderId),+ getNotes: (noteType, limit, folderId) =>+ ipcRenderer.invoke("db-get-notes", noteType, limit, folderId),updateNote: (id, updates) => ipcRenderer.invoke("db-update-note", id, updates),deleteNote: (id) => ipcRenderer.invoke("db-delete-note", id),exportNote: (noteId, format) => ipcRenderer.invoke("export-note", noteId, format),@@ -147,6 +156,21 @@ contextBridge.exposeInMainWorld("electronAPI", {whisperServerStop: () => ipcRenderer.invoke("whisper-server-stop"),whisperServerStatus: () => ipcRenderer.invoke("whisper-server-status"),+ // CUDA GPU acceleration+ detectGpu: () => ipcRenderer.invoke("detect-gpu"),+ getCudaWhisperStatus: () => ipcRenderer.invoke("get-cuda-whisper-status"),+ downloadCudaWhisperBinary: () => ipcRenderer.invoke("download-cuda-whisper-binary"),+ cancelCudaWhisperDownload: () => ipcRenderer.invoke("cancel-cuda-whisper-download"),+ deleteCudaWhisperBinary: () => ipcRenderer.invoke("delete-cuda-whisper-binary"),+ onCudaDownloadProgress: registerListener(+ "cuda-download-progress",+ (callback) => (_event, data) => callback(data)+ ),+ onCudaFallbackNotification: registerListener(+ "cuda-fallback-notification",+ (callback) => () => callback()+ ),+// Local Parakeet (NVIDIA) functionstranscribeLocalParakeet: (audioBlob, options) =>ipcRenderer.invoke("transcribe-local-parakeet", audioBlob, options),@@ -297,7 +321,8 @@ contextBridge.exposeInMainWorld("electronAPI", {cloudBillingPortal: () => ipcRenderer.invoke("cloud-billing-portal"),// Cloud audio file transcription- transcribeAudioFileCloud: (filePath) => ipcRenderer.invoke("transcribe-audio-file-cloud", filePath),+ transcribeAudioFileCloud: (filePath) =>+ ipcRenderer.invoke("transcribe-audio-file-cloud", filePath),transcribeAudioFileByok: (options) => ipcRenderer.invoke("transcribe-audio-file-byok", options),// Referral stats@@ -338,10 +363,22 @@ contextBridge.exposeInMainWorld("electronAPI", {deepgramStreamingFinalize: () => ipcRenderer.send("deepgram-streaming-finalize"),deepgramStreamingStop: () => ipcRenderer.invoke("deepgram-streaming-stop"),deepgramStreamingStatus: () => ipcRenderer.invoke("deepgram-streaming-status"),- onDeepgramPartialTranscript: registerListener("deepgram-partial-transcript", (callback) => (_event, text) => callback(text)),- onDeepgramFinalTranscript: registerListener("deepgram-final-transcript", (callback) => (_event, text) => callback(text)),- onDeepgramError: registerListener("deepgram-error", (callback) => (_event, error) => callback(error)),- onDeepgramSessionEnd: registerListener("deepgram-session-end", (callback) => (_event, data) => callback(data)),+ onDeepgramPartialTranscript: registerListener(+ "deepgram-partial-transcript",+ (callback) => (_event, text) => callback(text)+ ),+ onDeepgramFinalTranscript: registerListener(+ "deepgram-final-transcript",+ (callback) => (_event, text) => callback(text)+ ),+ onDeepgramError: registerListener(+ "deepgram-error",+ (callback) => (_event, error) => callback(error)+ ),+ onDeepgramSessionEnd: registerListener(+ "deepgram-session-end",+ (callback) => (_event, data) => callback(data)+ ),// Usage limit events (for showing UpgradePrompt in ControlPanel)notifyLimitReached: (data) => ipcRenderer.send("limit-reached", data),diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 020b5d4b0..1bc89686e 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -1,7 +1,7 @@import React, { Suspense, useState, useEffect, useRef, useCallback } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";-import { Download, RefreshCw, Loader2, AlertTriangle } from "lucide-react";+import { Download, RefreshCw, Loader2, AlertTriangle, Zap } from "lucide-react";import UpgradePrompt from "./UpgradePrompt";import { ConfirmDialog, AlertDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";@@ -21,6 +21,7 @@ import WindowControls from "./WindowControls";import { getCachedPlatform } from "../utils/platform";import { setActiveNoteId, setActiveFolderId } from "../stores/noteStore";import HistoryView from "./HistoryView";+import type { CudaWhisperStatus } from "../types/electron";const platform = getCachedPlatform();@@ -45,10 +46,20 @@ export default function ControlPanel() {const [showReferrals, setShowReferrals] = useState(false);const [showCloudMigrationBanner, setShowCloudMigrationBanner] = useState(false);const [activeView, setActiveView] = useState<ControlPanelView>("home");+ const [cudaStatus, setCudaStatus] = useState<CudaWhisperStatus | null>(null);+ const [gpuBannerDismissed, setGpuBannerDismissed] = useState(+ () => localStorage.getItem("gpuBannerDismissed") === "true"+ );const cloudMigrationProcessed = useRef(false);const { hotkey } = useHotkey();const { toast } = useToast();- const { useReasoningModel, setUseLocalWhisper, setCloudTranscriptionMode } = useSettings();+ const {+ useLocalWhisper,+ localTranscriptionProvider,+ useReasoningModel,+ setUseLocalWhisper,+ setCloudTranscriptionMode,+ } = useSettings();const { isSignedIn, isLoaded: authLoaded, user } = useAuth();const usage = useUsage();@@ -142,6 +153,25 @@ export default function ControlPanel() {setShowCloudMigrationBanner(true);}, [authLoaded, isSignedIn, setUseLocalWhisper, setCloudTranscriptionMode]);+ const fetchCudaStatus = useCallback(() => {+ if (platform === "darwin" || gpuBannerDismissed) return;+ if (!useLocalWhisper || localTranscriptionProvider !== "whisper") return;+ window.electronAPI+ ?.getCudaWhisperStatus?.()+ ?.then(setCudaStatus)+ .catch(() => {});+ }, [useLocalWhisper, localTranscriptionProvider, gpuBannerDismissed]);++ useEffect(() => {+ if (!showSettings) fetchCudaStatus();+ }, [showSettings, fetchCudaStatus]);++ const showGpuBanner =+ activeView === "home" &&+ !gpuBannerDismissed &&+ cudaStatus?.gpuInfo.hasNvidiaGpu === true &&+ cudaStatus.downloaded === false;+const loadTranscriptions = async () => {try {setIsLoading(true);@@ -401,6 +431,49 @@ export default function ControlPanel() {</div></div>)}+ {showGpuBanner && (+ <div className="max-w-3xl mx-auto w-full mb-3">+ <div className="rounded-lg border border-primary/20 dark:border-primary/15 bg-primary/5 p-3">+ <div className="flex items-start gap-3">+ <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/15 flex items-center justify-center">+ <Zap size={16} className="text-primary" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium text-foreground mb-0.5">+ GPU acceleration available+ </p>+ <p className="text-xs text-muted-foreground mb-2">+ {cudaStatus?.gpuInfo.gpuName+ ? `Your ${cudaStatus.gpuInfo.gpuName} can speed up local transcription.`+ : "Your NVIDIA GPU can speed up local transcription."}+ </p>+ <div className="flex items-center gap-3">+ <Button+ variant="default"+ size="sm"+ className="h-7 text-xs"+ onClick={() => {+ setSettingsSection("transcription");+ setShowSettings(true);+ }}+ >+ Enable GPU+ </Button>+ <button+ onClick={() => {+ setGpuBannerDismissed(true);+ localStorage.setItem("gpuBannerDismissed", "true");+ }}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ Not now+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ )}{activeView === "home" && (<HistoryViewhistory={history}diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex 7fee18d4f..e4bad1b29 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useMemo, useRef } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";import { Input } from "./ui/input";-import { Download, Trash2, Cloud, Lock, X } from "lucide-react";+import { Download, Trash2, Cloud, Lock, X, Zap, Check } from "lucide-react";import { ProviderIcon } from "./ui/ProviderIcon";import { ProviderTabs } from "./ui/ProviderTabs";import ModelCardList from "./ui/ModelCardList";@@ -10,7 +10,7 @@ import { DownloadProgressBar } from "./ui/DownloadProgressBar";import ApiKeyInput from "./ui/ApiKeyInput";import { ConfirmDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";-import { useModelDownload } from "../hooks/useModelDownload";+import { useModelDownload, type DownloadProgress } from "../hooks/useModelDownload";import {getTranscriptionProviders,TranscriptionProviderData,@@ -25,6 +25,8 @@ import {import { getProviderIcon, isMonochromeProvider } from "../utils/providerIcons";import { API_ENDPOINTS, normalizeBaseUrl } from "../config/constants";import { createExternalLinkHandler } from "../utils/externalLinks";+import { getCachedPlatform } from "../utils/platform";+import type { CudaWhisperStatus } from "../types/electron";import logger from "../utils/logger";interface LocalModel {@@ -283,6 +285,14 @@ export default function TranscriptionModelPicker({const [internalLocalProvider, setInternalLocalProvider] = useState(selectedLocalProvider);const hasLoadedRef = useRef(false);const hasLoadedParakeetRef = useRef(false);+ const [cudaStatus, setCudaStatus] = useState<CudaWhisperStatus | null>(null);+ const [cudaDownloading, setCudaDownloading] = useState(false);+ const [cudaProgress, setCudaProgress] = useState<DownloadProgress>({+ downloadedBytes: 0,+ totalBytes: 0,+ percentage: 0,+ });+ const [cudaDismissed, setCudaDismissed] = useState(false);useEffect(() => {if (selectedLocalProvider !== internalLocalProvider) {@@ -437,6 +447,47 @@ export default function TranscriptionModelPicker({return () => window.removeEventListener("openwhispr-models-cleared", handleModelsCleared);}, [loadLocalModels, loadParakeetModels]);+ useEffect(() => {+ if (!useLocalWhisper || internalLocalProvider !== "whisper") return;+ if (getCachedPlatform() === "darwin") return;+ window.electronAPI+ ?.getCudaWhisperStatus?.()+ ?.then(setCudaStatus)+ .catch(() => {});+ }, [useLocalWhisper, internalLocalProvider]);++ useEffect(() => {+ if (!cudaDownloading) return;+ const cleanup = window.electronAPI?.onCudaDownloadProgress?.((data) => {+ setCudaProgress(data);+ });+ return cleanup;+ }, [cudaDownloading]);++ const handleCudaDownload = async () => {+ setCudaDownloading(true);+ try {+ const result = await window.electronAPI?.downloadCudaWhisperBinary?.();+ if (result?.success) {+ const status = await window.electronAPI?.getCudaWhisperStatus?.();+ setCudaStatus(status || null);+ }+ } finally {+ setCudaDownloading(false);+ }+ };++ const handleCudaDelete = async () => {+ await window.electronAPI?.deleteCudaWhisperBinary?.();+ const status = await window.electronAPI?.getCudaWhisperStatus?.();+ setCudaStatus(status || null);+ };++ const handleCudaCancel = async () => {+ await window.electronAPI?.cancelCudaWhisperDownload?.();+ setCudaDownloading(false);+ };+const {downloadingModel,downloadProgress,@@ -875,6 +926,77 @@ export default function TranscriptionModelPicker({{progressDisplay}+ {cudaDownloading && internalLocalProvider === "whisper" && (+ <div>+ <DownloadProgressBar modelName="GPU acceleration" progress={cudaProgress} />+ <div className="px-2.5 pb-1 flex justify-end">+ <button+ onClick={handleCudaCancel}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ Cancel+ </button>+ </div>+ </div>+ )}++ {internalLocalProvider === "whisper" &&+ !cudaDismissed &&+ !cudaDownloading &&+ getCachedPlatform() !== "darwin" &&+ cudaStatus?.gpuInfo.hasNvidiaGpu && (+ <div className="mx-2 mt-2 rounded-md border border-border bg-surface-1 p-2.5">+ {cudaStatus.downloaded ? (+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-1.5">+ <Check size={13} className="text-success" />+ <span className="text-xs font-medium text-foreground">+ GPU acceleration active+ </span>+ </div>+ <Button+ onClick={handleCudaDelete}+ size="sm"+ variant="ghost"+ className="h-6 px-2 text-xs text-muted-foreground hover:text-destructive"+ >+ Remove+ </Button>+ </div>+ ) : (+ <div className="space-y-1.5">+ <div className="flex items-center gap-1.5">+ <Zap size={13} className="text-amber-500" />+ <span className="text-xs font-medium text-foreground">+ NVIDIA GPU detected+ {cudaStatus.gpuInfo.gpuName ? ` (${cudaStatus.gpuInfo.gpuName})` : ""}+ </span>+ </div>+ <p className="text-xs text-muted-foreground pl-5">+ GPU-accelerated Whisper available (~250 MB download)+ </p>+ <div className="flex items-center gap-2 pl-5">+ <Button+ onClick={handleCudaDownload}+ size="sm"+ variant="default"+ className="h-6 px-2.5 text-xs"+ >+ <Download size={11} className="mr-1" />+ Download+ </Button>+ <button+ onClick={() => setCudaDismissed(true)}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ Not now+ </button>+ </div>+ </div>+ )}+ </div>+ )}+<div className="p-2">{internalLocalProvider === "whisper" && renderLocalModels()}{internalLocalProvider === "nvidia" && renderParakeetModels()}diff --git a/src/helpers/environment.js b/src/helpers/environment.jsindex d32db8a4e..7b983861e 100644--- a/src/helpers/environment.js+++ b/src/helpers/environment.js@@ -21,6 +21,7 @@ const PERSISTED_KEYS = ["ACTIVATION_MODE","FLOATING_ICON_AUTO_HIDE","UI_LANGUAGE",+ "WHISPER_CUDA_ENABLED",];class EnvironmentManager {diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 8546f4b34..2f67d5a57 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -94,10 +94,17 @@ class IPCHandlers {this.updateManager = managers.updateManager;this.windowsKeyManager = managers.windowsKeyManager;this.getTrayManager = managers.getTrayManager;+ this.whisperCudaManager = managers.whisperCudaManager;this.sessionId = crypto.randomUUID();this.assemblyAiStreaming = null;this.deepgramStreaming = null;this.setupHandlers();++ if (this.whisperManager?.serverManager) {+ this.whisperManager.serverManager.on("cuda-fallback", () => {+ this.broadcastToWindows("cuda-fallback-notification", {});+ });+ }}_syncStartupEnv(setVars, clearVars = []) {@@ -607,7 +614,9 @@ class IPCHandlers {});ipcMain.handle("whisper-server-start", async (event, modelName) => {- return this.whisperManager.startServer(modelName);+ const useCuda =+ process.env.WHISPER_CUDA_ENABLED === "true" && this.whisperCudaManager?.isDownloaded();+ return this.whisperManager.startServer(modelName, { useCuda });});ipcMain.handle("whisper-server-stop", async () => {@@ -618,6 +627,59 @@ class IPCHandlers {return this.whisperManager.getServerStatus();});+ ipcMain.handle("detect-gpu", async () => {+ const { detectNvidiaGpu } = require("../utils/gpuDetection");+ return detectNvidiaGpu();+ });++ ipcMain.handle("get-cuda-whisper-status", async () => {+ const { detectNvidiaGpu } = require("../utils/gpuDetection");+ const gpuInfo = await detectNvidiaGpu();+ if (!this.whisperCudaManager) {+ return { downloaded: false, path: null, gpuInfo };+ }+ return {+ downloaded: this.whisperCudaManager.isDownloaded(),+ path: this.whisperCudaManager.getCudaBinaryPath(),+ gpuInfo,+ };+ });++ ipcMain.handle("download-cuda-whisper-binary", async (event) => {+ if (!this.whisperCudaManager) {+ return { success: false, error: "CUDA not supported on this platform" };+ }+ try {+ await this.whisperCudaManager.download((progress) => {+ if (progress.type === "progress" && !event.sender.isDestroyed()) {+ event.sender.send("cuda-download-progress", {+ downloadedBytes: progress.downloaded_bytes,+ totalBytes: progress.total_bytes,+ percentage: progress.percentage,+ });+ }+ });+ this._syncStartupEnv({ WHISPER_CUDA_ENABLED: "true" });+ return { success: true };+ } catch (error) {+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("cancel-cuda-whisper-download", async () => {+ if (!this.whisperCudaManager) return { success: false };+ return this.whisperCudaManager.cancelDownload();+ });++ ipcMain.handle("delete-cuda-whisper-binary", async () => {+ if (!this.whisperCudaManager) return { success: false };+ const result = await this.whisperCudaManager.delete();+ if (result.success) {+ this._syncStartupEnv({}, ["WHISPER_CUDA_ENABLED"]);+ }+ return result;+ });+ipcMain.handle("check-ffmpeg-availability", async (event) => {return this.whisperManager.checkFFmpegAvailability();});diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex d6beed2e5..1a1de6399 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -69,7 +69,7 @@ class WhisperManager {await cleanupStaleDownloads(this.getModelsDir());// Pre-warm whisper-server if local mode enabled (eliminates 2-5s cold-start delay)- const { localTranscriptionProvider, whisperModel } = settings;+ const { localTranscriptionProvider, whisperModel, useCuda } = settings;if (localTranscriptionProvider === "whisper" &&@@ -82,11 +82,12 @@ class WhisperManager {debugLogger.info("Pre-warming whisper-server", {model: whisperModel,modelPath,+ cuda: !!useCuda,});try {const serverStartTime = Date.now();- await this.serverManager.start(modelPath);+ await this.serverManager.start(modelPath, { useCuda: !!useCuda });this.currentServerModel = whisperModel;debugLogger.info("whisper-server pre-warmed successfully", {@@ -188,7 +189,7 @@ class WhisperManager {debugLogger.info(`[Dependencies] Models: ${modelsStatus}`);}- async startServer(modelName) {+ async startServer(modelName, options = {}) {if (!this.serverManager.isAvailable()) {return { success: false, reason: "whisper-server binary not found" };}@@ -199,7 +200,7 @@ class WhisperManager {}try {- await this.serverManager.start(modelPath);+ await this.serverManager.start(modelPath, options);this.currentServerModel = modelName;debugLogger.info("whisper-server started", {model: modelName,@@ -270,7 +271,7 @@ class WhisperManager {// Start server if not running or if model changedif (!this.serverManager.ready || this.currentServerModel !== model) {debugLogger.debug("Starting/restarting whisper-server for model", { model });- await this.serverManager.start(modelPath);+ await this.serverManager.start(modelPath, { useCuda: this.serverManager.useCuda });this.currentServerModel = model;}diff --git a/src/helpers/whisperCudaManager.js b/src/helpers/whisperCudaManager.jsnew file mode 100644index 000000000..bbf611f7a--- /dev/null+++ b/src/helpers/whisperCudaManager.js@@ -0,0 +1,301 @@+const fs = require("fs");+const { promises: fsPromises } = require("fs");+const path = require("path");+const https = require("https");+const { execFile } = require("child_process");+const { app } = require("electron");+const debugLogger = require("./debugLogger");+const {+ downloadFile,+ createDownloadSignal,+ checkDiskSpace,+ cleanupStaleDownloads,+} = require("./downloadUtils");+const { getSafeTempDir } = require("./safeTempDir");++const GITHUB_RELEASE_URL = "https://api.github.com/repos/OpenWhispr/whisper.cpp/releases/latest";++const PLATFORM_BINARY_NAMES = {+ linux: "whisper-server-linux-x64-cuda",+ win32: "whisper-server-win32-x64-cuda.exe",+};++const PLATFORM_ASSET_NAMES = {+ linux: "whisper-server-linux-x64-cuda.zip",+ win32: "whisper-server-win32-x64-cuda.zip",+};++const COMPANION_PATTERNS = {+ linux: /\.so(\.\d+)*$/,+ win32: /\.dll$/i,+};++function isSupportedPlatform() {+ return process.platform === "linux" || process.platform === "win32";+}++class WhisperCudaManager {+ constructor() {+ this._binDir = null;+ this._downloadSignal = null;+ }++ getCudaBinaryDir() {+ if (!this._binDir) {+ this._binDir = path.join(app.getPath("userData"), "bin");+ fs.mkdirSync(this._binDir, { recursive: true });+ }+ return this._binDir;+ }++ getCudaBinaryPath() {+ if (!isSupportedPlatform()) return null;++ const binaryName = PLATFORM_BINARY_NAMES[process.platform];+ const binaryPath = path.join(this.getCudaBinaryDir(), binaryName);+ return fs.existsSync(binaryPath) ? binaryPath : null;+ }++ isDownloaded() {+ return !!this.getCudaBinaryPath();+ }++ async fetchReleaseInfo() {+ if (!isSupportedPlatform()) {+ throw new Error(`CUDA binaries not available for ${process.platform}`);+ }++ const release = await this._fetchJson(GITHUB_RELEASE_URL);+ const assetName = PLATFORM_ASSET_NAMES[process.platform];+ const asset = release.assets?.find((a) => a.name === assetName);++ if (!asset) {+ throw new Error(`No CUDA asset found for ${process.platform} (expected ${assetName})`);+ }++ return {+ url: asset.browser_download_url,+ size: asset.size,+ version: release.tag_name,+ };+ }++ async download(progressCallback) {+ if (!isSupportedPlatform()) {+ throw new Error(`CUDA binaries not available for ${process.platform}`);+ }++ const releaseInfo = await this.fetchReleaseInfo();+ debugLogger.info("CUDA binary download starting", {+ version: releaseInfo.version,+ size: releaseInfo.size,+ });++ const binDir = this.getCudaBinaryDir();++ const spaceCheck = await checkDiskSpace(binDir, releaseInfo.size * 2);+ if (!spaceCheck.ok) {+ throw new Error(+ `Not enough disk space. Need ~${Math.round((releaseInfo.size * 2) / 1_000_000)}MB, ` ++ `only ${Math.round(spaceCheck.availableBytes / 1_000_000)}MB available.`+ );+ }++ await cleanupStaleDownloads(binDir);++ const { signal, abort } = createDownloadSignal();+ this._downloadSignal = { abort };++ const tempDir = getSafeTempDir();+ const zipPath = path.join(tempDir, `cuda-download-${Date.now()}.zip`);+ const extractDir = path.join(tempDir, `temp-extract-${Date.now()}`);++ try {+ await downloadFile(releaseInfo.url, zipPath, {+ timeout: 600000,+ signal,+ expectedSize: releaseInfo.size,+ onProgress: (downloaded, total) => {+ if (progressCallback) {+ progressCallback({+ type: "progress",+ downloaded_bytes: downloaded,+ total_bytes: total,+ percentage: total > 0 ? Math.round((downloaded / total) * 100) : 0,+ });+ }+ },+ });++ await fsPromises.mkdir(extractDir, { recursive: true });+ await this._extractZip(zipPath, extractDir);++ const binaryName = PLATFORM_BINARY_NAMES[process.platform];+ const companionPattern = COMPANION_PATTERNS[process.platform];+ const entries = await fsPromises.readdir(extractDir);++ for (const entry of entries) {+ if (entry === binaryName || companionPattern.test(entry)) {+ const src = path.join(extractDir, entry);+ const dest = path.join(binDir, entry);+ await fsPromises.copyFile(src, dest);++ if (process.platform === "linux") {+ await fsPromises.chmod(dest, 0o755);+ }+ }+ }++ if (!this.getCudaBinaryPath()) {+ throw new Error(`Extraction completed but binary "${binaryName}" not found in archive`);+ }++ debugLogger.info("CUDA binary download complete", {+ version: releaseInfo.version,+ path: this.getCudaBinaryPath(),+ });++ if (progressCallback) {+ progressCallback({ type: "complete", percentage: 100 });+ }+ } catch (error) {+ if (error.isAbort) {+ throw new Error("Download cancelled by user");+ }+ throw error;+ } finally {+ this._downloadSignal = null;+ await fsPromises.unlink(zipPath).catch(() => {});+ await fsPromises.rm(extractDir, { recursive: true, force: true }).catch(() => {});+ }+ }++ async cancelDownload() {+ if (this._downloadSignal) {+ this._downloadSignal.abort();+ this._downloadSignal = null;+ return { success: true, message: "Download cancelled" };+ }+ return { success: false, error: "No active download to cancel" };+ }++ async delete() {+ if (!isSupportedPlatform()) {+ return { success: false, error: "Not supported on this platform" };+ }++ const binDir = this.getCudaBinaryDir();+ const binaryName = PLATFORM_BINARY_NAMES[process.platform];+ const companionPattern = COMPANION_PATTERNS[process.platform];++ let deletedCount = 0;+ let freedBytes = 0;++ try {+ const entries = await fsPromises.readdir(binDir);++ for (const entry of entries) {+ if (entry === binaryName || companionPattern.test(entry)) {+ const filePath = path.join(binDir, entry);+ try {+ const stats = await fsPromises.stat(filePath);+ await fsPromises.unlink(filePath);+ freedBytes += stats.size;+ deletedCount++;+ } catch {+ // Continue with remaining files+ }+ }+ }+ } catch {+ // Directory may not exist+ }++ debugLogger.info("CUDA binary deleted", { deletedCount, freedBytes });++ return {+ success: deletedCount > 0,+ deleted_count: deletedCount,+ freed_bytes: freedBytes,+ freed_mb: Math.round(freedBytes / (1024 * 1024)),+ };+ }++ _fetchJson(url) {+ return new Promise((resolve, reject) => {+ https+ .get(+ url,+ {+ headers: {+ "User-Agent": "OpenWhispr/1.0",+ Accept: "application/vnd.github+json",+ },+ timeout: 15000,+ },+ (res) => {+ if (res.statusCode >= 300 && res.statusCode < 400) {+ const location = res.headers.location;+ if (!location) {+ reject(new Error("Redirect without location header"));+ return;+ }+ res.resume();+ this._fetchJson(location).then(resolve, reject);+ return;+ }++ if (res.statusCode !== 200) {+ res.resume();+ reject(new Error(`GitHub API returned HTTP ${res.statusCode}`));+ return;+ }++ let data = "";+ res.on("data", (chunk) => (data += chunk));+ res.on("end", () => {+ try {+ resolve(JSON.parse(data));+ } catch (e) {+ reject(new Error(`Failed to parse GitHub API response: ${e.message}`));+ }+ });+ res.on("error", reject);+ }+ )+ .on("error", reject)+ .on("timeout", function () {+ this.destroy();+ reject(new Error("GitHub API request timed out"));+ });+ });+ }++ _extractZip(zipPath, destDir) {+ if (process.platform === "win32") {+ return new Promise((resolve, reject) => {+ execFile(+ "powershell",+ [+ "-NoProfile",+ "-Command",+ `Expand-Archive -Force -Path '${zipPath}' -DestinationPath '${destDir}'`,+ ],+ (error) => {+ if (error) reject(new Error(`Zip extraction failed: ${error.message}`));+ else resolve();+ }+ );+ });+ }++ return new Promise((resolve, reject) => {+ execFile("unzip", ["-o", zipPath, "-d", destDir], (error) => {+ if (error) reject(new Error(`Zip extraction failed: ${error.message}`));+ else resolve();+ });+ });+ }+}++module.exports = WhisperCudaManager;diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.jsindex a9314a178..d12d1d522 100644--- a/src/helpers/whisperServer.js+++ b/src/helpers/whisperServer.js@@ -1,8 +1,10 @@const { spawn } = require("child_process");+const EventEmitter = require("events");const fs = require("fs");const net = require("net");const path = require("path");const http = require("http");+const { app } = require("electron");const debugLogger = require("./debugLogger");const { killProcess } = require("../utils/process");const { getSafeTempDir } = require("./safeTempDir");@@ -14,8 +16,9 @@ const STARTUP_TIMEOUT_MS = 30000;const HEALTH_CHECK_INTERVAL_MS = 5000;const HEALTH_CHECK_TIMEOUT_MS = 2000;-class WhisperServerManager {+class WhisperServerManager extends EventEmitter {constructor() {+ super();this.process = null;this.port = null;this.ready = false;@@ -25,6 +28,7 @@ class WhisperServerManager {this.cachedServerBinaryPath = null;this.cachedFFmpegPath = null;this.canConvert = false;+ this.useCuda = false;}getFFmpegPath() {@@ -117,7 +121,14 @@ class WhisperServerManager {return null;}- getServerBinaryPath() {+ getServerBinaryPath(options = {}) {+ if (options.preferCuda) {+ const ext = process.platform === "win32" ? ".exe" : "";+ const cudaBinary = `whisper-server-${process.platform}-${process.arch}-cuda${ext}`;+ const cudaPath = path.join(app.getPath("userData"), "bin", cudaBinary);+ if (fs.existsSync(cudaPath)) return cudaPath;+ }+if (this.cachedServerBinaryPath) return this.cachedServerBinaryPath;const platform = process.platform;@@ -199,12 +210,14 @@ class WhisperServerManager {}async _doStart(modelPath, options = {}) {- const serverBinary = this.getServerBinaryPath();+ const usingCuda = options.useCuda || false;+ const serverBinary = this.getServerBinaryPath(usingCuda ? { preferCuda: true } : {});if (!serverBinary) throw new Error("whisper-server binary not found");if (!fs.existsSync(modelPath)) throw new Error(`Model file not found: ${modelPath}`);this.port = await this.findAvailablePort();this.modelPath = modelPath;+ this.useCuda = usingCuda;// Check for FFmpeg first - only use --convert flag if FFmpeg is availableconst ffmpegPath = this.getFFmpegPath();@@ -242,8 +255,11 @@ class WhisperServerManager {modelPath,args,cwd: serverBinaryDir,+ cuda: usingCuda,});+ const startTime = Date.now();+this.process = spawn(serverBinary, args, {stdio: ["ignore", "pipe", "pipe"],windowsHide: true,@@ -253,6 +269,7 @@ class WhisperServerManager {let stderrBuffer = "";let exitCode = null;+ let earlyExit = false;this.process.stdout.on("data", (data) => {debugLogger.debug("whisper-server stdout", { data: data.toString().trim() });@@ -270,18 +287,33 @@ class WhisperServerManager {this.process.on("close", (code) => {exitCode = code;+ if (Date.now() - startTime < 10000) earlyExit = true;debugLogger.debug("whisper-server process exited", { code });this.ready = false;this.process = null;this.stopHealthCheck();});- await this.waitForReady(() => ({ stderr: stderrBuffer, exitCode }));+ try {+ await this.waitForReady(() => ({ stderr: stderrBuffer, exitCode }));+ } catch (err) {+ if (usingCuda && earlyExit) {+ debugLogger.warn("CUDA whisper-server failed, falling back to CPU", {+ exitCode,+ stderr: stderrBuffer.slice(0, 200),+ });+ this.emit("cuda-fallback");+ return this._doStart(modelPath, { ...options, useCuda: false });+ }+ throw err;+ }+this.startHealthCheck();debugLogger.info("whisper-server started successfully", {port: this.port,model: path.basename(modelPath),+ cuda: this.useCuda,});}diff --git a/src/types/electron.ts b/src/types/electron.tsindex dfc712128..4e3296092 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -43,6 +43,19 @@ export interface ActionItem {updated_at: string;}+export interface GpuInfo {+ hasNvidiaGpu: boolean;+ gpuName?: string;+ driverVersion?: string;+ vramMb?: number;+}++export interface CudaWhisperStatus {+ downloaded: boolean;+ path: string | null;+ gpuInfo: GpuInfo;+}+export interface WhisperCheckResult {installed: boolean;working: boolean;@@ -376,6 +389,21 @@ declare global {error?: string;}>;+ // CUDA GPU acceleration+ detectGpu: () => Promise<GpuInfo>;+ getCudaWhisperStatus: () => Promise<CudaWhisperStatus>;+ downloadCudaWhisperBinary: () => Promise<{ success: boolean; error?: string }>;+ cancelCudaWhisperDownload: () => Promise<{ success: boolean }>;+ deleteCudaWhisperBinary: () => Promise<{ success: boolean }>;+ onCudaDownloadProgress: (+ callback: (data: {+ downloadedBytes: number;+ totalBytes: number;+ percentage: number;+ }) => void+ ) => () => void;+ onCudaFallbackNotification: (callback: () => void) => () => void;+// Parakeet operations (NVIDIA via sherpa-onnx)transcribeLocalParakeet: (audioBlob: ArrayBuffer,diff --git a/src/utils/gpuDetection.js b/src/utils/gpuDetection.jsnew file mode 100644index 000000000..d35e3babf--- /dev/null+++ b/src/utils/gpuDetection.js@@ -0,0 +1,47 @@+const { execFile } = require("child_process");++let cachedGpuInfo = null;++function detectNvidiaGpu() {+ if (cachedGpuInfo) return Promise.resolve(cachedGpuInfo);++ if (process.platform === "darwin") {+ cachedGpuInfo = { hasNvidiaGpu: false };+ return Promise.resolve(cachedGpuInfo);+ }++ return new Promise((resolve) => {+ execFile(+ "nvidia-smi",+ ["--query-gpu=name,driver_version,memory.total", "--format=csv,noheader,nounits"],+ { timeout: 5000 },+ (error, stdout) => {+ if (error || !stdout) {+ cachedGpuInfo = { hasNvidiaGpu: false };+ resolve(cachedGpuInfo);+ return;+ }++ const parts = stdout+ .trim()+ .split(",")+ .map((s) => s.trim());+ if (parts.length < 3) {+ cachedGpuInfo = { hasNvidiaGpu: false };+ resolve(cachedGpuInfo);+ return;+ }++ cachedGpuInfo = {+ hasNvidiaGpu: true,+ gpuName: parts[0],+ driverVersion: parts[1],+ vramMb: parseInt(parts[2], 10) || undefined,+ };+ resolve(cachedGpuInfo);+ }+ );+ });+}++module.exports = { detectNvidiaGpu };