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: add pipeline timing instrumentation and whisper-server pre-warming
Gabriel Steine3919cedcdd8
diff --git a/main.js b/main.jsindex 6b9113208..2a66ec227 100644--- a/main.js+++ b/main.js@@ -120,8 +120,16 @@ async function startApp() {}// Initialize Whisper manager at startup (don't await to avoid blocking)- whisperManager.initializeAtStartup().catch((err) => {+ // Settings can be provided via environment variables for server pre-warming:+ // - USE_LOCAL_WHISPER=true to enable local whisper mode+ // - LOCAL_WHISPER_MODEL=base (or tiny, small, medium, large, turbo)+ const whisperSettings = {+ useLocalWhisper: process.env.USE_LOCAL_WHISPER === "true",+ whisperModel: process.env.LOCAL_WHISPER_MODEL || "base",+ };+ whisperManager.initializeAtStartup(whisperSettings).catch((err) => {// Whisper not being available at startup is not critical+ debugLogger.debug("Whisper startup init error (non-fatal)", { error: err.message });});// Log nircmd status on Windows (for debugging bundled dependencies)diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 74d27b4fb..58b96de50 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -137,6 +137,8 @@ class AudioManager {}async processAudio(audioBlob, metadata = {}) {+ const pipelineStart = performance.now();+try {const useLocalWhisper = localStorage.getItem("useLocalWhisper") === "true";const whisperModel = localStorage.getItem("whisperModel") || "base";@@ -147,8 +149,37 @@ class AudioManager {} else {result = await this.processWithOpenAIAPI(audioBlob, metadata);}+this.onTranscriptionComplete?.(result);++ const roundTripDurationMs = Math.round(performance.now() - pipelineStart);++ const timingData = {+ mode: useLocalWhisper ? "local" : "cloud",+ model: useLocalWhisper ? whisperModel : this.getTranscriptionModel(),+ audioDurationMs: metadata.durationSeconds ? Math.round(metadata.durationSeconds * 1000) : null,+ reasoningProcessingDurationMs: result?.timings?.reasoningProcessingDurationMs ?? null,+ roundTripDurationMs,+ audioSizeBytes: audioBlob.size,+ audioFormat: audioBlob.type,+ outputTextLength: result?.text?.length,+ };++ if (useLocalWhisper) {+ timingData.audioConversionDurationMs = result?.timings?.audioConversionDurationMs ?? null;+ }+ timingData.transcriptionProcessingDurationMs = result?.timings?.transcriptionProcessingDurationMs ?? null;++ logger.info("Pipeline timing", timingData, "performance");+} catch (error) {+ const errorAtMs = Math.round(performance.now() - pipelineStart);++ logger.error("Pipeline failed", {+ errorAtMs,+ error: error.message,+ }, "performance");+if (error.message !== "No audio detected") {this.onError?.({title: "Transcription Error",@@ -162,20 +193,43 @@ class AudioManager {}async processWithLocalWhisper(audioBlob, model = "base", metadata = {}) {+ const timings = {};+try {- const arrayBuffer = await audioBlob.arrayBuffer();+ const conversionStart = performance.now();+ const wavBlob = await this.optimizeAudio(audioBlob);+ timings.audioConversionDurationMs = Math.round(performance.now() - conversionStart);++ const arrayBuffer = await wavBlob.arrayBuffer();const language = localStorage.getItem("preferredLanguage");const options = { model };if (language && language !== "auto") {options.language = language;}+ logger.debug("Local transcription starting", {+ originalFormat: audioBlob.type,+ originalSizeBytes: audioBlob.size,+ wavSizeBytes: wavBlob.size,+ audioConversionDurationMs: timings.audioConversionDurationMs,+ }, "performance");++ const transcriptionStart = performance.now();const result = await window.electronAPI.transcribeLocalWhisper(arrayBuffer, options);+ timings.transcriptionProcessingDurationMs = Math.round(performance.now() - transcriptionStart);++ logger.debug("Local transcription complete", {+ transcriptionProcessingDurationMs: timings.transcriptionProcessingDurationMs,+ success: result.success,+ }, "performance");if (result.success && result.text) {+ const reasoningStart = performance.now();const text = await this.processTranscription(result.text, "local");+ timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);+if (text !== null && text !== undefined) {- return { success: true, text: text || result.text, source: "local" };+ return { success: true, text: text || result.text, source: "local", timings };} else {throw new Error("No text transcribed");}@@ -671,6 +725,7 @@ class AudioManager {}async processWithOpenAIAPI(audioBlob, metadata = {}) {+ const timings = {};const language = localStorage.getItem("preferredLanguage");const allowLocalFallback = localStorage.getItem("allowLocalFallback") === "true";const fallbackModel = localStorage.getItem("fallbackWhisperModel") || "base";@@ -775,6 +830,7 @@ class AudioManager {headers.Authorization = `Bearer ${apiKey}`;}+ const apiCallStart = performance.now();const response = await fetch(endpoint, {method: "POST",headers,@@ -861,7 +917,12 @@ class AudioManager {// Check for text - handle both empty string and missing fieldif (result.text && result.text.trim().length > 0) {+ timings.transcriptionProcessingDurationMs = Math.round(performance.now() - apiCallStart);++ const reasoningStart = performance.now();const text = await this.processTranscription(result.text, "openai");+ timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);+const source = (await this.isReasoningAvailable()) ? "openai-reasoned" : "openai";logger.debug("Transcription successful",@@ -869,10 +930,12 @@ class AudioManager {originalLength: result.text.length,processedLength: text.length,source,+ transcriptionProcessingDurationMs: timings.transcriptionProcessingDurationMs,+ reasoningProcessingDurationMs: timings.reasoningProcessingDurationMs,},"transcription");- return { success: true, text, source };+ return { success: true, text, source, timings };} else {// Log at info level so it shows without debug modelogger.info(diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.jsindex 897d21aed..9610aeeda 100644--- a/src/helpers/clipboard.js+++ b/src/helpers/clipboard.js@@ -6,8 +6,27 @@ const fs = require("fs");// Cache TTL constants - these mirror CACHE_CONFIG.AVAILABILITY_CHECK_TTL in src/config/constants.tsconst CACHE_TTL_MS = 30000;-// Paste delay before simulating keystroke - mirrors CACHE_CONFIG.PASTE_DELAY_MS-const PASTE_DELAY_MS = 50;++// Platform-specific paste delays (ms before simulating keystroke)+// Each platform has different timing requirements based on their paste mechanism+const PASTE_DELAYS = {+ darwin: 50, // macOS: AppleScript keystroke is async, needs time for clipboard to settle+ win32_nircmd: 2, // Windows nircmd: lightweight binary, near-instant (was 5ms)+ win32_pwsh: 10, // Windows PowerShell: startup time dominates, delay doesn't help much+ linux: 0, // Linux: xdotool sends X11 events directly, no delay needed+};++// Platform-specific clipboard restoration delays (ms after paste completes)+// Ensures paste is fully processed before restoring original clipboard content+const RESTORE_DELAYS = {+ darwin: 100, // macOS: AppleScript needs time to complete keystroke+ win32_nircmd: 5, // Windows nircmd: fast, minimal delay needed (was 10ms)+ win32_pwsh: 10, // Windows PowerShell: keep as-is+ linux: 200, // Linux: X11 event queue processing takes longer+};++// Legacy constant for backward compatibility (used by macOS)+const PASTE_DELAY_MS = PASTE_DELAYS.darwin;class ClipboardManager {constructor() {@@ -80,6 +99,10 @@ class ClipboardManager {}async pasteText(text) {+ const startTime = Date.now();+ const platform = process.platform;+ let method = "unknown";+try {// Save original clipboard content firstconst originalClipboard = clipboard.readText();@@ -92,7 +115,8 @@ class ClipboardManager {clipboard.writeText(text);this.safeLog("π Text copied to clipboard:", text.substring(0, 50) + "...");- if (process.platform === "darwin") {+ if (platform === "darwin") {+ method = "applescript";// Check accessibility permissions firstthis.safeLog("π Checking accessibility permissions for paste operation...");const hasPermissions = await this.checkAccessibilityPermissions();@@ -105,13 +129,30 @@ class ClipboardManager {}this.safeLog("β Permissions granted, attempting to paste...");- return await this.pasteMacOS(originalClipboard);- } else if (process.platform === "win32") {- return await this.pasteWindows(originalClipboard);+ await this.pasteMacOS(originalClipboard);+ } else if (platform === "win32") {+ const nircmdPath = this.getNircmdPath();+ method = nircmdPath ? "nircmd" : "powershell";+ await this.pasteWindows(originalClipboard);} else {- return await this.pasteLinux(originalClipboard);+ method = "linux-tools";+ await this.pasteLinux(originalClipboard);}++ // Log successful paste operation timing+ this.safeLog("β Paste operation complete", {+ platform,+ method,+ elapsedMs: Date.now() - startTime,+ textLength: text.length,+ });} catch (error) {+ this.safeLog("β Paste operation failed", {+ platform,+ method,+ elapsedMs: Date.now() - startTime,+ error: error.message,+ });throw error;}}@@ -186,14 +227,15 @@ class ClipboardManager {async pasteWithNircmd(nircmdPath, originalClipboard) {return new Promise((resolve, reject) => {- // Minimal delay for nircmd - it's very fast+ const pasteDelay = PASTE_DELAYS.win32_nircmd;+ const restoreDelay = RESTORE_DELAYS.win32_nircmd;+setTimeout(() => {let hasTimedOut = false;const startTime = Date.now();- this.safeLog("β‘ Starting nircmd paste operation...");+ this.safeLog(`β‘ nircmd paste starting (delay: ${pasteDelay}ms)`);- // nircmd sendkey ctrl+vconst pasteProcess = spawn(nircmdPath, ["sendkeypress", "ctrl+v"]);let errorOutput = "";@@ -209,19 +251,20 @@ class ClipboardManager {const elapsed = Date.now() - startTime;if (code === 0) {- this.safeLog(`β nircmd paste completed successfully in ${elapsed}ms`);+ this.safeLog(`β nircmd paste success`, {+ elapsedMs: elapsed,+ restoreDelayMs: restoreDelay,+ });setTimeout(() => {clipboard.writeText(originalClipboard);- this.safeLog("π Original clipboard content restored");- }, 10);+ this.safeLog("π Clipboard restored");+ }, restoreDelay);resolve();} else {- this.safeLog(- `β nircmd paste failed with code ${code} after ${elapsed}ms`,- errorOutput- );- // Fallback to PowerShell- this.safeLog("π Falling back to PowerShell...");+ this.safeLog(`β nircmd failed (code ${code}), falling back to PowerShell`, {+ elapsedMs: elapsed,+ stderr: errorOutput,+ });this.pasteWithPowerShell(originalClipboard).then(resolve).catch(reject);}});@@ -230,40 +273,40 @@ class ClipboardManager {if (hasTimedOut) return;clearTimeout(timeoutId);const elapsed = Date.now() - startTime;- this.safeLog(`β nircmd error after ${elapsed}ms:`, error.message);- // Fallback to PowerShell- this.safeLog("π Falling back to PowerShell...");+ this.safeLog(`β nircmd error, falling back to PowerShell`, {+ elapsedMs: elapsed,+ error: error.message,+ });this.pasteWithPowerShell(originalClipboard).then(resolve).catch(reject);});const timeoutId = setTimeout(() => {hasTimedOut = true;const elapsed = Date.now() - startTime;- this.safeLog(`β±οΈ nircmd paste timed out after ${elapsed}ms`);+ this.safeLog(`β±οΈ nircmd timeout, falling back to PowerShell`, { elapsedMs: elapsed });killProcess(pasteProcess, "SIGKILL");pasteProcess.removeAllListeners();- // Fallback to PowerShell- this.safeLog("π Falling back to PowerShell...");this.pasteWithPowerShell(originalClipboard).then(resolve).catch(reject);- }, 2000); // Shorter timeout for fast nircmd- }, 5); // Very short delay for nircmd+ }, 2000);+ }, pasteDelay);});}async pasteWithPowerShell(originalClipboard) {return new Promise((resolve, reject) => {- // Reduce delay - clipboard.writeText is synchronous so no need to wait+ const pasteDelay = PASTE_DELAYS.win32_pwsh;+ const restoreDelay = RESTORE_DELAYS.win32_pwsh;+setTimeout(() => {let hasTimedOut = false;const startTime = Date.now();- this.safeLog("πͺ Starting PowerShell paste operation...");+ this.safeLog(`πͺ PowerShell paste starting (delay: ${pasteDelay}ms)`);// Optimized PowerShell command:// - Uses [void] to suppress output (faster)// - WindowStyle Hidden to prevent window flash// - ExecutionPolicy Bypass to skip policy checks- // - Shorter variable names and compact syntaxconst pasteProcess = spawn("powershell.exe", ["-NoProfile","-NonInteractive",@@ -272,7 +315,6 @@ class ClipboardManager {"-ExecutionPolicy","Bypass","-Command",- // Optimized: Load assembly and send keys in one line, suppress output"[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');[System.Windows.Forms.SendKeys]::SendWait('^v')",]);@@ -289,17 +331,21 @@ class ClipboardManager {const elapsed = Date.now() - startTime;if (code === 0) {- this.safeLog(`β PowerShell paste completed successfully in ${elapsed}ms`);+ this.safeLog(`β PowerShell paste success`, {+ elapsedMs: elapsed,+ restoreDelayMs: restoreDelay,+ });setTimeout(() => {clipboard.writeText(originalClipboard);- this.safeLog("π Original clipboard content restored");- }, 10);+ this.safeLog("π Clipboard restored");+ }, restoreDelay);resolve();} else {- this.safeLog(- `β PowerShell paste failed with code ${code} after ${elapsed}ms`,- errorOutput- );+ this.safeLog(`β PowerShell paste failed`, {+ code,+ elapsedMs: elapsed,+ stderr: errorOutput,+ });reject(new Error(`Windows paste failed with code ${code}. Text is copied to clipboard - please paste manually with Ctrl+V.`@@ -312,7 +358,10 @@ class ClipboardManager {if (hasTimedOut) return;clearTimeout(timeoutId);const elapsed = Date.now() - startTime;- this.safeLog(`β PowerShell paste error after ${elapsed}ms:`, error.message);+ this.safeLog(`β PowerShell paste error`, {+ elapsedMs: elapsed,+ error: error.message,+ });reject(new Error(`Windows paste failed: ${error.message}. Text is copied to clipboard - please paste manually with Ctrl+V.`@@ -323,7 +372,7 @@ class ClipboardManager {const timeoutId = setTimeout(() => {hasTimedOut = true;const elapsed = Date.now() - startTime;- this.safeLog(`β±οΈ PowerShell paste operation timed out after ${elapsed}ms`);+ this.safeLog(`β±οΈ PowerShell paste timeout`, { elapsedMs: elapsed });killProcess(pasteProcess, "SIGKILL");pasteProcess.removeAllListeners();reject(@@ -332,7 +381,7 @@ class ClipboardManager {));}, 5000);- }, 10); // Reduced from PASTE_DELAY_MS (50ms) to 10ms - clipboard write is synchronous+ }, pasteDelay);});}diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex 981df2b0d..a016f52eb 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -212,15 +212,69 @@ class WhisperManager {this.cachedBinaryPath = null;}- async initializeAtStartup() {+ async initializeAtStartup(settings = {}) {+ const startTime = Date.now();+try {await this.getWhisperBinaryPath();this.isInitialized = true;++ // Pre-warm whisper-server if local mode enabled (eliminates 2-5s cold-start delay)+ const { useLocalWhisper, whisperModel } = settings;++ if (useLocalWhisper && whisperModel && this.serverManager.isAvailable()) {+ const modelPath = this.getModelPath(whisperModel);++ if (fs.existsSync(modelPath)) {+ debugLogger.info("Pre-warming whisper-server", {+ model: whisperModel,+ modelPath,+ });++ try {+ const serverStartTime = Date.now();+ await this.serverManager.start(modelPath);+ this.currentServerModel = whisperModel;++ debugLogger.info("whisper-server pre-warmed successfully", {+ model: whisperModel,+ startupTimeMs: Date.now() - serverStartTime,+ port: this.serverManager.port,+ });+ } catch (err) {+ debugLogger.warn("Server pre-warm failed (will start on first use)", {+ error: err.message,+ model: whisperModel,+ });+ // Non-fatal: server will start on first transcription+ }+ } else {+ debugLogger.debug("Skipping server pre-warm: model not downloaded", {+ model: whisperModel,+ modelPath,+ });+ }+ } else {+ debugLogger.debug("Skipping server pre-warm", {+ reason: !useLocalWhisper+ ? "local mode disabled"+ : !whisperModel+ ? "no model selected"+ : "server binary not available",+ });+ }} catch (error) {- debugLogger.log("whisper.cpp not available at startup:", error.message);- this.isInitialized = true;+ debugLogger.warn("Whisper initialization error", {+ error: error.message,+ });+ this.isInitialized = true; // Mark initialized even on error}+ debugLogger.info("Whisper initialization complete", {+ totalTimeMs: Date.now() - startTime,+ serverRunning: this.serverManager.ready,+ });+// Log dependency status for debuggingawait this.logDependencyStatus();}diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.jsindex 0d46c43d6..c72c3743a 100644--- a/src/helpers/whisperServer.js+++ b/src/helpers/whisperServer.js@@ -225,6 +225,11 @@ class WhisperServerManager {async waitForReady(getProcessInfo) {const startTime = Date.now();+ let pollCount = 0;++ // Poll every 100ms during startup (faster than ongoing health checks at 5000ms)+ // This saves 0-400ms average vs 500ms polling+ const STARTUP_POLL_INTERVAL_MS = 100;while (Date.now() - startTime < STARTUP_TIMEOUT_MS) {if (!this.process || this.process.killed) {@@ -236,12 +241,17 @@ class WhisperServerManager {);}+ pollCount++;if (await this.checkHealth()) {this.ready = true;+ debugLogger.debug("whisper-server ready", {+ startupTimeMs: Date.now() - startTime,+ pollCount,+ });return;}- await new Promise((resolve) => setTimeout(resolve, 500));+ await new Promise((resolve) => setTimeout(resolve, STARTUP_POLL_INTERVAL_MS));}throw new Error(`whisper-server failed to start within ${STARTUP_TIMEOUT_MS}ms`);