From 9973e00dc5917019e7e0c1ea9890a0e09c774760 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 7 Apr 2026 12:55:59 -0400 Subject: [PATCH] loop: loop-stt-overhaul-lazy-mic-audioworklet-session-cleanup completed after 4 iterations --- backend/src/routes/stt.ts | 20 +-- frontend/public/audio-worklet-processor.js | 22 +++ .../src/components/message/PromptInput.tsx | 7 + frontend/src/hooks/useSTT.ts | 34 +++-- frontend/src/lib/audioRecorder.ts | 137 +++++++++--------- 5 files changed, 122 insertions(+), 98 deletions(-) create mode 100644 frontend/public/audio-worklet-processor.js diff --git a/backend/src/routes/stt.ts b/backend/src/routes/stt.ts index f891c9a5..eb3884fe 100644 --- a/backend/src/routes/stt.ts +++ b/backend/src/routes/stt.ts @@ -10,17 +10,7 @@ import { generateDiscoveryCacheKey, fetchAvailableModels, } from '../utils/discovery-cache' - -type STTConfigExtended = { - enabled: boolean - provider: 'external' | 'builtin' - endpoint: string - apiKey: string - model: string - language: string - availableModels?: string[] - lastModelsFetch?: number -} +import { type STTConfig } from '@opencode-manager/shared' export function createSTTRoutes(db: Database) { const app = new Hono() @@ -38,7 +28,7 @@ export function createSTTRoutes(db: Database) { const settingsService = new SettingsService(db) const settings = settingsService.getSettings(userId) - const sttConfig = settings.preferences.stt as STTConfigExtended | undefined + const sttConfig = settings.preferences.stt as STTConfig | undefined if (!sttConfig?.enabled) { return c.json({ error: 'STT is not enabled' }, 400) @@ -146,7 +136,7 @@ export function createSTTRoutes(db: Database) { const settingsService = new SettingsService(db) const settings = settingsService.getSettings(userId) - const sttConfig = settings.preferences.stt as STTConfigExtended | undefined + const sttConfig = settings.preferences.stt as STTConfig | undefined if (!sttConfig?.endpoint) { return c.json({ error: 'STT not configured' }, 400) @@ -178,7 +168,7 @@ export function createSTTRoutes(db: Database) { ...sttConfig, availableModels: models, lastModelsFetch: Date.now() - } as STTConfigExtended + } as STTConfig }, userId) logger.info(`Fetched ${models.length} STT models`) @@ -193,7 +183,7 @@ export function createSTTRoutes(db: Database) { const userId = c.req.query('userId') || 'default' const settingsService = new SettingsService(db) const settings = settingsService.getSettings(userId) - const sttConfig = settings.preferences.stt as STTConfigExtended | undefined + const sttConfig = settings.preferences.stt as STTConfig | undefined return c.json({ enabled: sttConfig?.enabled || false, diff --git a/frontend/public/audio-worklet-processor.js b/frontend/public/audio-worklet-processor.js new file mode 100644 index 00000000..7a3c9631 --- /dev/null +++ b/frontend/public/audio-worklet-processor.js @@ -0,0 +1,22 @@ +class RecorderProcessor extends AudioWorkletProcessor { + constructor() { + super() + this._active = true + this.port.onmessage = (e) => { + if (e.data === 'stop') { + this._active = false + } + } + } + + process(inputs) { + if (!this._active) return false + const input = inputs[0] + if (input && input[0] && input[0].length > 0) { + this.port.postMessage(new Float32Array(input[0])) + } + return true + } +} + +registerProcessor('recorder-processor', RecorderProcessor) diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index fb3c5c5b..f4ebf22a 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -754,7 +754,14 @@ const { model, modelString } = useModelSelection(opcodeUrl, directory) }, [prompt, onPromptChange]) useEffect(() => { + if (isRecording) { + abortRecording() + } + clearSTT() + lastAddedTranscriptRef.current = '' + setIsTogglingRecording(false) setLocalMode(null) + // eslint-disable-next-line react-hooks/exhaustive-deps -- Intentionally only run on sessionID change to avoid clearing transcript when recording state changes }, [sessionID]) diff --git a/frontend/src/hooks/useSTT.ts b/frontend/src/hooks/useSTT.ts index 262315eb..9320accd 100644 --- a/frontend/src/hooks/useSTT.ts +++ b/frontend/src/hooks/useSTT.ts @@ -17,9 +17,10 @@ export function useSTT(userId = 'default') { const recognizer = useRef(getWebSpeechRecognizer()) const audioRecorder = useRef(null) - const hasShownPermissionError = useRef(false) const abortControllerRef = useRef(null) const userIdRef = useRef(userId) + const errorTimeoutRef = useRef | null>(null) + const lastProcessedBlobRef = useRef(null) useEffect(() => { userIdRef.current = userId @@ -60,13 +61,11 @@ export function useSTT(userId = 'default') { setIsError(true) setError(errorMessage) - if (!hasShownPermissionError.current && errorMessage.includes('denied')) { - hasShownPermissionError.current = true - } - - setTimeout(() => { + if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current) + errorTimeoutRef.current = setTimeout(() => { setIsError(false) setError(null) + errorTimeoutRef.current = null }, 3000) }) @@ -112,13 +111,20 @@ export function useSTT(userId = 'default') { setIsError(true) setError(errorMessage) - setTimeout(() => { + if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current) + errorTimeoutRef.current = setTimeout(() => { setIsError(false) setError(null) + errorTimeoutRef.current = null }, 3000) }) recorder.setOnDataAvailable(async (blob) => { + if (lastProcessedBlobRef.current === blob) { + return + } + lastProcessedBlobRef.current = blob + setInterimTranscript('Processing...') setIsProcessing(true) @@ -145,9 +151,11 @@ export function useSTT(userId = 'default') { const errorMessage = err instanceof Error ? err.message : 'Transcription failed' setError(errorMessage) - setTimeout(() => { + if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current) + errorTimeoutRef.current = setTimeout(() => { setIsError(false) setError(null) + errorTimeoutRef.current = null }, 3000) } finally { setIsProcessing(false) @@ -166,8 +174,6 @@ export function useSTT(userId = 'default') { audioRecorder.current = new AudioRecorder() } - audioRecorder.current.warmup() - setupAudioRecorder(audioRecorder.current) return () => { @@ -194,7 +200,7 @@ export function useSTT(userId = 'default') { setInterimTranscript('') setIsError(false) setError(null) - hasShownPermissionError.current = false + lastProcessedBlobRef.current = null if (isExternalProvider) { if (!audioRecorder.current) { @@ -273,6 +279,12 @@ export function useSTT(userId = 'default') { setInterimTranscript('') }, []) + useEffect(() => { + return () => { + if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current) + } + }, []) + return { isRecording, isProcessing, diff --git a/frontend/src/lib/audioRecorder.ts b/frontend/src/lib/audioRecorder.ts index 3ad00cc0..0f80b61b 100644 --- a/frontend/src/lib/audioRecorder.ts +++ b/frontend/src/lib/audioRecorder.ts @@ -78,8 +78,9 @@ export class AudioRecorder { private mediaStream: MediaStream | null = null private source: MediaStreamAudioSourceNode | null = null private processor: ScriptProcessorNode | null = null - private audioBuffer: Float32Array | null = null - private recordingLength: number = 0 + private workletNode: AudioWorkletNode | null = null + private chunks: Float32Array[] = [] + private totalSamples: number = 0 private state: AudioRecorderState = 'idle' private options: AudioRecorderOptions private isAborted: boolean = false @@ -102,26 +103,6 @@ export class AudioRecorder { ) } - async warmup(): Promise { - if (!AudioRecorder.isSupported()) { - return false - } - - try { - const stream = await navigator.mediaDevices.getUserMedia({ - audio: { - echoCancellation: true, - noiseSuppression: true, - autoGainControl: true, - }, - }) - stream.getTracks().forEach(track => track.stop()) - return true - } catch { - return false - } - } - getState(): AudioRecorderState { return this.state } @@ -152,7 +133,8 @@ export class AudioRecorder { try { this.isAborted = false - this.recordingLength = 0 + this.chunks = [] + this.totalSamples = 0 this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: { @@ -168,26 +150,33 @@ export class AudioRecorder { this.source = this.audioContext.createMediaStreamSource(this.mediaStream) - const bufferSize = 4096 - this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1) - - this.audioBuffer = new Float32Array(0) - - this.processor.onaudioprocess = (e) => { - if (this.audioBuffer) { - const inputData = e.inputBuffer.getChannelData(0) - const newLength = this.recordingLength + inputData.length - const newBuffer = new Float32Array(newLength) - newBuffer.set(this.audioBuffer, 0) - newBuffer.set(inputData, this.recordingLength) - this.audioBuffer = newBuffer - this.recordingLength = newLength + if (this.audioContext.audioWorklet) { + try { + await this.audioContext.audioWorklet.addModule('/audio-worklet-processor.js') + this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor') + this.workletNode.port.onmessage = (e: MessageEvent) => { + this.chunks.push(e.data) + this.totalSamples += e.data.length + } + this.source.connect(this.workletNode) + this.workletNode.connect(this.audioContext.destination) + } catch { + this.audioContext.close() + this.audioContext = null + throw new Error('Failed to load audio worklet processor') } + } else if (this.audioContext) { + const bufferSize = 4096 + this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1) + this.processor.onaudioprocess = (e) => { + const inputData = new Float32Array(e.inputBuffer.getChannelData(0)) + this.chunks.push(inputData) + this.totalSamples += inputData.length + } + this.source.connect(this.processor) + this.processor.connect(this.audioContext.destination) } - this.source.connect(this.processor) - this.processor.connect(this.audioContext.destination) - this.setState('recording') } catch (error) { this.setState('error') @@ -210,37 +199,41 @@ export class AudioRecorder { } stop(): void { - if (this.processor) { + if (this.processor || this.workletNode) { this.processRecording() } + this.resetRecordingState() this.cleanup() this.setState('stopped') } abort(): void { this.isAborted = true - this.audioBuffer = null - this.recordingLength = 0 + this.resetRecordingState() this.cleanup() this.setState('idle') } private processRecording(): void { - if (this.isAborted || !this.audioBuffer || this.recordingLength === 0) { + if (this.isAborted || this.chunks.length === 0 || this.totalSamples === 0) { return } try { + const merged = new Float32Array(this.totalSamples) + let offset = 0 + for (const chunk of this.chunks) { + merged.set(chunk, offset) + offset += chunk.length + } + const audioBuffer = this.audioContext!.createBuffer( 1, - this.recordingLength, + this.totalSamples, this.audioContext!.sampleRate ) - const channelData = new Float32Array(this.recordingLength) - channelData.set(this.audioBuffer!.subarray(0, this.recordingLength)) - audioBuffer.copyToChannel(channelData, 0) - + audioBuffer.copyToChannel(merged, 0) const wavBlob = encodeWAV(audioBuffer) this.onDataAvailable?.(wavBlob) } catch { @@ -250,7 +243,15 @@ export class AudioRecorder { } private cleanup(): void { + if (this.workletNode) { + this.workletNode.port.onmessage = null + this.workletNode.port.postMessage('stop') + this.workletNode.disconnect() + this.workletNode = null + } + if (this.processor) { + this.processor.onaudioprocess = null this.processor.disconnect() this.processor = null } @@ -271,42 +272,34 @@ export class AudioRecorder { } } + private resetRecordingState(): void { + this.chunks = [] + this.totalSamples = 0 + } + getRecordingBlob(): Blob | null { - if (!this.audioContext || !this.audioBuffer || this.recordingLength === 0) { + if (!this.audioContext || this.chunks.length === 0 || this.totalSamples === 0) { return null } try { + const merged = new Float32Array(this.totalSamples) + let offset = 0 + for (const chunk of this.chunks) { + merged.set(chunk, offset) + offset += chunk.length + } + const audioBuffer = this.audioContext.createBuffer( 1, - this.recordingLength, + this.totalSamples, this.audioContext.sampleRate ) - const channelData = new Float32Array(this.recordingLength) - channelData.set(this.audioBuffer.subarray(0, this.recordingLength)) - audioBuffer.copyToChannel(channelData, 0) + audioBuffer.copyToChannel(merged, 0) return encodeWAV(audioBuffer) } catch { return null } } } - -let recorderInstance: AudioRecorder | null = null - -export function getAudioRecorder(): AudioRecorder { - if (!recorderInstance) { - recorderInstance = new AudioRecorder() - } - return recorderInstance -} - -export function isAudioRecordingSupported(): boolean { - return AudioRecorder.isSupported() -} - -export async function warmupAudioRecorder(): Promise { - const recorder = getAudioRecorder() - return recorder.warmup() -}