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(nemotron): single-pass streaming commit and tuned sherpa-onnx online pipeline (#1238)
Gabriel Stein1f10639154b7
diff --git a/CLAUDE.md b/CLAUDE.mdindex d7d71607e..e7826c95b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -182,9 +182,11 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- `nemotron-speech-streaming-en-0.6b`: English-only, ~632MB, cache-aware streaming FastConformer (`"runtime": "online"` in the registry)- `nemotron-3.5-asr-streaming-0.6b`: Multilingual (15 transcription-ready languages, auto detection), ~650MB, cache-aware streaming FastConformer (`"runtime": "online"`)-- **Runtimes**: Models are `offline` (default) or `online` per their registry `runtime` field. Offline models use the bundled `sherpa-onnx-ws-{platform}-{arch}` (offline websocket server); online models use `sherpa-onnx-online-ws-{platform}-{arch}` (online websocket server). Both are downloaded by `scripts/download-sherpa-onnx.js`. The final transcription path still records-then-transcribes; audio is chunked over the websocket and partial/final JSON results are merged by `parakeetWsResult.js`.+- **Runtimes**: Models are `offline` (default) or `online` per their registry `runtime` field. Offline models use the bundled `sherpa-onnx-ws-{platform}-{arch}` (offline websocket server); online models use `sherpa-onnx-online-ws-{platform}-{arch}` (online websocket server). Both are downloaded by `scripts/download-sherpa-onnx.js`. Partial/final JSON results are merged by `parakeetWsResult.js`.-- **Live Transcription Preview**: When the preview toggle is on and an online-runtime model is selected, the preview uses a persistent websocket stream (`createOnlineStream` in `parakeetWsServer.js`): worklet PCM is fed as it is captured (`sendPcm16` converts to the float32 wire format inside the ws layer), and partial results update the preview window live (replacing text via `showTranscriptionPreview`). Offline models keep the 1.5s buffered-chunk path (appending via `appendTranscriptionPreview`). If the stream can't start, the preview falls back to the chunked path. Tests: `test/helpers/parakeetOnlineStream.test.js` (mock websocket server).+- **Streaming Commit (online models)**: For online-runtime models, dictation streams worklet PCM to a persistent websocket stream during capture (regardless of the preview toggle) and commits the flushed text at stop as the final transcript — no second decode of the recording. The stop flush is truncation-aware (`finish()` extends its deadline while results keep arriving and flags `truncated`); anything but a clean flush falls back to the record-then-transcribe path (`transcribe-local-parakeet`), which for online models decodes the whole recording over a single stream (no 15s segmentation; segments only bound memory for very long files).++- **Live Transcription Preview**: When the preview toggle is on and an online-runtime model is selected, the preview shares the streaming-commit websocket: partial results update the preview window live (replacing text via `showTranscriptionPreview`). Offline models keep the 1.5s buffered-chunk path (appending via `appendTranscriptionPreview`). If the stream can't start or dies mid-dictation, the preview falls back to the chunked path and the final transcript falls back to the full decode. Tests: `test/helpers/parakeetOnlineStream.test.js` (mock websocket server).- **Download URLs**: Models from sherpa-onnx ASR models release on GitHub@@ -406,11 +408,12 @@ The app can open OS-level settings for microphone permissions, sound input selec- `open-accessibility-settings`: Opens accessibility privacy settings (macOS only)**Platform-specific URLs**:-| Platform | Microphone Privacy | Sound Input | Accessibility |-|----------|-------------------|-------------|---------------|-| macOS | `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone` | `x-apple.systempreferences:com.apple.preference.sound?input` | `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility` |-| Windows | `ms-settings:privacy-microphone` | `ms-settings:sound` | N/A |-| Linux | Manual (no URL scheme) | Manual (e.g., pavucontrol) | N/A |++| Platform | Microphone Privacy | Sound Input | Accessibility |+| -------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------- |+| macOS | `x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone` | `x-apple.systempreferences:com.apple.preference.sound?input` | `x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility` |+| Windows | `ms-settings:privacy-microphone` | `ms-settings:sound` | N/A |+| Linux | Manual (no URL scheme) | Manual (e.g., pavucontrol) | N/A |**UI Component** (`MicPermissionWarning.tsx`):diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 791c7e693..70a65d7ef 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -26,7 +26,11 @@ import {isCloudTranslationMode,} from "../stores/settingsStore";import { recordCleanupFailure } from "../stores/cleanupFailureStore";-import { getBatchTranscriptionModel, getTranscriptionProvider } from "../models/ModelRegistry";+import {+ getBatchTranscriptionModel,+ getTranscriptionProvider,+ isOnlineParakeetModel,+} from "../models/ModelRegistry";import { shouldSkipTranscriptionApiKey } from "./transcriptionAuth";import {isSelfHostedTranscription,@@ -330,6 +334,8 @@ class AudioManager {this.lastAudioBlob = null;this.lastAudioMetadata = null;this._localSpeechGateState = null;+ this._streamingCommitActive = false;+ this._previewFlushResolve = null;}getWorkletBlobUrl() {@@ -350,6 +356,7 @@ class PCMStreamingProcessor extends AudioWorkletProcessor {this._buffer = new Int16Array(BUFFER_SIZE);this._offset = 0;}+ this.port.postMessage("flushed");this._stopped = true;}};@@ -731,7 +738,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.mediaRecorder.onstop = async () => {this.teardownSpeechGate();- this.cleanupPreview({ showCleanup: this.shouldShowPreviewCleanupState() });+ const previewStopPromise = this.cleanupPreview({+ showCleanup: this.shouldShowPreviewCleanupState(),+ });this.isRecording = false;this.isProcessing = true;@@ -778,7 +787,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return;}- await this.processAudio(audioBlob, { durationSeconds });+ // Non-commit sessions stop concurrently with the decode below.+ const previewStop = this._streamingCommitActive ? await previewStopPromise : null;+ this._streamingCommitActive = false;++ await this.processAudio(audioBlob, {+ durationSeconds,+ ...(previewStop?.streamed ? { streamedText: previewStop.text } : {}),+ });micStream.getTracks().forEach((track) => track.stop());};@@ -794,7 +810,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);whisperModel,parakeetModel,} = getSettings();- if (showTranscriptionPreview && useLocalWhisper) {+ const isNvidia = localTranscriptionProvider === "nvidia";+ // Online models stream+commit during capture, so PCM runs even with preview off.+ const streamingCommit = useLocalWhisper && isNvidia && isOnlineParakeetModel(parakeetModel);+ this._streamingCommitActive = false;+ if (useLocalWhisper && (showTranscriptionPreview || streamingCommit)) {try {this._previewAudioContext = new AudioContext({ sampleRate: 16000 });this._previewSource = this._previewAudioContext.createMediaStreamSource(micStream);@@ -805,14 +825,24 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);"pcm-streaming-processor");this._previewProcessor.port.onmessage = (event) => {+ if (event.data === "flushed") {+ this._previewFlushResolve?.();+ return;+ }window.electronAPI?.sendDictationPreviewAudio?.(event.data);};this._previewSource.connect(this._previewProcessor);- const provider = localTranscriptionProvider === "nvidia" ? "nvidia" : "whisper";- const model = provider === "nvidia" ? parakeetModel : whisperModel;+ const provider = isNvidia ? "nvidia" : "whisper";+ const model = isNvidia ? parakeetModel : whisperModel;const language = getBaseLanguageCode(getSettings().preferredLanguage);- window.electronAPI?.startDictationPreview?.({ provider, model, language });+ window.electronAPI?.startDictationPreview?.({+ provider,+ model,+ language,+ display: showTranscriptionPreview,+ });+ this._streamingCommitActive = streamingCommit;} catch (e) {logger.warn("Preview worklet setup failed", { error: e.message }, "audio");}@@ -1158,32 +1188,43 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const timings = {};try {- const arrayBuffer = await audioBlob.arrayBuffer();+ let result;+ if (typeof metadata.streamedText === "string") {+ const streamedText = metadata.streamedText.trim();+ if (!streamedText) {+ throw new Error("No audio detected");+ }+ logger.debug("Parakeet using committed streaming transcript", { model }, "performance");+ timings.transcriptionProcessingDurationMs = 0;+ result = { success: true, text: streamedText };+ } else {+ const arrayBuffer = await audioBlob.arrayBuffer();- logger.debug(- "Parakeet transcription starting",- {- audioFormat: audioBlob.type,- audioSizeBytes: audioBlob.size,- model,- },- "performance"- );+ logger.debug(+ "Parakeet transcription starting",+ {+ audioFormat: audioBlob.type,+ audioSizeBytes: audioBlob.size,+ model,+ },+ "performance"+ );- const transcriptionStart = performance.now();- const result = await window.electronAPI.transcribeLocalParakeet(arrayBuffer, { model });- timings.transcriptionProcessingDurationMs = Math.round(- performance.now() - transcriptionStart- );+ const transcriptionStart = performance.now();+ result = await window.electronAPI.transcribeLocalParakeet(arrayBuffer, { model });+ timings.transcriptionProcessingDurationMs = Math.round(+ performance.now() - transcriptionStart+ );- logger.debug(- "Parakeet transcription complete",- {- transcriptionProcessingDurationMs: timings.transcriptionProcessingDurationMs,- success: result.success,- },- "performance"- );+ logger.debug(+ "Parakeet transcription complete",+ {+ transcriptionProcessingDurationMs: timings.transcriptionProcessingDurationMs,+ success: result.success,+ },+ "performance"+ );+ }if (result.success && result.text) {const rawText = result.text;@@ -1198,6 +1239,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);rawText,source: "local-parakeet",timings,+ ...(result.warning ? { warning: result.warning } : {}),};} else {throw new Error("No text transcribed");@@ -3655,27 +3697,39 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor););}- cleanupPreview(options = {}) {+ async cleanupPreview(options = {}) {const { dismiss = false, showCleanup = false } = options;- if (this._previewProcessor) {- this._previewProcessor.port.postMessage("stop");- this._previewProcessor.disconnect();- this._previewProcessor = null;- }- if (this._previewSource) {- this._previewSource.disconnect();- this._previewSource = null;- }- if (this._previewAudioContext) {- this._previewAudioContext.close().catch(() => {});- this._previewAudioContext = null;- }+ // Claim the session's nodes synchronously so a recording started during the+ // flush await can never have its fresh nodes torn down by this cleanup.+ const processor = this._previewProcessor;+ const source = this._previewSource;+ const audioContext = this._previewAudioContext;+ this._previewProcessor = null;+ this._previewSource = null;+ this._previewAudioContext = null;++ if (processor) {+ // Wait for the worklet to flush its partial buffer so the final PCM+ // chunk reaches the stream before it is finished.+ let resolveFlush;+ const flushed = new Promise((resolve) => {+ resolveFlush = resolve;+ setTimeout(resolve, 150);+ });+ this._previewFlushResolve = resolveFlush;+ processor.port.postMessage("stop");+ await flushed;+ if (this._previewFlushResolve === resolveFlush) this._previewFlushResolve = null;+ processor.disconnect();+ }+ source?.disconnect();+ audioContext?.close().catch(() => {});if (dismiss) {window.electronAPI?.dismissDictationPreview?.();- return;+ return null;}- window.electronAPI?.stopDictationPreview?.({ showCleanup });+ return (await window.electronAPI?.stopDictationPreview?.({ showCleanup })) || null;}cleanupStreamingAudio() {diff --git a/src/helpers/ffmpegUtils.js b/src/helpers/ffmpegUtils.jsindex 2800d7d47..f2a8d4e7a 100644--- a/src/helpers/ffmpegUtils.js+++ b/src/helpers/ffmpegUtils.js@@ -184,6 +184,28 @@ function convertToWav(inputPath, outputPath, options = {}) {});}+function parseWavFormat(wavBuffer) {+ if (!isWavFormat(wavBuffer)) return null;++ let offset = 12; // Skip RIFF header (4) + size (4) + WAVE (4)+ while (offset < wavBuffer.length - 8) {+ const chunkId = wavBuffer.toString("ascii", offset, offset + 4);+ const chunkSize = wavBuffer.readUInt32LE(offset + 4);++ if (chunkId === "fmt ") {+ return {+ channels: wavBuffer.readUInt16LE(offset + 10),+ sampleRate: wavBuffer.readUInt32LE(offset + 12),+ bitsPerSample: wavBuffer.readUInt16LE(offset + 22),+ };+ }++ offset += 8 + chunkSize;+ }++ return null;+}+function wavToFloat32Samples(wavBuffer) {if (!isWavFormat(wavBuffer)) {throw new Error("Buffer is not a valid WAV file");@@ -331,6 +353,7 @@ function clearCache() {module.exports = {getFFmpegPath,isWavFormat,+ parseWavFormat,convertToWav,splitAudioFile,wavToFloat32Samples,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 049ff7dbb..f87c42c0b 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2365,9 +2365,13 @@ class IPCHandlers {ipcMain.handle("parakeet-server-start", async (event, modelName) => {const result = await this.parakeetManager.startServer(modelName);- process.env.LOCAL_TRANSCRIPTION_PROVIDER = "nvidia";- process.env.PARAKEET_MODEL = modelName;- await this.environmentManager.saveAllKeysToEnvFile();+ // Persisting a provider that failed to start would wedge every launch+ // into a failing pre-warm.+ if (result.success) {+ process.env.LOCAL_TRANSCRIPTION_PROVIDER = "nvidia";+ process.env.PARAKEET_MODEL = modelName;+ await this.environmentManager.saveAllKeysToEnvFile();+ }return result;});@@ -5835,6 +5839,8 @@ class IPCHandlers {let dictationPreviewChunkCount = 0;// Online-runtime models stream here instead of the 1.5s chunked path.let dictationPreviewStream = null;+ // false = headless streaming session (commit-only, no preview window).+ let dictationPreviewDisplay = true;// Bumped on every reset so async preview work can detect a stale session.let dictationPreviewGen = 0;@@ -5857,9 +5863,18 @@ class IPCHandlers {dictationPreviewProvider = null;dictationPreviewModel = null;dictationPreviewLanguage = null;+ dictationPreviewDisplay = true;+ };++ const startDictationPreviewTimer = () => {+ if (!dictationPreviewTimer) {+ dictationPreviewTimer = setInterval(() => transcribeDictationPreviewChunk(), 1500);+ }};const transcribeDictationPreviewChunk = async () => {+ // The chunked path only feeds the preview window.+ if (!dictationPreviewDisplay) return;if (dictationPreviewTranscribing) return;if (!dictationPreviewBuffer.length) return;@@ -6540,48 +6555,69 @@ class IPCHandlers {return { success: true, text: result.text || "" };});- ipcMain.handle("start-dictation-preview", async (_event, { provider, model, language }) => {- resetDictationPreviewState();- const gen = dictationPreviewGen;- dictationPreviewMode = true;- dictationPreviewSessionActive = true;- dictationPreviewProvider = provider;- dictationPreviewModel = model;- dictationPreviewLanguage = language || null;- dictationPreviewChunkCount = 0;- this.windowManager.showTranscriptionPreview("");-- if (provider === "nvidia" && this.parakeetManager.supportsOnlineStreaming(model)) {- try {- const stream = await this.parakeetManager.createOnlineStream(model, {- onUpdate: (text) => {- if (gen === dictationPreviewGen && text) {- this.windowManager.showTranscriptionPreview(text);- }- },- });- if (gen !== dictationPreviewGen) {- stream.abort();+ ipcMain.handle(+ "start-dictation-preview",+ async (_event, { provider, model, language, display = true }) => {+ resetDictationPreviewState();+ const gen = dictationPreviewGen;+ dictationPreviewMode = true;+ dictationPreviewSessionActive = true;+ dictationPreviewProvider = provider;+ dictationPreviewModel = model;+ dictationPreviewLanguage = language || null;+ dictationPreviewDisplay = display;+ dictationPreviewChunkCount = 0;+ if (display) this.windowManager.showTranscriptionPreview("");++ if (provider === "nvidia" && this.parakeetManager.supportsOnlineStreaming(model)) {+ try {+ const stream = await this.parakeetManager.createOnlineStream(model, {+ onUpdate: (text) => {+ if (gen === dictationPreviewGen && text && dictationPreviewDisplay) {+ this.windowManager.showTranscriptionPreview(text);+ }+ },+ onError: (error) => {+ if (gen !== dictationPreviewGen || dictationPreviewStream !== stream) return;+ // Keep the preview alive on the chunked path; the final+ // transcript falls back to decoding the full recording.+ debugLogger.warn("Online preview stream failed mid-session, falling back", {+ model,+ error: error.message,+ });+ dictationPreviewStream = null;+ if (dictationPreviewDisplay) startDictationPreviewTimer();+ },+ });+ if (gen !== dictationPreviewGen) {+ stream.abort();+ return { success: true };+ }+ dictationPreviewStream = stream;+ for (const chunk of dictationPreviewBuffer) {+ stream.sendPcm16(chunk);+ }+ dictationPreviewBuffer = [];return { success: true };+ } catch (error) {+ debugLogger.warn("Online preview stream unavailable, falling back to chunked preview", {+ model,+ error: error.message,+ });}- dictationPreviewStream = stream;- for (const chunk of dictationPreviewBuffer) {- stream.sendPcm16(chunk);- }- dictationPreviewBuffer = [];+ }++ if (gen !== dictationPreviewGen) return { success: true };+ if (!display) {+ // A headless session exists only to feed the online stream; without+ // one, buffered PCM would just accumulate with no consumer.+ resetDictationPreviewState();return { success: true };- } catch (error) {- debugLogger.warn("Online preview stream unavailable, falling back to chunked preview", {- model,- error: error.message,- });}+ startDictationPreviewTimer();+ return { success: true };}-- if (gen !== dictationPreviewGen) return { success: true };- dictationPreviewTimer = setInterval(() => transcribeDictationPreviewChunk(), 1500);- return { success: true };- });+ );ipcMain.on("dictation-preview-audio", (_event, audioBuffer) => {if (!dictationPreviewMode) return;@@ -6635,26 +6671,38 @@ class IPCHandlers {ipcMain.handle("stop-dictation-preview", async (_event, options = {}) => {if (!dictationPreviewMode && !dictationPreviewSessionActive) {- return { success: true };+ return { success: true, streamed: false, text: "" };}clearInterval(dictationPreviewTimer);dictationPreviewTimer = null;+ const display = dictationPreviewDisplay;+ let streamed = false;+ let streamedText = "";if (dictationPreviewStream) {const stream = dictationPreviewStream;dictationPreviewStream = null;- const { text } = await stream.finish().catch(() => ({ text: "" }));- if (text && dictationPreviewSessionActive) {- this.windowManager.showTranscriptionPreview(text);+ const gen = dictationPreviewGen;+ const result = await stream.finish().catch(() => null);+ if (gen !== dictationPreviewGen) {+ return { success: true, streamed: false, text: "" };+ }+ if (result) {+ streamedText = result.text || "";+ // Only a clean flush is trustworthy as the final transcript.+ streamed = !result.truncated;+ }+ if (streamedText && display && dictationPreviewSessionActive) {+ this.windowManager.showTranscriptionPreview(streamedText);}} else {await transcribeDictationPreviewChunk();}- resetDictationPreviewState({ preserveSession: true });- if (!dictationPreviewSessionActive) {- return { success: true };+ resetDictationPreviewState({ preserveSession: display });+ if (!display || !dictationPreviewSessionActive) {+ return { success: true, streamed, text: streamedText };}this.windowManager.holdTranscriptionPreview(options);- return { success: true };+ return { success: true, streamed, text: streamedText };});ipcMain.handle("update-transcription-text", async (_event, id, text, rawText) => {diff --git a/src/helpers/parakeet.js b/src/helpers/parakeet.jsindex 0e16cde68..91549183d 100644--- a/src/helpers/parakeet.js+++ b/src/helpers/parakeet.js@@ -267,7 +267,10 @@ class ParakeetManager {return { success: false, message: "No audio detected" };}- return { success: true, text };+ // Surfaced by the renderer as a partial-transcription warning toast.+ return output.truncated+ ? { success: true, text, warning: "truncated" }+ : { success: true, text };}async downloadParakeetModel(modelName, progressCallback = null) {@@ -299,12 +302,15 @@ class ParakeetManager {let archiveReady = false;try {const stats = await fsPromises.stat(archivePath);- if (stats.size > 0) {+ // A visibly truncated leftover would just fail extraction forever.+ if (stats.size >= modelConfig.size * 0.9) {archiveReady = true;debugLogger.info("Reusing existing archive from previous attempt", {archivePath,size: stats.size,});+ } else if (stats.size > 0) {+ await fsPromises.unlink(archivePath).catch(() => {});}} catch {}@@ -342,6 +348,8 @@ class ParakeetManager {error: extractError.message,});if (attempt >= MAX_EXTRACT_RETRIES) {+ // The archive is the prime suspect; drop it so the next attempt re-downloads.+ await fsPromises.unlink(archivePath).catch(() => {});const err = new Error(`Model installation failed: ${extractError.message}`);err.code = "EXTRACTION_FAILED";throw err;@@ -354,7 +362,14 @@ class ParakeetManager {progressCallback({ type: "complete", model: modelName, percentage: 100 });}- if (this.serverManager.isAvailable(getModelRuntime(modelName))) {+ // Pre-warm the downloaded model, but never hijack a server that is already+ // serving (or starting) another model — e.g. mid-dictation.+ const serverStatus = this.serverManager.getServerStatus();+ if (+ this.serverManager.isAvailable(getModelRuntime(modelName)) &&+ !serverStatus.running &&+ !serverStatus.starting+ ) {this.serverManager.startServer(modelName).catch((err) => {debugLogger.warn("Post-download server pre-warm failed (non-fatal)", {error: err.message,diff --git a/src/helpers/parakeetServer.js b/src/helpers/parakeetServer.jsindex 4d3d8be16..280ea1531 100644--- a/src/helpers/parakeetServer.js+++ b/src/helpers/parakeetServer.js@@ -5,6 +5,7 @@ const { getModelsDirForService } = require("./modelDirUtils");const {getFFmpegPath,isWavFormat,+ parseWavFormat,convertToWav,wavToFloat32Samples,computeFloat32RMS,@@ -16,7 +17,9 @@ const { getModelRuntime, REQUIRED_MODEL_FILES } = require("./parakeetModelInfo")const SAMPLE_RATE = 16000;const BYTES_PER_SAMPLE = 4; // float32const MAX_SEGMENT_SECONDS = 15;-const MAX_SEGMENT_BYTES = MAX_SEGMENT_SECONDS * SAMPLE_RATE * BYTES_PER_SAMPLE;+// Cache-aware streaming models take arbitrarily long audio in one stream; the+// bound only caps memory when transcribing very long files.+const ONLINE_MAX_SEGMENT_SECONDS = 600;const SILENCE_RMS_THRESHOLD = 0.001;class ParakeetServerManager {@@ -48,8 +51,13 @@ class ParakeetServerManager {}async _ensureWav(audioBuffer) {- const isWav = isWavFormat(audioBuffer);- if (isWav) return { wavBuffer: audioBuffer, filesToCleanup: [] };+ if (isWavFormat(audioBuffer)) {+ const format = parseWavFormat(audioBuffer);+ if (format?.sampleRate === SAMPLE_RATE && format?.channels === 1) {+ return { wavBuffer: audioBuffer, filesToCleanup: [] };+ }+ debugLogger.debug("WAV input needs resampling", { format });+ }const ffmpegPath = getFFmpegPath();if (!ffmpegPath) {@@ -90,9 +98,9 @@ class ParakeetServerManager {const { wavBuffer, filesToCleanup } = await this._ensureWav(audioBuffer);try {- if (!this.wsServer.ready || this.wsServer.modelName !== modelName) {- await this.wsServer.start(modelName, modelDir, getModelRuntime(modelName));- }+ const runtime = getModelRuntime(modelName);+ // Awaiting unconditionally also covers a startup's warm-up completion.+ await this.wsServer.start(modelName, modelDir, runtime);const samples = wavToFloat32Samples(wavBuffer);const durationSeconds = samples.length / BYTES_PER_SAMPLE / SAMPLE_RATE;@@ -103,7 +111,11 @@ class ParakeetServerManager {return { text: "", elapsed: 0 };}- if (samples.length <= MAX_SEGMENT_BYTES) {+ const maxSegmentSeconds =+ runtime === "online" ? ONLINE_MAX_SEGMENT_SECONDS : MAX_SEGMENT_SECONDS;+ const maxSegmentBytes = maxSegmentSeconds * SAMPLE_RATE * BYTES_PER_SAMPLE;++ if (samples.length <= maxSegmentBytes) {const result = await this.wsServer.transcribe(samples, SAMPLE_RATE);if (!result.text?.trim()) {debugLogger.warn("Parakeet returned empty text for non-silent audio", {@@ -117,28 +129,33 @@ class ParakeetServerManager {debugLogger.debug("Parakeet segmenting long audio", {durationSeconds,- segmentCount: Math.ceil(samples.length / MAX_SEGMENT_BYTES),+ segmentCount: Math.ceil(samples.length / maxSegmentBytes),});const texts = [];let totalElapsed = 0;+ let truncated = false;- for (let offset = 0; offset < samples.length; offset += MAX_SEGMENT_BYTES) {- const end = Math.min(offset + MAX_SEGMENT_BYTES, samples.length);+ for (let offset = 0; offset < samples.length; offset += maxSegmentBytes) {+ const end = Math.min(offset + maxSegmentBytes, samples.length);const segment = samples.subarray(offset, end);const result = await this.wsServer.transcribe(segment, SAMPLE_RATE);totalElapsed += result.elapsed || 0;+ if (result.truncated) truncated = true;if (result.text) {texts.push(result.text);} else {debugLogger.warn("Parakeet segment returned empty text", {- segmentIndex: offset / MAX_SEGMENT_BYTES,+ segmentIndex: offset / maxSegmentBytes,segmentDuration: segment.length / BYTES_PER_SAMPLE / SAMPLE_RATE,});}}- return { text: texts.join(" "), elapsed: totalElapsed };+ const text = texts.join(" ");+ return truncated+ ? { text, elapsed: totalElapsed, truncated }+ : { text, elapsed: totalElapsed };} finally {this._cleanupFiles(filesToCleanup);}diff --git a/src/helpers/parakeetWsServer.js b/src/helpers/parakeetWsServer.jsindex 2a0b8d243..3b2f1629f 100644--- a/src/helpers/parakeetWsServer.js+++ b/src/helpers/parakeetWsServer.js@@ -20,7 +20,11 @@ const STARTUP_TIMEOUT_MS = 60000;const HEALTH_CHECK_INTERVAL_MS = 5000;const TRANSCRIPTION_TIMEOUT_MS = 300000;const ONLINE_CHUNK_BYTES = 8000 * 4;-const ONLINE_FINISH_TIMEOUT_MS = 10000;+const FLOAT32_BYTES_PER_SECOND = 16000 * 4;+// After "Done" is sent, give up only after this long without any result message.+const ONLINE_FINISH_IDLE_TIMEOUT_MS = 10000;+// Must cover the model's 560ms chunk so the flush decodes the final words.+const ONLINE_END_TAIL_PADDING_S = 0.6;class ParakeetWsServer {constructor() {@@ -31,6 +35,7 @@ class ParakeetWsServer {this.modelDir = null;this.modelRuntime = "offline";this.startupPromise = null;+ this.startingModelName = null;this.healthCheckInterval = null;this.cachedBinaryPaths = {};}@@ -57,16 +62,25 @@ class ParakeetWsServer {}async start(modelName, modelDir, runtime = "offline") {- if (this.startupPromise) return this.startupPromise;+ // Serialize with any in-flight startup; join it only when it's for the same model.+ while (this.startupPromise) {+ if (this.startingModelName === modelName) return this.startupPromise;+ await this.startupPromise.catch(() => {});+ }if (this.ready && this.modelName === modelName) return;- if (this.process) await this.stop();- this.startupPromise = this._doStart(modelName, modelDir, runtime);- try {- await this.startupPromise;- } finally {- this.startupPromise = null;- }+ this.startingModelName = modelName;+ // Assigned before any await so concurrent callers can never double-spawn.+ this.startupPromise = (async () => {+ try {+ if (this.process) await this.stop();+ await this._doStart(modelName, modelDir, runtime);+ } finally {+ this.startupPromise = null;+ this.startingModelName = null;+ }+ })();+ return this.startupPromise;}async _doStart(modelName, modelDir, runtime) {@@ -87,19 +101,31 @@ class ParakeetWsServer {`--joiner=${path.join(modelDir, "joiner.int8.onnx")}`,`--port=${this.port}`,...(runtime === "online"- ? [`--num-work-threads=${threads}`, "--warm-up=0"]+ ? [+ // --num-threads is ONNX intra-op parallelism for the single dictation+ // stream; --num-work-threads only spreads across concurrent streams.+ `--num-threads=${threads}`,+ "--num-work-threads=2",+ // Default 10ms decode-loop tick adds idle time to faster-than-realtime decode.+ "--loop-interval-ms=2",+ `--end-tail-padding=${ONLINE_END_TAIL_PADDING_S}`,+ // Nonzero --warm-up aborts startup for non-zipformer2 models; _warmUp()+ // covers it app-side.+ "--warm-up=0",+ ]: [`--num-threads=${threads}`]),];debugLogger.debug("Starting parakeet WS server", { port: this.port, modelName, runtime, args });- this.process = spawn(wsBinary, args, {+ const child = spawn(wsBinary, args, {stdio: ["ignore", "pipe", "pipe"],windowsHide: true,cwd: getSafeTempDir(),detached: process.platform !== "win32",});- sidecarPidFile.write("parakeet", this.process.pid);+ this.process = child;+ sidecarPidFile.write("parakeet", child.pid);let stderrBuffer = "";let exitCode = null;@@ -108,11 +134,11 @@ class ParakeetWsServer {readyResolve = resolve;});- this.process.stdout.on("data", (data) => {+ child.stdout.on("data", (data) => {debugLogger.debug("parakeet-ws stdout", { data: data.toString().trim() });});- this.process.stderr.on("data", (data) => {+ child.stderr.on("data", (data) => {stderrBuffer += data.toString();debugLogger.debug("parakeet-ws stderr", { data: data.toString().trim() });if (data.toString().includes("Listening on:")) {@@ -120,19 +146,22 @@ class ParakeetWsServer {}});- this.process.on("error", (error) => {+ child.on("error", (error) => {debugLogger.error("parakeet-ws process error", { error: error.message });- this.ready = false;+ if (this.process === child) this.ready = false;readyResolve(false);});- this.process.on("close", (code) => {+ child.on("close", (code) => {exitCode = code;debugLogger.debug("parakeet-ws process exited", { code });- this.ready = false;- this.process = null;- this.stopHealthCheck();- sidecarPidFile.clear("parakeet");+ // A superseded child must not clobber the state of its replacement.+ if (this.process === child) {+ this.ready = false;+ this.process = null;+ this.stopHealthCheck();+ sidecarPidFile.clear("parakeet");+ }readyResolve(false);});@@ -273,6 +302,13 @@ class ParakeetWsServer {clearTimeout(timeout);const elapsed = Date.now() - startTime;+ // The offline server always sends one result message (even for silence),+ // so closing without one means the server died or was stopped mid-request.+ if (!result) {+ reject(new Error("parakeet-ws connection closed before transcription completed"));+ return;+ }+debugLogger.debug("parakeet-ws transcription completed", {elapsed,code,@@ -309,12 +345,19 @@ class ParakeetWsServer {stream.sendFloat32(samplesBuffer.subarray(offset, offset + ONLINE_CHUNK_BYTES));}- const timeout = setTimeout(() => {- timedOut = true;- stream.abort();- }, TRANSCRIPTION_TIMEOUT_MS);+ // Blasted audio drains faster than real time but not instantly; scale both+ // the hard cap and the quiet-period allowance with the audio length.+ const audioSeconds = samplesBuffer.length / FLOAT32_BYTES_PER_SECOND;+ const timeout = setTimeout(+ () => {+ timedOut = true;+ stream.abort();+ },+ Math.max(TRANSCRIPTION_TIMEOUT_MS, audioSeconds * 2000)+ );try {- const { text } = await stream.finish();+ const idleTimeoutMs = Math.max(ONLINE_FINISH_IDLE_TIMEOUT_MS, audioSeconds * 500);+ const { text, truncated } = await stream.finish({ idleTimeoutMs });if (timedOut) throw new Error("parakeet-ws transcription timed out");if (streamError) {throw new Error(`parakeet-ws transcription failed: ${streamError.message}`);@@ -323,10 +366,11 @@ class ParakeetWsServer {const elapsed = Date.now() - startTime;debugLogger.debug("parakeet-ws streaming transcription completed", {elapsed,+ truncated,resultLength: text.length,resultPreview: text.slice(0, 200),});- return { text, elapsed };+ return truncated ? { text, elapsed, truncated } : { text, elapsed };} finally {clearTimeout(timeout);}@@ -343,15 +387,45 @@ class ParakeetWsServer {const results = createOnlineAccumulator();const pendingChunks = [];let finishResolve = null;+ let finishPromise = null;+ let idleTimeoutMs = ONLINE_FINISH_IDLE_TIMEOUT_MS;+ let idleTimer = null;let closed = false;+ let aborted = false;+ let serverDone = false;+ let truncated = false;let lastEmitted = "";const ws = new WebSocket(`ws://127.0.0.1:${this.port}`);+ const clearIdleTimer = () => {+ if (idleTimer) {+ clearTimeout(idleTimer);+ idleTimer = null;+ }+ };+const settle = () => {if (closed) return;closed = true;- if (finishResolve) finishResolve({ text: results.text() });+ clearIdleTimer();+ if (finishResolve) finishResolve({ text: results.text(), truncated });+ };++ // Backstop for a server that goes quiet after "Done": while results keep+ // arriving the deadline keeps extending; only true silence is a truncation.+ const armIdleTimer = () => {+ clearIdleTimer();+ idleTimer = setTimeout(() => {+ if (closed) return;+ truncated = true;+ debugLogger.warn("parakeet-ws online finish timed out; result may be truncated");+ try {+ ws.close();+ } catch {}+ settle();+ }, idleTimeoutMs);+ idleTimer.unref?.();};const sendFloat32 = (float32Samples) => {@@ -377,7 +451,9 @@ class ParakeetWsServer {ws.on("message", (data) => {const message = data.toString();+ if (finishResolve) armIdleTimer();if (message === "Done!") {+ serverDone = true;ws.close();return;}@@ -388,10 +464,17 @@ class ParakeetWsServer {}});- ws.on("close", () => settle());+ ws.on("close", () => {+ if (!serverDone && !aborted && !closed) {+ truncated = true;+ onError?.(new Error("connection closed before transcription completed"));+ }+ settle();+ });ws.on("error", (error) => {debugLogger.warn("parakeet-ws online stream error", { error: error.message });+ if (!serverDone && !aborted) truncated = true;onError?.(error);settle();});@@ -399,25 +482,22 @@ class ParakeetWsServer {return {sendFloat32,sendPcm16: (pcmBuffer) => sendFloat32(pcm16ToFloat32(pcmBuffer)),- finish: () =>- new Promise((resolve) => {+ finish: (options = {}) => {+ if (finishPromise) return finishPromise;+ if (options.idleTimeoutMs) idleTimeoutMs = options.idleTimeoutMs;+ finishPromise = new Promise((resolve) => {if (closed) {- resolve({ text: results.text() });+ resolve({ text: results.text(), truncated });return;}finishResolve = resolve;if (ws.readyState === WebSocket.OPEN) ws.send("Done");- // Backstop in case the server never acknowledges with "Done!".- setTimeout(() => {- if (!closed) {- try {- ws.close();- } catch {}- settle();- }- }, ONLINE_FINISH_TIMEOUT_MS).unref?.();- }),+ armIdleTimer();+ });+ return finishPromise;+ },abort: () => {+ aborted = true;try {ws.close();} catch {}@@ -454,8 +534,9 @@ class ParakeetWsServer {return {available: this.hasAnyWsBinary(),running: this.ready && this.process !== null,+ starting: this.startupPromise !== null,port: this.port,- modelName: this.modelName,+ modelName: this.modelName || this.startingModelName,};}}diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.tsindex 9745b8485..837c68967 100644--- a/src/models/ModelRegistry.ts+++ b/src/models/ModelRegistry.ts@@ -489,6 +489,10 @@ export function getParakeetModelInfo(modelId: string): ParakeetModelInfo | undefreturn modelData.parakeetModels[modelId];}+export function isOnlineParakeetModel(modelId: string): boolean {+ return modelData.parakeetModels[modelId]?.runtime === "online";+}+export const PARAKEET_MODEL_INFO = modelData.parakeetModels;export function getWhisperModelConfig(modelId: string): WhisperModelConfig | null {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 101453a3f..b639ad56f 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1968,8 +1968,11 @@ declare global {provider: string;model: string;language?: string;+ display?: boolean;}) => Promise<{ success: boolean }>;- stopDictationPreview?: (opts?: { showCleanup?: boolean }) => Promise<{ success: boolean }>;+ stopDictationPreview?: (opts?: {+ showCleanup?: boolean;+ }) => Promise<{ success: boolean; streamed?: boolean; text?: string }>;dismissDictationPreview?: () => Promise<{ success: boolean }>;completeDictationPreview?: (payload: { text?: string }) => Promise<{ success: boolean }>;hideDictationPreview?: () => Promise<{ success: boolean }>;diff --git a/src/utils/serverUtils.js b/src/utils/serverUtils.jsindex 57683e6e3..0d0362b73 100644--- a/src/utils/serverUtils.js+++ b/src/utils/serverUtils.js@@ -8,7 +8,8 @@ const GRACEFUL_STOP_TIMEOUT_MS = 5000;function tryBind(port, host) {return new Promise((resolve) => {const s = net.createServer();- s.once("error", () => resolve(false));+ // A host whose address family is absent (e.g. IPv6 disabled) can't conflict on the port.+ s.once("error", (err) => resolve(err.code === "EADDRNOTAVAIL" || err.code === "EAFNOSUPPORT"));s.once("listening", () => s.close(() => resolve(true)));s.listen(port, host);});diff --git a/test/helpers/parakeetOnlineStream.test.js b/test/helpers/parakeetOnlineStream.test.jsindex 18d02ba6e..79c35c4e4 100644--- a/test/helpers/parakeetOnlineStream.test.js+++ b/test/helpers/parakeetOnlineStream.test.js@@ -12,6 +12,7 @@ async function startMockOnlineServer({ onBinary, finalSegment = 0 }) {const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });await once(wss, "listening");+ let ignoringDone = false;wss.on("connection", (socket) => {let binaryFrames = 0;socket.on("message", (data, isBinary) => {@@ -20,7 +21,7 @@ async function startMockOnlineServer({ onBinary, finalSegment = 0 }) {onBinary?.(socket, data, binaryFrames);return;}- if (data.toString() === "Done") {+ if (data.toString() === "Done" && !ignoringDone) {socket.send(JSON.stringify({text: `final after ${binaryFrames} frames`,@@ -35,6 +36,9 @@ async function startMockOnlineServer({ onBinary, finalSegment = 0 }) {return {port: wss.address().port,+ ignoreDone: () => {+ ignoringDone = true;+ },close: () => new Promise((resolve) => wss.close(resolve)),};}@@ -51,9 +55,7 @@ function onlineWsServerAt(port) {test("online stream emits live updates and finish resolves with the final text", async () => {const mock = await startMockOnlineServer({onBinary: (socket, _data, frameCount) => {- socket.send(- JSON.stringify({ text: `partial ${frameCount}`, segment: 0, is_final: false })- );+ socket.send(JSON.stringify({ text: `partial ${frameCount}`, segment: 0, is_final: false }));},});@@ -125,13 +127,87 @@ test("abort closes the stream without waiting for the server", async () => {const stream = onlineWsServerAt(mock.port).createOnlineStream({});stream.sendPcm16(Buffer.alloc(3200));stream.abort();- const { text } = await stream.finish();+ const { text, truncated } = await stream.finish();assert.equal(text, "");+ assert.equal(truncated, false);+ } finally {+ await mock.close();+ }+});++test("finish flags truncation when the server never acknowledges Done", async () => {+ // Server sends a partial but ignores "Done" entirely.+ const mock = await startMockOnlineServer({+ onBinary: (socket) => {+ socket.send(JSON.stringify({ text: "partial", segment: 0, is_final: false }));+ },+ });+ mock.ignoreDone();++ try {+ const stream = onlineWsServerAt(mock.port).createOnlineStream({});+ stream.sendPcm16(Buffer.alloc(3200));+ const { text, truncated } = await stream.finish({ idleTimeoutMs: 200 });+ assert.equal(text, "partial");+ assert.equal(truncated, true);+ } finally {+ await mock.close();+ }+});++test("unexpected close before Done! reports an error and truncation", async () => {+ const mock = await startMockOnlineServer({+ onBinary: (socket) => {+ socket.send(JSON.stringify({ text: "cut off", segment: 0, is_final: false }));+ socket.close();+ },+ });++ try {+ const errors = [];+ const stream = onlineWsServerAt(mock.port).createOnlineStream({+ onError: (err) => errors.push(err),+ });+ stream.sendPcm16(Buffer.alloc(3200));+ const { text, truncated } = await stream.finish({ idleTimeoutMs: 1000 });+ assert.equal(text, "cut off");+ assert.equal(truncated, true);+ assert.equal(errors.length, 1);+ assert.match(errors[0].message, /closed before/);} finally {await mock.close();}});+test("finish is idempotent and returns the same result", async () => {+ const mock = await startMockOnlineServer({});+ try {+ const stream = onlineWsServerAt(mock.port).createOnlineStream({});+ stream.sendPcm16(Buffer.alloc(3200));+ const [first, second] = await Promise.all([stream.finish(), stream.finish()]);+ assert.deepEqual(first, second);+ } finally {+ await mock.close();+ }+});++test("offline transcription rejects when the connection closes without a result", async () => {+ const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });+ await once(wss, "listening");+ wss.on("connection", (socket) => socket.close());++ try {+ const server = onlineWsServerAt(wss.address().port);+ server.modelRuntime = "offline";+ await assert.rejects(+ () => server.transcribe(Buffer.alloc(3200), 16000),+ /closed before transcription completed/+ );+ } finally {+ await new Promise((resolve) => wss.close(resolve));+ }+});+test("pcm16ToFloat32 converts int16 samples to normalized float32", () => {const pcm = Buffer.alloc(8);pcm.writeInt16LE(0, 0);