diff --git a/frontend/public/audio-worklet-processor.js b/frontend/public/audio-worklet-processor.js deleted file mode 100644 index 0a0e584d..00000000 --- a/frontend/public/audio-worklet-processor.js +++ /dev/null @@ -1,72 +0,0 @@ -class RecorderProcessor extends AudioWorkletProcessor { - constructor(options) { - super() - this._targetSampleRate = options?.processorOptions?.targetSampleRate ?? 16000 - this._inputSampleRate = sampleRate - this._ratio = this._inputSampleRate / this._targetSampleRate - this._fraction = 0 - this._lastSample = 0 - this._active = true - this._buffer = [] - this.port.onmessage = (e) => { - if (e.data === 'stop') { - this._active = false - } - } - } - - process(inputs) { - if (!this._active) { - if (this._buffer.length > 0) { - this._flushBuffer() - } - return false - } - - const input = inputs[0]?.[0] - if (!input || input.length === 0) { - return true - } - - const outputLength = Math.floor((input.length - this._fraction) / this._ratio) - for (let i = 0; i < outputLength; i++) { - const index = i * this._ratio + this._fraction - const sample = this._interpolate(input, index) - this._buffer.push(sample) - } - this._fraction = (outputLength * this._ratio) + this._fraction - input.length - this._lastSample = input[input.length - 1] - - if (this._buffer.length >= 1024) { - this._flushBuffer() - } - - return true - } - - _interpolate(input, index) { - if (index < 0) { - const t = (index % 1) + 1 - return this._lastSample * (1 - t) + input[0] * t - } - const prevIndex = Math.floor(index) - const nextIndex = prevIndex + 1 - if (nextIndex >= input.length) { - return input[prevIndex] - } - const t = index - prevIndex - return input[prevIndex] * (1 - t) + input[nextIndex] * t - } - - _flushBuffer() { - const int16 = new Int16Array(this._buffer.length) - for (let i = 0; i < this._buffer.length; i++) { - const sample = Math.max(-1, Math.min(1, this._buffer[i])) - int16[i] = sample < 0 ? sample * 32768 : sample * 32767 - } - this.port.postMessage(int16, [int16.buffer]) - this._buffer = [] - } -} - -registerProcessor('recorder-processor', RecorderProcessor) diff --git a/frontend/src/api/stt.test.ts b/frontend/src/api/stt.test.ts index deb67b37..ca0f7113 100644 --- a/frontend/src/api/stt.test.ts +++ b/frontend/src/api/stt.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { sttApi } from './stt' +import { FetchError } from './fetchWrapper' describe('WAV extension selection logic', () => { const originalFetch = global.fetch @@ -69,6 +70,18 @@ describe('WAV extension selection logic', () => { expect(audioFile.name).toBe('recording.m4a') }) + it('should return webm for audio/webm;codecs=opus blob', async () => { + const blob = new Blob([], { type: 'audio/webm;codecs=opus' }) + mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' })) + + await sttApi.transcribe(blob, 'test-user') + + const callArgs = mockFetch.mock.calls[0] + const formData = callArgs[1]?.body as FormData + const audioFile = formData.get('audio') as File + expect(audioFile.name).toBe('recording.webm') + }) + it('should default to wav for unknown types', async () => { const blob = new Blob([], { type: 'audio/unknown' }) mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' })) @@ -123,3 +136,85 @@ describe('WAV extension selection logic', () => { expect(formData.get('audio')).toBeInstanceOf(File) }) }) + +describe('sttApi.transcribe cancellation and timeout', () => { + const originalFetch = global.fetch + + beforeEach(() => { + vi.stubGlobal('fetch', vi.fn()) + }) + + afterEach(() => { + vi.restoreAllMocks() + global.fetch = originalFetch + }) + + it('throws 499 CANCELED when caller aborts', async () => { + const blob = new Blob([], { type: 'audio/webm;codecs=opus' }) + const abortController = new AbortController() + + const mockFetch = global.fetch as ReturnType + mockFetch.mockImplementation((_url: string, options: RequestInit) => { + const signal = options.signal as AbortSignal + return new Promise((_resolve, reject) => { + if (signal.aborted) { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + return + } + signal.addEventListener('abort', () => { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + }, { once: true }) + }) + }) + + const promise = sttApi.transcribe(blob, 'test-user', abortController.signal) + + abortController.abort() + + await expect(promise).rejects.toThrow(FetchError) + await expect(promise).rejects.toMatchObject({ + statusCode: 499, + code: 'CANCELED', + }) + }) + + it('throws 408 TIMEOUT when transcription times out', async () => { + vi.useFakeTimers() + + const blob = new Blob([], { type: 'audio/webm;codecs=opus' }) + + const mockFetch = global.fetch as ReturnType + mockFetch.mockImplementation((_url: string, options: RequestInit) => { + const signal = options.signal as AbortSignal + return new Promise((_resolve, reject) => { + if (signal.aborted) { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + return + } + signal.addEventListener('abort', () => { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + reject(err) + }, { once: true }) + }) + }) + + const promise = sttApi.transcribe(blob, 'test-user') + + vi.advanceTimersByTime(60000) + + await expect(promise).rejects.toThrow(FetchError) + await expect(promise).rejects.toMatchObject({ + statusCode: 408, + code: 'TIMEOUT', + }) + + vi.useRealTimers() + }) +}) diff --git a/frontend/src/api/stt.ts b/frontend/src/api/stt.ts index b068c4e1..01d6291d 100644 --- a/frontend/src/api/stt.ts +++ b/frontend/src/api/stt.ts @@ -54,18 +54,27 @@ export const sttApi = { urlObj.searchParams.set('userId', userId) const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), 60000) + let timeoutFired = false + const timeoutId = setTimeout(() => { + timeoutFired = true + controller.abort() + }, 60000) - const abortSignal = signal || controller.signal + if (signal?.aborted) { + controller.abort() + } + const onAbort = () => controller.abort() + signal?.addEventListener('abort', onAbort, { once: true }) try { const response = await fetch(urlObj.toString(), { method: 'POST', body: formData, - signal: abortSignal, + signal: controller.signal, }) clearTimeout(timeoutId) + signal?.removeEventListener('abort', onAbort) if (!response.ok) { const data = await response.json().catch(() => ({ error: 'Transcription failed' })) @@ -75,7 +84,12 @@ export const sttApi = { return response.json() } catch (error) { clearTimeout(timeoutId) + signal?.removeEventListener('abort', onAbort) + if (error instanceof Error && error.name === 'AbortError') { + if (signal?.aborted && !timeoutFired) { + throw new FetchError('Transcription canceled', 499, 'CANCELED') + } throw new FetchError('Transcription timeout', 408, 'TIMEOUT') } throw error diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 2f2b6173..4dc6b696 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -47,7 +47,8 @@ const revokeBlobUrls = (attachments: ImageAttachment[]) => { const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"] -const VOICE_SEND_SWIPE_THRESHOLD = 30 +const VOICE_SEND_SWIPE_ARM_THRESHOLD = 24 +const VOICE_SEND_SWIPE_DISARM_THRESHOLD = 8 type VoiceButtonVariant = 'desktop' | 'mobile' @@ -496,6 +497,7 @@ export const PromptInput = memo(forwardRef( return } + event.preventDefault() voiceGestureStartYRef.current = event.clientY voiceSwipeArmedRef.current = false setIsVoiceSwipeArmed(false) @@ -510,8 +512,11 @@ export const PromptInput = memo(forwardRef( return } + event.preventDefault() const deltaY = voiceGestureStartYRef.current - event.clientY - const nextIsSwipeArmed = deltaY >= VOICE_SEND_SWIPE_THRESHOLD + const nextIsSwipeArmed = voiceSwipeArmedRef.current + ? deltaY >= VOICE_SEND_SWIPE_DISARM_THRESHOLD + : deltaY >= VOICE_SEND_SWIPE_ARM_THRESHOLD if (nextIsSwipeArmed !== voiceSwipeArmedRef.current) { voiceSwipeArmedRef.current = nextIsSwipeArmed @@ -532,6 +537,7 @@ export const PromptInput = memo(forwardRef( return } + event.preventDefault() voiceGestureStartYRef.current = null if (canceled || !voiceSwipeArmedRef.current) { @@ -1096,7 +1102,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) : 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border active:bg-muted-foreground/30 active:scale-95' }` - const containerClassName = isDesktop ? 'relative hidden md:block' : 'relative flex w-full' + const containerClassName = isDesktop ? 'relative hidden md:block' : 'relative flex w-full touch-none select-none' return (
+ {!isDesktop && showVoiceFeedback && ( +