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 streaming liveness check, batch fallback, and full locale codes
Gabriel Steinc589a563df47
diff --git a/README.md b/README.mdindex 3f2d49b2c..482053a84 100644--- a/README.md+++ b/README.md@@ -177,9 +177,39 @@ chmod +x dist/OpenWhispr-*.AppImage./dist/OpenWhispr-*.AppImage```-**Optional Dependencies for Automatic Paste**:+**Native Paste Binary (`linux-fast-paste`)**:-The clipboard paste feature requires platform-specific tools:+OpenWhispr ships a native C binary for pasting text on Linux, compiled automatically at build time. This is the **primary** paste mechanism — external tools like `xdotool` and `wtype` are only used as fallbacks if the native binary fails.++How it works:+- **X11**: Uses the XTest extension to synthesize `Ctrl+V` (or `Ctrl+Shift+V` in terminals) directly, with no external dependencies beyond X11 itself+- **Wayland**: Uses the Linux `uinput` subsystem to create a virtual keyboard and inject keystrokes. Falls back to XTest via XWayland if uinput is unavailable+- **Terminal detection**: Recognizes 20+ terminal emulators (kitty, alacritty, gnome-terminal, wezterm, ghostty, etc.) and automatically uses `Ctrl+Shift+V` instead of `Ctrl+V`+- **Window targeting**: Can target a specific window ID via `--window` to ensure keystrokes reach the correct application++Build dependencies (for compiling from source):+```bash+# Debian/Ubuntu+sudo apt install gcc libx11-dev libxtst-dev++# Fedora/RHEL+sudo dnf install gcc libX11-devel libXtst-devel++# Arch+sudo pacman -S gcc libx11 libxtst+```++The build script (`scripts/build-linux-fast-paste.js`) runs during `npm run compile:linux-paste` and:+1. Detects whether `linux/uinput.h` headers are available+2. Compiles with `-DHAVE_UINPUT` if so (enables Wayland uinput support)+3. Caches the binary and skips rebuilds unless the source or flags change+4. Gracefully falls back to system tools if compilation fails++If the native binary isn't available, OpenWhispr falls back to external paste tools in this order:++**Fallback Dependencies for Automatic Paste**:++The following tools are used as fallbacks when the native paste binary is unavailable or fails:**X11 (Traditional Linux Desktop)**:```bash@@ -240,7 +270,7 @@ sudo dnf install kdotool # Fedora/RHELsudo pacman -S kdotool # Arch```-> ℹ️ **Note**: OpenWhispr automatically tries paste tools in this order: `wtype` → `ydotool` → `xdotool` (for XWayland apps). If no paste tool is installed, text will still be copied to the clipboard - you'll just need to paste manually with Ctrl+V.+> ℹ️ **Note**: OpenWhispr automatically tries paste methods in this order: native `linux-fast-paste` binary (XTest or uinput) → `wtype` → `ydotool` → `xdotool` (for XWayland apps). If no paste method works, text will still be copied to the clipboard - you'll just need to paste manually with Ctrl+V.> ⚠️ **ydotool Requirements**: The `ydotoold` daemon must be running for ydotool to work. Start it manually with `sudo ydotoold &` or enable the systemd service as shown above.diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex bc2b901c3..fa17f3ece 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -62,6 +62,8 @@ class AudioManager {this.workletBlobUrl = null;this.streamingStartInProgress = false;this.stopRequestedDuringStreamingStart = false;+ this.streamingFallbackRecorder = null;+ this.streamingFallbackChunks = [];}getWorkletBlobUrl() {@@ -1754,9 +1756,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const [, wsResult] = await Promise.all([this.cacheMicrophoneDeviceId(),withSessionRefresh(async () => {+ const warmupLang = localStorage.getItem("preferredLanguage");const res = await window.electronAPI.deepgramStreamingWarmup({sampleRate: 16000,- language: getBaseLanguageCode(localStorage.getItem("preferredLanguage")),+ language: warmupLang && warmupLang !== "auto" ? warmupLang : undefined,keyterms: this.getKeyterms(),});// Throw error to trigger retry if AUTH_EXPIRED@@ -1873,6 +1876,19 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor););}+ // Start fallback recorder in case streaming produces no results+ try {+ this.streamingFallbackChunks = [];+ this.streamingFallbackRecorder = new MediaRecorder(stream);+ this.streamingFallbackRecorder.ondataavailable = (e) => {+ if (e.data.size > 0) this.streamingFallbackChunks.push(e.data);+ };+ this.streamingFallbackRecorder.start();+ } catch (e) {+ logger.debug("Fallback recorder failed to start", { error: e.message }, "streaming");+ this.streamingFallbackRecorder = null;+ }+// 2. Set up audio pipeline so frames flow the instant WebSocket is ready.// Frames sent before WebSocket connects are silently dropped by sendAudio().const audioContext = await this.getOrCreateAudioContext();@@ -1947,9 +1963,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// 4. Connect WebSocket — audio is already flowing from the pipeline above,// so Deepgram receives data immediately (no idle timeout).const result = await withSessionRefresh(async () => {+ const preferredLang = localStorage.getItem("preferredLanguage");const res = await window.electronAPI.deepgramStreamingStart({sampleRate: 16000,- language: getBaseLanguageCode(localStorage.getItem("preferredLanguage")),+ language: preferredLang && preferredLang !== "auto" ? preferredLang : undefined,keyterms: this.getKeyterms(),});@@ -2073,6 +2090,21 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.streamingSource = null;}this.streamingAudioContext = null;++ // Stop fallback recorder before stopping media tracks+ let fallbackBlob = null;+ if (this.streamingFallbackRecorder?.state === "recording") {+ fallbackBlob = await new Promise((resolve) => {+ this.streamingFallbackRecorder.onstop = () => {+ const mimeType = this.streamingFallbackRecorder.mimeType || "audio/webm";+ resolve(new Blob(this.streamingFallbackChunks, { type: mimeType }));+ };+ this.streamingFallbackRecorder.stop();+ });+ }+ this.streamingFallbackRecorder = null;+ this.streamingFallbackChunks = [];+if (this.streamingStream) {this.streamingStream.getTracks().forEach((track) => track.stop());this.streamingStream = null;@@ -2191,6 +2223,26 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}}+ // If streaming produced no text, fall back to batch transcription+ if (!finalText && durationSeconds > 2 && fallbackBlob?.size > 0) {+ logger.info(+ "Streaming produced no text, falling back to batch transcription",+ { durationSeconds, blobSize: fallbackBlob.size },+ "streaming"+ );+ try {+ const batchResult = await this.processWithOpenWhisprCloud(fallbackBlob, {+ durationSeconds,+ });+ if (batchResult?.text) {+ finalText = batchResult.text;+ logger.info("Batch fallback succeeded", { textLength: finalText.length }, "streaming");+ }+ } catch (fallbackErr) {+ logger.error("Batch fallback failed", { error: fallbackErr.message }, "streaming");+ }+ }+if (finalText) {const tBeforePaste = performance.now();this.onTranscriptionComplete?.({@@ -2222,6 +2274,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}cleanupStreamingAudio() {+ if (this.streamingFallbackRecorder?.state === "recording") {+ try {+ this.streamingFallbackRecorder.stop();+ } catch {}+ }+ this.streamingFallbackRecorder = null;+ this.streamingFallbackChunks = [];+if (this.streamingProcessor) {try {this.streamingProcessor.port.postMessage("stop");diff --git a/src/helpers/deepgramStreaming.js b/src/helpers/deepgramStreaming.jsindex a57a6c453..513d5acae 100644--- a/src/helpers/deepgramStreaming.js+++ b/src/helpers/deepgramStreaming.js@@ -10,13 +10,58 @@ const REWARM_DELAY_MS = 2000;const MAX_REWARM_ATTEMPTS = 10;const KEEPALIVE_INTERVAL_MS = 3000;const COLD_START_BUFFER_MAX = 3 * SAMPLE_RATE * 2; // 3 seconds of 16-bit PCM+const LIVENESS_TIMEOUT_MS = 2500; // Max wait for first Results from a warm connection// Languages supported by Nova-3 (base codes). If a language isn't here, fall back to Nova-2.const NOVA3_LANGUAGES = new Set([- "ar", "be", "bn", "bs", "bg", "ca", "hr", "cs", "da", "nl", "en", "et",- "fi", "fr", "de", "el", "he", "hi", "hu", "id", "it", "ja", "kn", "ko",- "lv", "lt", "mk", "ms", "mr", "no", "fa", "pl", "pt", "ro", "ru", "sr",- "sk", "sl", "es", "sv", "tl", "ta", "te", "tr", "uk", "ur", "vi", "multi",+ "ar",+ "be",+ "bn",+ "bs",+ "bg",+ "ca",+ "hr",+ "cs",+ "da",+ "nl",+ "en",+ "et",+ "fi",+ "fr",+ "de",+ "el",+ "he",+ "hi",+ "hu",+ "id",+ "it",+ "ja",+ "kn",+ "ko",+ "lv",+ "lt",+ "mk",+ "ms",+ "mr",+ "no",+ "fa",+ "pl",+ "pt",+ "ro",+ "ru",+ "sr",+ "sk",+ "sl",+ "es",+ "sv",+ "tl",+ "ta",+ "te",+ "tr",+ "uk",+ "ur",+ "vi",+ "multi",]);// 100ms of silence at 16kHz 16-bit mono — sent to warm connections to prevent@@ -52,6 +97,13 @@ class DeepgramStreaming {this.coldStartBufferSize = 0;this.tokenRefreshFn = null;this.proactiveRefreshTimer = null;+ this._generation = 0;+ this.audioBytesSent = 0;+ this.resultsReceived = 0;+ this.livenessTimer = null;+ this.replayBuffer = [];+ this.replayBufferSize = 0;+ this.connectionOptions = null;}setTokenRefreshFn(fn) {@@ -423,8 +475,59 @@ class DeepgramStreaming {return result;}+ startLivenessCheck() {+ clearTimeout(this.livenessTimer);+ this.livenessTimer = setTimeout(() => {+ this.handleLivenessTimeout().catch((err) => {+ debugLogger.error("Deepgram liveness reconnect error", { error: err.message });+ });+ }, LIVENESS_TIMEOUT_MS);+ }++ async handleLivenessTimeout() {+ if (this.resultsReceived > 0 || !this.isConnected) return;++ const gen = this._generation;+ const savedReplay = this.replayBuffer;++ debugLogger.warn("Deepgram warm connection unresponsive, reconnecting", {+ audioBytesSent: this.audioBytesSent,+ });++ this.isDisconnecting = true;+ this.cleanup();+ this.isDisconnecting = false;++ if (gen !== this._generation) return;++ let token = this.getCachedToken();+ if (!token && this.tokenRefreshFn) {+ try {+ token = await this.tokenRefreshFn();+ if (token) this.cacheToken(token);+ } catch (err) {+ debugLogger.error("Deepgram reconnect token refresh failed", { error: err.message });+ return;+ }+ }+ if (!token) return;+ if (gen !== this._generation) return;++ try {+ await this.connect({+ ...this.connectionOptions,+ token,+ replayBuffer: savedReplay,+ forceNew: true,+ });+ debugLogger.debug("Deepgram liveness reconnect succeeded");+ } catch (err) {+ debugLogger.error("Deepgram liveness reconnect failed", { error: err.message });+ }+ }+async connect(options = {}) {- const { token } = options;+ const { token, replayBuffer, forceNew } = options;if (!token) {throw new Error("Streaming token is required");}@@ -434,13 +537,31 @@ class DeepgramStreaming {return;}+ this.connectionOptions = {+ sampleRate: options.sampleRate,+ language: options.language,+ keyterms: options.keyterms,+ };this.accumulatedText = "";this.finalSegments = [];- this.coldStartBuffer = [];- this.coldStartBufferSize = 0;+ this.audioBytesSent = 0;+ this.resultsReceived = 0;++ if (replayBuffer && replayBuffer.length > 0) {+ this.coldStartBuffer = replayBuffer;+ this.coldStartBufferSize = replayBuffer.reduce((sum, b) => sum + b.length, 0);+ debugLogger.debug("Deepgram replaying buffered audio", {+ chunks: replayBuffer.length,+ bytes: this.coldStartBufferSize,+ });+ } else {+ this.coldStartBuffer = [];+ this.coldStartBufferSize = 0;+ }- if (this.hasWarmConnection()) {+ if (!forceNew && this.hasWarmConnection()) {if (this.useWarmConnection()) {+ this.startLivenessCheck();debugLogger.debug("Deepgram using warm connection - instant start");return;}@@ -488,6 +609,11 @@ class DeepgramStreaming {reason: reason?.toString(),wasActive,});+ if (this.pendingReject) {+ this.pendingReject(new Error(`WebSocket closed before ready (code: ${code})`));+ this.pendingReject = null;+ this.pendingResolve = null;+ }if (this.closeResolve) {this.closeResolve({ text: this.accumulatedText });}@@ -528,6 +654,13 @@ class DeepgramStreaming {break;case "Results": {+ this.resultsReceived++;+ if (this.livenessTimer) {+ clearTimeout(this.livenessTimer);+ this.livenessTimer = null;+ this.replayBuffer = [];+ this.replayBufferSize = 0;+ }const transcript = message.channel?.alternatives?.[0]?.transcript;if (!transcript) break;@@ -602,6 +735,13 @@ class DeepgramStreaming {this.coldStartBufferSize = 0;}+ if (this.livenessTimer) {+ const copy = Buffer.from(pcmBuffer);+ this.replayBuffer.push(copy);+ this.replayBufferSize += copy.length;+ }++ this.audioBytesSent += pcmBuffer.length;this.ws.send(pcmBuffer);return true;}@@ -617,6 +757,16 @@ class DeepgramStreaming {}async disconnect(closeStream = true) {+ this._generation++;+ clearTimeout(this.livenessTimer);+ this.livenessTimer = null;++ debugLogger.debug("Deepgram disconnect", {+ audioBytesSent: this.audioBytesSent,+ resultsReceived: this.resultsReceived,+ textLength: this.accumulatedText.length,+ });+if (!this.ws) return { text: this.accumulatedText };this.isDisconnecting = true;@@ -658,6 +808,10 @@ class DeepgramStreaming {this.stopKeepAlive();clearTimeout(this.connectionTimeout);this.connectionTimeout = null;+ clearTimeout(this.livenessTimer);+ this.livenessTimer = null;+ this.replayBuffer = [];+ this.replayBufferSize = 0;if (this.ws) {try {