mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
loop: loop-stt-overhaul-lazy-mic-audioworklet-session-cleanup completed after 4 iterations
This commit is contained in:
1 parent
1da1ec617a
commit
9973e00dc5
5 files changed
+122
-98
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
@@ -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])
|
||||
|
||||
|
||||
|
||||
@@ -17,9 +17,10 @@ export function useSTT(userId = 'default') {
|
||||
|
||||
const recognizer = useRef(getWebSpeechRecognizer())
|
||||
const audioRecorder = useRef<AudioRecorder | null>(null)
|
||||
const hasShownPermissionError = useRef(false)
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
const userIdRef = useRef(userId)
|
||||
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const lastProcessedBlobRef = useRef<Blob | null>(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,
|
||||
|
||||
@@ -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<boolean> {
|
||||
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<Float32Array>) => {
|
||||
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<boolean> {
|
||||
const recorder = getAudioRecorder()
|
||||
return recorder.warmup()
|
||||
}
|
||||
Reference in new issue
Block a user