From 2b2cb6d23d8aa30ff7db56019040dd467bc16bf4 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 2 Jun 2026 12:30:33 -0400 Subject: [PATCH] feat(stt): add energy-based VAD with silence gate and auto-stop (#249) * loop: stt-warmup completed after 6 iterations * refactor: extract STT startup helpers and simplify audio recorder * feat(stt): add energy-based VAD with silence gate and auto-stop - New VoiceActivityDetector class: adaptive noise floor, per-frame RMS classification, trailing-silence endpointing, configurable thresholds - AudioWorkletProcessor computes RMS in existing flush loop and posts {samples, rms} instead of a bare Int16Array - AudioRecorder integrates VAD via handleVadFrame() in both worklet and ScriptProcessor paths; auto-calls stop() on trailing silence; silence gate in processRecording() fires onNoSpeech instead of sending empty audio to the transcription API (fixes Whisper hallucination bug) - useSTT wires setOnNoSpeech to reset isProcessing/isRecording cleanly without surfacing an error - computeRms() exported helper for ScriptProcessor fallback path * fix(stt): clear processing state when stopping a silent recording stopRecording() called recorder.stop() before setIsProcessing(true). For a silent take the recorder synchronously fires onNoSpeech (which sets processing false), so the subsequent setIsProcessing(true) won and the voice overlay was stuck in the processing state forever. Set processing before stop() so the recorder callback (onNoSpeech or onDataAvailable) has the final say on the processing flag. * fix(stt): always emit a terminal signal so the voice overlay never sticks Two remaining stuck paths after the silent-stop fix: - processRecording() early-returned without firing onNoSpeech when a take had no captured audio (e.g. a quick start/stop under one worklet flush, totalSamples === 0). Now any non-emitting path (empty audio or no detected speech) fires onNoSpeech, while a genuine abort still returns silently. - stopRecording() set isProcessing true even when the recorder was no longer recording (double-stop or post auto-stop), where stop() skips processRecording entirely and nothing clears the flag. Guard the external path on recorder state before entering processing. * loop: mediarecorder-stt completed after 6 iterations * refactor(stt): extract shared helpers and cleanup * refactor(stt): add separate arm/disarm thresholds for voice swipe * fix(stt): prevent default touch behavior on voice gesture handlers * feat(stt): add audio-level speech detection before emitting data --- frontend/public/audio-worklet-processor.js | 72 -- frontend/src/api/stt.test.ts | 95 +++ frontend/src/api/stt.ts | 20 +- .../src/components/message/PromptInput.tsx | 15 +- .../components/message/VoiceStatusOverlay.tsx | 2 +- .../src/components/settings/STTSettings.tsx | 3 + frontend/src/hooks/useSTT.test.tsx | 454 ++++++++++++ frontend/src/hooks/useSTT.ts | 244 +++---- frontend/src/index.css | 9 + frontend/src/lib/audioRecorder.test.ts | 650 ++++++++++++++---- frontend/src/lib/audioRecorder.ts | 324 ++++----- frontend/src/lib/webSpeechRecognizer.test.ts | 226 ++++++ frontend/src/lib/webSpeechRecognizer.ts | 60 +- 13 files changed, 1625 insertions(+), 549 deletions(-) delete mode 100644 frontend/public/audio-worklet-processor.js create mode 100644 frontend/src/hooks/useSTT.test.tsx create mode 100644 frontend/src/lib/webSpeechRecognizer.test.ts diff --git a/frontend/public/audio-worklet-processor.js b/frontend/public/audio-worklet-processor.js deleted file mode 100644 index 0a0e584d..00000000 --- a/frontend/public/audio-worklet-processor.js +++ /dev/null @@ -1,72 +0,0 @@ -class RecorderProcessor extends AudioWorkletProcessor { - constructor(options) { - super() - this._targetSampleRate = options?.processorOptions?.targetSampleRate ?? 16000 - this._inputSampleRate = sampleRate - this._ratio = this._inputSampleRate / this._targetSampleRate - this._fraction = 0 - this._lastSample = 0 - this._active = true - this._buffer = [] - this.port.onmessage = (e) => { - if (e.data === 'stop') { - this._active = false - } - } - } - - process(inputs) { - if (!this._active) { - if (this._buffer.length > 0) { - this._flushBuffer() - } - return false - } - - const input = inputs[0]?.[0] - if (!input || input.length === 0) { - return true - } - - const outputLength = Math.floor((input.length - this._fraction) / this._ratio) - for (let i = 0; i < outputLength; i++) { - const index = i * this._ratio + this._fraction - const sample = this._interpolate(input, index) - this._buffer.push(sample) - } - this._fraction = (outputLength * this._ratio) + this._fraction - input.length - this._lastSample = input[input.length - 1] - - if (this._buffer.length >= 1024) { - this._flushBuffer() - } - - return true - } - - _interpolate(input, index) { - if (index < 0) { - const t = (index % 1) + 1 - return this._lastSample * (1 - t) + input[0] * t - } - const prevIndex = Math.floor(index) - const nextIndex = prevIndex + 1 - if (nextIndex >= input.length) { - return input[prevIndex] - } - const t = index - prevIndex - return input[prevIndex] * (1 - t) + input[nextIndex] * t - } - - _flushBuffer() { - const int16 = new Int16Array(this._buffer.length) - for (let i = 0; i < this._buffer.length; i++) { - const sample = Math.max(-1, Math.min(1, this._buffer[i])) - int16[i] = sample < 0 ? sample * 32768 : sample * 32767 - } - this.port.postMessage(int16, [int16.buffer]) - this._buffer = [] - } -} - -registerProcessor('recorder-processor', RecorderProcessor) diff --git a/frontend/src/api/stt.test.ts b/frontend/src/api/stt.test.ts index deb67b37..ca0f7113 100644 --- a/frontend/src/api/stt.test.ts +++ b/frontend/src/api/stt.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { sttApi } from './stt' +import { FetchError } from './fetchWrapper' describe('WAV extension selection logic', () => { const originalFetch = global.fetch @@ -69,6 +70,18 @@ describe('WAV extension selection logic', () => { expect(audioFile.name).toBe('recording.m4a') }) + it('should return webm for audio/webm;codecs=opus blob', async () => { + const blob = new Blob([], { type: 'audio/webm;codecs=opus' }) + mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' })) + + await sttApi.transcribe(blob, 'test-user') + + const callArgs = mockFetch.mock.calls[0] + const formData = callArgs[1]?.body as FormData + const audioFile = formData.get('audio') as File + expect(audioFile.name).toBe('recording.webm') + }) + it('should default to wav for unknown types', async () => { const blob = new Blob([], { type: 'audio/unknown' }) mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' })) @@ -123,3 +136,85 @@ describe('WAV extension selection logic', () => { expect(formData.get('audio')).toBeInstanceOf(File) }) }) + +describe('sttApi.transcribe cancellation and timeout', () => { + const originalFetch = global.fetch + + beforeEach(() => { + vi.stubGlobal('fetch', vi.fn()) + }) + + afterEach(() => { + vi.restoreAllMocks() + global.fetch = originalFetch + }) + + it('throws 499 CANCELED when caller aborts', async () => { + const blob = new Blob([], { type: 'audio/webm;codecs=opus' }) + const abortController = new AbortController() + + const mockFetch = global.fetch as ReturnType + mockFetch.mockImplementation((_url: string, options: RequestInit) => { + const signal = options.signal as AbortSignal + return new Promise((_resolve, reject) => { + if (signal.aborted) { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + return + } + signal.addEventListener('abort', () => { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + }, { once: true }) + }) + }) + + const promise = sttApi.transcribe(blob, 'test-user', abortController.signal) + + abortController.abort() + + await expect(promise).rejects.toThrow(FetchError) + await expect(promise).rejects.toMatchObject({ + statusCode: 499, + code: 'CANCELED', + }) + }) + + it('throws 408 TIMEOUT when transcription times out', async () => { + vi.useFakeTimers() + + const blob = new Blob([], { type: 'audio/webm;codecs=opus' }) + + const mockFetch = global.fetch as ReturnType + mockFetch.mockImplementation((_url: string, options: RequestInit) => { + const signal = options.signal as AbortSignal + return new Promise((_resolve, reject) => { + if (signal.aborted) { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + return + } + signal.addEventListener('abort', () => { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + }, { once: true }) + }) + }) + + const promise = sttApi.transcribe(blob, 'test-user') + + vi.advanceTimersByTime(60000) + + await expect(promise).rejects.toThrow(FetchError) + await expect(promise).rejects.toMatchObject({ + statusCode: 408, + code: 'TIMEOUT', + }) + + vi.useRealTimers() + }) +}) diff --git a/frontend/src/api/stt.ts b/frontend/src/api/stt.ts index b068c4e1..01d6291d 100644 --- a/frontend/src/api/stt.ts +++ b/frontend/src/api/stt.ts @@ -54,18 +54,27 @@ export const sttApi = { urlObj.searchParams.set('userId', userId) const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), 60000) + let timeoutFired = false + const timeoutId = setTimeout(() => { + timeoutFired = true + controller.abort() + }, 60000) - const abortSignal = signal || controller.signal + if (signal?.aborted) { + controller.abort() + } + const onAbort = () => controller.abort() + signal?.addEventListener('abort', onAbort, { once: true }) try { const response = await fetch(urlObj.toString(), { method: 'POST', body: formData, - signal: abortSignal, + signal: controller.signal, }) clearTimeout(timeoutId) + signal?.removeEventListener('abort', onAbort) if (!response.ok) { const data = await response.json().catch(() => ({ error: 'Transcription failed' })) @@ -75,7 +84,12 @@ export const sttApi = { return response.json() } catch (error) { clearTimeout(timeoutId) + signal?.removeEventListener('abort', onAbort) + if (error instanceof Error && error.name === 'AbortError') { + if (signal?.aborted && !timeoutFired) { + throw new FetchError('Transcription canceled', 499, 'CANCELED') + } throw new FetchError('Transcription timeout', 408, 'TIMEOUT') } throw error diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 2f2b6173..4dc6b696 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -47,7 +47,8 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => { const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"] -const VOICE_SEND_SWIPE_THRESHOLD = 30 +const VOICE_SEND_SWIPE_ARM_THRESHOLD = 24 +const VOICE_SEND_SWIPE_DISARM_THRESHOLD = 8 type VoiceButtonVariant = 'desktop' | 'mobile' @@ -496,6 +497,7 @@ export const PromptInput = memo(forwardRef( return } + event.preventDefault() voiceGestureStartYRef.current = event.clientY voiceSwipeArmedRef.current = false setIsVoiceSwipeArmed(false) @@ -510,8 +512,11 @@ export const PromptInput = memo(forwardRef( return } + event.preventDefault() const deltaY = voiceGestureStartYRef.current - event.clientY - const nextIsSwipeArmed = deltaY >= VOICE_SEND_SWIPE_THRESHOLD + const nextIsSwipeArmed = voiceSwipeArmedRef.current + ? deltaY >= VOICE_SEND_SWIPE_DISARM_THRESHOLD + : deltaY >= VOICE_SEND_SWIPE_ARM_THRESHOLD if (nextIsSwipeArmed !== voiceSwipeArmedRef.current) { voiceSwipeArmedRef.current = nextIsSwipeArmed @@ -532,6 +537,7 @@ export const PromptInput = memo(forwardRef( return } + event.preventDefault() voiceGestureStartYRef.current = null if (canceled || !voiceSwipeArmedRef.current) { @@ -1096,7 +1102,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) : 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border active:bg-muted-foreground/30 active:scale-95' }` - const containerClassName = isDesktop ? 'relative hidden md:block' : 'relative flex w-full' + const containerClassName = isDesktop ? 'relative hidden md:block' : 'relative flex w-full touch-none select-none' return (
+ {!isDesktop && showVoiceFeedback && ( +