mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
Merge dev: STT feature, git date fixes, and session improvements (#82)
* fix session last active * Feature/sst (#81) * Use CSS field-sizing for textarea auto-height and abort STT recording on clear * Fix invalid date display in git commits * Use Unix timestamps for git log dates
This commit is contained in:
1 parent
21010956f7
commit
cb1714a4e0
17 files changed
+2475
-76
No files matched your search
@@ -0,0 +1,65 @@
|
||||
import axios from 'axios'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
export interface STTModelsResponse {
|
||||
models: string[]
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface STTStatusResponse {
|
||||
enabled: boolean
|
||||
configured: boolean
|
||||
provider: 'external' | 'builtin'
|
||||
model: string
|
||||
}
|
||||
|
||||
export interface STTTranscribeResponse {
|
||||
text: string
|
||||
}
|
||||
|
||||
export interface STTErrorResponse {
|
||||
error: string
|
||||
details?: string
|
||||
}
|
||||
|
||||
export const sttApi = {
|
||||
getModels: async (userId = 'default', forceRefresh = false): Promise<STTModelsResponse> => {
|
||||
const { data } = await axios.get(`${API_BASE_URL}/api/stt/models`, {
|
||||
params: { userId, ...(forceRefresh && { refresh: 'true' }) },
|
||||
})
|
||||
return data
|
||||
},
|
||||
|
||||
getStatus: async (userId = 'default'): Promise<STTStatusResponse> => {
|
||||
const { data } = await axios.get(`${API_BASE_URL}/api/stt/status`, {
|
||||
params: { userId },
|
||||
})
|
||||
return data
|
||||
},
|
||||
|
||||
transcribe: async (
|
||||
audioBlob: Blob,
|
||||
userId = 'default',
|
||||
signal?: AbortSignal
|
||||
): Promise<STTTranscribeResponse> => {
|
||||
const formData = new FormData()
|
||||
|
||||
const extension = audioBlob.type.includes('webm') ? 'webm' :
|
||||
audioBlob.type.includes('ogg') ? 'ogg' :
|
||||
audioBlob.type.includes('mp4') ? 'm4a' : 'webm'
|
||||
formData.append('audio', audioBlob, `recording.${extension}`)
|
||||
|
||||
const { data } = await axios.post<STTTranscribeResponse>(
|
||||
`${API_BASE_URL}/api/stt/transcribe`,
|
||||
formData,
|
||||
{
|
||||
params: { userId },
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
signal,
|
||||
}
|
||||
)
|
||||
return data
|
||||
},
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import {
|
||||
DEFAULT_TTS_CONFIG,
|
||||
DEFAULT_STT_CONFIG,
|
||||
DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
DEFAULT_USER_PREFERENCES,
|
||||
DEFAULT_LEADER_KEY,
|
||||
type TTSConfig,
|
||||
type STTConfig,
|
||||
type OpenCodeConfigContent,
|
||||
} from '@opencode-manager/shared'
|
||||
|
||||
export type { TTSConfig, OpenCodeConfigContent }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY }
|
||||
|
||||
export interface CustomCommand {
|
||||
name: string
|
||||
@@ -51,6 +53,7 @@ export interface UserPreferences {
|
||||
gitCredentials?: GitCredential[]
|
||||
gitIdentity?: GitIdentity
|
||||
tts?: TTSConfig
|
||||
stt?: STTConfig
|
||||
repoOrder?: number[]
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,13 @@ import { useFileSearch } from '@/hooks/useFileSearch'
|
||||
import { useModelSelection } from '@/hooks/useModelSelection'
|
||||
import { useVariants } from '@/hooks/useVariants'
|
||||
import { useSessionAgent } from '@/hooks/useSessionAgent'
|
||||
import { useSTT } from '@/hooks/useSTT'
|
||||
|
||||
import { useUserBash } from '@/stores/userBashStore'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { usePermissions } from '@/contexts/EventContext'
|
||||
import { ChevronDown, Upload, X } from 'lucide-react'
|
||||
import { ChevronDown, Upload, X, Mic } from 'lucide-react'
|
||||
|
||||
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
|
||||
import { SquareFill } from '@/components/ui/square-fill'
|
||||
@@ -91,6 +92,18 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
const [selectedAgent, setSelectedAgent] = useState<string | null>(null)
|
||||
const [localMode, setLocalMode] = useState<string | null>(null)
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
|
||||
const {
|
||||
isRecording,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
abortRecording,
|
||||
isSupported: sttSupported,
|
||||
isEnabled: sttEnabled,
|
||||
interimTranscript,
|
||||
transcript,
|
||||
clear: clearSTT,
|
||||
} = useSTT()
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
@@ -98,11 +111,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
useImperativeHandle(ref, () => ({
|
||||
setPromptValue: (value: string) => {
|
||||
setPrompt(value)
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
|
||||
textareaRef.current.focus()
|
||||
}
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
clearPrompt: () => {
|
||||
setPrompt('')
|
||||
@@ -110,15 +119,17 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
setSelectedAgent(null)
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
textareaRef.current.focus()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
triggerFileUpload: () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
}), [imageAttachments])
|
||||
}), [imageAttachments, clearSTT, isRecording, abortRecording])
|
||||
const sendPrompt = useSendPrompt(opcodeUrl, directory)
|
||||
const sendShell = useSendShell(opcodeUrl, directory)
|
||||
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
|
||||
@@ -188,9 +199,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
setSelectedAgent(null)
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
}
|
||||
clearSTT()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -204,9 +213,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
})
|
||||
setPrompt('')
|
||||
setIsBashMode(false)
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
}
|
||||
clearSTT()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -220,9 +227,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
if (command) {
|
||||
executeCommand(command, commandArgs?.trim() || '')
|
||||
setPrompt('')
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
}
|
||||
clearSTT()
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -242,9 +247,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
setSelectedAgent(null)
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
}
|
||||
clearSTT()
|
||||
}
|
||||
|
||||
const handleStop = () => {
|
||||
@@ -269,8 +272,6 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
textareaRef.current.setSelectionRange(cleanedTemplate.length, cleanedTemplate.length)
|
||||
textareaRef.current.style.height = 'auto'
|
||||
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
|
||||
}
|
||||
}, 0)
|
||||
} else {
|
||||
@@ -351,6 +352,28 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
setLocalMode(agent)
|
||||
}
|
||||
|
||||
const handleVoiceToggle = async () => {
|
||||
if (isRecording) {
|
||||
stopRecording()
|
||||
} else {
|
||||
await startRecording()
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.blur()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const textToUse = transcript || interimTranscript
|
||||
if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') {
|
||||
const trimmedTranscript = textToUse.trim()
|
||||
if (trimmedTranscript && (prompt === '' || prompt === 'Processing...' || prompt === 'Recording...')) {
|
||||
setPrompt(trimmedTranscript)
|
||||
textareaRef.current?.focus()
|
||||
}
|
||||
}
|
||||
}, [isRecording, interimTranscript, transcript, prompt])
|
||||
|
||||
const addImageAttachment = (file: File) => {
|
||||
const generateId = () => {
|
||||
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
||||
@@ -607,9 +630,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
setPrompt('')
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
}
|
||||
clearSTT()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') {
|
||||
e.preventDefault()
|
||||
if (hasVariants) {
|
||||
@@ -632,11 +653,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
}
|
||||
|
||||
setPrompt(value)
|
||||
|
||||
if (textareaRef.current) {
|
||||
textareaRef.current.style.height = 'auto'
|
||||
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
|
||||
}
|
||||
|
||||
if (isBashMode) {
|
||||
return
|
||||
@@ -744,7 +760,7 @@ return (
|
||||
disabled={disabled}
|
||||
onFocus={() => setIsFocused(true)}
|
||||
onBlur={() => setIsFocused(false)}
|
||||
className={`w-full bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg ${
|
||||
className={`w-full bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg [field-sizing:content] ${
|
||||
isBashMode
|
||||
? 'border-purple-500/50 bg-purple-500/5 focus:bg-purple-500/10'
|
||||
: isDragging ? 'border-blue-500/50 border-dashed bg-blue-500/5' : ''
|
||||
@@ -839,19 +855,49 @@ return (
|
||||
>
|
||||
<Upload className="w-5 h-5" />
|
||||
</button>
|
||||
{sttEnabled && sttSupported && (
|
||||
<button
|
||||
data-submit-prompt
|
||||
onClick={hasPendingPermissionForSession ? () => setShowDialog(true) : handleSubmit}
|
||||
disabled={hasPendingPermissionForSession ? false : ((!prompt.trim() && imageAttachments.length === 0) || disabled)}
|
||||
className={`px-4 md:px-5 py-1.5 md:py-2 rounded-lg text-sm font-medium transition-colors dark:border flex-shrink-0 min-w-[52px] ${
|
||||
hasPendingPermissionForSession
|
||||
? 'bg-orange-500 hover:bg-orange-600 border-orange-400 text-primary-foreground ring-orange-500/20'
|
||||
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground border-white/30'
|
||||
}`}
|
||||
title={hasPendingPermissionForSession ? 'View pending permission' : (hasActiveStream ? 'Queue message' : 'Send')}
|
||||
>
|
||||
<span className="whitespace-nowrap">{hasPendingPermissionForSession ? 'View' : (hasActiveStream ? 'Queue' : 'Send')}</span>
|
||||
type="button"
|
||||
onClick={handleVoiceToggle}
|
||||
disabled={disabled}
|
||||
className={`hidden md:flex p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border items-center justify-center ${
|
||||
isRecording
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-red-500/60 animate-pulse'
|
||||
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
|
||||
}`}
|
||||
title={isRecording ? 'Stop recording' : 'Voice input'}
|
||||
>
|
||||
{isRecording ? <SquareFill className="w-5 h-5" /> : <Mic className="w-5 h-5" />}
|
||||
</button>
|
||||
)}
|
||||
{isMobile && !prompt.trim() && imageAttachments.length === 0 && sttEnabled && sttSupported && !hasPendingPermissionForSession ? (
|
||||
<button
|
||||
onClick={handleVoiceToggle}
|
||||
disabled={disabled}
|
||||
className={`px-4 py-2 rounded-lg transition-all duration-200 active:scale-95 flex items-center justify-center min-w-[52px] ${
|
||||
isRecording
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-2 border-red-500/60 shadow-lg shadow-red-500/30 animate-pulse'
|
||||
: 'bg-primary hover:bg-primary/90 text-primary-foreground border border-white/30'
|
||||
}`}
|
||||
title={isRecording ? 'Stop recording' : 'Voice input'}
|
||||
>
|
||||
{isRecording ? <SquareFill className="w-5 h-5" /> : <Mic className="w-5 h-5" />}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
data-submit-prompt
|
||||
onClick={hasPendingPermissionForSession ? () => setShowDialog(true) : handleSubmit}
|
||||
disabled={hasPendingPermissionForSession ? false : ((!prompt.trim() && imageAttachments.length === 0) || disabled)}
|
||||
className={`px-4 md:px-5 py-1.5 md:py-2 rounded-lg text-sm font-medium transition-colors dark:border flex-shrink-0 min-w-[52px] ${
|
||||
hasPendingPermissionForSession
|
||||
? 'bg-orange-500 hover:bg-orange-600 border-orange-400 text-primary-foreground ring-orange-500/20'
|
||||
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground border-white/30'
|
||||
}`}
|
||||
title={hasPendingPermissionForSession ? 'View pending permission' : (hasActiveStream ? 'Queue message' : 'Send')}
|
||||
>
|
||||
<span className="whitespace-nowrap">{hasPendingPermissionForSession ? 'View' : (hasActiveStream ? 'Queue' : 'Send')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { X, Mic } from 'lucide-react'
|
||||
import { SquareFill } from '@/components/ui/square-fill'
|
||||
|
||||
interface RecordingOverlayProps {
|
||||
interimTranscript: string
|
||||
onStop: () => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
export function RecordingOverlay({
|
||||
interimTranscript,
|
||||
onStop,
|
||||
onCancel
|
||||
}: RecordingOverlayProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 py-2">
|
||||
<div className="flex items-center justify-center h-12">
|
||||
<div className="flex items-center gap-2 text-red-500">
|
||||
<Mic className="w-5 h-5 animate-pulse" />
|
||||
<span className="text-sm font-medium">Recording...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-[40px] px-3 py-2 bg-muted/50 rounded-lg">
|
||||
{interimTranscript ? (
|
||||
<p className="text-sm text-foreground">{interimTranscript}</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground italic">Listening...</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
<span>Cancel</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
className="flex items-center gap-2 px-4 py-1.5 rounded-lg text-sm font-medium bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-white border border-red-500/60 shadow-md shadow-red-500/30 transition-all duration-200 active:scale-95"
|
||||
>
|
||||
<SquareFill className="w-3 h-3" />
|
||||
<span>Done</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ 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()
|
||||
@@ -108,6 +109,10 @@ export function GeneralSettings() {
|
||||
<div className="mt-6">
|
||||
<TTSSettings />
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<STTSettings />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useSTT } from '@/hooks/useSTT'
|
||||
import { isWebRecognitionSupported, getAvailableLanguages } from '@/lib/webSpeechRecognizer'
|
||||
import { sttApi } from '@/api/stt'
|
||||
import { Mic, Loader2, XCircle, CheckCircle2, RefreshCw, Eye, EyeOff } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { SquareFill } from '@/components/ui/square-fill'
|
||||
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
|
||||
import { Combobox } from '@/components/ui/combobox'
|
||||
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
|
||||
|
||||
const sttFormSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']),
|
||||
endpoint: z.string(),
|
||||
apiKey: z.string(),
|
||||
model: z.string(),
|
||||
language: z.string(),
|
||||
continuous: z.boolean(),
|
||||
}).superRefine((data, ctx) => {
|
||||
if (!data.enabled) return
|
||||
|
||||
if (data.provider === 'external') {
|
||||
if (!data.endpoint || data.endpoint.trim().length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['endpoint'],
|
||||
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',
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
type STTFormValues = z.infer<typeof sttFormSchema>
|
||||
|
||||
export function STTSettings() {
|
||||
const { preferences, updateSettings } = useSettings()
|
||||
const { startRecording, stopRecording, abortRecording, isRecording, isProcessing, transcript, interimTranscript, error: sttError, isExternalProvider } = useSTT()
|
||||
|
||||
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
|
||||
const [isTesting, setIsTesting] = useState(false)
|
||||
const [testTranscript, setTestTranscript] = useState('')
|
||||
const [testResult, setTestResult] = useState<'idle' | 'success' | 'failed'>('idle')
|
||||
const [showApiKey, setShowApiKey] = useState(false)
|
||||
const [availableModels, setAvailableModels] = useState<string[]>(['whisper-1'])
|
||||
const [isLoadingModels, setIsLoadingModels] = useState(false)
|
||||
|
||||
const isWebSpeechAvailable = isWebRecognitionSupported()
|
||||
|
||||
const form = useForm<STTFormValues>({
|
||||
resolver: zodResolver(sttFormSchema),
|
||||
defaultValues: {
|
||||
...DEFAULT_STT_CONFIG,
|
||||
model: DEFAULT_STT_CONFIG.model || 'whisper-1',
|
||||
},
|
||||
})
|
||||
|
||||
const { reset, formState: { isDirty, isValid }, getValues, setValue } = form
|
||||
|
||||
const availableLanguages = getAvailableLanguages()
|
||||
|
||||
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
|
||||
|
||||
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])
|
||||
}
|
||||
} catch {
|
||||
setAvailableModels(['whisper-1'])
|
||||
} finally {
|
||||
setIsLoadingModels(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (watchProvider === 'external' && watchEndpoint && watchApiKey) {
|
||||
const timer = setTimeout(() => {
|
||||
fetchModels()
|
||||
}, 500)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [watchProvider, watchEndpoint, watchApiKey])
|
||||
|
||||
const handleTest = async () => {
|
||||
if (isTesting || isRecording) {
|
||||
if (isExternalProvider) {
|
||||
stopRecording()
|
||||
} else {
|
||||
abortRecording()
|
||||
setIsTesting(false)
|
||||
if (testTranscript) {
|
||||
setTestResult('success')
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
setTestTranscript('')
|
||||
setTestResult('idle')
|
||||
setIsTesting(true)
|
||||
await startRecording()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (isTesting && !isRecording && !isProcessing) {
|
||||
if (transcript) {
|
||||
setTestTranscript(transcript)
|
||||
setTestResult('success')
|
||||
setTimeout(() => {
|
||||
setIsTesting(false)
|
||||
}, 1000)
|
||||
} else if (sttError) {
|
||||
setTestResult('failed')
|
||||
setIsTesting(false)
|
||||
}
|
||||
}
|
||||
}, [isTesting, isRecording, isProcessing, transcript, sttError])
|
||||
|
||||
useEffect(() => {
|
||||
if (isTesting && interimTranscript && interimTranscript !== 'Processing...' && interimTranscript !== 'Recording...') {
|
||||
setTestTranscript(interimTranscript)
|
||||
}
|
||||
}, [isTesting, interimTranscript])
|
||||
|
||||
useEffect(() => {
|
||||
if (preferences?.stt) {
|
||||
const sttPrefs = preferences.stt as typeof preferences.stt & { model?: string; availableModels?: string[] }
|
||||
reset({
|
||||
enabled: sttPrefs.enabled ?? DEFAULT_STT_CONFIG.enabled,
|
||||
provider: sttPrefs.provider ?? DEFAULT_STT_CONFIG.provider,
|
||||
endpoint: sttPrefs.endpoint ?? DEFAULT_STT_CONFIG.endpoint,
|
||||
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)
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [preferences?.stt])
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
if (isDirty && isValid) {
|
||||
const formData = getValues()
|
||||
updateSettings({ stt: formData })
|
||||
setSaveStatus('saved')
|
||||
setTimeout(() => setSaveStatus('idle'), 1500)
|
||||
}
|
||||
}, 800)
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}, [watchEnabled, watchProvider, watchLanguage, watchContinuous, watchEndpoint, watchApiKey, watchModel, isDirty, isValid, getValues, updateSettings])
|
||||
|
||||
const canTestBuiltin = watchEnabled && watchProvider === 'builtin' && isWebSpeechAvailable
|
||||
const canTestExternal = watchEnabled && watchProvider === 'external' && watchEndpoint && watchApiKey
|
||||
const canTest = canTestBuiltin || canTestExternal
|
||||
|
||||
return (
|
||||
<div className="bg-card border-t pt-4">
|
||||
<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">
|
||||
{saveStatus === 'saved' && (
|
||||
<>
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span className="text-green-600">Saved</span>
|
||||
</>
|
||||
)}
|
||||
{saveStatus === 'idle' && isDirty && isValid && (
|
||||
<span className="text-amber-600">Unsaved changes</span>
|
||||
)}
|
||||
{saveStatus === 'idle' && !isDirty && (
|
||||
<span className="text-muted-foreground">All changes saved</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Form {...form}>
|
||||
<form className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
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">Enable STT</FormLabel>
|
||||
<FormDescription>
|
||||
Allow speech-to-text input for voice messages
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
|
||||
|
||||
{watchEnabled && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="provider"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Provider</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
options={[
|
||||
...(isWebSpeechAvailable ? [{ value: 'builtin', label: 'Built-in Browser' }] : []),
|
||||
{ value: 'external', label: 'External API (OpenAI Whisper)' },
|
||||
]}
|
||||
placeholder="Select provider..."
|
||||
allowCustomValue={false}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{watchProvider === 'builtin'
|
||||
? "Uses browser's built-in speech recognition (free, requires Chrome/Safari/Edge)"
|
||||
: "Uses OpenAI Whisper API or compatible endpoint (requires API key)"
|
||||
}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{watchProvider === 'external' && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="endpoint"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>API Endpoint</FormLabel>
|
||||
<FormControl>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="https://api.openai.com"
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Base URL for the Whisper-compatible API (e.g., OpenAI, local Whisper server)
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="apiKey"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>API Key</FormLabel>
|
||||
<FormControl>
|
||||
<div className="relative">
|
||||
<input
|
||||
type={showApiKey ? 'text' : 'password'}
|
||||
placeholder="sk-..."
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
{...field}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowApiKey(!showApiKey)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Your API key for the speech-to-text service
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="model"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<div className="flex items-center justify-between">
|
||||
<FormLabel>Model</FormLabel>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fetchModels(true)}
|
||||
disabled={isLoadingModels || !watchEndpoint || !watchApiKey}
|
||||
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' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Combobox
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
options={availableModels.map(model => ({
|
||||
value: model,
|
||||
label: model,
|
||||
}))}
|
||||
placeholder="Select model..."
|
||||
disabled={isLoadingModels}
|
||||
allowCustomValue={true}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
The speech-to-text model to use (e.g., whisper-1)
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{watchProvider === 'builtin' && (
|
||||
<>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="language"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Language</FormLabel>
|
||||
<FormControl>
|
||||
<Combobox
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
options={availableLanguages.map(lang => ({
|
||||
value: lang,
|
||||
label: lang.replace('-', ' - ')
|
||||
}))}
|
||||
placeholder="Select language..."
|
||||
disabled={!isWebSpeechAvailable}
|
||||
allowCustomValue={false}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Select the language for speech recognition
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</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>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{sttError && (
|
||||
<div className="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-4">
|
||||
<div className="text-sm text-amber-800 dark:text-amber-200 flex items-start gap-2">
|
||||
<XCircle className="h-4 w-4 mt-0.5 shrink-0" />
|
||||
<div>{sttError}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
|
||||
<div className="space-y-0.5 flex-1 mr-4">
|
||||
<div className="text-base font-medium">Test STT</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{watchProvider === 'external'
|
||||
? 'Record audio, then click Stop to transcribe'
|
||||
: 'Verify your speech recognition is working'
|
||||
}
|
||||
</p>
|
||||
{(isTesting || isProcessing) && (
|
||||
<div className="mt-2 p-2 bg-muted rounded max-h-24 overflow-y-auto">
|
||||
<p className="text-sm">{testTranscript || (isProcessing ? 'Processing...' : 'Listening...')}</p>
|
||||
{isRecording && (
|
||||
<div className="flex items-center gap-1 mt-1">
|
||||
<Loader2 className="h-3 w-3 animate-spin text-primary" />
|
||||
<span className="text-xs text-muted-foreground">Recording...</span>
|
||||
</div>
|
||||
)}
|
||||
{isProcessing && !isRecording && (
|
||||
<div className="flex items-center gap-1 mt-1">
|
||||
<Loader2 className="h-3 w-3 animate-spin text-primary" />
|
||||
<span className="text-xs text-muted-foreground">Transcribing...</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!isTesting && !isProcessing && testResult === 'success' && testTranscript && (
|
||||
<div className="mt-2 p-2 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded max-h-24 overflow-y-auto">
|
||||
<div className="flex items-center gap-1 mb-1">
|
||||
<CheckCircle2 className="h-3 w-3 text-green-600 dark:text-green-400" />
|
||||
<span className="text-xs font-medium text-green-700 dark:text-green-300">Test successful</span>
|
||||
</div>
|
||||
<p className="text-sm text-green-800 dark:text-green-200">{testTranscript}</p>
|
||||
</div>
|
||||
)}
|
||||
{!isTesting && !isProcessing && testResult === 'failed' && (
|
||||
<div className="mt-2 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded">
|
||||
<div className="flex items-center gap-1">
|
||||
<XCircle className="h-3 w-3 text-red-600 dark:text-red-400" />
|
||||
<span className="text-xs font-medium text-red-700 dark:text-red-300">Test failed - {sttError || 'no speech detected'}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleTest}
|
||||
disabled={!canTest && !isRecording && !isProcessing}
|
||||
className={`px-4 py-2 rounded-lg transition-all duration-200 active:scale-95 flex items-center gap-2 ${
|
||||
!canTest && !isRecording && !isProcessing
|
||||
? 'bg-muted text-muted-foreground cursor-not-allowed'
|
||||
: isRecording
|
||||
? 'bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border-2 border-red-500/60 shadow-lg shadow-red-500/30'
|
||||
: isProcessing
|
||||
? 'bg-muted text-muted-foreground cursor-wait'
|
||||
: 'bg-primary hover:bg-primary/90 text-primary-foreground'
|
||||
}`}
|
||||
>
|
||||
{isRecording ? (
|
||||
<>
|
||||
<SquareFill className="w-4 h-4" />
|
||||
Stop
|
||||
</>
|
||||
) : isProcessing ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Processing
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Mic className="w-4 h-4" />
|
||||
Test
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -8,8 +8,9 @@ interface CommitsTabProps {
|
||||
onSelectCommit?: (hash: string) => void
|
||||
}
|
||||
|
||||
function formatRelativeTime(dateString: string): string {
|
||||
const date = new Date(dateString)
|
||||
function formatRelativeTime(timestamp: string): string {
|
||||
const date = new Date(parseInt(timestamp, 10) * 1000)
|
||||
|
||||
const now = new Date()
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
const diffSeconds = Math.floor(diffMs / 1000)
|
||||
|
||||
@@ -29,17 +29,26 @@ export function Combobox({
|
||||
allowCustomValue = true,
|
||||
}: ComboboxProps) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [inputValue, setInputValue] = useState(value)
|
||||
const [inputValue, setInputValue] = useState(() => {
|
||||
const selectedOption = options.find(o => o.value === value)
|
||||
return selectedOption?.label || value
|
||||
})
|
||||
const [selectedIndex, setSelectedIndex] = useState(0)
|
||||
const [isUserTyping, setIsUserTyping] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setInputValue(value)
|
||||
}, [value])
|
||||
if (!isUserTyping) {
|
||||
const selectedOption = options.find(o => o.value === value)
|
||||
setInputValue(selectedOption?.label || value)
|
||||
}
|
||||
}, [value, options, isUserTyping])
|
||||
|
||||
const filteredOptions = options.filter(option =>
|
||||
const isExactMatch = options.some(o => o.value === value || o.label === inputValue)
|
||||
|
||||
const filteredOptions = (isExactMatch && !isUserTyping) ? options : options.filter(option =>
|
||||
option.value.toLowerCase().includes(inputValue.toLowerCase()) ||
|
||||
option.label.toLowerCase().includes(inputValue.toLowerCase()) ||
|
||||
(option.description?.toLowerCase().includes(inputValue.toLowerCase()))
|
||||
@@ -87,11 +96,13 @@ export function Combobox({
|
||||
}, [selectedIndex, isOpen])
|
||||
|
||||
const handleSelect = useCallback((optionValue: string) => {
|
||||
setInputValue(optionValue)
|
||||
const selectedOption = options.find(o => o.value === optionValue)
|
||||
setInputValue(selectedOption?.label || optionValue)
|
||||
onChange(optionValue)
|
||||
setIsOpen(false)
|
||||
setIsUserTyping(false)
|
||||
inputRef.current?.blur()
|
||||
}, [onChange])
|
||||
}, [onChange, options])
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (!isOpen) {
|
||||
@@ -137,6 +148,7 @@ export function Combobox({
|
||||
const newValue = e.target.value
|
||||
setInputValue(newValue)
|
||||
setIsOpen(true)
|
||||
setIsUserTyping(true)
|
||||
if (allowCustomValue) {
|
||||
onChange(newValue)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
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 { AudioRecorder } from '@/lib/audioRecorder'
|
||||
import { sttApi } from '@/api/stt'
|
||||
import { DEFAULT_STT_CONFIG } from '@/api/types/settings'
|
||||
|
||||
export function useSTT(userId = 'default') {
|
||||
const { preferences } = useSettings(userId)
|
||||
const [isRecording, setIsRecording] = useState(false)
|
||||
const [isProcessing, setIsProcessing] = useState(false)
|
||||
const [isError, setIsError] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [transcript, setTranscript] = useState('')
|
||||
const [interimTranscript, setInterimTranscript] = useState('')
|
||||
const [state, setState] = useState<RecognitionState>('idle')
|
||||
|
||||
const recognizer = useRef(getWebSpeechRecognizer())
|
||||
const audioRecorder = useRef<AudioRecorder | null>(null)
|
||||
const hasShownPermissionError = useRef(false)
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
const userIdRef = useRef(userId)
|
||||
|
||||
useEffect(() => {
|
||||
userIdRef.current = userId
|
||||
}, [userId])
|
||||
|
||||
const isEnabled = preferences?.stt?.enabled ?? false
|
||||
const config = preferences?.stt ?? DEFAULT_STT_CONFIG
|
||||
const isExternalProvider = config.provider === 'external'
|
||||
|
||||
const isSupported = isExternalProvider
|
||||
? true
|
||||
: isWebRecognitionSupported()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEnabled || isExternalProvider) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!isWebRecognitionSupported()) {
|
||||
return
|
||||
}
|
||||
|
||||
const rec = recognizer.current
|
||||
|
||||
rec.onResult((result: SpeechRecognitionResult) => {
|
||||
setIsProcessing(false)
|
||||
setTranscript((prev) => prev + ' ' + result.transcript)
|
||||
setIsRecording(false)
|
||||
})
|
||||
|
||||
rec.onInterimResult((interim: string) => {
|
||||
setInterimTranscript(interim.trim())
|
||||
})
|
||||
|
||||
rec.onError((errorMessage: string) => {
|
||||
setIsProcessing(false)
|
||||
setIsRecording(false)
|
||||
setIsError(true)
|
||||
setError(errorMessage)
|
||||
|
||||
if (!hasShownPermissionError.current && errorMessage.includes('denied')) {
|
||||
hasShownPermissionError.current = true
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
}, 3000)
|
||||
})
|
||||
|
||||
rec.onEnd(() => {
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
})
|
||||
|
||||
rec.onStart(() => {
|
||||
setIsRecording(true)
|
||||
setState('listening')
|
||||
setInterimTranscript('')
|
||||
})
|
||||
|
||||
return () => {
|
||||
rec.clearCallbacks()
|
||||
}
|
||||
}, [isEnabled, isExternalProvider])
|
||||
|
||||
const setupAudioRecorder = useCallback((recorder: AudioRecorder) => {
|
||||
recorder.setOnStateChange((recState) => {
|
||||
if (recState === 'recording') {
|
||||
setIsRecording(true)
|
||||
setState('listening')
|
||||
setInterimTranscript('Recording...')
|
||||
} else if (recState === 'stopped') {
|
||||
setIsRecording(false)
|
||||
} else if (recState === 'error') {
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
} else if (recState === 'idle') {
|
||||
setState('idle')
|
||||
}
|
||||
})
|
||||
|
||||
recorder.setOnError((errorMessage) => {
|
||||
setIsProcessing(false)
|
||||
setIsRecording(false)
|
||||
setIsError(true)
|
||||
setError(errorMessage)
|
||||
|
||||
setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
}, 3000)
|
||||
})
|
||||
|
||||
recorder.setOnDataAvailable(async (blob) => {
|
||||
setInterimTranscript('Processing...')
|
||||
setIsProcessing(true)
|
||||
|
||||
try {
|
||||
abortControllerRef.current = new AbortController()
|
||||
const result = await sttApi.transcribe(
|
||||
blob,
|
||||
userIdRef.current || 'default',
|
||||
abortControllerRef.current.signal
|
||||
)
|
||||
|
||||
setTranscript((prev) => {
|
||||
const prevTrimmed = prev.trim()
|
||||
const newText = result.text.trim()
|
||||
return prevTrimmed ? `${prevTrimmed} ${newText}` : newText
|
||||
})
|
||||
setInterimTranscript('')
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === 'CanceledError') {
|
||||
return
|
||||
}
|
||||
|
||||
setIsError(true)
|
||||
const errorMessage = err instanceof Error ? err.message : 'Transcription failed'
|
||||
setError(errorMessage)
|
||||
|
||||
setTimeout(() => {
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
}, 3000)
|
||||
} finally {
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
abortControllerRef.current = null
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isEnabled || !isExternalProvider) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!audioRecorder.current) {
|
||||
audioRecorder.current = new AudioRecorder()
|
||||
}
|
||||
|
||||
setupAudioRecorder(audioRecorder.current)
|
||||
|
||||
return () => {
|
||||
if (audioRecorder.current) {
|
||||
audioRecorder.current.abort()
|
||||
}
|
||||
}
|
||||
}, [isEnabled, isExternalProvider, setupAudioRecorder])
|
||||
|
||||
const startRecording = useCallback(async () => {
|
||||
if (!isSupported) {
|
||||
setError('Speech recognition is not supported in this browser')
|
||||
setIsError(true)
|
||||
return
|
||||
}
|
||||
|
||||
if (!isEnabled) {
|
||||
setError('Speech recognition is not enabled')
|
||||
setIsError(true)
|
||||
return
|
||||
}
|
||||
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
hasShownPermissionError.current = false
|
||||
|
||||
if (isExternalProvider) {
|
||||
if (!audioRecorder.current) {
|
||||
audioRecorder.current = new AudioRecorder()
|
||||
setupAudioRecorder(audioRecorder.current)
|
||||
}
|
||||
|
||||
try {
|
||||
setIsProcessing(true)
|
||||
await audioRecorder.current.start()
|
||||
setIsProcessing(false)
|
||||
} catch (err) {
|
||||
setIsProcessing(false)
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
}
|
||||
} else {
|
||||
const options: SpeechRecognitionOptions = {
|
||||
language: config.language,
|
||||
continuous: config.continuous,
|
||||
interimResults: true,
|
||||
maxAlternatives: 1,
|
||||
}
|
||||
|
||||
try {
|
||||
setIsProcessing(true)
|
||||
await recognizer.current.start(options)
|
||||
} catch (err) {
|
||||
setIsProcessing(false)
|
||||
setIsError(true)
|
||||
setError(err instanceof Error ? err.message : 'Failed to start recording')
|
||||
}
|
||||
}
|
||||
}, [isSupported, isEnabled, isExternalProvider, config.language, config.continuous, setupAudioRecorder])
|
||||
|
||||
const stopRecording = useCallback(() => {
|
||||
if (isExternalProvider && audioRecorder.current) {
|
||||
audioRecorder.current.stop()
|
||||
setIsProcessing(true)
|
||||
} else {
|
||||
recognizer.current.stop()
|
||||
setIsProcessing(true)
|
||||
}
|
||||
}, [isExternalProvider])
|
||||
|
||||
const abortRecording = useCallback(() => {
|
||||
if (isExternalProvider && audioRecorder.current) {
|
||||
audioRecorder.current.abort()
|
||||
} else {
|
||||
recognizer.current.abort()
|
||||
}
|
||||
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort()
|
||||
abortControllerRef.current = null
|
||||
}
|
||||
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
}, [isExternalProvider])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
setIsError(false)
|
||||
setError(null)
|
||||
setIsRecording(false)
|
||||
setIsProcessing(false)
|
||||
setState('idle')
|
||||
}, [])
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setTranscript('')
|
||||
setInterimTranscript('')
|
||||
}, [])
|
||||
|
||||
return {
|
||||
isRecording,
|
||||
isProcessing,
|
||||
isError,
|
||||
error,
|
||||
transcript,
|
||||
interimTranscript,
|
||||
state,
|
||||
isSupported,
|
||||
isEnabled,
|
||||
isExternalProvider,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
abortRecording,
|
||||
reset,
|
||||
clear,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
export type AudioRecorderState = 'idle' | 'recording' | 'stopped' | 'error'
|
||||
|
||||
export interface AudioRecorderOptions {
|
||||
mimeType?: string
|
||||
audioBitsPerSecond?: number
|
||||
}
|
||||
|
||||
const DEFAULT_OPTIONS: AudioRecorderOptions = {
|
||||
mimeType: 'audio/webm;codecs=opus',
|
||||
audioBitsPerSecond: 128000,
|
||||
}
|
||||
|
||||
function getSupportedMimeType(): string {
|
||||
const mimeTypes = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/mp4',
|
||||
]
|
||||
|
||||
for (const mimeType of mimeTypes) {
|
||||
if (MediaRecorder.isTypeSupported(mimeType)) {
|
||||
return mimeType
|
||||
}
|
||||
}
|
||||
|
||||
return 'audio/webm'
|
||||
}
|
||||
|
||||
export class AudioRecorder {
|
||||
private mediaRecorder: MediaRecorder | null = null
|
||||
private audioChunks: Blob[] = []
|
||||
private stream: MediaStream | null = null
|
||||
private state: AudioRecorderState = 'idle'
|
||||
private options: AudioRecorderOptions
|
||||
private isAborted: boolean = false
|
||||
|
||||
private onStateChange?: (state: AudioRecorderState) => void
|
||||
private onError?: (error: string) => void
|
||||
private onDataAvailable?: (blob: Blob) => void
|
||||
|
||||
constructor(options: AudioRecorderOptions = {}) {
|
||||
this.options = { ...DEFAULT_OPTIONS, ...options }
|
||||
}
|
||||
|
||||
static isSupported(): boolean {
|
||||
return !!(
|
||||
typeof navigator !== 'undefined' &&
|
||||
navigator.mediaDevices &&
|
||||
typeof navigator.mediaDevices.getUserMedia === 'function' &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.MediaRecorder === 'function'
|
||||
)
|
||||
}
|
||||
|
||||
getState(): AudioRecorderState {
|
||||
return this.state
|
||||
}
|
||||
|
||||
setOnStateChange(callback: (state: AudioRecorderState) => void): void {
|
||||
this.onStateChange = callback
|
||||
}
|
||||
|
||||
setOnError(callback: (error: string) => void): void {
|
||||
this.onError = callback
|
||||
}
|
||||
|
||||
setOnDataAvailable(callback: (blob: Blob) => void): void {
|
||||
this.onDataAvailable = callback
|
||||
}
|
||||
|
||||
private setState(newState: AudioRecorderState): void {
|
||||
this.state = newState
|
||||
this.onStateChange?.(newState)
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (!AudioRecorder.isSupported()) {
|
||||
this.setState('error')
|
||||
this.onError?.('Audio recording is not supported in this browser')
|
||||
throw new Error('Audio recording is not supported in this browser')
|
||||
}
|
||||
|
||||
try {
|
||||
this.audioChunks = []
|
||||
this.isAborted = false
|
||||
|
||||
this.stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
},
|
||||
})
|
||||
|
||||
const mimeType = getSupportedMimeType()
|
||||
this.mediaRecorder = new MediaRecorder(this.stream, {
|
||||
mimeType,
|
||||
audioBitsPerSecond: this.options.audioBitsPerSecond,
|
||||
})
|
||||
|
||||
this.mediaRecorder.ondataavailable = (event) => {
|
||||
if (event.data.size > 0) {
|
||||
this.audioChunks.push(event.data)
|
||||
}
|
||||
}
|
||||
|
||||
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.mediaRecorder.onerror = () => {
|
||||
this.setState('error')
|
||||
this.onError?.('Recording error occurred')
|
||||
this.cleanup()
|
||||
}
|
||||
|
||||
this.mediaRecorder.start(100)
|
||||
this.setState('recording')
|
||||
} catch (error) {
|
||||
this.setState('error')
|
||||
|
||||
if (error instanceof DOMException) {
|
||||
if (error.name === 'NotAllowedError') {
|
||||
this.onError?.('Microphone permission denied')
|
||||
} else if (error.name === 'NotFoundError') {
|
||||
this.onError?.('No microphone found')
|
||||
} else {
|
||||
this.onError?.(`Microphone error: ${error.message}`)
|
||||
}
|
||||
} else {
|
||||
this.onError?.('Failed to start recording')
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
|
||||
this.mediaRecorder.stop()
|
||||
}
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
this.isAborted = true
|
||||
this.audioChunks = []
|
||||
if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
|
||||
this.mediaRecorder.stop()
|
||||
}
|
||||
this.setState('idle')
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
if (this.stream) {
|
||||
this.stream.getTracks().forEach(track => track.stop())
|
||||
this.stream = null
|
||||
}
|
||||
this.mediaRecorder = null
|
||||
}
|
||||
|
||||
getRecordingBlob(): Blob | null {
|
||||
if (this.audioChunks.length === 0) {
|
||||
return null
|
||||
}
|
||||
const mimeType = this.mediaRecorder?.mimeType || 'audio/webm'
|
||||
return new Blob(this.audioChunks, { type: mimeType })
|
||||
}
|
||||
}
|
||||
|
||||
let recorderInstance: AudioRecorder | null = null
|
||||
|
||||
export function getAudioRecorder(): AudioRecorder {
|
||||
if (!recorderInstance) {
|
||||
recorderInstance = new AudioRecorder()
|
||||
}
|
||||
return recorderInstance
|
||||
}
|
||||
|
||||
export function isAudioRecordingSupported(): boolean {
|
||||
return AudioRecorder.isSupported()
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* Web Speech API recognizer - Browser-native STT without external dependencies
|
||||
*/
|
||||
|
||||
export interface SpeechRecognitionResult {
|
||||
transcript: string;
|
||||
isFinal: boolean;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
export interface SpeechRecognitionOptions {
|
||||
language?: string;
|
||||
continuous?: boolean;
|
||||
interimResults?: boolean;
|
||||
maxAlternatives?: number;
|
||||
}
|
||||
|
||||
export type RecognitionState = 'idle' | 'listening' | 'processing' | 'error';
|
||||
|
||||
interface SpeechRecognition extends EventTarget {
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
lang: string;
|
||||
maxAlternatives: number;
|
||||
onstart: (event: Event) => void;
|
||||
onend: (event: Event) => void;
|
||||
onerror: (event: SpeechRecognitionErrorEvent) => void;
|
||||
onresult: (event: SpeechRecognitionEvent) => void;
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
abort: () => void;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionEvent extends Event {
|
||||
resultIndex: number;
|
||||
results: SpeechRecognitionResultList;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionResultList {
|
||||
length: number;
|
||||
item(index: number): SpeechRecognitionAlternativeList;
|
||||
[index: number]: SpeechRecognitionAlternativeList;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionAlternativeList {
|
||||
length: number;
|
||||
item(index: number): SpeechRecognitionAlternative;
|
||||
isFinal: boolean;
|
||||
[index: number]: SpeechRecognitionAlternative;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionAlternative {
|
||||
transcript: string;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
interface SpeechRecognitionErrorEvent extends Event {
|
||||
error: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
SpeechRecognition?: {
|
||||
new (): SpeechRecognition;
|
||||
};
|
||||
webkitSpeechRecognition?: {
|
||||
new (): SpeechRecognition;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class WebSpeechRecognizer {
|
||||
private recognition: SpeechRecognition | null = null;
|
||||
private isListening = false;
|
||||
private state: RecognitionState = 'idle';
|
||||
private onResultCallbacks: ((result: SpeechRecognitionResult) => void)[] = [];
|
||||
private onInterimResultCallbacks: ((transcript: string) => void)[] = [];
|
||||
private onErrorCallbacks: ((error: string) => void)[] = [];
|
||||
private onEndCallbacks: (() => void)[] = [];
|
||||
private onStartCallbacks: (() => void)[] = [];
|
||||
private finalTranscript = '';
|
||||
|
||||
constructor() {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const RecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||||
|
||||
if (RecognitionClass) {
|
||||
this.recognition = new RecognitionClass();
|
||||
this.recognition.continuous = false;
|
||||
this.recognition.interimResults = true;
|
||||
this.recognition.maxAlternatives = 1;
|
||||
|
||||
this.recognition.onstart = () => {
|
||||
this.isListening = true;
|
||||
this.state = 'listening';
|
||||
this.onStartCallbacks.forEach((cb) => cb());
|
||||
};
|
||||
|
||||
this.recognition.onresult = (event: SpeechRecognitionEvent) => {
|
||||
let interimTranscript = '';
|
||||
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const result = event.results[i];
|
||||
|
||||
if (result.isFinal) {
|
||||
const finalResult: SpeechRecognitionResult = {
|
||||
transcript: result[0].transcript,
|
||||
isFinal: true,
|
||||
confidence: result[0].confidence || 1.0,
|
||||
};
|
||||
|
||||
this.finalTranscript = result[0].transcript;
|
||||
this.onResultCallbacks.forEach((cb) => cb(finalResult));
|
||||
} else {
|
||||
interimTranscript += result[0].transcript;
|
||||
}
|
||||
}
|
||||
|
||||
if (interimTranscript) {
|
||||
this.onInterimResultCallbacks.forEach((cb) => cb(this.finalTranscript + ' ' + interimTranscript));
|
||||
}
|
||||
};
|
||||
|
||||
this.recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
|
||||
this.state = 'error';
|
||||
this.isListening = false;
|
||||
|
||||
let errorMsg = event.error || 'Unknown error';
|
||||
|
||||
switch (event.error) {
|
||||
case 'no-speech':
|
||||
errorMsg = 'No speech detected. Please try again.';
|
||||
break;
|
||||
case 'audio-capture':
|
||||
errorMsg = 'No microphone found. Please check your audio input.';
|
||||
break;
|
||||
case 'not-allowed':
|
||||
errorMsg = 'Microphone access denied. Please allow microphone permissions.';
|
||||
break;
|
||||
case 'network':
|
||||
errorMsg = 'Network error occurred.';
|
||||
break;
|
||||
case 'aborted':
|
||||
errorMsg = 'Recording was aborted.';
|
||||
break;
|
||||
}
|
||||
|
||||
this.onErrorCallbacks.forEach((cb) => cb(errorMsg));
|
||||
};
|
||||
|
||||
this.recognition.onend = () => {
|
||||
this.isListening = false;
|
||||
|
||||
if (this.state !== 'error') {
|
||||
this.state = 'idle';
|
||||
}
|
||||
|
||||
this.onEndCallbacks.forEach((cb) => cb());
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
isSupported(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return !!(window.SpeechRecognition || window.webkitSpeechRecognition);
|
||||
}
|
||||
|
||||
start(options: SpeechRecognitionOptions = {}): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.isSupported()) {
|
||||
reject(new Error('Web Speech API is not supported in this browser'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isListening) {
|
||||
reject(new Error('Already listening'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.recognition) {
|
||||
reject(new Error('Recognition not initialized'));
|
||||
return;
|
||||
}
|
||||
|
||||
this.finalTranscript = '';
|
||||
this.state = 'listening';
|
||||
|
||||
if (options.language) {
|
||||
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;
|
||||
}
|
||||
|
||||
if (options.maxAlternatives) {
|
||||
this.recognition.maxAlternatives = options.maxAlternatives;
|
||||
}
|
||||
|
||||
const onStartOnce = () => {
|
||||
this.onStartCallbacks = this.onStartCallbacks.filter(cb => cb !== onStartOnce);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const onErrorOnce = (error: string) => {
|
||||
this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce);
|
||||
reject(new Error(error));
|
||||
};
|
||||
|
||||
this.onStartCallbacks.push(onStartOnce);
|
||||
this.onErrorCallbacks.push(onErrorOnce);
|
||||
|
||||
try {
|
||||
this.recognition.start();
|
||||
} catch (error) {
|
||||
this.state = 'error';
|
||||
reject(error || new Error('Failed to start recognition'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.stop();
|
||||
} catch {
|
||||
this.isListening = false;
|
||||
this.state = 'idle';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abort(): void {
|
||||
if (this.recognition) {
|
||||
try {
|
||||
this.recognition.abort();
|
||||
} catch {
|
||||
// Ignore abort errors
|
||||
}
|
||||
this.state = 'idle';
|
||||
this.isListening = false;
|
||||
this.finalTranscript = '';
|
||||
}
|
||||
}
|
||||
|
||||
isCurrentlyListening(): boolean {
|
||||
return this.isListening;
|
||||
}
|
||||
|
||||
getState(): RecognitionState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
onResult(callback: (result: SpeechRecognitionResult) => void): void {
|
||||
this.onResultCallbacks.push(callback);
|
||||
}
|
||||
|
||||
onInterimResult(callback: (transcript: string) => void): void {
|
||||
this.onInterimResultCallbacks.push(callback);
|
||||
}
|
||||
|
||||
onError(callback: (error: string) => void): void {
|
||||
this.onErrorCallbacks.push(callback);
|
||||
}
|
||||
|
||||
onEnd(callback: () => void): void {
|
||||
this.onEndCallbacks.push(callback);
|
||||
}
|
||||
|
||||
onStart(callback: () => void): void {
|
||||
this.onStartCallbacks.push(callback);
|
||||
}
|
||||
|
||||
clearCallbacks(): void {
|
||||
this.onResultCallbacks = [];
|
||||
this.onInterimResultCallbacks = [];
|
||||
this.onErrorCallbacks = [];
|
||||
this.onEndCallbacks = [];
|
||||
this.onStartCallbacks = [];
|
||||
}
|
||||
|
||||
getFinalTranscript(): string {
|
||||
return this.finalTranscript;
|
||||
}
|
||||
}
|
||||
|
||||
let recognizerInstance: WebSpeechRecognizer | null = null;
|
||||
|
||||
export function getWebSpeechRecognizer(): WebSpeechRecognizer {
|
||||
if (!recognizerInstance) {
|
||||
recognizerInstance = new WebSpeechRecognizer();
|
||||
}
|
||||
return recognizerInstance;
|
||||
}
|
||||
|
||||
export function isWebRecognitionSupported(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return !!(window.SpeechRecognition || window.webkitSpeechRecognition);
|
||||
}
|
||||
|
||||
export function getAvailableLanguages(): string[] {
|
||||
if (typeof window === 'undefined' || !isWebRecognitionSupported()) {
|
||||
return ['en-US'];
|
||||
}
|
||||
|
||||
const commonLanguages = [
|
||||
'en-US', 'en-GB', 'en-AU', 'en-CA', 'en-IN',
|
||||
'es-ES', 'es-MX', 'es-AR', 'es-CO',
|
||||
'fr-FR', 'fr-CA', 'fr-BE',
|
||||
'de-DE', 'de-AT', 'de-CH',
|
||||
'it-IT', 'pt-BR', 'pt-PT',
|
||||
'zh-CN', 'zh-TW', 'ja-JP', 'ko-KR',
|
||||
'ru-RU', 'ar-SA', 'hi-IN',
|
||||
];
|
||||
|
||||
return commonLanguages;
|
||||
}
|
||||
Reference in new issue
Block a user