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
perf(dictation): hand local engines a raw 16 kHz copy instead of decoding WebM (#2179)
Gabriel Stein7f6a85359875
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 102944b4c..a7a33f982 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Transcription- **Long local dictations transcribe faster.** Parakeet and Orukeet decode audio in 15-second segments, and the app sent them to the local server one after another even though the server decodes on three threads. Segments now decode side by side, one per server thread and sized to the machine's cores, so a one-minute dictation no longer waits on four serial passes. Dictations under 15 seconds are unchanged. (#2178)+- **Local dictation skips a decode step after you stop.** The app records in compressed WebM/Opus and used to hand that to FFmpeg to unpack before Parakeet, Orukeet, Cohere Transcribe or whisper.cpp could start, about half a second on Windows and a few milliseconds on macOS. The microphone now also keeps a raw 16 kHz copy from the moment it opens, pre-roll included, and the local engine decodes that directly. The WebM is still saved to history and remains what cloud providers, very long recordings and any fallback receive. Transcripts are unchanged: on the real engine, raw and Opus-decoded audio differed in about one word in a hundred, in the raw copy's favour. whisper.cpp also no longer needs FFmpeg present for a ready WAV. (#2179)- **Your own Deepgram key works again.** Every Deepgram connection failed with `Unexpected server response: 401`, even though the same key tested fine in Settings and worked against Deepgram directly. Deepgram accepts a raw API key only under its `Token` authorization scheme and reserves `Bearer` for the short-lived tokens OpenWhispr Cloud mints on your behalf — and the app was presenting your key as a `Bearer`. This broke bring-your-own-key dictation as well as Note Recording. (#2140, thanks @nikhilmaddirala)- **Your own AssemblyAI key works in Note Recording again.** Recordings died seconds in with `Input Duration Violation: 40.0 ms`, followed by a cascade of reconnect errors. AssemblyAI accepts audio in 50-1000 ms frames, and the app measured those frames against dictation's 16 kHz — but Note Recording streams at 24 kHz, where the same frame lasts only 33-40 ms. The frame size now follows the rate each session actually opened at, and an oversized burst — which a busy moment can produce on the system-audio channel — is split instead of being sent as one frame that trips the same limit from the other end. Dictation was never affected. (#2140, thanks @nikhilmaddirala)- **Local transcription no longer silently drops parts of a recording.** whisper.cpp decodes audio in 30-second windows, and the app was starting whisper-server with `--no-timestamps`. Without timestamp tokens the decoder cannot report where it stopped inside a window, so whisper.cpp skipped to the next 30-second mark regardless and the speech in between was discarded — with no gap or warning, and the surviving text still reading as a complete thought. Dictation was the most exposed, but notes and meeting recordings lost the same words whenever a passage ran up to a window boundary. The 60-character segment wrap that `--no-timestamps` was there to suppress is now switched off directly, so words still never split mid-word. (#2150)diff --git a/CLAUDE.md b/CLAUDE.mdindex 57aac5867..d15cdfa85 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -308,6 +308,8 @@ FFmpeg is bundled with the app and doesn't require system installation:7. whisper.cpp processes file → Result sent back8. Temporary file deleted+For offline local engines (whisper.cpp, Parakeet/Orukeet, Cohere) the renderer also keeps a 16 kHz mono PCM copy of the same stream from the moment the mic opens (`pcmTap.js`, pre-roll included, capped at 4 minutes) and sends that WAV instead of the WebM, so no FFmpeg decode runs after stop; the WebM still goes to history and remains the fallback for cloud providers and long recordings.+### 3. Local Whisper Models (GGML format)Models stored in `~/.cache/openwhispr/whisper-models/`:diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex e167bc55d..e263e9380 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -23,6 +23,7 @@ import {PRE_ROLL_MAX_AGE_MS,} from "./preparedMicCapture";import { MicStreamHold } from "./micStreamHold";+import { PcmTap } from "./pcmTap";import { ActiveMicRecoveryController } from "./activeMicRecovery";import { followsSystemDefaultMic } from "./micSelectionRecovery";import { isCacheableMicrophoneResolution, resolvePreferredMicrophone } from "./microphoneSelection";@@ -623,6 +624,7 @@ class AudioManager {this._streamingCommitActive = false;this._previewFlushResolve = null;this._batchSegments = [];+ this._batchPcmTap = null;this._rotatingBatchRecorder = null;this._rotationResolve = null;this._stopRequestedDuringMicRecovery = false;@@ -1093,11 +1095,27 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}try {const prepared = await this.preparedMicCapture.prepare(async () => {- const constraints = await this.getAudioConstraints();- const stream = await this._acquireCaptureStream(constraints);- const value = { stream, constraints, recorder: null, chunks: [], startedAt: Date.now() };- if (!this.shouldUseStreaming()) this._startPreRollRecorder(value);- return value;+ // Built before the mic opens so its graph is rendering by the time the+ // pre-roll recorder starts; a tap attached later misses the first frames.+ const pcmTap = this._startPcmTap();+ try {+ const constraints = await this.getAudioConstraints();+ const stream = await this._acquireCaptureStream(constraints);+ const value = {+ stream,+ constraints,+ recorder: null,+ chunks: [],+ pcmTap: null,+ startedAt: Date.now(),+ };+ if (!this.shouldUseStreaming()) this._startPreRollRecorder(value, pcmTap);+ if (!value.pcmTap) pcmTap?.close();+ return value;+ } catch (error) {+ pcmTap?.close();+ throw error;+ }});if (prepared) {logger.debug("Microphone capture prepared", { preRoll: !!prepared.recorder }, "audio");@@ -1133,19 +1151,44 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// Record from the instant the prepared stream delivers frames. If the hold// guard confirms a real dictation these chunks become the recording's opening;// a cancel discards them without the audio ever leaving the renderer.- _startPreRollRecorder(prepared) {+ _startPreRollRecorder(prepared, pcmTap) {try {const recorder = new MediaRecorder(prepared.stream);recorder.ondataavailable = (event) => {if (event.data && event.data.size > 0) prepared.chunks.push(event.data);};recorder.start(RECORDING_TIMESLICE_MS);+ pcmTap?.attach(prepared.stream);prepared.recorder = recorder;+ prepared.pcmTap = pcmTap;} catch (e) {logger.debug("Pre-roll recorder unavailable", { error: e.message }, "audio");}}+ // Offline local engines decode a renderer-captured 16 kHz WAV as-is, so the+ // batch recorder gets a PCM shadow (PcmTap). Online models commit their own+ // stream and every cloud lane wants the smaller WebM, so those get none.+ _startPcmTap() {+ const { useLocalWhisper, localTranscriptionProvider, parakeetModel } = getSettings();+ const offlineLocal =+ useLocalWhisper &&+ !getManagedTranscriptionResolution() &&+ !(localTranscriptionProvider === "nvidia" && isOnlineParakeetModel(parakeetModel));+ if (!offlineLocal) return null;+ try {+ return new PcmTap(this.getWorkletBlobUrl());+ } catch (e) {+ logger.debug("PCM tap unavailable", { error: e.message }, "audio");+ return null;+ }+ }++ _closeBatchPcmTap() {+ this._batchPcmTap?.close();+ this._batchPcmTap = null;+ }+_constraintsKey(constraints) {return JSON.stringify(constraints?.audio ?? constraints ?? {});}@@ -1259,6 +1302,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);async startRecording(forceDefaultMic = false) {let prepared = null;let preparedAdopted = false;+ let freshTap = null;this._startInProgress = true;try {if (!this.isRecordingAllowedByPolicy()) {@@ -1279,6 +1323,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);prepared = forceDefaultMic ? null : await this.preparedMicCapture.take();const constraints =prepared?.constraints ?? (await this.getAudioConstraints(forceDefaultMic));+ // Without a prepared capture the tap starts here, before the mic opens.+ freshTap = prepared ? null : this._startPcmTap();const micStream = prepared?.stream ?? (await this._acquireCaptureStream(constraints));const micReadyAt = performance.now();@@ -1334,22 +1380,28 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.audioChunks = [];this._batchSegments = [];+ this._closeBatchPcmTap();this._stopRequestedDuringMicRecovery = false;this._cancelRequestedDuringMicRecovery = false;this._receivedAudioData = false;- if (prepared && Date.now() - prepared.startedAt > PRE_ROLL_MAX_AGE_MS) {- discardPreRoll(prepared);- }- const preRoll =- prepared?.recorder && prepared.recorder.state === "recording"- ? { recorder: prepared.recorder, chunks: prepared.chunks }- : null;+ const preRollUsable =+ prepared?.recorder?.state === "recording" &&+ Date.now() - prepared.startedAt <= PRE_ROLL_MAX_AGE_MS;+ if (!preRollUsable) discardPreRoll(prepared);+ const preRoll = preRollUsable+ ? { recorder: prepared.recorder, chunks: prepared.chunks }+ : null;// Pre-roll audio is part of the recording, so the reported duration// starts when the prepared stream started — but only when its recorder// was adopted; a prepared stream without pre-roll contributes no audio// before this point, and back-dating would inflate durationSeconds.this.recordingStartTime = preRoll ? prepared.startedAt : Date.now();+ // The tap shadows the recorder from its first frame: the pre-roll's own,+ // or the one built before the mic opened. A tap started now would miss+ // the opening, so an unusable pre-roll leaves the WebM path in charge.+ this._batchPcmTap = preRoll ? prepared.pcmTap : freshTap;this.createBatchRecorder(micStream, preRoll);+ freshTap?.attach(micStream);preparedAdopted = true;this.isRecording = true;this.onStateChange?.({@@ -1426,6 +1478,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);} catch (error) {// A prepared value the recording never adopted still owns a live stream// (and possibly a pre-roll recorder); release it before any retry.+ freshTap?.close();if (prepared && !preparedAdopted) this._disposePrepared(prepared);if (isStaleDeviceError(error) && !forceDefaultMic) {// Pinned mic is gone (Chromium rotates IDs / device unplugged). Retry once on the default mic. See #900.@@ -1526,6 +1579,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const previewStopPromise = this.cleanupPreview({showCleanup: this.shouldShowPreviewCleanupState(),});+ const rawWavPromise = this._batchPcmTap?.stop();+ this._batchPcmTap = null;this.isRecording = false;this.isProcessing = true;this.onStateChange?.({@@ -1599,6 +1654,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);return;}this._streamingCommitActive = false;+ const rawWav = await rawWavPromise;await this.processAudio(audioBlob,@@ -1607,6 +1663,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);analyticsOccurredAt,...(salvagedRecording ? { salvagedRecording: true } : {}),...(previewStop?.streamed ? { streamedText: previewStop.text } : {}),+ ...(rawWav ? { rawWav } : {}),},processingPipeline);@@ -1637,6 +1694,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this._previewSource = this._previewAudioContext.createMediaStreamSource(replacement);this._previewSource.connect(this._previewProcessor);}+ this._batchPcmTap?.attach(replacement);this.createBatchRecorder(replacement);} finally {// Honor a stop/cancel that arrived mid-rotation even when the swap failed —@@ -1771,6 +1829,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this._localSpeechGateState = null;this.cleanupPreview({ dismiss: true });+ this._closeBatchPcmTap();this.isRecording = false;this.isProcessing = false;this.mediaRecorder = null;@@ -1985,7 +2044,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);model: activeModel || null,};- result = withSalvageWarning(result, metadata.salvagedRecording);+ // A salvaged WebM only matters to whoever decoded it; the tap's WAV spans+ // the whole recording.+ result = withSalvageWarning(result, metadata.salvagedRecording && !result?.decodedRawWav);result = {...result,@@ -2087,9 +2148,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const timings = {};try {- // Send original audio to main process - FFmpeg in main process handles conversion- // (renderer-side AudioContext conversion was unreliable with WebM/Opus format)- const arrayBuffer = await audioBlob.arrayBuffer();+ // The PCM tap's WAV skips FFmpeg in the main process; the WebM stays the+ // fallback and is what history and any cloud retry receive.+ const source = metadata.rawWav ?? audioBlob;+ const arrayBuffer = await source.arrayBuffer();const language = getBaseLanguageCode(this.getEffectiveSttLanguage(getSettings()));const options = { model };if (language) {@@ -2106,8 +2168,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);logger.debug("Local transcription starting",{- audioFormat: audioBlob.type,- audioSizeBytes: audioBlob.size,+ audioFormat: source.type,+ audioSizeBytes: source.size,},"performance");@@ -2222,7 +2284,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);if (text !== null && text !== undefined) {- return { success: true, text: text || result.text, rawText, source: "local", timings };+ return {+ success: true,+ text: text || result.text,+ rawText,+ source: "local",+ timings,+ ...(metadata.rawWav ? { decodedRawWav: true } : {}),+ };} else {throw new Error("No text transcribed");}@@ -2286,13 +2355,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);timings.transcriptionProcessingDurationMs = 0;result = { success: true, text: streamedText };} else {- const arrayBuffer = await audioBlob.arrayBuffer();+ const source = metadata.rawWav ?? audioBlob;+ const arrayBuffer = await source.arrayBuffer();logger.debug("Parakeet transcription starting",{- audioFormat: audioBlob.type,- audioSizeBytes: audioBlob.size,+ audioFormat: source.type,+ audioSizeBytes: source.size,model,},"performance"@@ -2331,6 +2401,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);source: "local-parakeet",timings,...(result.warning ? { warning: result.warning } : {}),+ ...(metadata.rawWav ? { decodedRawWav: true } : {}),};} else {throw new Error("No text transcribed");@@ -5418,6 +5489,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);this.micRecovery.stop();this._unsubscribeSettings?.();this.preparedMicCapture.cancel();+ this._closeBatchPcmTap();this.micStreamHold.drop();this.lastAudioBlob = null;this.lastAudioMetadata = null;diff --git a/src/helpers/ffmpegUtils.js b/src/helpers/ffmpegUtils.jsindex be89f81fa..4039f99b6 100644--- a/src/helpers/ffmpegUtils.js+++ b/src/helpers/ffmpegUtils.js@@ -209,6 +209,17 @@ function parseWavFormat(wavBuffer) {return null;}+// Local engines take 16 kHz mono PCM16 WAV as-is; anything else goes through FFmpeg.+function isPcm16Mono16kWav(buffer) {+ const format = parseWavFormat(buffer);+ return (+ format?.audioFormat === 1 &&+ format.channels === 1 &&+ format.sampleRate === 16000 &&+ format.bitsPerSample === 16+ );+}+function wavToFloat32Samples(wavBuffer) {if (!isWavFormat(wavBuffer)) {throw new Error("Buffer is not a valid WAV file");@@ -458,6 +469,7 @@ module.exports = {getFFmpegPath,isWavFormat,parseWavFormat,+ isPcm16Mono16kWav,convertToWav,splitAudioFile,parseFfmpegDuration,diff --git a/src/helpers/parakeetServer.js b/src/helpers/parakeetServer.jsindex 657c6f01f..230dbf77d 100644--- a/src/helpers/parakeetServer.js+++ b/src/helpers/parakeetServer.js@@ -6,6 +6,7 @@ const {getFFmpegPath,isWavFormat,parseWavFormat,+ isPcm16Mono16kWav,convertToWav,wavToFloat32Samples,computeFloat32RMS,@@ -81,18 +82,9 @@ class ParakeetServerManager {}async _ensureWav(audioBuffer) {- if (isWavFormat(audioBuffer)) {- const format = parseWavFormat(audioBuffer);- if (- format?.audioFormat === 1 &&- format?.bitsPerSample === 16 &&- format?.sampleRate === SAMPLE_RATE &&- format?.channels === 1- ) {- return { wavBuffer: audioBuffer, filesToCleanup: [] };- }- debugLogger.debug("WAV input needs normalization", { format });- }+ if (isPcm16Mono16kWav(audioBuffer)) return { wavBuffer: audioBuffer, filesToCleanup: [] };+ const format = parseWavFormat(audioBuffer);+ if (format) debugLogger.debug("WAV input needs normalization", { format });const ffmpegPath = getFFmpegPath();if (!ffmpegPath) {diff --git a/src/helpers/pcmTap.js b/src/helpers/pcmTap.jsnew file mode 100644index 000000000..8c2e8d136--- /dev/null+++ b/src/helpers/pcmTap.js@@ -0,0 +1,115 @@+import { buildWav } from "../utils/wavBuilder";++const SAMPLE_RATE = 16000;+// Longer recordings fall back to the WebM path: the WAV crosses IPC in one+// message and must stay well inside Electron's comfortable payload size.+const MAX_SECONDS = 240;+const FLUSH_WATCHDOG_MS = 1000;+// A copy shorter than its recording by more than this lost frames to a render+// loop that came up late or stalled; the WebM has them, so it wins.+const COVERAGE_TOLERANCE_MS = 100;++// A 16 kHz mono PCM16 shadow of the batch MediaRecorder, so an offline local+// engine decodes it as-is instead of waiting for FFmpeg to unpack WebM/Opus+// after stop. Reuses the preview worklet processor. Build it before the mic+// opens so the graph is already rendering when attach() runs beside+// recorder.start(); stop() yields null for anything the copy cannot vouch for.+export class PcmTap {+ constructor(+ workletUrl,+ { maxSamples = SAMPLE_RATE * MAX_SECONDS, now = () => performance.now() } = {}+ ) {+ this._chunks = [];+ this._samples = 0;+ this._maxSamples = maxSamples;+ this._now = now;+ this._attachedAt = null;+ this._dropped = false;+ this._node = null;+ this._source = null;+ this._flushResolve = null;+ this._context = new AudioContext({ sampleRate: SAMPLE_RATE });+ // Not awaited: resume() can hang when the output device is wedged.+ if (this._context.state === "suspended") this._context.resume().catch(() => {});+ this._ready = this._context.audioWorklet+ .addModule(workletUrl)+ .then(() => {+ // Mono like FFmpeg's -ac 1, so a stereo device with one live channel+ // decodes the same either way.+ this._node = new AudioWorkletNode(this._context, "pcm-streaming-processor", {+ channelCount: 1,+ channelCountMode: "explicit",+ });+ this._node.port.onmessage = (event) => this._onMessage(event.data);+ this._source?.connect(this._node);+ })+ .catch(() => {+ this._dropped = true;+ });+ }++ _onMessage(data) {+ if (data === "flushed") {+ this._flushResolve?.();+ return;+ }+ if (this._dropped) return;+ const chunk = new Int16Array(data);+ this._samples += chunk.length;+ if (this._samples > this._maxSamples) {+ this._dropped = true;+ this._chunks = [];+ return;+ }+ this._chunks.push(chunk);+ }++ // Feeds the recorder's stream, or moves the tap onto a replacement mic.+ attach(stream) {+ this._source?.disconnect();+ this._source = this._context.createMediaStreamSource(stream);+ if (this._node) this._source.connect(this._node);+ this._attachedAt ??= this._now();+ }++ // Resolves to the capture as a WAV blob, or null when the copy cannot stand+ // in for the WebM: the worklet failed to load, the recording ran too long,+ // the flush never arrived, or the copy is shorter than the recording.+ async stop() {+ let watchdog;+ const flushed = await Promise.race([+ this._ready.then(() => {+ if (!this._node || this._dropped) return false;+ return new Promise((resolve) => {+ this._flushResolve = () => resolve(true);+ this._node.port.postMessage("stop");+ });+ }),+ new Promise((resolve) => {+ watchdog = setTimeout(() => resolve(false), FLUSH_WATCHDOG_MS);+ }),+ ]);+ clearTimeout(watchdog);+ const { _chunks: chunks, _samples: total, _dropped: dropped, _attachedAt: attachedAt } = this;+ const covered =+ attachedAt !== null &&+ total >= ((this._now() - attachedAt - COVERAGE_TOLERANCE_MS) / 1000) * SAMPLE_RATE;+ this.close();+ if (!flushed || dropped || !covered || total === 0) return null;+ const samples = new Int16Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ samples.set(chunk, offset);+ offset += chunk.length;+ }+ return buildWav(samples, SAMPLE_RATE);+ }++ close() {+ this._chunks = [];+ this._samples = 0;+ this._node?.disconnect();+ this._source?.disconnect();+ this._context.close().catch(() => {});+ }+}diff --git a/src/helpers/preparedMicCapture.js b/src/helpers/preparedMicCapture.jsindex 163498549..d98ef99df 100644--- a/src/helpers/preparedMicCapture.js+++ b/src/helpers/preparedMicCapture.js@@ -22,6 +22,10 @@ export const discardPreRoll = (prepared) => {prepared.recorder = null;}if (prepared?.chunks) prepared.chunks.length = 0;+ if (prepared?.pcmTap) {+ prepared.pcmTap.close();+ prepared.pcmTap = null;+ }};export const disposePreparedCapture = (prepared) => {diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.jsindex 939ae779c..2c45a86fb 100644--- a/src/helpers/whisperServer.js+++ b/src/helpers/whisperServer.js@@ -8,7 +8,7 @@ const debugLogger = require("./debugLogger");const { killProcess } = require("../utils/process");const { isPortAvailable, getAvailableParallelism } = require("../utils/serverUtils");const { getSafeTempDir } = require("./safeTempDir");-const { convertToWav } = require("./ffmpegUtils");+const { convertToWav, isPcm16Mono16kWav } = require("./ffmpegUtils");const { createAbortError } = require("./abortError");const sidecarPidFile = require("./sidecarPidFile");const { BIN_SUBDIR: CUDA_BIN_SUBDIR } = require("./whisperCudaManager");@@ -868,12 +868,14 @@ class WhisperServerManager extends EventEmitter {const { language, initialPrompt, signal, skipDecoderThresholds } = options;if (signal?.aborted) throw createAbortError("whisper-server transcription cancelled");- // Always convert to 16kHz mono WAV - whisper.cpp requires this exact format+ // whisper.cpp wants 16 kHz mono PCM16; a renderer PCM tap delivers exactly that.let finalBuffer = audioBuffer;- if (!this.canConvert) {- throw new Error("FFmpeg not found - required for audio conversion");+ if (!isPcm16Mono16kWav(audioBuffer)) {+ if (!this.canConvert) {+ throw new Error("FFmpeg not found - required for audio conversion");+ }+ finalBuffer = await this._convertToWav(audioBuffer);}- finalBuffer = await this._convertToWav(audioBuffer);const boundary = `----WhisperBoundary${Date.now()}`;const parts = [];diff --git a/test/helpers/audioManagerPcmTapLifecycle.test.js b/test/helpers/audioManagerPcmTapLifecycle.test.jsnew file mode 100644index 000000000..28193af4e--- /dev/null+++ b/test/helpers/audioManagerPcmTapLifecycle.test.js@@ -0,0 +1,252 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { loadAudioManager } = require("./harness/audioManager");+const { installMicCaptureGlobals } = require("../lib/rendererTestHarness");++// The PCM tap must follow the batch recorder exactly: handed over at finalize,+// released on cancel, and carried onto a replacement microphone.++async function load(t) {+ const { AudioManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-pcm-tap-lifecycle-test-",+ settingsKey: "__pcmTapLifecycleSettings",+ });+ return AudioManager;+}++const webm = () => new Blob([new Uint8Array(512)], { type: "audio/webm" });+const wav = () => new Blob([new Uint8Array(4)], { type: "audio/wav" });++function finalizingManager(AudioManager, tap) {+ let handoff = null;+ const manager = Object.assign(Object.create(AudioManager.prototype), {+ isRecording: true,+ isProcessing: false,+ _processingCancellationGeneration: 0,+ _streamingCancellationGeneration: 0,+ _streamingStopPromise: null,+ _activeTranscriptionAbortController: null,+ _batchSegments: [],+ _batchPcmTap: tap,+ _receivedAudioData: true,+ _localSpeechGateState: null,+ _streamingCommitActive: false,+ recordingMimeType: "audio/webm",+ recordingStartTime: Date.now(),+ lastAudioBlob: null,+ micRecovery: { stop() {} },+ teardownSpeechGate() {},+ cleanupPreview: async () => null,+ shouldShowPreviewCleanupState: () => false,+ mergeRecordedSegments: async () => webm(),+ getLargestRecordedSegment: () => null,+ processAudio: async (blob, metadata) => {+ handoff = { blob, metadata };+ },+ onStateChange() {},+ _requestStreamingCancellation() {},+ });+ return { manager, handoff: () => handoff };+}++test("finalize waits for the tap and hands its WAV over beside the WebM", async (t) => {+ const AudioManager = await load(t);+ const rawWav = wav();+ const { manager, handoff } = finalizingManager(AudioManager, { stop: async () => rawWav });++ await manager.finalizeBatchRecording(webm());++ assert.equal(handoff().blob.type, "audio/webm", "the WebM remains the recording of record");+ assert.strictEqual(handoff().metadata.rawWav, rawWav);+ assert.equal(manager._batchPcmTap, null);+});++test("a dropped tap leaves the WebM path exactly as before", async (t) => {+ const AudioManager = await load(t);+ const { manager, handoff } = finalizingManager(AudioManager, { stop: async () => null });++ await manager.finalizeBatchRecording(webm());++ assert.equal("rawWav" in handoff().metadata, false);+});++test("cancelling a recording releases the tap", async (t) => {+ const AudioManager = await load(t);+ let closes = 0;+ const manager = Object.assign(Object.create(AudioManager.prototype), {+ _batchPcmTap: { close: () => (closes += 1) },+ teardownSpeechGate() {},+ cleanupPreview() {},+ onStateChange() {},+ });++ manager.resetDiscardedBatchRecordingState();++ assert.equal(closes, 1);+ assert.equal(manager._batchPcmTap, null);+});++test("a replacement microphone is bound into the same tap", async (t) => {+ const AudioManager = await load(t);+ const replacement = { id: "headset" };+ const rebound = [];+ const recorders = [];+ const manager = Object.assign(Object.create(AudioManager.prototype), {+ isRecording: true,+ mediaRecorder: { state: "inactive" },+ _silenceSource: null,+ _silenceCtx: null,+ _previewSource: null,+ _previewAudioContext: null,+ _batchPcmTap: { attach: (stream) => rebound.push(stream) },+ _cancelRequestedDuringMicRecovery: false,+ _stopRequestedDuringMicRecovery: false,+ createBatchRecorder: (stream) => recorders.push(stream),+ });++ await manager.replaceBatchMic(replacement);++ assert.deepEqual(rebound, [replacement]);+ assert.deepEqual(recorders, [replacement]);+});++async function loadWithSettings(t, settings, mockModules = {}) {+ const loaded = await loadAudioManager(t, {+ cachePrefix: "openwhispr-pcm-tap-start-test-",+ settingsKey: "__pcmTapStartSettings",+ settings,+ mockModules,+ });+ installMicCaptureGlobals(t);+ return loaded;+}++const offlineLocal = {+ useLocalWhisper: true,+ localTranscriptionProvider: "nvidia",+ parakeetModel: "orukeet-v0.1.0",+ showTranscriptionPreview: false,+};++test("only offline local engines get a tap", async (t) => {+ const { setSettings, createManager } = await loadWithSettings(t, offlineLocal);+ const manager = createManager({ getWorkletBlobUrl: () => "blob:worklet" });+ const taps = (settings) => {+ setSettings(settings);+ const tap = manager._startPcmTap();+ tap?.close();+ return tap !== null;+ };++ assert.equal(taps({ useLocalWhisper: true, localTranscriptionProvider: "whisper" }), true);+ assert.equal(taps(offlineLocal), true);+ assert.equal(taps({ useLocalWhisper: true, localTranscriptionProvider: "cohere" }), true);+ assert.equal(+ taps({+ useLocalWhisper: true,+ localTranscriptionProvider: "nvidia",+ parakeetModel: "nemotron-speech-streaming-en-0.6b",+ }),+ false,+ "online models commit their own stream"+ );+ assert.equal(taps({ useLocalWhisper: false, cloudTranscriptionMode: "byok" }), false);+ assert.equal(taps({ useLocalWhisper: false, cloudTranscriptionMode: "openwhispr" }), false);+});++test("managed enterprise transcription gets no tap even with local settings", async (t) => {+ const { createManager } = await loadWithSettings(t, offlineLocal, {+ "/services/managedTranscription.ts": `+ export const getManagedTranscriptionResolution = () => ({ kind: "managed" });+ export const isManagedTranscriptionActive = () => true;+ `,+ });+ const manager = createManager({ getWorkletBlobUrl: () => "blob:worklet" });++ assert.equal(manager._startPcmTap(), null);+});++function startingManager(AudioManager, { prepared, tap, events }) {+ const stream = { getAudioTracks: () => [], getTracks: () => [] };+ return Object.assign(Object.create(AudioManager.prototype), {+ isRecording: false,+ isProcessing: false,+ isStreaming: false,+ _streamingStopPromise: null,+ mediaRecorder: null,+ _batchPcmTap: null,+ _batchSegments: [],+ audioChunks: [],+ preparedMicCapture: { take: async () => prepared },+ isRecordingAllowedByPolicy: () => true,+ getAudioConstraints: async () => ({ audio: true }),+ _acquireCaptureStream: async () => {+ events.push("acquire");+ return stream;+ },+ _startPcmTap: () => {+ events.push("tap");+ return tap;+ },+ createBatchRecorder: () => events.push("recorder"),+ beginMicRecovery: async () => {},+ onStateChange() {},+ });+}++const fakeTap = (events, name) => ({+ attach: () => events.push(`attach:${name}`),+ close: () => events.push(`close:${name}`),+});++test("a fresh pre-roll hands its tap to the recording", async (t) => {+ const { AudioManager } = await loadWithSettings(t, offlineLocal);+ const events = [];+ const preRollTap = fakeTap(events, "preroll");+ const prepared = {+ stream: { getAudioTracks: () => [], getTracks: () => [] },+ constraints: { audio: true },+ recorder: { state: "recording" },+ chunks: [],+ pcmTap: preRollTap,+ startedAt: Date.now(),+ };+ const manager = startingManager(AudioManager, { prepared, tap: null, events });+ t.after(() => manager.teardownSpeechGate());++ assert.equal(await manager.startRecording(), true);+ assert.strictEqual(manager._batchPcmTap, preRollTap);+ assert.deepEqual(events, ["recorder"], "no second tap is built and nothing is re-attached");+});++test("an expired pre-roll takes its tap with it and the WebM path runs", async (t) => {+ const { AudioManager, vite } = await loadWithSettings(t, offlineLocal);+ const { PRE_ROLL_MAX_AGE_MS } = await vite.ssrLoadModule("/helpers/preparedMicCapture.js");+ const events = [];+ const prepared = {+ stream: { getAudioTracks: () => [], getTracks: () => [] },+ constraints: { audio: true },+ recorder: { state: "recording", stop: () => events.push("recorder-stop") },+ chunks: ["stale"],+ pcmTap: fakeTap(events, "preroll"),+ startedAt: Date.now() - PRE_ROLL_MAX_AGE_MS - 1,+ };+ const manager = startingManager(AudioManager, { prepared, tap: null, events });+ t.after(() => manager.teardownSpeechGate());++ assert.equal(await manager.startRecording(), true);+ assert.equal(manager._batchPcmTap, null);+ assert.deepEqual(events, ["recorder-stop", "close:preroll", "recorder"]);+});++test("without a prepared capture the tap is built before the mic opens and attached with the recorder", async (t) => {+ const { AudioManager } = await loadWithSettings(t, offlineLocal);+ const events = [];+ const tap = fakeTap(events, "fresh");+ const manager = startingManager(AudioManager, { prepared: null, tap, events });+ t.after(() => manager.teardownSpeechGate());++ assert.equal(await manager.startRecording(), true);+ assert.strictEqual(manager._batchPcmTap, tap);+ assert.deepEqual(events, ["tap", "acquire", "recorder", "attach:fresh"]);+});diff --git a/test/helpers/audioManagerRawWav.test.js b/test/helpers/audioManagerRawWav.test.jsnew file mode 100644index 000000000..fb1aa790f--- /dev/null+++ b/test/helpers/audioManagerRawWav.test.js@@ -0,0 +1,103 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { loadAudioManager } = require("./harness/audioManager");++// The PCM tap's WAV is what the local engine decodes; the WebM keeps being the+// recording of record for history and cloud fallbacks, so it must stay untouched.++async function loadManager(t) {+ const { window, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-raw-wav-test-",+ settingsKey: "__rawWavSettings",+ });+ setSettings({+ useLocalWhisper: true,+ localTranscriptionProvider: "nvidia",+ parakeetModel: "orukeet-v0.1.0",+ preferredLanguage: "en",+ customDictionary: [],+ });+ const sent = [];+ window.electronAPI.transcribeLocalParakeet = async (buffer) => {+ sent.push(Array.from(new Uint8Array(buffer)));+ return { success: true, text: "hi" };+ };+ window.electronAPI.transcribeLocalWhisper = window.electronAPI.transcribeLocalParakeet;+ const manager = createManager({ processTranscription: async (text) => text });+ return { manager, sent };+}++const webm = () => new Blob([new Uint8Array([1, 2, 3])], { type: "audio/webm" });+const wav = () => new Blob([new Uint8Array([82, 73, 70, 70])], { type: "audio/wav" });++test("the PCM tap's WAV goes to Parakeet instead of the WebM", async (t) => {+ const { manager, sent } = await loadManager(t);++ const result = await manager.processWithLocalParakeet(webm(), "orukeet-v0.1.0", {+ rawWav: wav(),+ });++ assert.equal(result.text, "hi");+ assert.deepEqual(sent, [[82, 73, 70, 70]]);+});++test("the PCM tap's WAV goes to whisper.cpp instead of the WebM", async (t) => {+ const { manager, sent } = await loadManager(t);++ await manager.processWithLocalWhisper(webm(), "base", { rawWav: wav() });++ assert.deepEqual(sent, [[82, 73, 70, 70]]);+});++test("without a tap the WebM is sent as before", async (t) => {+ const { manager, sent } = await loadManager(t);++ await manager.processWithLocalParakeet(webm(), "orukeet-v0.1.0", {});++ assert.deepEqual(sent, [[1, 2, 3]]);+});++async function loadFallbackManager(t, transcribeKey) {+ const { window, setSettings, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-raw-wav-fallback-test-",+ settingsKey: "__rawWavFallbackSettings",+ });+ setSettings({+ useLocalWhisper: true,+ localTranscriptionProvider: "nvidia",+ parakeetModel: "orukeet-v0.1.0",+ preferredLanguage: "en",+ customDictionary: [],+ allowOpenAIFallback: true,+ cloudTranscriptionProvider: "openai",+ });+ window.electronAPI[transcribeKey] = async () => ({ success: false, message: "engine down" });+ let uploaded = null;+ const manager = createManager({+ processWithOpenAIAPI: async (blob) => {+ uploaded = blob;+ return { success: true, text: "cloud" };+ },+ });+ return { manager, uploaded: () => uploaded };+}++test("a failed Parakeet decode falls back to the cloud with the WebM, never the WAV", async (t) => {+ const { manager, uploaded } = await loadFallbackManager(t, "transcribeLocalParakeet");++ const result = await manager.processWithLocalParakeet(webm(), "orukeet-v0.1.0", {+ rawWav: wav(),+ });++ assert.equal(result.source, "openai-fallback");+ assert.equal(uploaded().type, "audio/webm");+});++test("a failed whisper decode falls back to the cloud with the WebM, never the WAV", async (t) => {+ const { manager, uploaded } = await loadFallbackManager(t, "transcribeLocalWhisper");++ const result = await manager.processWithLocalWhisper(webm(), "base", { rawWav: wav() });++ assert.equal(result.source, "openai-fallback");+ assert.equal(uploaded().type, "audio/webm");+});diff --git a/test/helpers/ffmpegUtils.test.js b/test/helpers/ffmpegUtils.test.jsindex ca6ae2901..14f591cc5 100644--- a/test/helpers/ffmpegUtils.test.js+++ b/test/helpers/ffmpegUtils.test.js@@ -1,7 +1,8 @@const test = require("node:test");const assert = require("node:assert/strict");-const { parseFfmpegDuration } = require("../../src/helpers/ffmpegUtils");+const { parseFfmpegDuration, isPcm16Mono16kWav } = require("../../src/helpers/ffmpegUtils");+const { wavHeader } = require("./harness/wavFixtures");test("parseFfmpegDuration reads the input duration from ffmpeg output", () => {const stderr = "Input #0, mp3, from 'recording.mp3':\n Duration: 01:13:00.25, start: 0.000000";@@ -12,3 +13,11 @@ test("parseFfmpegDuration returns null when ffmpeg reports no duration", () => {assert.equal(parseFfmpegDuration("Duration: N/A"), null);assert.equal(parseFfmpegDuration(""), null);});++test("isPcm16Mono16kWav accepts only what the local engines decode as-is", () => {+ assert.equal(isPcm16Mono16kWav(wavHeader()), true);+ assert.equal(isPcm16Mono16kWav(wavHeader({ sampleRate: 48000 })), false);+ assert.equal(isPcm16Mono16kWav(wavHeader({ channels: 2 })), false);+ assert.equal(isPcm16Mono16kWav(wavHeader({ audioFormat: 3, bitsPerSample: 32 })), false);+ assert.equal(isPcm16Mono16kWav(Buffer.from("not a wav")), false);+});diff --git a/test/helpers/harness/wavFixtures.js b/test/helpers/harness/wavFixtures.jsnew file mode 100644index 000000000..16573388b--- /dev/null+++ b/test/helpers/harness/wavFixtures.js@@ -0,0 +1,34 @@+const { pcm16ToWav } = require("../../../src/utils/audioUtils");++// Minimal RIFF/WAVE builders for tests that need a real header without FFmpeg.++function wavHeader({+ audioFormat = 1,+ channels = 1,+ sampleRate = 16000,+ bitsPerSample = 16,+ dataSize = 0,+} = {}) {+ const header = Buffer.alloc(44);+ header.write("RIFF", 0);+ header.writeUInt32LE(36 + dataSize, 4);+ header.write("WAVE", 8);+ header.write("fmt ", 12);+ header.writeUInt32LE(16, 16);+ header.writeUInt16LE(audioFormat, 20);+ header.writeUInt16LE(channels, 22);+ header.writeUInt32LE(sampleRate, 24);+ header.writeUInt32LE((sampleRate * channels * bitsPerSample) / 8, 28);+ header.writeUInt16LE((channels * bitsPerSample) / 8, 32);+ header.writeUInt16LE(bitsPerSample, 34);+ header.write("data", 36);+ header.writeUInt32LE(dataSize, 40);+ return header;+}++// 16 kHz mono PCM16, the shape every local engine decodes as-is.+function pcm16Mono16kWav(samples = [0, 100, -100, 200]) {+ return pcm16ToWav(Buffer.from(Int16Array.from(samples).buffer));+}++module.exports = { wavHeader, pcm16Mono16kWav };diff --git a/test/helpers/pcmTap.test.js b/test/helpers/pcmTap.test.jsnew file mode 100644index 000000000..9e0691400--- /dev/null+++ b/test/helpers/pcmTap.test.js@@ -0,0 +1,225 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/pcmTap.js");++// Fakes for the WebAudio surface the tap touches. `onStop` decides what the+// worklet posts back when asked to flush; the real one posts its partial+// buffer, then "flushed".+function installFakes(+ t,+ { failModule = false, state = "running", onStop = (node) => node.reply("flushed") } = {}+) {+ const contexts = [];+ const nodes = [];+ class FakeAudioContext {+ constructor({ sampleRate }) {+ this.sampleRate = sampleRate;+ this.state = state;+ this.resumed = 0;+ this.sources = [];+ this.closed = 0;+ this.audioWorklet = {+ addModule: async () => {+ if (failModule) throw new Error("no worklet");+ },+ };+ contexts.push(this);+ }+ createMediaStreamSource(stream) {+ const source = {+ stream,+ connected: null,+ connect(node) {+ this.connected = node;+ },+ disconnect() {+ this.connected = null;+ },+ };+ this.sources.push(source);+ return source;+ }+ async resume() {+ this.resumed += 1;+ }+ async close() {+ this.closed += 1;+ }+ }+ class FakeAudioWorkletNode {+ constructor(context, name, options) {+ this.options = options;+ this.port = {+ onmessage: null,+ postMessage: (message) => {+ if (message === "stop") queueMicrotask(() => onStop(this));+ },+ };+ nodes.push(this);+ }+ reply(data) {+ this.port.onmessage?.({ data });+ }+ connect() {}+ disconnect() {}+ }+ globalThis.AudioContext = FakeAudioContext;+ globalThis.AudioWorkletNode = FakeAudioWorkletNode;+ t.after(() => {+ delete globalThis.AudioContext;+ delete globalThis.AudioWorkletNode;+ });+ return { contexts, nodes };+}++const ready = () => new Promise((resolve) => setImmediate(resolve));+const chunk = (values) => Int16Array.from(values).buffer;+const mic = { id: "mic" };++// A tap attached at t=0 on an injected clock; `clock.now` is read at stop().+async function attachedTap(PcmTap, options = {}) {+ const clock = { now: 0 };+ const tap = new PcmTap("blob:worklet", { now: () => clock.now, ...options });+ tap.attach(mic);+ await ready();+ return { tap, clock };+}++async function decodeWav(blob) {+ const bytes = Buffer.from(await blob.arrayBuffer());+ return {+ header: bytes.subarray(0, 44),+ samples: Array.from(+ new Int16Array(bytes.buffer, bytes.byteOffset + 44, (bytes.length - 44) / 2)+ ),+ };+}++test("stop returns a 16 kHz mono PCM16 WAV of every chunk in order", async (t) => {+ const { contexts, nodes } = installFakes(t);+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap);++ nodes[0].reply(chunk([1, 2, 3]));+ nodes[0].reply(chunk([4, 5]));+ const { header, samples } = await decodeWav(await tap.stop());++ assert.equal(header.toString("ascii", 0, 4), "RIFF");+ assert.equal(header.readUInt16LE(22), 1, "mono");+ assert.equal(header.readUInt32LE(24), 16000, "16 kHz");+ assert.equal(header.readUInt16LE(34), 16, "PCM16");+ assert.deepEqual(samples, [1, 2, 3, 4, 5]);+ assert.equal(contexts[0].sampleRate, 16000);+ assert.equal(contexts[0].closed, 1);+});++test("a stream attached before the worklet loads is connected once it does, downmixed to mono", async (t) => {+ const { contexts, nodes } = installFakes(t);+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap);++ assert.equal(contexts[0].sources[0].connected, nodes[0]);+ assert.deepEqual(nodes[0].options, { channelCount: 1, channelCountMode: "explicit" });+ tap.close();+});++test("a recording past the cap yields no copy", async (t) => {+ const { nodes } = installFakes(t);+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap, { maxSamples: 4 });++ nodes[0].reply(chunk([1, 2, 3]));+ nodes[0].reply(chunk([4, 5]));++ assert.equal(await tap.stop(), null);+});++test("a chunk that crosses the cap while flushing drops the copy", async (t) => {+ const { nodes } = installFakes(t, {+ onStop: (node) => {+ node.reply(chunk([4, 5]));+ node.reply("flushed");+ },+ });+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap, { maxSamples: 4 });+ nodes[0].reply(chunk([1, 2, 3]));++ assert.equal(await tap.stop(), null);+});++test("a copy shorter than its recording is dropped, a complete one is kept", async (t) => {+ const { nodes } = installFakes(t);+ const { PcmTap } = await load();+ const second = () => Int16Array.from({ length: 16000 }, () => 1).buffer;++ const short = await attachedTap(PcmTap);+ nodes[0].reply(second());+ short.clock.now = 5000;+ assert.equal(await short.tap.stop(), null, "one second of audio for five seconds attached");++ const complete = await attachedTap(PcmTap);+ nodes[1].reply(second());+ complete.clock.now = 1000;+ assert.ok(await complete.tap.stop(), "one second of audio for one second attached");+});++test("a worklet that fails to load yields no copy and still releases the context", async (t) => {+ const { contexts } = installFakes(t, { failModule: true });+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap);++ assert.equal(await tap.stop(), null);+ assert.equal(contexts[0].closed, 1);+});++test("a worklet that never answers the flush yields no copy once the watchdog fires", async (t) => {+ const { contexts, nodes } = installFakes(t, { onStop: () => {} });+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap);+ nodes[0].reply(chunk([1, 2]));+ t.mock.timers.enable({ apis: ["setTimeout"] });++ const pending = tap.stop();+ t.mock.timers.tick(1000);++ assert.equal(await pending, null);+ assert.equal(contexts[0].closed, 1);+});++test("attach follows the recording onto a replacement microphone", async (t) => {+ const { contexts, nodes } = installFakes(t);+ const { PcmTap } = await load();+ const replacement = { id: "headset" };+ const { tap } = await attachedTap(PcmTap);++ tap.attach(replacement);+ const [original, rebound] = contexts[0].sources;++ assert.equal(original.connected, null);+ assert.equal(rebound.stream, replacement);+ assert.equal(rebound.connected, nodes[0]);+ tap.close();+});++test("a suspended context is nudged awake", async (t) => {+ const { contexts } = installFakes(t, { state: "suspended" });+ const { PcmTap } = await load();+ const tap = new PcmTap("blob:worklet");++ assert.equal(contexts[0].resumed, 1);+ tap.close();+});++test("close discards the copy and releases the context", async (t) => {+ const { contexts, nodes } = installFakes(t);+ const { PcmTap } = await load();+ const { tap } = await attachedTap(PcmTap);+ nodes[0].reply(chunk([1, 2]));++ tap.close();++ assert.equal(contexts[0].closed, 1);+ assert.equal(await tap.stop(), null);+});diff --git a/test/helpers/preparedMicCapture.test.js b/test/helpers/preparedMicCapture.test.jsindex 0a19433f3..47a08d827 100644--- a/test/helpers/preparedMicCapture.test.js+++ b/test/helpers/preparedMicCapture.test.js@@ -147,14 +147,16 @@ test("a prepared value that expired is not handed to a later prepare", async ()assert.equal((await capture.take()).id, "second");});-test("discardPreRoll drops the recorder and chunks but keeps the stream", async () => {+test("discardPreRoll drops the recorder, chunks and PCM tap but keeps the stream", async () => {const { discardPreRoll } = await load();let streamStops = 0;let recorderStops = 0;+ let tapCloses = 0;const prepared = {stream: fakeStream(() => (streamStops += 1)),recorder: { state: "recording", ondataavailable: () => {}, stop: () => (recorderStops += 1) },chunks: ["a", "b"],+ pcmTap: { close: () => (tapCloses += 1) },};discardPreRoll(prepared);@@ -162,6 +164,8 @@ test("discardPreRoll drops the recorder and chunks but keeps the stream", asyncassert.equal(recorderStops, 1);assert.equal(prepared.recorder, null);assert.deepEqual(prepared.chunks, []);+ assert.equal(tapCloses, 1);+ assert.equal(prepared.pcmTap, null);assert.equal(streamStops, 0);});diff --git a/test/helpers/whisperServerWavInput.test.js b/test/helpers/whisperServerWavInput.test.jsnew file mode 100644index 000000000..7940bc143--- /dev/null+++ b/test/helpers/whisperServerWavInput.test.js@@ -0,0 +1,69 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const http = require("node:http");+const WhisperServerManager = require("../../src/helpers/whisperServer");+const { pcm16Mono16kWav } = require("./harness/wavFixtures");++function startServer(handler) {+ const server = http.createServer(handler);+ return new Promise((resolve) => {+ server.listen(0, "127.0.0.1", () => resolve({ server, port: server.address().port }));+ });+}++async function serveTranscript(t, onBody) {+ const { server, port } = await startServer((req, res) => {+ const chunks = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ onBody(Buffer.concat(chunks));+ res.writeHead(200, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ text: "hello" }));+ });+ });+ t.after(() => server.close());+ return port;+}++function createManager(port, canConvert) {+ const manager = new WhisperServerManager();+ Object.assign(manager, {+ ready: true,+ hostname: "127.0.0.1",+ port,+ useCuda: false,+ useVulkan: false,+ canConvert,+ process: {},+ modelPath: "/tmp/model.bin",+ lastStartOptions: { useCuda: false, useVulkan: false },+ });+ return manager;+}++test("a 16 kHz mono PCM16 WAV is posted as-is, with no FFmpeg pass", async (t) => {+ let body = null;+ const manager = createManager(await serveTranscript(t, (received) => (body = received)), false);+ manager._convertToWav = async () => {+ throw new Error("FFmpeg must not run for a ready WAV");+ };+ const wav = pcm16Mono16kWav();++ const result = await manager.transcribe(wav);++ assert.equal(result.text, "hello");+ assert.ok(body.includes(wav), "the WAV bytes reach whisper-server unchanged");+});++test("any other input still goes through FFmpeg", async (t) => {+ const manager = createManager(await serveTranscript(t, () => {}), true);+ let conversions = 0;+ manager._convertToWav = async (buffer) => {+ conversions += 1;+ return buffer;+ };++ await manager.transcribe(Buffer.from("webm bytes"));++ assert.equal(conversions, 1);+});