mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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
This commit is contained in:
1 parent
ab624a0970
commit
2b2cb6d23d
13 files changed
+1625
-549
No files matched your search
@@ -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)
|
||||
@@ -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<typeof vi.fn>
|
||||
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<typeof vi.fn>
|
||||
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()
|
||||
})
|
||||
})
|
||||
+17
-3
@@ -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
|
||||
|
||||
@@ -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<PromptInputHandle, PromptInputProps>(
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
voiceGestureStartYRef.current = event.clientY
|
||||
voiceSwipeArmedRef.current = false
|
||||
setIsVoiceSwipeArmed(false)
|
||||
@@ -510,8 +512,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
|
||||
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<PromptInputHandle, PromptInputProps>(
|
||||
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 (
|
||||
<div
|
||||
@@ -1104,6 +1110,9 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
className={containerClassName}
|
||||
{...voiceGestureHandlers}
|
||||
>
|
||||
{!isDesktop && showVoiceFeedback && (
|
||||
<div aria-hidden="true" className="absolute inset-x-0 bottom-full z-20 h-44 touch-none" />
|
||||
)}
|
||||
<VoiceStatusOverlay show={!isDesktop && showVoiceFeedback} label={voiceFeedbackLabel} state={voiceFeedbackState} />
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -48,7 +48,7 @@ export function VoiceStatusOverlay({ show, label, state }: VoiceStatusOverlayPro
|
||||
className="pointer-events-none absolute inset-x-0 bottom-0 z-10"
|
||||
>
|
||||
<span className="sr-only">{label}</span>
|
||||
<div className="relative flex h-36 w-full flex-col items-center justify-between overflow-hidden rounded-xl border border-green-300/70 bg-gradient-to-t from-green-700 via-green-500 to-emerald-400 px-1 py-3 text-white shadow-lg shadow-green-500/40">
|
||||
<div className="animate-voice-overlay-in relative flex h-44 w-full flex-col items-center justify-between overflow-hidden rounded-xl border border-green-300/70 bg-gradient-to-t from-green-700 via-green-500 to-emerald-400 px-1 py-4 text-white shadow-lg shadow-green-500/40">
|
||||
<div className="absolute inset-x-1 top-1 h-10 rounded-full bg-white/20 blur-sm" />
|
||||
<div className="relative flex flex-1 flex-col items-center justify-center gap-1">
|
||||
{isLoading ? (
|
||||
|
||||
@@ -127,6 +127,9 @@ export function STTSettings() {
|
||||
} else if (sttError) {
|
||||
setTestResult('failed')
|
||||
setIsTesting(false)
|
||||
} else {
|
||||
setTestResult('idle')
|
||||
setIsTesting(false)
|
||||
}
|
||||
}
|
||||
}, [isTesting, isRecording, isProcessing, transcript, sttError])
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, act, waitFor } from '@testing-library/react'
|
||||
import { useSTT } from './useSTT'
|
||||
|
||||
type MockRecorder = {
|
||||
start: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
abort: ReturnType<typeof vi.fn>
|
||||
dispose: ReturnType<typeof vi.fn>
|
||||
getState: ReturnType<typeof vi.fn>
|
||||
setOnStateChange: ReturnType<typeof vi.fn>
|
||||
setOnError: ReturnType<typeof vi.fn>
|
||||
setOnDataAvailable: ReturnType<typeof vi.fn>
|
||||
setOnNoSpeech: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useSettings: vi.fn(),
|
||||
AudioRecorder: Object.assign(vi.fn(), { isSupported: vi.fn() }),
|
||||
getWebSpeechRecognizer: vi.fn(),
|
||||
isWebRecognitionSupported: vi.fn(),
|
||||
sttApi: { transcribe: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: mocks.useSettings,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/audioRecorder', () => ({
|
||||
AudioRecorder: mocks.AudioRecorder,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/webSpeechRecognizer', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/webSpeechRecognizer')>()
|
||||
return {
|
||||
appendTranscriptSegment: actual.appendTranscriptSegment,
|
||||
getWebSpeechRecognizer: mocks.getWebSpeechRecognizer,
|
||||
isWebRecognitionSupported: mocks.isWebRecognitionSupported,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/api/stt', () => ({
|
||||
sttApi: mocks.sttApi,
|
||||
}))
|
||||
|
||||
const externalSTTPreferences = {
|
||||
preferences: {
|
||||
stt: {
|
||||
enabled: true,
|
||||
provider: 'external' as const,
|
||||
endpoint: 'https://api.openai.com',
|
||||
apiKey: 'test-key',
|
||||
model: 'whisper-1',
|
||||
language: 'en-US',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
describe('useSTT external provider lifecycle', () => {
|
||||
let mockRecorder: MockRecorder
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockRecorder = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn(),
|
||||
abort: vi.fn(),
|
||||
dispose: vi.fn(),
|
||||
getState: vi.fn().mockReturnValue('recording'),
|
||||
setOnStateChange: vi.fn(),
|
||||
setOnError: vi.fn(),
|
||||
setOnDataAvailable: vi.fn(),
|
||||
setOnNoSpeech: vi.fn(),
|
||||
}
|
||||
|
||||
mocks.AudioRecorder.mockImplementation(() => mockRecorder)
|
||||
mocks.AudioRecorder.isSupported.mockReturnValue(true)
|
||||
mocks.useSettings.mockReturnValue(externalSTTPreferences)
|
||||
mocks.getWebSpeechRecognizer.mockReturnValue({
|
||||
start: vi.fn(),
|
||||
stop: vi.fn(),
|
||||
abort: vi.fn(),
|
||||
clearCallbacks: vi.fn(),
|
||||
onResult: vi.fn(),
|
||||
onInterimResult: vi.fn(),
|
||||
onError: vi.fn(),
|
||||
onEnd: vi.fn(),
|
||||
onStart: vi.fn(),
|
||||
})
|
||||
mocks.isWebRecognitionSupported.mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('returns false when external provider is not supported', async () => {
|
||||
mocks.AudioRecorder.isSupported = vi.fn().mockReturnValue(false)
|
||||
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
let started: boolean | undefined
|
||||
await act(async () => {
|
||||
started = await result.current.startRecording()
|
||||
})
|
||||
|
||||
expect(started).toBe(false)
|
||||
expect(result.current.isError).toBe(true)
|
||||
expect(result.current.error).toBe('Speech recognition is not supported in this browser')
|
||||
})
|
||||
|
||||
it('does not instantiate AudioRecorder until startRecording is called', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
expect(mocks.AudioRecorder).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
expect(mocks.AudioRecorder).toHaveBeenCalledTimes(1)
|
||||
expect(mockRecorder.start).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('clears processing without an error when no speech is detected', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
const onNoSpeech = mockRecorder.setOnNoSpeech.mock.calls[0][0] as () => void
|
||||
|
||||
act(() => {
|
||||
onNoSpeech()
|
||||
})
|
||||
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.isRecording).toBe(false)
|
||||
expect(result.current.isError).toBe(false)
|
||||
expect(result.current.error).toBeNull()
|
||||
})
|
||||
|
||||
it('does not get stuck processing when stopping a silent recording', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
const onNoSpeech = mockRecorder.setOnNoSpeech.mock.calls[0][0] as () => void
|
||||
mockRecorder.stop.mockImplementation(() => {
|
||||
onNoSpeech()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.stopRecording()
|
||||
})
|
||||
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.isRecording).toBe(false)
|
||||
expect(result.current.isError).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores stopRecording when the recorder is not recording', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
mockRecorder.getState.mockReturnValue('stopped')
|
||||
|
||||
act(() => {
|
||||
result.current.stopRecording()
|
||||
})
|
||||
|
||||
expect(mockRecorder.stop).not.toHaveBeenCalled()
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
})
|
||||
|
||||
it('disposes external recorder resources on unmount', async () => {
|
||||
const { result, unmount } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
const recorder = mockRecorder
|
||||
|
||||
unmount()
|
||||
|
||||
expect(recorder.dispose).toHaveBeenCalledTimes(1)
|
||||
expect(recorder.abort).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('successfully transcribes recorded audio', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
const onStateChange = mockRecorder.setOnStateChange.mock.calls[0][0] as (state: string) => void
|
||||
const onDataAvailable = mockRecorder.setOnDataAvailable.mock.calls[0][0] as (blob: Blob) => void
|
||||
|
||||
act(() => {
|
||||
onStateChange('recording')
|
||||
})
|
||||
|
||||
expect(result.current.isRecording).toBe(true)
|
||||
expect(result.current.state).toBe('listening')
|
||||
expect(result.current.interimTranscript).toBe('Recording...')
|
||||
|
||||
mocks.sttApi.transcribe.mockResolvedValueOnce({ text: 'hello world' })
|
||||
const audioBlob = new Blob([], { type: 'audio/webm;codecs=opus' })
|
||||
|
||||
await act(async () => {
|
||||
await onDataAvailable(audioBlob)
|
||||
})
|
||||
|
||||
expect(result.current.transcript).toBe('hello world')
|
||||
expect(result.current.interimTranscript).toBe('')
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.state).toBe('idle')
|
||||
})
|
||||
|
||||
it('does not show error when transcription is canceled', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
const onDataAvailable = mockRecorder.setOnDataAvailable.mock.calls[0][0] as (blob: Blob) => void
|
||||
|
||||
let rejectTranscribe!: (reason: unknown) => void
|
||||
const transcribePromise = new Promise((_resolve, reject) => {
|
||||
rejectTranscribe = reject
|
||||
})
|
||||
mocks.sttApi.transcribe.mockReturnValue(transcribePromise)
|
||||
|
||||
const audioBlob = new Blob([], { type: 'audio/webm;codecs=opus' })
|
||||
|
||||
act(() => {
|
||||
onDataAvailable(audioBlob)
|
||||
})
|
||||
|
||||
const signalArg = mocks.sttApi.transcribe.mock.calls[0][2] as AbortSignal
|
||||
expect(signalArg).toBeDefined()
|
||||
expect(signalArg.aborted).toBe(false)
|
||||
|
||||
act(() => {
|
||||
result.current.abortRecording()
|
||||
})
|
||||
|
||||
expect(signalArg.aborted).toBe(true)
|
||||
|
||||
const cancelError = new Error('canceled')
|
||||
cancelError.name = 'CanceledError'
|
||||
rejectTranscribe(cancelError)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(false)
|
||||
})
|
||||
|
||||
expect(result.current.error).toBeNull()
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.state).toBe('idle')
|
||||
})
|
||||
})
|
||||
|
||||
const builtinSTTPreferences = {
|
||||
preferences: {
|
||||
stt: {
|
||||
enabled: true,
|
||||
provider: 'builtin' as const,
|
||||
endpoint: '',
|
||||
apiKey: '',
|
||||
model: '',
|
||||
language: 'en-US',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
describe('useSTT builtin provider lifecycle', () => {
|
||||
let mockRecognizer: {
|
||||
start: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
abort: ReturnType<typeof vi.fn>
|
||||
clearCallbacks: ReturnType<typeof vi.fn>
|
||||
onResult: ReturnType<typeof vi.fn>
|
||||
onInterimResult: ReturnType<typeof vi.fn>
|
||||
onError: ReturnType<typeof vi.fn>
|
||||
onEnd: ReturnType<typeof vi.fn>
|
||||
onStart: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
const registeredCallbacks: {
|
||||
onResult: Array<(result: { transcript: string; isFinal: boolean; confidence: number }) => void>
|
||||
onInterimResult: Array<(transcript: string) => void>
|
||||
onError: Array<(error: string) => void>
|
||||
onEnd: Array<() => void>
|
||||
onStart: Array<() => void>
|
||||
} = {
|
||||
onResult: [],
|
||||
onInterimResult: [],
|
||||
onError: [],
|
||||
onEnd: [],
|
||||
onStart: [],
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
registeredCallbacks.onResult = []
|
||||
registeredCallbacks.onInterimResult = []
|
||||
registeredCallbacks.onError = []
|
||||
registeredCallbacks.onEnd = []
|
||||
registeredCallbacks.onStart = []
|
||||
|
||||
mockRecognizer = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
stop: vi.fn(),
|
||||
abort: vi.fn(),
|
||||
clearCallbacks: vi.fn(),
|
||||
onResult: vi.fn((cb: (result: { transcript: string; isFinal: boolean; confidence: number }) => void) => {
|
||||
registeredCallbacks.onResult.push(cb)
|
||||
}),
|
||||
onInterimResult: vi.fn((cb: (transcript: string) => void) => {
|
||||
registeredCallbacks.onInterimResult.push(cb)
|
||||
}),
|
||||
onError: vi.fn((cb: (error: string) => void) => {
|
||||
registeredCallbacks.onError.push(cb)
|
||||
}),
|
||||
onEnd: vi.fn((cb: () => void) => {
|
||||
registeredCallbacks.onEnd.push(cb)
|
||||
}),
|
||||
onStart: vi.fn((cb: () => void) => {
|
||||
registeredCallbacks.onStart.push(cb)
|
||||
}),
|
||||
}
|
||||
|
||||
mocks.useSettings.mockReturnValue(builtinSTTPreferences)
|
||||
mocks.getWebSpeechRecognizer.mockReturnValue(mockRecognizer)
|
||||
mocks.isWebRecognitionSupported.mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('starts recognition with correct options for builtin provider', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
expect(mockRecognizer.start).toHaveBeenCalledWith({
|
||||
language: 'en-US',
|
||||
interimResults: true,
|
||||
maxAlternatives: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('onStart callback sets isRecording=true and state=listening', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
})
|
||||
|
||||
expect(result.current.isRecording).toBe(true)
|
||||
expect(result.current.state).toBe('listening')
|
||||
})
|
||||
|
||||
it('onInterimResult callback updates interimTranscript', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
registeredCallbacks.onInterimResult[0]('partial')
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.interimTranscript).toBe('partial')
|
||||
})
|
||||
})
|
||||
|
||||
it('onResult callback appends final transcript, clears processing, and keeps isRecording=true', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onResult[0]({
|
||||
transcript: 'final',
|
||||
isFinal: true,
|
||||
confidence: 1,
|
||||
})
|
||||
})
|
||||
|
||||
expect(result.current.transcript).toBe('final')
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.isRecording).toBe(true)
|
||||
expect(result.current.state).toBe('listening')
|
||||
})
|
||||
|
||||
it('onEnd callback resets to idle', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onEnd[0]()
|
||||
})
|
||||
|
||||
expect(result.current.isRecording).toBe(false)
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.state).toBe('idle')
|
||||
})
|
||||
|
||||
it('abortRecording calls recognizer abort and resets state', async () => {
|
||||
const { result } = renderHook(() => useSTT())
|
||||
|
||||
await act(async () => {
|
||||
await result.current.startRecording()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
registeredCallbacks.onStart[0]()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.abortRecording()
|
||||
})
|
||||
|
||||
expect(mockRecognizer.abort).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.transcript).toBe('')
|
||||
expect(result.current.interimTranscript).toBe('')
|
||||
expect(result.current.isRecording).toBe(false)
|
||||
expect(result.current.isProcessing).toBe(false)
|
||||
expect(result.current.state).toBe('idle')
|
||||
})
|
||||
})
|
||||
+104
-140
@@ -1,8 +1,9 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { getWebSpeechRecognizer, isWebRecognitionSupported, type SpeechRecognitionOptions, type SpeechRecognitionResult, type RecognitionState } from '@/lib/webSpeechRecognizer'
|
||||
import { getWebSpeechRecognizer, isWebRecognitionSupported, appendTranscriptSegment, type SpeechRecognitionOptions, type SpeechRecognitionResult, type RecognitionState } from '@/lib/webSpeechRecognizer'
|
||||
import { AudioRecorder } from '@/lib/audioRecorder'
|
||||
import { sttApi } from '@/api/stt'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
|
||||
|
||||
const STT_START_TIMEOUT_MS = 10_000
|
||||
@@ -38,9 +39,27 @@ export function useSTT(userId = 'default') {
|
||||
const isExternalProvider = config.provider === 'external'
|
||||
|
||||
const isSupported = isExternalProvider
|
||||
? true
|
||||
? AudioRecorder.isSupported()
|
||||
: isWebRecognitionSupported()
|
||||
|
||||
const flashError = useCallback((message: string) => {
|
||||
setIsError(true)
|
||||
setError(message)
|
||||
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
|
||||
errorTimeoutRef.current = setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
errorTimeoutRef.current = null
|
||||
}, 3000)
|
||||
}, [])
|
||||
|
||||
const resetToIdle = useCallback((clearInterim = false) => {
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
if (clearInterim) setInterimTranscript('')
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEnabled || isExternalProvider) {
|
||||
return
|
||||
@@ -54,12 +73,7 @@ export function useSTT(userId = 'default') {
|
||||
|
||||
rec.onResult((result: SpeechRecognitionResult) => {
|
||||
setIsProcessing(false)
|
||||
setTranscript((prev) => {
|
||||
const prevTrimmed = prev.trim()
|
||||
const next = result.transcript.trim()
|
||||
return prevTrimmed ? `${prevTrimmed} ${next}` : next
|
||||
})
|
||||
setIsRecording(false)
|
||||
setTranscript((prev) => appendTranscriptSegment(prev, result.transcript))
|
||||
})
|
||||
|
||||
rec.onInterimResult((interim: string) => {
|
||||
@@ -74,21 +88,11 @@ export function useSTT(userId = 'default') {
|
||||
rec.onError((errorMessage: string) => {
|
||||
setIsProcessing(false)
|
||||
setIsRecording(false)
|
||||
setIsError(true)
|
||||
setError(errorMessage)
|
||||
|
||||
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
|
||||
errorTimeoutRef.current = setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
errorTimeoutRef.current = null
|
||||
}, 3000)
|
||||
flashError(errorMessage)
|
||||
})
|
||||
|
||||
rec.onEnd(() => {
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
resetToIdle()
|
||||
})
|
||||
|
||||
rec.onStart(() => {
|
||||
@@ -105,7 +109,7 @@ export function useSTT(userId = 'default') {
|
||||
interimRafRef.current = null
|
||||
}
|
||||
}
|
||||
}, [isEnabled, isExternalProvider])
|
||||
}, [isEnabled, isExternalProvider, flashError, resetToIdle])
|
||||
|
||||
const setupAudioRecorder = useCallback((recorder: AudioRecorder) => {
|
||||
recorder.setOnStateChange((recState) => {
|
||||
@@ -117,9 +121,7 @@ export function useSTT(userId = 'default') {
|
||||
} else if (recState === 'stopped') {
|
||||
setIsRecording(false)
|
||||
} else if (recState === 'error') {
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
resetToIdle()
|
||||
} else if (recState === 'idle') {
|
||||
setState('idle')
|
||||
}
|
||||
@@ -128,15 +130,11 @@ export function useSTT(userId = 'default') {
|
||||
recorder.setOnError((errorMessage) => {
|
||||
setIsProcessing(false)
|
||||
setIsRecording(false)
|
||||
setIsError(true)
|
||||
setError(errorMessage)
|
||||
flashError(errorMessage)
|
||||
})
|
||||
|
||||
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
|
||||
errorTimeoutRef.current = setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
errorTimeoutRef.current = null
|
||||
}, 3000)
|
||||
recorder.setOnNoSpeech(() => {
|
||||
resetToIdle(true)
|
||||
})
|
||||
|
||||
recorder.setOnDataAvailable(async (blob) => {
|
||||
@@ -156,55 +154,49 @@ export function useSTT(userId = 'default') {
|
||||
abortControllerRef.current.signal
|
||||
)
|
||||
|
||||
setTranscript((prev) => {
|
||||
const prevTrimmed = prev.trim()
|
||||
const newText = result.text.trim()
|
||||
return prevTrimmed ? `${prevTrimmed} ${newText}` : newText
|
||||
})
|
||||
setTranscript((prev) => appendTranscriptSegment(prev, result.text))
|
||||
setInterimTranscript('')
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === 'CanceledError') {
|
||||
if (err instanceof Error && (
|
||||
err.name === 'CanceledError' ||
|
||||
(err instanceof FetchError && (err.code === 'CANCELED' || err.statusCode === 499))
|
||||
)) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsError(true)
|
||||
const errorMessage = err instanceof Error ? err.message : 'Transcription failed'
|
||||
setError(errorMessage)
|
||||
|
||||
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current)
|
||||
errorTimeoutRef.current = setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
errorTimeoutRef.current = null
|
||||
}, 3000)
|
||||
flashError(err instanceof Error ? err.message : 'Transcription failed')
|
||||
} finally {
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
abortControllerRef.current = null
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEnabled || !isExternalProvider) {
|
||||
return
|
||||
}
|
||||
}, [flashError, resetToIdle])
|
||||
|
||||
const ensureAudioRecorder = useCallback((): AudioRecorder => {
|
||||
if (!audioRecorder.current) {
|
||||
audioRecorder.current = new AudioRecorder()
|
||||
}
|
||||
|
||||
if (!recorderConfiguredRef.current) {
|
||||
setupAudioRecorder(audioRecorder.current)
|
||||
recorderConfiguredRef.current = true
|
||||
}
|
||||
return audioRecorder.current
|
||||
}, [setupAudioRecorder])
|
||||
|
||||
return () => {
|
||||
if (audioRecorder.current) {
|
||||
audioRecorder.current.abort()
|
||||
}
|
||||
const disposeAudioRecorder = useCallback(() => {
|
||||
if (audioRecorder.current) {
|
||||
audioRecorder.current.dispose()
|
||||
audioRecorder.current = null
|
||||
}
|
||||
}, [isEnabled, isExternalProvider, setupAudioRecorder])
|
||||
recorderConfiguredRef.current = false
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
disposeAudioRecorder()
|
||||
}
|
||||
}, [isEnabled, isExternalProvider, disposeAudioRecorder])
|
||||
|
||||
const clearStartupTimeout = useCallback(() => {
|
||||
if (startupTimeoutRef.current) {
|
||||
@@ -214,17 +206,46 @@ export function useSTT(userId = 'default') {
|
||||
}, [])
|
||||
|
||||
const abortAndResetOnTimeout = useCallback(() => {
|
||||
if (isExternalProvider && audioRecorder.current) {
|
||||
audioRecorder.current.abort()
|
||||
if (isExternalProvider) {
|
||||
disposeAudioRecorder()
|
||||
} else {
|
||||
recognizer.current.abort()
|
||||
}
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
resetToIdle()
|
||||
setIsError(true)
|
||||
setError('Microphone start timed out')
|
||||
}, [isExternalProvider])
|
||||
}, [isExternalProvider, disposeAudioRecorder, resetToIdle])
|
||||
|
||||
const runStartupWithTimeout = useCallback(
|
||||
async (startup: () => Promise<void>, startOpId: number): Promise<boolean> => {
|
||||
try {
|
||||
const startupPromise = startup()
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
startupTimeoutRef.current = setTimeout(() => {
|
||||
if (startOpIdRef.current !== startOpId) return
|
||||
reject(new Error('Microphone start timed out'))
|
||||
}, STT_START_TIMEOUT_MS)
|
||||
})
|
||||
|
||||
await Promise.race([startupPromise, timeoutPromise])
|
||||
clearStartupTimeout()
|
||||
|
||||
return startOpIdRef.current === startOpId
|
||||
} catch (err) {
|
||||
clearStartupTimeout()
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
setIsProcessing(false)
|
||||
if (err instanceof Error && err.message === 'Microphone start timed out') {
|
||||
abortAndResetOnTimeout()
|
||||
return false
|
||||
}
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
return false
|
||||
}
|
||||
},
|
||||
[clearStartupTimeout, abortAndResetOnTimeout],
|
||||
)
|
||||
|
||||
const startRecording = useCallback(async (): Promise<boolean> => {
|
||||
if (!isSupported) {
|
||||
@@ -249,41 +270,14 @@ export function useSTT(userId = 'default') {
|
||||
clearStartupTimeout()
|
||||
|
||||
if (isExternalProvider) {
|
||||
if (!audioRecorder.current) {
|
||||
audioRecorder.current = new AudioRecorder()
|
||||
setupAudioRecorder(audioRecorder.current)
|
||||
}
|
||||
|
||||
try {
|
||||
setIsProcessing(true)
|
||||
|
||||
const startupPromise = audioRecorder.current.start()
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
startupTimeoutRef.current = setTimeout(() => {
|
||||
if (startOpIdRef.current !== startOpId) return
|
||||
reject(new Error('Microphone start timed out'))
|
||||
}, STT_START_TIMEOUT_MS)
|
||||
})
|
||||
|
||||
await Promise.race([startupPromise, timeoutPromise])
|
||||
clearStartupTimeout()
|
||||
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
const recorder = ensureAudioRecorder()
|
||||
|
||||
setIsProcessing(true)
|
||||
const started = await runStartupWithTimeout(() => recorder.start(), startOpId)
|
||||
if (started) {
|
||||
setIsProcessing(false)
|
||||
return true
|
||||
} catch (err) {
|
||||
clearStartupTimeout()
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
setIsProcessing(false)
|
||||
if (err instanceof Error && err.message === 'Microphone start timed out') {
|
||||
abortAndResetOnTimeout()
|
||||
return false
|
||||
}
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
return false
|
||||
}
|
||||
return started
|
||||
} else {
|
||||
const options: SpeechRecognitionOptions = {
|
||||
language: config.language,
|
||||
@@ -291,45 +285,21 @@ export function useSTT(userId = 'default') {
|
||||
maxAlternatives: 1,
|
||||
}
|
||||
|
||||
try {
|
||||
setIsProcessing(true)
|
||||
|
||||
const startupPromise = recognizer.current.start(options)
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
startupTimeoutRef.current = setTimeout(() => {
|
||||
if (startOpIdRef.current !== startOpId) return
|
||||
reject(new Error('Microphone start timed out'))
|
||||
}, STT_START_TIMEOUT_MS)
|
||||
})
|
||||
|
||||
await Promise.race([startupPromise, timeoutPromise])
|
||||
clearStartupTimeout()
|
||||
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
clearStartupTimeout()
|
||||
if (startOpIdRef.current !== startOpId) return false
|
||||
setIsProcessing(false)
|
||||
if (err instanceof Error && err.message === 'Microphone start timed out') {
|
||||
abortAndResetOnTimeout()
|
||||
return false
|
||||
}
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
return false
|
||||
}
|
||||
setIsProcessing(true)
|
||||
return runStartupWithTimeout(() => recognizer.current.start(options), startOpId)
|
||||
}
|
||||
}, [isSupported, isEnabled, isExternalProvider, config.language, setupAudioRecorder, clearStartupTimeout, abortAndResetOnTimeout])
|
||||
}, [isSupported, isEnabled, isExternalProvider, config.language, clearStartupTimeout, ensureAudioRecorder, runStartupWithTimeout])
|
||||
|
||||
const stopRecording = useCallback(() => {
|
||||
if (isExternalProvider && audioRecorder.current) {
|
||||
if (audioRecorder.current.getState() !== 'recording') {
|
||||
return
|
||||
}
|
||||
setIsProcessing(true)
|
||||
audioRecorder.current.stop()
|
||||
setIsProcessing(true)
|
||||
} else {
|
||||
recognizer.current.stop()
|
||||
setIsProcessing(true)
|
||||
recognizer.current.stop()
|
||||
}
|
||||
}, [isExternalProvider])
|
||||
|
||||
@@ -346,21 +316,15 @@ export function useSTT(userId = 'default') {
|
||||
}
|
||||
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
}, [isExternalProvider])
|
||||
resetToIdle(true)
|
||||
}, [isExternalProvider, resetToIdle])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
}, [])
|
||||
resetToIdle(true)
|
||||
}, [resetToIdle])
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setTranscript('')
|
||||
|
||||
@@ -128,6 +128,15 @@ body {
|
||||
animation: page-slide-in-from-left 300ms cubic-bezier(0.2, 0.9, 0.3, 1) forwards;
|
||||
}
|
||||
|
||||
@keyframes voice-overlay-in {
|
||||
from { transform: translateY(12px) scale(0.97); opacity: 0; }
|
||||
to { transform: translateY(0) scale(1); opacity: 1; }
|
||||
}
|
||||
|
||||
.animate-voice-overlay-in {
|
||||
animation: voice-overlay-in 180ms cubic-bezier(0.2, 0.9, 0.3, 1);
|
||||
}
|
||||
|
||||
@keyframes shine-loading {
|
||||
0% {
|
||||
background-position: -200% 0;
|
||||
|
||||
@@ -1,160 +1,514 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AudioRecorder, downsampleAndConvert, encodeWavFromInt16 } from './audioRecorder'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { waitFor } from '@testing-library/react'
|
||||
import { AudioRecorder } from './audioRecorder'
|
||||
|
||||
const blobToArrayBuffer = (blob: Blob): Promise<ArrayBuffer> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as ArrayBuffer)
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsArrayBuffer(blob)
|
||||
})
|
||||
class FakeMediaRecorder {
|
||||
static _instances: FakeMediaRecorder[] = []
|
||||
static _supportedTypes = new Set<string>([
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
])
|
||||
|
||||
describe('downsampleAndConvert', () => {
|
||||
it('should produce correct output length for 48kHz to 16kHz', () => {
|
||||
const inputLength = 4800
|
||||
const input = new Float32Array(inputLength)
|
||||
const output = downsampleAndConvert(input, 48000, 16000)
|
||||
|
||||
const expectedLength = Math.floor(inputLength * 16000 / 48000)
|
||||
expect(output.length).toBe(expectedLength)
|
||||
expect(output.length).toBe(inputLength / 3)
|
||||
})
|
||||
static isTypeSupported(type: string): boolean {
|
||||
return FakeMediaRecorder._supportedTypes.has(type)
|
||||
}
|
||||
|
||||
it('should produce correct output length for 44.1kHz to 16kHz', () => {
|
||||
const inputLength = 4410
|
||||
const input = new Float32Array(inputLength)
|
||||
const output = downsampleAndConvert(input, 44100, 16000)
|
||||
|
||||
const expectedLength = Math.floor(inputLength * 16000 / 44100)
|
||||
expect(output.length).toBeCloseTo(expectedLength, 0)
|
||||
})
|
||||
state: 'inactive' | 'recording' = 'inactive'
|
||||
stream: MediaStream
|
||||
mimeType: string
|
||||
ondataavailable: ((event: BlobEvent) => void) | null = null
|
||||
onstop: (() => void) | null = null
|
||||
onerror: ((event: Event) => void) | null = null
|
||||
|
||||
it('should clamp values in range [-1, 1] to Int16 range', () => {
|
||||
const input = new Float32Array([1.0, -1.0, 0.5, -0.5, 0.0])
|
||||
const output = downsampleAndConvert(input, 16000, 16000)
|
||||
|
||||
expect(output[0]).toBe(32767)
|
||||
expect(output[1]).toBe(-32768)
|
||||
expect(output[2]).toBeCloseTo(16383, 0)
|
||||
expect(output[3]).toBeCloseTo(-16384, 0)
|
||||
expect(output[4]).toBe(0)
|
||||
})
|
||||
constructor(stream: MediaStream, options?: MediaRecorderOptions) {
|
||||
this.stream = stream
|
||||
this.mimeType = options?.mimeType ?? ''
|
||||
FakeMediaRecorder._instances.push(this)
|
||||
}
|
||||
|
||||
it('should clamp values outside [-1, 1] range', () => {
|
||||
const input = new Float32Array([1.5, -1.5, 2.0, -2.0])
|
||||
const output = downsampleAndConvert(input, 16000, 16000)
|
||||
|
||||
expect(output[0]).toBe(32767)
|
||||
expect(output[1]).toBe(-32768)
|
||||
expect(output[2]).toBe(32767)
|
||||
expect(output[3]).toBe(-32768)
|
||||
})
|
||||
start(): void {
|
||||
this.state = 'recording'
|
||||
}
|
||||
|
||||
it('should return Int16Array type', () => {
|
||||
const input = new Float32Array(100)
|
||||
const output = downsampleAndConvert(input, 48000, 16000)
|
||||
|
||||
expect(output instanceof Int16Array).toBe(true)
|
||||
})
|
||||
})
|
||||
stop(): void {
|
||||
this.state = 'inactive'
|
||||
this.onstop?.()
|
||||
}
|
||||
}
|
||||
|
||||
describe('encodeWavFromInt16', () => {
|
||||
it('should create a Blob with audio/wav type', () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
|
||||
expect(blob.type).toBe('audio/wav')
|
||||
})
|
||||
function createMockTrack(): MediaStreamTrack {
|
||||
return { stop: vi.fn(), kind: 'audio' } as unknown as MediaStreamTrack
|
||||
}
|
||||
|
||||
it('should have RIFF header at offset 0', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const riff = String.fromCharCode(
|
||||
view.getUint8(0),
|
||||
view.getUint8(1),
|
||||
view.getUint8(2),
|
||||
view.getUint8(3)
|
||||
)
|
||||
expect(riff).toBe('RIFF')
|
||||
})
|
||||
|
||||
it('should have WAVE identifier at offset 8', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const wave = String.fromCharCode(
|
||||
view.getUint8(8),
|
||||
view.getUint8(9),
|
||||
view.getUint8(10),
|
||||
view.getUint8(11)
|
||||
)
|
||||
expect(wave).toBe('WAVE')
|
||||
})
|
||||
|
||||
it('should have sample rate at offset 24', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const sampleRate = view.getUint32(24, true)
|
||||
expect(sampleRate).toBe(16000)
|
||||
})
|
||||
|
||||
it('should have data identifier at offset 36', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const data = String.fromCharCode(
|
||||
view.getUint8(36),
|
||||
view.getUint8(37),
|
||||
view.getUint8(38),
|
||||
view.getUint8(39)
|
||||
)
|
||||
expect(data).toBe('data')
|
||||
})
|
||||
|
||||
it('should have correct file size for 1000 samples', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
|
||||
expect(arrayBuffer.byteLength).toBe(44 + 1000 * 2)
|
||||
})
|
||||
|
||||
it('should handle different sample rates', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 44100, 1)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const sampleRate = view.getUint32(24, true)
|
||||
expect(sampleRate).toBe(44100)
|
||||
})
|
||||
|
||||
it('should handle stereo channels', async () => {
|
||||
const samples = new Int16Array(1000)
|
||||
const blob = encodeWavFromInt16(samples, 16000, 2)
|
||||
const arrayBuffer = await blobToArrayBuffer(blob)
|
||||
const view = new DataView(arrayBuffer)
|
||||
|
||||
const channels = view.getUint16(22, true)
|
||||
expect(channels).toBe(2)
|
||||
})
|
||||
})
|
||||
function createMockStream(tracks: MediaStreamTrack[] = [createMockTrack()]): MediaStream {
|
||||
return {
|
||||
getTracks: () => tracks,
|
||||
getAudioTracks: () => tracks.filter(t => t.kind === 'audio'),
|
||||
getVideoTracks: () => [],
|
||||
addTrack: vi.fn(),
|
||||
removeTrack: vi.fn(),
|
||||
clone: vi.fn(),
|
||||
getTrackById: vi.fn(),
|
||||
active: true,
|
||||
id: 'mock-stream',
|
||||
onaddtrack: null,
|
||||
onremovetrack: null,
|
||||
} as unknown as MediaStream
|
||||
}
|
||||
|
||||
describe('AudioRecorder.isSupported', () => {
|
||||
it('should return boolean without throwing', () => {
|
||||
expect(() => {
|
||||
const result = AudioRecorder.isSupported()
|
||||
expect(typeof result).toBe('boolean')
|
||||
}).not.toThrow()
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
delete (Blob.prototype as { arrayBuffer?: unknown }).arrayBuffer
|
||||
})
|
||||
|
||||
it('returns true when navigator.mediaDevices.getUserMedia and window.MediaRecorder exist', () => {
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: vi.fn() },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
expect(AudioRecorder.isSupported()).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when navigator.mediaDevices.getUserMedia is missing', () => {
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: {},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
expect(AudioRecorder.isSupported()).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when window.MediaRecorder is undefined', () => {
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: vi.fn() },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: undefined,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
expect(AudioRecorder.isSupported()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder start', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let mockStream: MediaStream
|
||||
let recorder: AudioRecorder
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
let onError: ReturnType<typeof vi.fn>
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onNoSpeech: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set([
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockStream = createMockStream([mockTrack])
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(mockStream)
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onStateChange = vi.fn()
|
||||
onError = vi.fn()
|
||||
onDataAvailable = vi.fn()
|
||||
onNoSpeech = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
recorder.setOnError(onError)
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnNoSpeech(onNoSpeech)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('requests microphone with echoCancellation, noiseSuppression, and autoGainControl', async () => {
|
||||
await recorder.start()
|
||||
expect(mockGetUserMedia).toHaveBeenCalledWith({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('selects the first supported MIME type from the preferred list', async () => {
|
||||
await recorder.start()
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('audio/webm;codecs=opus')
|
||||
})
|
||||
|
||||
it('selects a lower-priority MIME when higher ones are unsupported', async () => {
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/ogg;codecs=opus'])
|
||||
await recorder.start()
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('audio/ogg;codecs=opus')
|
||||
})
|
||||
|
||||
it('constructs MediaRecorder without options when no MIME type is supported', async () => {
|
||||
FakeMediaRecorder._supportedTypes = new Set()
|
||||
await recorder.start()
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('')
|
||||
})
|
||||
|
||||
it('transitions to recording state', async () => {
|
||||
await recorder.start()
|
||||
expect(recorder.getState()).toBe('recording')
|
||||
expect(onStateChange).toHaveBeenCalledWith('recording')
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('AudioRecorder stop', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let mockStream: MediaStream
|
||||
let recorder: AudioRecorder
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onNoSpeech: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/webm;codecs=opus'])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockStream = createMockStream([mockTrack])
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(mockStream)
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onStateChange = vi.fn()
|
||||
onDataAvailable = vi.fn()
|
||||
onNoSpeech = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnNoSpeech(onNoSpeech)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('emits one combined blob via setOnDataAvailable and transitions to stopped', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
const chunk1 = new Blob(['part1'], { type: 'audio/webm;codecs=opus' })
|
||||
const chunk2 = new Blob(['part2'], { type: 'audio/webm;codecs=opus' })
|
||||
mr.ondataavailable?.({ data: chunk1 } as BlobEvent)
|
||||
mr.ondataavailable?.({ data: chunk2 } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('stopped')
|
||||
expect(onStateChange).toHaveBeenCalledWith('stopped')
|
||||
|
||||
expect(onDataAvailable).toHaveBeenCalledTimes(1)
|
||||
const emittedBlob = onDataAvailable.mock.calls[0][0] as Blob
|
||||
expect(emittedBlob).toBeInstanceOf(Blob)
|
||||
expect(emittedBlob.type).toBe('audio/webm;codecs=opus')
|
||||
})
|
||||
|
||||
it('stops all tracks after stopping', async () => {
|
||||
const track2 = createMockTrack()
|
||||
const stream2 = createMockStream([mockTrack, track2])
|
||||
mockGetUserMedia.mockResolvedValue(stream2)
|
||||
|
||||
await recorder.start()
|
||||
recorder.stop()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalledTimes(1)
|
||||
expect(track2.stop).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does nothing when not recording', async () => {
|
||||
recorder.stop()
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
expect(onNoSpeech).not.toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('idle')
|
||||
})
|
||||
|
||||
it('uses first chunk type as fallback when no MIME type is configured or available', async () => {
|
||||
FakeMediaRecorder._supportedTypes = new Set()
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
expect(mr.mimeType).toBe('')
|
||||
|
||||
const chunk1 = new Blob(['audio-data'], { type: 'audio/ogg' })
|
||||
mr.ondataavailable?.({ data: chunk1 } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
expect(onDataAvailable).toHaveBeenCalledTimes(1)
|
||||
const emittedBlob = onDataAvailable.mock.calls[0][0] as Blob
|
||||
expect(emittedBlob.type).toBe('audio/ogg')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder no-speech', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let recorder: AudioRecorder
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onNoSpeech: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(async () => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/webm;codecs=opus'])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(createMockStream([mockTrack]))
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onDataAvailable = vi.fn()
|
||||
onNoSpeech = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnNoSpeech(onNoSpeech)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('calls setOnNoSpeech when no chunks were collected', async () => {
|
||||
await recorder.start()
|
||||
recorder.stop()
|
||||
|
||||
expect(onNoSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls setOnNoSpeech when the combined blob is zero size', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob([], { type: 'audio/webm;codecs=opus' }) } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
expect(onNoSpeech).toHaveBeenCalledTimes(1)
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls setOnNoSpeech when decoded audio has no energy', async () => {
|
||||
class FakeAudioContext {
|
||||
decodeAudioData = vi.fn().mockResolvedValue({
|
||||
numberOfChannels: 1,
|
||||
getChannelData: () => new Float32Array([0, 0, 0, 0]),
|
||||
})
|
||||
|
||||
close = vi.fn().mockResolvedValue(undefined)
|
||||
}
|
||||
|
||||
Object.defineProperty(window, 'AudioContext', {
|
||||
value: FakeAudioContext,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(Blob.prototype, 'arrayBuffer', {
|
||||
value: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
|
||||
configurable: true,
|
||||
})
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob(['encoded-silence'], { type: 'audio/webm;codecs=opus' }) } as BlobEvent)
|
||||
|
||||
recorder.stop()
|
||||
|
||||
await waitFor(() => expect(onNoSpeech).toHaveBeenCalledTimes(1))
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder abort and dispose', () => {
|
||||
let mockGetUserMedia: ReturnType<typeof vi.fn>
|
||||
let mockTrack: ReturnType<typeof createMockTrack>
|
||||
let recorder: AudioRecorder
|
||||
let onDataAvailable: ReturnType<typeof vi.fn>
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(async () => {
|
||||
FakeMediaRecorder._instances = []
|
||||
FakeMediaRecorder._supportedTypes = new Set(['audio/webm;codecs=opus'])
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
mockTrack = createMockTrack()
|
||||
mockGetUserMedia = vi.fn().mockResolvedValue(createMockStream([mockTrack]))
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: mockGetUserMedia },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onDataAvailable = vi.fn()
|
||||
onStateChange = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnDataAvailable(onDataAvailable)
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('abort stops tracks and transitions to idle', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob(['audio-data']) } as BlobEvent)
|
||||
|
||||
recorder.abort()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalled()
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('idle')
|
||||
})
|
||||
|
||||
it('dispose stops tracks and transitions to idle', async () => {
|
||||
await recorder.start()
|
||||
|
||||
const mr = FakeMediaRecorder._instances[0]
|
||||
mr.ondataavailable?.({ data: new Blob(['audio-data']) } as BlobEvent)
|
||||
|
||||
recorder.dispose()
|
||||
|
||||
expect(mockTrack.stop).toHaveBeenCalled()
|
||||
expect(onDataAvailable).not.toHaveBeenCalled()
|
||||
expect(recorder.getState()).toBe('idle')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AudioRecorder error handling', () => {
|
||||
let recorder: AudioRecorder
|
||||
let onError: ReturnType<typeof vi.fn>
|
||||
let onStateChange: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'MediaRecorder', {
|
||||
value: FakeMediaRecorder,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
value: { getUserMedia: vi.fn() },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
onError = vi.fn()
|
||||
onStateChange = vi.fn()
|
||||
|
||||
recorder = new AudioRecorder()
|
||||
recorder.setOnError(onError)
|
||||
recorder.setOnStateChange(onStateChange)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('maps NotAllowedError to Microphone permission denied', async () => {
|
||||
const error = new DOMException('Permission denied', 'NotAllowedError')
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('Microphone permission denied')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('maps NotFoundError to No microphone found', async () => {
|
||||
const error = new DOMException('No device found', 'NotFoundError')
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('No microphone found')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('maps other DOMException to formatted message', async () => {
|
||||
const error = new DOMException('Something else', 'SecurityError')
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(error)
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('Microphone error: Something else')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('maps non-DOMException errors to Failed to start recording', async () => {
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onError).toHaveBeenCalledWith('Failed to start recording')
|
||||
expect(recorder.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('transitions to error state on microphone failure', async () => {
|
||||
navigator.mediaDevices.getUserMedia = vi.fn().mockRejectedValue(new Error('fail'))
|
||||
|
||||
await expect(recorder.start()).rejects.toThrow()
|
||||
expect(onStateChange).toHaveBeenCalledWith('error')
|
||||
})
|
||||
})
|
||||
+150
-174
@@ -1,104 +1,76 @@
|
||||
export type AudioRecorderState = 'idle' | 'recording' | 'stopped' | 'error'
|
||||
|
||||
export interface AudioRecorderOptions {
|
||||
sampleRate?: number
|
||||
channelCount?: number
|
||||
const DEFAULT_AUDIO_CONSTRAINTS: MediaTrackConstraints = {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
}
|
||||
|
||||
const DEFAULT_OPTIONS: AudioRecorderOptions = {
|
||||
sampleRate: 16000,
|
||||
channelCount: 1,
|
||||
const PREFERRED_MIME_TYPES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/ogg',
|
||||
'audio/mp4',
|
||||
'audio/wav',
|
||||
]
|
||||
const SPEECH_RMS_THRESHOLD = 0.005
|
||||
const SPEECH_PEAK_THRESHOLD = 0.02
|
||||
|
||||
type AudioContextConstructor = new () => AudioContext
|
||||
|
||||
function selectMimeType(): string | undefined {
|
||||
return PREFERRED_MIME_TYPES.find(type => MediaRecorder.isTypeSupported(type))
|
||||
}
|
||||
|
||||
const workletModulePromises = new WeakMap<AudioContext, Promise<void>>()
|
||||
|
||||
function ensureWorkletLoaded(ctx: AudioContext): Promise<void> {
|
||||
const existingPromise = workletModulePromises.get(ctx)
|
||||
|
||||
if (existingPromise) {
|
||||
return existingPromise
|
||||
}
|
||||
|
||||
const promise = ctx.audioWorklet.addModule('/audio-worklet-processor.js')
|
||||
workletModulePromises.set(ctx, promise)
|
||||
return promise
|
||||
function getAudioContextConstructor(): AudioContextConstructor | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
return window.AudioContext ?? (window as Window & { webkitAudioContext?: AudioContextConstructor }).webkitAudioContext ?? null
|
||||
}
|
||||
|
||||
export function downsampleAndConvert(input: Float32Array, inputRate: number, targetRate: number): Int16Array {
|
||||
const ratio = inputRate / targetRate
|
||||
const outputLength = Math.floor(input.length / ratio)
|
||||
const output = new Int16Array(outputLength)
|
||||
|
||||
for (let i = 0; i < outputLength; i++) {
|
||||
const index = i * ratio
|
||||
const prevIndex = Math.floor(index)
|
||||
const nextIndex = prevIndex + 1
|
||||
const t = index - prevIndex
|
||||
|
||||
let sample: number
|
||||
if (nextIndex >= input.length) {
|
||||
sample = input[prevIndex]
|
||||
} else {
|
||||
sample = input[prevIndex] * (1 - t) + input[nextIndex] * t
|
||||
async function blobHasSpeech(blob: Blob, AudioContextClass: AudioContextConstructor): Promise<boolean> {
|
||||
let context: AudioContext | null = null
|
||||
try {
|
||||
context = new AudioContextClass()
|
||||
const audioBuffer = await context.decodeAudioData(await blob.arrayBuffer())
|
||||
let peak = 0
|
||||
let sumSquares = 0
|
||||
let sampleCount = 0
|
||||
|
||||
for (let channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
|
||||
const samples = audioBuffer.getChannelData(channel)
|
||||
for (let i = 0; i < samples.length; i++) {
|
||||
const sample = samples[i]
|
||||
const amplitude = Math.abs(sample)
|
||||
peak = Math.max(peak, amplitude)
|
||||
sumSquares += sample * sample
|
||||
sampleCount++
|
||||
}
|
||||
}
|
||||
|
||||
const clamped = Math.max(-1, Math.min(1, sample))
|
||||
output[i] = clamped < 0 ? clamped * 32768 : clamped * 32767
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
export function encodeWavFromInt16(samples: Int16Array, sampleRate: number, channels: number): Blob {
|
||||
const dataLength = samples.length * 2
|
||||
const bufferSize = 44 + dataLength
|
||||
const buffer = new ArrayBuffer(bufferSize)
|
||||
const view = new DataView(buffer)
|
||||
|
||||
writeString(view, 0, 'RIFF')
|
||||
view.setUint32(4, 36 + dataLength, true)
|
||||
writeString(view, 8, 'WAVE')
|
||||
writeString(view, 12, 'fmt ')
|
||||
view.setUint32(16, 16, true)
|
||||
view.setUint16(20, 1, true)
|
||||
view.setUint16(22, channels, true)
|
||||
view.setUint32(24, sampleRate, true)
|
||||
view.setUint32(28, sampleRate * channels * 2, true)
|
||||
view.setUint16(32, channels * 2, true)
|
||||
view.setUint16(34, 16, true)
|
||||
writeString(view, 36, 'data')
|
||||
view.setUint32(40, dataLength, true)
|
||||
|
||||
new Int16Array(buffer, 44).set(samples)
|
||||
|
||||
return new Blob([buffer], { type: 'audio/wav' })
|
||||
}
|
||||
|
||||
function writeString(view: DataView, offset: number, string: string): void {
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
view.setUint8(offset + i, string.charCodeAt(i))
|
||||
if (sampleCount === 0) return false
|
||||
const rms = Math.sqrt(sumSquares / sampleCount)
|
||||
return rms >= SPEECH_RMS_THRESHOLD || peak >= SPEECH_PEAK_THRESHOLD
|
||||
} catch {
|
||||
return true
|
||||
} finally {
|
||||
await context?.close().catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioRecorder {
|
||||
private audioContext: AudioContext | null = null
|
||||
private mediaStream: MediaStream | null = null
|
||||
private source: MediaStreamAudioSourceNode | null = null
|
||||
private processor: ScriptProcessorNode | null = null
|
||||
private workletNode: AudioWorkletNode | null = null
|
||||
private chunks: Int16Array[] = []
|
||||
private totalSamples: number = 0
|
||||
private state: AudioRecorderState = 'idle'
|
||||
private options: AudioRecorderOptions
|
||||
private isAborted: boolean = false
|
||||
private mediaStream: MediaStream | null = null
|
||||
private mediaRecorder: MediaRecorder | null = null
|
||||
private chunks: Blob[] = []
|
||||
private firstChunkType = ''
|
||||
private isAborted = false
|
||||
private outputType = ''
|
||||
|
||||
private onStateChange?: (state: AudioRecorderState) => void
|
||||
private onError?: (error: string) => void
|
||||
private onDataAvailable?: (blob: Blob) => void
|
||||
|
||||
constructor(options: AudioRecorderOptions = {}) {
|
||||
this.options = { ...DEFAULT_OPTIONS, ...options }
|
||||
}
|
||||
private onNoSpeech?: () => void
|
||||
|
||||
static isSupported(): boolean {
|
||||
return !!(
|
||||
@@ -106,7 +78,7 @@ export class AudioRecorder {
|
||||
navigator.mediaDevices &&
|
||||
typeof navigator.mediaDevices.getUserMedia === 'function' &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.AudioContext !== 'undefined'
|
||||
typeof window.MediaRecorder !== 'undefined'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -126,6 +98,10 @@ export class AudioRecorder {
|
||||
this.onDataAvailable = callback
|
||||
}
|
||||
|
||||
setOnNoSpeech(callback: () => void): void {
|
||||
this.onNoSpeech = callback
|
||||
}
|
||||
|
||||
private setState(newState: AudioRecorderState): void {
|
||||
this.state = newState
|
||||
this.onStateChange?.(newState)
|
||||
@@ -141,56 +117,45 @@ export class AudioRecorder {
|
||||
try {
|
||||
this.isAborted = false
|
||||
this.chunks = []
|
||||
this.totalSamples = 0
|
||||
this.firstChunkType = ''
|
||||
|
||||
this.mediaStream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
},
|
||||
})
|
||||
this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: DEFAULT_AUDIO_CONSTRAINTS })
|
||||
|
||||
this.audioContext = new AudioContext({
|
||||
sampleRate: this.options.sampleRate,
|
||||
})
|
||||
|
||||
this.source = this.audioContext.createMediaStreamSource(this.mediaStream)
|
||||
|
||||
if (this.audioContext.audioWorklet) {
|
||||
try {
|
||||
await ensureWorkletLoaded(this.audioContext)
|
||||
this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor', {
|
||||
processorOptions: { targetSampleRate: this.options.sampleRate },
|
||||
})
|
||||
this.workletNode.port.onmessage = (e: MessageEvent<Int16Array>) => {
|
||||
this.chunks.push(e.data)
|
||||
this.totalSamples += e.data.length
|
||||
}
|
||||
this.source.connect(this.workletNode)
|
||||
} catch (error) {
|
||||
this.audioContext.close()
|
||||
this.audioContext = null
|
||||
throw new Error('Failed to load audio worklet processor', { cause: error })
|
||||
}
|
||||
} else if (this.audioContext) {
|
||||
const bufferSize = 4096
|
||||
this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1)
|
||||
const targetRate = this.options.sampleRate ?? 16000
|
||||
const inputRate = this.audioContext.sampleRate
|
||||
this.processor.onaudioprocess = (e) => {
|
||||
const inputData = e.inputBuffer.getChannelData(0)
|
||||
const int16Chunk = downsampleAndConvert(inputData, inputRate, targetRate)
|
||||
this.chunks.push(int16Chunk)
|
||||
this.totalSamples += int16Chunk.length
|
||||
}
|
||||
this.source.connect(this.processor)
|
||||
if (this.isAborted) {
|
||||
this.releaseResources()
|
||||
return
|
||||
}
|
||||
|
||||
const selectedMimeType = selectMimeType()
|
||||
this.mediaRecorder = new MediaRecorder(
|
||||
this.mediaStream,
|
||||
selectedMimeType ? { mimeType: selectedMimeType } : undefined,
|
||||
)
|
||||
|
||||
this.outputType = this.mediaRecorder.mimeType || selectedMimeType || ''
|
||||
|
||||
this.mediaRecorder.ondataavailable = (e: BlobEvent) => {
|
||||
if (e.data.size > 0) {
|
||||
if (this.chunks.length === 0 && e.data.type) {
|
||||
this.firstChunkType = e.data.type
|
||||
}
|
||||
this.chunks.push(e.data)
|
||||
}
|
||||
}
|
||||
|
||||
this.mediaRecorder.onstop = () => {
|
||||
this.finishRecording()
|
||||
}
|
||||
|
||||
this.mediaRecorder.onerror = () => {
|
||||
this.reset('error')
|
||||
this.onError?.('MediaRecorder error')
|
||||
}
|
||||
|
||||
this.mediaRecorder.start()
|
||||
this.setState('recording')
|
||||
} catch (error) {
|
||||
this.setState('error')
|
||||
this.cleanup()
|
||||
this.reset('error')
|
||||
|
||||
if (error instanceof DOMException) {
|
||||
if (error.name === 'NotAllowedError') {
|
||||
@@ -209,73 +174,84 @@ export class AudioRecorder {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.processor || this.workletNode) {
|
||||
this.processRecording()
|
||||
if (!this.mediaRecorder || this.mediaRecorder.state !== 'recording') {
|
||||
return
|
||||
}
|
||||
this.resetRecordingState()
|
||||
this.cleanup()
|
||||
this.setState('stopped')
|
||||
this.mediaRecorder.stop()
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.isAborted = true
|
||||
this.resetRecordingState()
|
||||
this.cleanup()
|
||||
this.setState('idle')
|
||||
}
|
||||
|
||||
private processRecording(): void {
|
||||
if (this.isAborted || this.chunks.length === 0 || this.totalSamples === 0) {
|
||||
private finishRecording(): void {
|
||||
if (this.isAborted) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const merged = new Int16Array(this.totalSamples)
|
||||
let offset = 0
|
||||
for (const chunk of this.chunks) {
|
||||
merged.set(chunk, offset)
|
||||
offset += chunk.length
|
||||
}
|
||||
const wavBlob = encodeWavFromInt16(merged, this.options.sampleRate ?? 16000, 1)
|
||||
this.onDataAvailable?.(wavBlob)
|
||||
} catch {
|
||||
this.onError?.('Failed to process recording')
|
||||
this.setState('error')
|
||||
const type = this.outputType || this.firstChunkType || ''
|
||||
const combinedBlob = new Blob(this.chunks, { type })
|
||||
|
||||
if (this.chunks.length === 0 || combinedBlob.size === 0) {
|
||||
this.onNoSpeech?.()
|
||||
this.reset('stopped')
|
||||
return
|
||||
}
|
||||
|
||||
const AudioContextClass = getAudioContextConstructor()
|
||||
if (!AudioContextClass) {
|
||||
this.onDataAvailable?.(combinedBlob)
|
||||
this.reset('stopped')
|
||||
return
|
||||
}
|
||||
|
||||
void this.finishRecordingWithSpeechDetection(combinedBlob, AudioContextClass)
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
if (this.workletNode) {
|
||||
this.workletNode.port.onmessage = null
|
||||
this.workletNode.port.postMessage('stop')
|
||||
this.workletNode.disconnect()
|
||||
this.workletNode = null
|
||||
private async finishRecordingWithSpeechDetection(combinedBlob: Blob, AudioContextClass: AudioContextConstructor): Promise<void> {
|
||||
const hasSpeech = await blobHasSpeech(combinedBlob, AudioContextClass)
|
||||
if (this.isAborted) {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.processor) {
|
||||
this.processor.onaudioprocess = null
|
||||
this.processor.disconnect()
|
||||
this.processor = null
|
||||
if (hasSpeech) {
|
||||
this.onDataAvailable?.(combinedBlob)
|
||||
} else {
|
||||
this.onNoSpeech?.()
|
||||
}
|
||||
|
||||
if (this.source) {
|
||||
this.source.disconnect()
|
||||
this.source = null
|
||||
}
|
||||
this.reset('stopped')
|
||||
}
|
||||
|
||||
if (this.audioContext && this.audioContext.state !== 'closed') {
|
||||
this.audioContext.close()
|
||||
this.audioContext = null
|
||||
}
|
||||
abort(): void {
|
||||
this.teardown()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.teardown()
|
||||
}
|
||||
|
||||
private teardown(): void {
|
||||
this.isAborted = true
|
||||
if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
|
||||
this.mediaRecorder.stop()
|
||||
}
|
||||
this.reset('idle')
|
||||
}
|
||||
|
||||
private stopTracks(): void {
|
||||
if (this.mediaStream) {
|
||||
this.mediaStream.getTracks().forEach(track => track.stop())
|
||||
this.mediaStream = null
|
||||
}
|
||||
}
|
||||
|
||||
private resetRecordingState(): void {
|
||||
private releaseResources(): void {
|
||||
this.stopTracks()
|
||||
this.mediaRecorder = null
|
||||
this.mediaStream = null
|
||||
this.chunks = []
|
||||
this.totalSamples = 0
|
||||
this.firstChunkType = ''
|
||||
this.outputType = ''
|
||||
}
|
||||
|
||||
private reset(nextState: AudioRecorderState): void {
|
||||
this.releaseResources()
|
||||
this.setState(nextState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { WebSpeechRecognizer } from './webSpeechRecognizer'
|
||||
|
||||
interface FakeSpeechRecognition {
|
||||
continuous: boolean
|
||||
interimResults: boolean
|
||||
lang: string
|
||||
maxAlternatives: number
|
||||
onstart: ((event: Event) => void) | null
|
||||
onend: ((event: Event) => void) | null
|
||||
onerror: ((event: { error: string }) => void) | null
|
||||
onresult: ((event: Record<string, unknown>) => void) | null
|
||||
start: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
abort: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function createFakeSpeechRecognition(): FakeSpeechRecognition {
|
||||
return {
|
||||
continuous: false,
|
||||
interimResults: false,
|
||||
lang: '',
|
||||
maxAlternatives: 1,
|
||||
onstart: null,
|
||||
onend: null,
|
||||
onerror: null,
|
||||
onresult: null,
|
||||
start: vi.fn(function (this: FakeSpeechRecognition) {
|
||||
setTimeout(() => {
|
||||
if (this.onstart) this.onstart(new Event('start'))
|
||||
}, 0)
|
||||
}),
|
||||
stop: vi.fn(),
|
||||
abort: vi.fn(),
|
||||
}
|
||||
}
|
||||
|
||||
function makeResultEvent(
|
||||
resultIndex: number,
|
||||
resultsLength: number,
|
||||
entries: Array<{
|
||||
isFinal: boolean
|
||||
transcript: string
|
||||
confidence: number
|
||||
}>,
|
||||
): Record<string, unknown> {
|
||||
const results: Record<number, Record<string, unknown>> = {}
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
results[i] = {
|
||||
isFinal: entries[i].isFinal,
|
||||
0: { transcript: entries[i].transcript, confidence: entries[i].confidence },
|
||||
}
|
||||
}
|
||||
return {
|
||||
resultIndex,
|
||||
results: { ...results, length: resultsLength },
|
||||
}
|
||||
}
|
||||
|
||||
describe('WebSpeechRecognizer', () => {
|
||||
let fakeRec: FakeSpeechRecognition
|
||||
|
||||
beforeEach(() => {
|
||||
fakeRec = createFakeSpeechRecognition()
|
||||
;(window as any).SpeechRecognition = vi.fn(() => fakeRec)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as any).SpeechRecognition
|
||||
})
|
||||
|
||||
it('configures continuous=true, interimResults=true, maxAlternatives=1, and lang on start()', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start({ language: 'en-US', interimResults: true, maxAlternatives: 1 })
|
||||
|
||||
expect(fakeRec.continuous).toBe(true)
|
||||
expect(fakeRec.interimResults).toBe(true)
|
||||
expect(fakeRec.maxAlternatives).toBe(1)
|
||||
expect(fakeRec.lang).toBe('en-US')
|
||||
})
|
||||
|
||||
it('appends multiple final result segments instead of replacing', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const results: Array<{ transcript: string; isFinal: boolean; confidence: number }> = []
|
||||
rec.onResult((r) => results.push(r))
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
]))
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(1, 2, [
|
||||
{ isFinal: false, transcript: 'hello', confidence: 0.9 },
|
||||
{ isFinal: true, transcript: 'world', confidence: 0.8 },
|
||||
]))
|
||||
|
||||
expect(rec.getFinalTranscript()).toBe('hello world')
|
||||
expect(results).toHaveLength(2)
|
||||
expect(results[0].transcript).toBe('hello')
|
||||
expect(results[1].transcript).toBe('world')
|
||||
})
|
||||
|
||||
it('emits combined final+interim transcript on interim events', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const interims: string[] = []
|
||||
rec.onInterimResult((t) => interims.push(t))
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
]))
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(1, 2, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
{ isFinal: false, transcript: 'world', confidence: 0.0 },
|
||||
]))
|
||||
|
||||
expect(interims).toHaveLength(1)
|
||||
expect(interims[0]).toBe('hello world')
|
||||
})
|
||||
|
||||
it('calls native stop after 2 seconds of inactivity following a result', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
|
||||
expect(fakeRec.stop).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('abort() clears accumulated transcript and inactivity timer', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'hello', confidence: 0.9 },
|
||||
]))
|
||||
|
||||
expect(rec.getFinalTranscript()).toBe('hello')
|
||||
|
||||
rec.abort()
|
||||
expect(rec.getFinalTranscript()).toBe('')
|
||||
expect(fakeRec.abort).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.useFakeTimers()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('onend clears inactivity timer and sets state to idle', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('idle')
|
||||
|
||||
vi.useFakeTimers()
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('removes one-shot start/error listeners after resolve so late errors do not leak', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onError = vi.fn()
|
||||
rec.onError(onError)
|
||||
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onerror!({ error: 'aborted' })
|
||||
|
||||
expect(onError).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('error')
|
||||
})
|
||||
|
||||
it('onend after error resets state to idle', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
const onEnd = vi.fn()
|
||||
rec.onEnd(onEnd)
|
||||
await rec.start()
|
||||
|
||||
fakeRec.onerror!({ error: 'no-speech' })
|
||||
expect(rec.getState()).toBe('error')
|
||||
|
||||
fakeRec.onend!(new Event('end'))
|
||||
|
||||
expect(onEnd).toHaveBeenCalledTimes(1)
|
||||
expect(rec.getState()).toBe('idle')
|
||||
expect(rec.isCurrentlyListening()).toBe(false)
|
||||
})
|
||||
|
||||
it('clearCallbacks clears pending inactivity timeout', async () => {
|
||||
const rec = new WebSpeechRecognizer()
|
||||
await rec.start()
|
||||
|
||||
vi.useFakeTimers()
|
||||
|
||||
fakeRec.onresult!(makeResultEvent(0, 1, [
|
||||
{ isFinal: true, transcript: 'test', confidence: 1.0 },
|
||||
]))
|
||||
|
||||
rec.clearCallbacks()
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(fakeRec.stop).not.toHaveBeenCalled()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -65,6 +65,14 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
const WEB_SPEECH_INACTIVITY_TIMEOUT_MS = 2000;
|
||||
|
||||
export function appendTranscriptSegment(current: string, segment: string): string {
|
||||
const trimmedCurrent = current.trim();
|
||||
const trimmedSegment = segment.trim();
|
||||
return trimmedCurrent ? `${trimmedCurrent} ${trimmedSegment}` : trimmedSegment;
|
||||
}
|
||||
|
||||
export class WebSpeechRecognizer {
|
||||
private recognition: SpeechRecognition | null = null;
|
||||
private isListening = false;
|
||||
@@ -75,6 +83,25 @@ export class WebSpeechRecognizer {
|
||||
private onEndCallbacks: (() => void)[] = [];
|
||||
private onStartCallbacks: (() => void)[] = [];
|
||||
private finalTranscript = '';
|
||||
private inactivityTimeoutRef: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
private clearInactivityTimeout(): void {
|
||||
if (this.inactivityTimeoutRef !== null) {
|
||||
clearTimeout(this.inactivityTimeoutRef);
|
||||
this.inactivityTimeoutRef = null;
|
||||
}
|
||||
}
|
||||
|
||||
private resetInactivityTimeout(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.isListening) {
|
||||
this.inactivityTimeoutRef = setTimeout(() => {
|
||||
if (this.isListening) {
|
||||
this.stop();
|
||||
}
|
||||
}, WEB_SPEECH_INACTIVITY_TIMEOUT_MS);
|
||||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
if (typeof window === 'undefined') return;
|
||||
@@ -83,7 +110,7 @@ export class WebSpeechRecognizer {
|
||||
|
||||
if (RecognitionClass) {
|
||||
this.recognition = new RecognitionClass();
|
||||
this.recognition.continuous = false;
|
||||
this.recognition.continuous = true;
|
||||
this.recognition.interimResults = true;
|
||||
this.recognition.maxAlternatives = 1;
|
||||
|
||||
@@ -100,13 +127,15 @@ export class WebSpeechRecognizer {
|
||||
const result = event.results[i];
|
||||
|
||||
if (result.isFinal) {
|
||||
const segment = result[0].transcript;
|
||||
this.finalTranscript = appendTranscriptSegment(this.finalTranscript, segment);
|
||||
|
||||
const finalResult: SpeechRecognitionResult = {
|
||||
transcript: result[0].transcript,
|
||||
transcript: segment,
|
||||
isFinal: true,
|
||||
confidence: result[0].confidence || 1.0,
|
||||
};
|
||||
|
||||
this.finalTranscript = result[0].transcript;
|
||||
this.onResultCallbacks.forEach((cb) => cb(finalResult));
|
||||
} else {
|
||||
interimTranscript += result[0].transcript;
|
||||
@@ -116,9 +145,12 @@ export class WebSpeechRecognizer {
|
||||
if (interimTranscript) {
|
||||
this.onInterimResultCallbacks.forEach((cb) => cb(this.finalTranscript + ' ' + interimTranscript));
|
||||
}
|
||||
|
||||
this.resetInactivityTimeout();
|
||||
};
|
||||
|
||||
this.recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
|
||||
this.clearInactivityTimeout();
|
||||
this.state = 'error';
|
||||
this.isListening = false;
|
||||
|
||||
@@ -146,10 +178,9 @@ export class WebSpeechRecognizer {
|
||||
};
|
||||
|
||||
this.recognition.onend = () => {
|
||||
this.clearInactivityTimeout();
|
||||
this.isListening = false;
|
||||
if (this.state !== 'error') {
|
||||
this.state = 'idle';
|
||||
}
|
||||
this.state = 'idle';
|
||||
this.onEndCallbacks.forEach((cb) => cb());
|
||||
};
|
||||
}
|
||||
@@ -192,13 +223,23 @@ export class WebSpeechRecognizer {
|
||||
this.recognition.maxAlternatives = options.maxAlternatives;
|
||||
}
|
||||
|
||||
const onStartOnce = () => {
|
||||
let settled = false;
|
||||
|
||||
const cleanup = () => {
|
||||
settled = true;
|
||||
this.onStartCallbacks = this.onStartCallbacks.filter(cb => cb !== onStartOnce);
|
||||
this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce);
|
||||
};
|
||||
|
||||
const onStartOnce = () => {
|
||||
if (settled) return;
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
|
||||
const onErrorOnce = (error: string) => {
|
||||
this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce);
|
||||
if (settled) return;
|
||||
cleanup();
|
||||
reject(new Error(error));
|
||||
};
|
||||
|
||||
@@ -217,6 +258,7 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.stop();
|
||||
@@ -228,6 +270,7 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.clearInactivityTimeout();
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.abort();
|
||||
@@ -270,6 +313,7 @@ export class WebSpeechRecognizer {
|
||||
}
|
||||
|
||||
clearCallbacks(): void {
|
||||
this.clearInactivityTimeout();
|
||||
this.onResultCallbacks = [];
|
||||
this.onInterimResultCallbacks = [];
|
||||
this.onErrorCallbacks = [];
|
||||
|
||||
Reference in new issue
Block a user