Merge branch 'main' into dev

This commit is contained in:
Chris Scott committed 2026-02-02 22:28:21 -05:00
commit 264451a1f7
12 files changed
+310 -185

No files matched your search

+17 -14
View File
@@ -14,7 +14,6 @@ type STTConfigExtended = {
apiKey: string
model: string
language: string
continuous: boolean
availableModels?: string[]
lastModelsFetch?: number
}
@@ -62,7 +61,7 @@ async function cacheDiscovery(cacheKey: string, data: string[]): Promise<void> {
function generateDiscoveryCacheKey(endpoint: string, apiKey: string, type: 'models'): string {
const hash = createHash('sha256')
hash.update(`stt|${endpoint}|${apiKey.substring(0, 8)}|${type}`)
hash.update(`stt|${endpoint}|${apiKey ? apiKey.substring(0, 8) : 'no-key'}|${type}`)
return hash.digest('hex')
}
@@ -77,7 +76,7 @@ async function fetchAvailableModels(endpoint: string, apiKey: string): Promise<s
try {
const response = await fetch(modelEndpoint, {
headers: {
'Authorization': `Bearer ${apiKey}`,
...(apiKey && { 'Authorization': `Bearer ${apiKey}` }),
'Content-Type': 'application/json',
},
})
@@ -142,10 +141,6 @@ export function createSTTRoutes(db: Database) {
return c.json({ error: 'External STT provider is not selected' }, 400)
}
if (!sttConfig.apiKey) {
return c.json({ error: 'STT API key is not configured' }, 400)
}
if (!sttConfig.endpoint) {
return c.json({ error: 'STT endpoint is not configured' }, 400)
}
@@ -166,13 +161,13 @@ export function createSTTRoutes(db: Database) {
return new Response(null, { status: 499 })
}
logger.info(`STT transcription request: model=${model}, language=${language}, size=${audioFile.size}`)
logger.info(`STT transcription request: model=${model}, language=${language}, size=${audioFile.size}, type=${audioFile.type}`)
const baseUrl = normalizeToBaseUrl(endpoint)
const transcriptionEndpoint = `${baseUrl}/v1/audio/transcriptions`
const apiFormData = new FormData()
apiFormData.append('file', audioFile, audioFile.name || 'audio.webm')
apiFormData.append('file', audioFile, audioFile.name || 'audio.wav')
apiFormData.append('model', model)
if (language && language !== 'auto') {
@@ -185,7 +180,7 @@ export function createSTTRoutes(db: Database) {
const response = await fetch(transcriptionEndpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
...(apiKey && { 'Authorization': `Bearer ${apiKey}` }),
},
body: apiFormData,
signal: abortController.signal,
@@ -216,9 +211,17 @@ export function createSTTRoutes(db: Database) {
}, status)
}
const result = await response.json() as { text: string }
logger.info(`STT transcription successful: ${result.text.substring(0, 50)}...`)
const result = await response.json() as { text?: string } & Record<string, unknown>
if (!result.text || typeof result.text !== 'string') {
logger.error('STT API response missing text field:', { result })
return c.json({
error: 'STT API returned invalid response',
details: `Response missing text field. Full response: ${JSON.stringify(result)}`
}, 500)
}
logger.info(`STT transcription successful: ${result.text.substring(0, 50)}...`)
return c.json({ text: result.text })
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
@@ -238,7 +241,7 @@ export function createSTTRoutes(db: Database) {
const settings = settingsService.getSettings(userId)
const sttConfig = settings.preferences.stt as STTConfigExtended | undefined
if (!sttConfig?.apiKey || !sttConfig?.endpoint) {
if (!sttConfig?.endpoint) {
return c.json({ error: 'STT not configured' }, 400)
}
@@ -282,7 +285,7 @@ export function createSTTRoutes(db: Database) {
return c.json({
enabled: sttConfig?.enabled || false,
configured: !!(sttConfig?.apiKey && sttConfig?.endpoint),
configured: !!sttConfig?.endpoint,
provider: sttConfig?.provider || 'builtin',
model: sttConfig?.model || 'whisper-1',
})
+88 -29
View File
@@ -65,7 +65,6 @@ describe('STT Routes', () => {
endpoint: 'https://api.openai.com',
model: 'whisper-1',
language: 'en-US',
continuous: false,
},
},
})
@@ -198,34 +197,6 @@ describe('STT Routes', () => {
expect(json.error).toBe('External STT provider is not selected')
})
it('should reject when API key is missing', async () => {
mockGetSettings.mockReturnValue({
preferences: {
stt: {
enabled: true,
provider: 'external',
apiKey: '',
endpoint: 'https://api.openai.com',
model: 'whisper-1',
},
},
})
const audioBlob = new Blob(['fake audio'], { type: 'audio/webm' })
const formData = new FormData()
formData.append('audio', audioBlob, 'test.webm')
const req = new Request('http://localhost/transcribe?userId=test', {
method: 'POST',
body: formData,
})
const res = await sttApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(400)
expect(json.error).toBe('STT API key is not configured')
})
it('should reject when endpoint is missing', async () => {
mockGetSettings.mockReturnValue({
preferences: {
@@ -330,6 +301,94 @@ describe('STT Routes', () => {
globalThis.fetch = originalFetch
})
it('should handle response with missing text field', async () => {
const originalFetch = globalThis.fetch
mockGetSettings.mockReturnValue({
preferences: {
stt: {
enabled: true,
provider: 'external',
apiKey: 'test-api-key',
endpoint: 'https://api.openai.com',
model: 'whisper-1',
language: 'en-US',
},
},
})
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ error: 'some error', text: undefined }),
})
globalThis.fetch = mockFetch as unknown as typeof fetch
const audioBlob = new Blob(['fake audio data'], { type: 'audio/webm' })
const formData = new FormData()
formData.append('audio', audioBlob, 'audio.webm')
const req = new Request('http://localhost/transcribe?userId=test', {
method: 'POST',
body: formData,
})
const res = await sttApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(500)
expect(json.error).toBe('STT API returned invalid response')
expect(json.details).toContain('Response missing text field')
globalThis.fetch = originalFetch
})
it('should successfully transcribe without API key', async () => {
const originalFetch = globalThis.fetch
mockGetSettings.mockReturnValue({
preferences: {
stt: {
enabled: true,
provider: 'external',
apiKey: '',
endpoint: 'https://api.openai.com',
model: 'whisper-1',
language: 'en-US',
},
},
})
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ text: 'Hello, world!' }),
})
globalThis.fetch = mockFetch as unknown as typeof fetch
const audioBlob = new Blob(['fake audio data'], { type: 'audio/webm' })
const formData = new FormData()
formData.append('audio', audioBlob, 'audio.webm')
const req = new Request('http://localhost/transcribe?userId=test', {
method: 'POST',
body: formData,
})
const res = await sttApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.text).toBe('Hello, world!')
expect(mockFetch).toHaveBeenCalledWith(
'https://api.openai.com/v1/audio/transcriptions',
expect.objectContaining({
headers: expect.not.objectContaining({
'Authorization': expect.any(String),
}),
})
)
globalThis.fetch = originalFetch
})
})
describe('GET /models', () => {
@@ -3,8 +3,6 @@ import { Loader2 } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { TTSSettings } from './TTSSettings'
import { STTSettings } from './STTSettings'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
@@ -105,14 +103,6 @@ export function GeneralSettings() {
</div>
)}
</div>
<div className="mt-6">
<TTSSettings />
</div>
<div className="mt-6">
<STTSettings />
</div>
</div>
)
}
@@ -20,7 +20,6 @@ const sttFormSchema = z.object({
apiKey: z.string(),
model: z.string(),
language: z.string(),
continuous: z.boolean(),
}).superRefine((data, ctx) => {
if (!data.enabled) return
@@ -32,13 +31,6 @@ const sttFormSchema = z.object({
message: 'Endpoint is required for external provider',
})
}
if (!data.apiKey || data.apiKey.trim().length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['apiKey'],
message: 'API key is required for external provider',
})
}
}
})
@@ -73,19 +65,18 @@ export function STTSettings() {
const watchEnabled = form.watch('enabled')
const watchProvider = form.watch('provider')
const watchLanguage = form.watch('language')
const watchContinuous = form.watch('continuous')
const watchEndpoint = form.watch('endpoint')
const watchApiKey = form.watch('apiKey')
const watchModel = form.watch('model')
const fetchModels = async (forceRefresh = false) => {
if (!watchEndpoint || !watchApiKey) return
if (!watchEndpoint) return
setIsLoadingModels(true)
try {
const response = await sttApi.getModels('default', forceRefresh)
setAvailableModels(response.models.length > 0 ? response.models : ['whisper-1'])
if (!watchModel && response.models.length > 0) {
setValue('model', response.models[0])
}
@@ -97,14 +88,14 @@ export function STTSettings() {
}
useEffect(() => {
if (watchProvider === 'external' && watchEndpoint && watchApiKey) {
if (watchProvider === 'external' && watchEndpoint) {
const timer = setTimeout(() => {
fetchModels()
}, 500)
return () => clearTimeout(timer)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [watchProvider, watchEndpoint, watchApiKey])
}, [watchProvider, watchEndpoint])
const handleTest = async () => {
if (isTesting || isRecording) {
@@ -157,9 +148,8 @@ export function STTSettings() {
apiKey: sttPrefs.apiKey ?? DEFAULT_STT_CONFIG.apiKey,
model: sttPrefs.model ?? 'whisper-1',
language: sttPrefs.language ?? DEFAULT_STT_CONFIG.language,
continuous: sttPrefs.continuous ?? DEFAULT_STT_CONFIG.continuous,
})
if (sttPrefs.availableModels && sttPrefs.availableModels.length > 0) {
setAvailableModels(sttPrefs.availableModels)
}
@@ -178,14 +168,14 @@ export function STTSettings() {
}, 800)
return () => clearTimeout(timer)
}, [watchEnabled, watchProvider, watchLanguage, watchContinuous, watchEndpoint, watchApiKey, watchModel, isDirty, isValid, getValues, updateSettings])
}, [watchEnabled, watchProvider, watchLanguage, watchEndpoint, watchApiKey, watchModel, isDirty, isValid, getValues, updateSettings])
const canTestBuiltin = watchEnabled && watchProvider === 'builtin' && isWebSpeechAvailable
const canTestExternal = watchEnabled && watchProvider === 'external' && watchEndpoint && watchApiKey
const canTestExternal = watchEnabled && watchProvider === 'external' && watchEndpoint
const canTest = canTestBuiltin || canTestExternal
return (
<div className="bg-card border-t pt-4">
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-lg font-semibold text-foreground">Speech-to-Text</h2>
<div className="flex items-center gap-2 text-sm">
@@ -308,7 +298,7 @@ export function STTSettings() {
</div>
</FormControl>
<FormDescription>
Your API key for the speech-to-text service
Your API key for the speech-to-text service (optional for some servers)
</FormDescription>
<FormMessage />
</FormItem>
@@ -325,7 +315,7 @@ export function STTSettings() {
<button
type="button"
onClick={() => fetchModels(true)}
disabled={isLoadingModels || !watchEndpoint || !watchApiKey}
disabled={isLoadingModels || !watchEndpoint}
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 disabled:opacity-50"
>
<RefreshCw className={`h-3 w-3 ${isLoadingModels ? 'animate-spin' : ''}`} />
@@ -383,28 +373,6 @@ export function STTSettings() {
</FormItem>
)}
/>
<FormField
control={form.control}
name="continuous"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Continuous Mode</FormLabel>
<FormDescription>
Keep listening after a pause (experimental)
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
disabled={!isWebSpeechAvailable}
/>
</FormControl>
</FormItem>
)}
/>
</>
)}
@@ -5,9 +5,10 @@ import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { AccountSettings } from '@/components/settings/AccountSettings'
import { VoiceSettings } from '@/components/settings/VoiceSettings'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch, User } from 'lucide-react'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key, GitBranch, User, Volume2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useSwipeBack } from '@/hooks/useMobile'
@@ -16,7 +17,7 @@ interface SettingsDialogProps {
onOpenChange: (open: boolean) => void
}
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account'
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice'
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const [mobileView, setMobileView] = useState<SettingsView>('menu')
@@ -42,6 +43,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const menuItems = [
{ id: 'account', icon: User, label: 'Account', description: 'Profile, passkeys, and sign out' },
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
{ id: 'voice', icon: Volume2, label: 'Voice', description: 'Text-to-speech and speech-to-text settings' },
{ id: 'git', icon: GitBranch, label: 'Git', description: 'Git identity and credentials for repositories' },
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
{ id: 'opencode', icon: Code, label: 'OpenCode Config', description: 'Manage OpenCode configurations, commands, and agents' },
@@ -69,13 +71,16 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
</div>
<Tabs defaultValue="account" className="w-full flex flex-col flex-1 min-h-0">
<div className="px-6 pt-6 pb-4 flex-shrink-0">
<TabsList className="grid w-full grid-cols-6 bg-card p-1">
<TabsList className="grid w-full grid-cols-7 bg-card p-1">
<TabsTrigger value="account" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Account
</TabsTrigger>
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
General
</TabsTrigger>
<TabsTrigger value="voice" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Voice
</TabsTrigger>
<TabsTrigger value="git" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Git
</TabsTrigger>
@@ -95,6 +100,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
<div className="px-6 pb-6">
<TabsContent value="account" className="mt-0"><AccountSettings /></TabsContent>
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
<TabsContent value="voice" className="mt-0"><VoiceSettings /></TabsContent>
<TabsContent value="git" className="mt-0"><GitSettings /></TabsContent>
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
<TabsContent value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
@@ -156,6 +162,7 @@ export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
{mobileView === 'account' && <AccountSettings />}
{mobileView === 'general' && <GeneralSettings />}
{mobileView === 'voice' && <VoiceSettings />}
{mobileView === 'git' && <GitSettings />}
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
{mobileView === 'opencode' && <OpenCodeConfigManager />}
@@ -239,7 +239,7 @@ export function TTSSettings() {
}
return (
<div className="bg-card border-t pt-4">
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-lg font-semibold text-foreground">Text-to-Speech</h2>
{/* Show auto-save status instead of save button */}
@@ -0,0 +1,11 @@
import { TTSSettings } from './TTSSettings'
import { STTSettings } from './STTSettings'
export function VoiceSettings() {
return (
<div className="space-y-6">
<TTSSettings />
<STTSettings />
</div>
)
}
+4 -5
View File
@@ -201,7 +201,7 @@ export function useSTT(userId = 'default') {
audioRecorder.current = new AudioRecorder()
setupAudioRecorder(audioRecorder.current)
}
try {
setIsProcessing(true)
await audioRecorder.current.start()
@@ -214,7 +214,6 @@ export function useSTT(userId = 'default') {
} else {
const options: SpeechRecognitionOptions = {
language: config.language,
continuous: config.continuous,
interimResults: true,
maxAlternatives: 1,
}
@@ -228,7 +227,7 @@ export function useSTT(userId = 'default') {
setError(err instanceof Error ? err.message : 'Failed to start recording')
}
}
}, [isSupported, isEnabled, isExternalProvider, config.language, config.continuous, setupAudioRecorder])
}, [isSupported, isEnabled, isExternalProvider, config.language, setupAudioRecorder])
const stopRecording = useCallback(() => {
if (isExternalProvider && audioRecorder.current) {
@@ -246,12 +245,12 @@ export function useSTT(userId = 'default') {
} else {
recognizer.current.abort()
}
if (abortControllerRef.current) {
abortControllerRef.current.abort()
abortControllerRef.current = null
}
setTranscript('')
setInterimTranscript('')
setIsRecording(false)
+160 -61
View File
@@ -1,36 +1,85 @@
export type AudioRecorderState = 'idle' | 'recording' | 'stopped' | 'error'
export interface AudioRecorderOptions {
mimeType?: string
audioBitsPerSecond?: number
sampleRate?: number
channelCount?: number
}
const DEFAULT_OPTIONS: AudioRecorderOptions = {
mimeType: 'audio/webm;codecs=opus',
audioBitsPerSecond: 128000,
sampleRate: 16000,
channelCount: 1,
}
function getSupportedMimeType(): string {
const mimeTypes = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/mp4',
]
function encodeWAV(audioBuffer: AudioBuffer): Blob {
const numberOfChannels = audioBuffer.numberOfChannels
const sampleRate = audioBuffer.sampleRate
const format = 1
const bitDepth = 16
for (const mimeType of mimeTypes) {
if (MediaRecorder.isTypeSupported(mimeType)) {
return mimeType
const channelData: Float32Array[] = []
for (let i = 0; i < numberOfChannels; i++) {
channelData.push(audioBuffer.getChannelData(i))
}
const interleaved = interleave(channelData)
const dataLength = interleaved.length * (bitDepth / 8)
const buffer = new ArrayBuffer(44 + dataLength)
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, format, true)
view.setUint16(22, numberOfChannels, true)
view.setUint32(24, sampleRate, true)
view.setUint32(28, sampleRate * numberOfChannels * (bitDepth / 8), true)
view.setUint16(32, numberOfChannels * (bitDepth / 8), true)
view.setUint16(34, bitDepth, true)
writeString(view, 36, 'data')
view.setUint32(40, dataLength, true)
floatTo16BitPCM(view, 44, interleaved)
return new Blob([view], { type: 'audio/wav' })
}
function interleave(channelData: Float32Array[]): Float32Array {
const length = channelData[0].length * channelData.length
const result = new Float32Array(length)
let offset = 0
for (let i = 0; i < channelData[0].length; i++) {
for (let channel = 0; channel < channelData.length; channel++) {
result[offset++] = channelData[channel][i]
}
}
return 'audio/webm'
return result
}
function writeString(view: DataView, offset: number, string: string): void {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i))
}
}
function floatTo16BitPCM(view: DataView, offset: number, input: Float32Array): void {
for (let i = 0; i < input.length; i++, offset += 2) {
const s = Math.max(-1, Math.min(1, input[i]))
view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true)
}
}
export class AudioRecorder {
private mediaRecorder: MediaRecorder | null = null
private audioChunks: Blob[] = []
private stream: MediaStream | null = null
private audioContext: AudioContext | null = null
private mediaStream: MediaStream | null = null
private source: MediaStreamAudioSourceNode | null = null
private processor: ScriptProcessorNode | null = null
private audioBuffer: Float32Array | null = null
private recordingLength: number = 0
private state: AudioRecorderState = 'idle'
private options: AudioRecorderOptions
private isAborted: boolean = false
@@ -49,7 +98,7 @@ export class AudioRecorder {
navigator.mediaDevices &&
typeof navigator.mediaDevices.getUserMedia === 'function' &&
typeof window !== 'undefined' &&
typeof window.MediaRecorder === 'function'
typeof window.AudioContext !== 'undefined'
)
}
@@ -102,10 +151,10 @@ export class AudioRecorder {
}
try {
this.audioChunks = []
this.isAborted = false
this.stream = await navigator.mediaDevices.getUserMedia({
this.recordingLength = 0
this.mediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
@@ -113,39 +162,37 @@ export class AudioRecorder {
},
})
const mimeType = getSupportedMimeType()
this.mediaRecorder = new MediaRecorder(this.stream, {
mimeType,
audioBitsPerSecond: this.options.audioBitsPerSecond,
this.audioContext = new AudioContext({
sampleRate: this.options.sampleRate,
})
this.mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
this.audioChunks.push(event.data)
this.source = this.audioContext.createMediaStreamSource(this.mediaStream)
const bufferSize = 4096
this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1)
this.audioBuffer = new Float32Array(0)
this.processor.onaudioprocess = (e) => {
if (this.audioBuffer) {
const inputData = e.inputBuffer.getChannelData(0)
const newLength = this.recordingLength + inputData.length
const newBuffer = new Float32Array(newLength)
newBuffer.set(this.audioBuffer, 0)
newBuffer.set(inputData, this.recordingLength)
this.audioBuffer = newBuffer
this.recordingLength = newLength
}
}
this.mediaRecorder.onstop = () => {
if (!this.isAborted) {
const mimeType = this.mediaRecorder?.mimeType || 'audio/webm'
const audioBlob = new Blob(this.audioChunks, { type: mimeType })
this.onDataAvailable?.(audioBlob)
this.setState('stopped')
}
this.cleanup()
}
this.source.connect(this.processor)
this.processor.connect(this.audioContext.destination)
this.mediaRecorder.onerror = () => {
this.setState('error')
this.onError?.('Recording error occurred')
this.cleanup()
}
this.mediaRecorder.start(100)
this.setState('recording')
} catch (error) {
this.setState('error')
this.cleanup()
if (error instanceof DOMException) {
if (error.name === 'NotAllowedError') {
this.onError?.('Microphone permission denied')
@@ -157,40 +204,92 @@ export class AudioRecorder {
} else {
this.onError?.('Failed to start recording')
}
throw error
}
}
stop(): void {
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
this.mediaRecorder.stop()
if (this.processor) {
this.processRecording()
}
this.cleanup()
this.setState('stopped')
}
abort(): void {
this.isAborted = true
this.audioChunks = []
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
this.mediaRecorder.stop()
}
this.audioBuffer = null
this.recordingLength = 0
this.cleanup()
this.setState('idle')
}
private cleanup(): void {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop())
this.stream = null
private processRecording(): void {
if (this.isAborted || !this.audioBuffer || this.recordingLength === 0) {
return
}
try {
const audioBuffer = this.audioContext!.createBuffer(
1,
this.recordingLength,
this.audioContext!.sampleRate
)
const channelData = new Float32Array(this.recordingLength)
channelData.set(this.audioBuffer!.subarray(0, this.recordingLength))
audioBuffer.copyToChannel(channelData, 0)
const wavBlob = encodeWAV(audioBuffer)
this.onDataAvailable?.(wavBlob)
} catch {
this.onError?.('Failed to process recording')
this.setState('error')
}
}
private cleanup(): void {
if (this.processor) {
this.processor.disconnect()
this.processor = null
}
if (this.source) {
this.source.disconnect()
this.source = null
}
if (this.audioContext && this.audioContext.state !== 'closed') {
this.audioContext.close()
this.audioContext = null
}
if (this.mediaStream) {
this.mediaStream.getTracks().forEach(track => track.stop())
this.mediaStream = null
}
this.mediaRecorder = null
}
getRecordingBlob(): Blob | null {
if (this.audioChunks.length === 0) {
if (!this.audioContext || !this.audioBuffer || this.recordingLength === 0) {
return null
}
try {
const audioBuffer = this.audioContext.createBuffer(
1,
this.recordingLength,
this.audioContext.sampleRate
)
const channelData = new Float32Array(this.recordingLength)
channelData.set(this.audioBuffer.subarray(0, this.recordingLength))
audioBuffer.copyToChannel(channelData, 0)
return encodeWAV(audioBuffer)
} catch {
return null
}
const mimeType = this.mediaRecorder?.mimeType || 'audio/webm'
return new Blob(this.audioChunks, { type: mimeType })
}
}
+7 -15
View File
@@ -1,7 +1,3 @@
/**
* Web Speech API recognizer - Browser-native STT without external dependencies
*/
export interface SpeechRecognitionResult {
transcript: string;
isFinal: boolean;
@@ -10,7 +6,6 @@ export interface SpeechRecognitionResult {
export interface SpeechRecognitionOptions {
language?: string;
continuous?: boolean;
interimResults?: boolean;
maxAlternatives?: number;
}
@@ -152,11 +147,9 @@ export class WebSpeechRecognizer {
this.recognition.onend = () => {
this.isListening = false;
if (this.state !== 'error') {
this.state = 'idle';
}
this.onEndCallbacks.forEach((cb) => cb());
};
}
@@ -191,10 +184,6 @@ export class WebSpeechRecognizer {
this.recognition.lang = options.language;
}
if (typeof options.continuous === 'boolean') {
this.recognition.continuous = options.continuous;
}
if (typeof options.interimResults === 'boolean') {
this.recognition.interimResults = options.interimResults;
}
@@ -220,6 +209,8 @@ export class WebSpeechRecognizer {
this.recognition.start();
} catch (error) {
this.state = 'error';
this.onStartCallbacks = this.onStartCallbacks.filter(cb => cb !== onStartOnce);
this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce);
reject(error || new Error('Failed to start recognition'));
}
});
@@ -241,12 +232,13 @@ export class WebSpeechRecognizer {
try {
this.recognition.abort();
} catch {
// Ignore abort errors
this.state = 'idle';
this.isListening = false;
}
this.state = 'idle';
this.isListening = false;
this.finalTranscript = '';
}
this.state = 'idle';
this.isListening = false;
this.finalTranscript = '';
}
isCurrentlyListening(): boolean {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opencode-manager",
"version": "0.8.21",
"version": "0.8.22",
"private": false,
"type": "module",
"packageManager": "pnpm@10.28.1",
-3
View File
@@ -27,7 +27,6 @@ export const STTConfigSchema = z.object({
apiKey: z.string(),
model: z.string(),
language: z.string().default('en-US'),
continuous: z.boolean().default(false),
availableModels: z.array(z.string()).optional(),
lastModelsFetch: z.number().optional(),
});
@@ -59,7 +58,6 @@ export type STTConfig = {
apiKey: string;
model: string;
language: string;
continuous: boolean;
availableModels?: string[];
lastModelsFetch?: number;
};
@@ -151,7 +149,6 @@ export const DEFAULT_STT_CONFIG: STTConfig = {
apiKey: "",
model: '',
language: 'en-US',
continuous: false,
availableModels: [],
lastModelsFetch: 0,
};