Add GitHub token validation and improve TTS configuration

- Add git token validation endpoint and UI validation
- Improve TTS endpoint normalization and discovery
- Move shared types to workspace package
- Add better error handling for TTS API calls
- Support composite voices for Kokoro-style TTS
- Auto-fetch TTS models and voices on config change
This commit is contained in:
Chris Scott committed 2025-12-15 14:43:03 -05:00
1 parent 406ff8fd4a
commit c7de65290a
11 files changed
+410 -154

No files matched your search

+75
View File
@@ -12,6 +12,11 @@ import {
import { logger } from '../utils/logger'
import { opencodeServerManager } from '../services/opencode-single-server'
import { DEFAULT_AGENTS_MD } from '../index'
import { createGitHubGitEnv } from '../utils/git-auth'
import { exec } from 'child_process'
import { promisify } from 'util'
const execAsync = promisify(exec)
const UpdateSettingsSchema = z.object({
preferences: UserPreferencesSchema.partial(),
@@ -41,6 +46,10 @@ const UpdateCustomCommandSchema = z.object({
promptTemplate: z.string().min(1).max(10000),
})
const ValidateGitTokenSchema = z.object({
gitToken: z.string(),
})
export function createSettingsRoutes(db: Database) {
const app = new Hono()
const settingsService = new SettingsService(db)
@@ -370,5 +379,71 @@ export function createSettingsRoutes(db: Database) {
}
})
app.post('/validate-git-token', async (c) => {
try {
const body = await c.req.json()
const { gitToken } = ValidateGitTokenSchema.parse(body)
if (!gitToken) {
return c.json({ valid: true, message: 'No token provided' })
}
// Test the token by trying to access a public GitHub repo via git ls-remote
const testRepoUrl = 'https://github.com/octocat/Hello-World.git'
const env = createGitHubGitEnv(gitToken)
try {
await execAsync(`git ls-remote ${testRepoUrl}`, {
env: { ...process.env, ...env },
timeout: 10000
})
// If command succeeded (exit code 0), token is valid
// stderr may contain warnings but that's ok
return c.json({
valid: true,
message: 'Token is valid'
})
} catch (error) {
logger.error('Git token validation failed:', error)
if (error instanceof Error) {
const errorMsg = error.message.toLowerCase()
if (errorMsg.includes('authentication failed') ||
errorMsg.includes('not authorized') ||
errorMsg.includes('invalid username or token') ||
errorMsg.includes('password authentication is not supported') ||
errorMsg.includes('401') ||
errorMsg.includes('403') ||
errorMsg.includes('code 128')) {
return c.json({
valid: false,
message: 'Invalid GitHub token. Please check your token and permissions.'
})
}
if (errorMsg.includes('timeout') || errorMsg.includes('network')) {
return c.json({
valid: false,
message: 'Network error - could not validate token. Please try again.'
})
}
}
return c.json({
valid: false,
message: 'Failed to validate token: ' + (error instanceof Error ? error.message : 'Unknown error')
})
}
} catch (error) {
logger.error('Token validation endpoint error:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
return c.json({ error: 'Failed to validate token' }, 500)
}
})
return app
}
+64 -14
View File
@@ -23,6 +23,13 @@ function generateCacheKey(text: string, voice: string, model: string, speed: num
return hash.digest('hex')
}
function normalizeToBaseUrl(endpoint: string): string {
return endpoint
.replace(/\/v1\/audio\/speech$/, '')
.replace(/\/audio\/speech$/, '')
.replace(/\/$/, '')
}
async function ensureCacheDir(): Promise<void> {
await mkdir(TTS_CACHE_DIR, { recursive: true })
}
@@ -85,11 +92,10 @@ function generateDiscoveryCacheKey(endpoint: string, apiKey: string, type: 'mode
}
async function fetchAvailableModels(endpoint: string, apiKey: string): Promise<string[]> {
// Try different endpoint formats for models
const baseUrl = normalizeToBaseUrl(endpoint)
const endpointVariations = [
`${endpoint.replace(/\/audio\/speech$/, '')}/v1/models`,
`${endpoint.replace(/\/audio\/speech$/, '')}/models`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/models`,
`${baseUrl}/v1/models`,
`${baseUrl}/models`,
]
for (const modelEndpoint of endpointVariations) {
@@ -120,7 +126,7 @@ async function fetchAvailableModels(endpoint: string, apiKey: string): Promise<s
}
}
} catch (error) {
logger.debug(`Failed to fetch models from ${modelEndpoint}:`, error)
logger.warn(`Failed to fetch models from ${modelEndpoint}:`, error)
continue
}
}
@@ -129,12 +135,11 @@ async function fetchAvailableModels(endpoint: string, apiKey: string): Promise<s
}
async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise<string[]> {
// Try different endpoint formats for voices
const baseUrl = normalizeToBaseUrl(endpoint)
const endpointVariations = [
`${endpoint.replace(/\/audio\/speech$/, '')}/v1/audio/voices`,
`${endpoint.replace(/\/audio\/speech$/, '')}/voices`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/audio/voices`,
`${endpoint.replace(/\/v1\/audio\/speech$/, '')}/audio/voices`,
`${baseUrl}/v1/audio/voices`,
`${baseUrl}/voices`,
`${baseUrl}/audio/voices`,
]
for (const voiceEndpoint of endpointVariations) {
@@ -148,7 +153,7 @@ async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise<s
if (response.ok) {
type VoiceItem = { id?: string; name?: string; voice?: string }
const data = await response.json() as { data?: VoiceItem[] } | (string | VoiceItem)[]
const data = await response.json() as { data?: VoiceItem[]; voices?: string[] } | (string | VoiceItem)[]
// Handle different response formats
if ('data' in data && Array.isArray(data.data)) {
@@ -156,6 +161,9 @@ async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise<s
return data.data
.filter((voice) => voice.id || voice.name)
.map((voice) => (voice.id || voice.name)!)
} else if ('voices' in data && Array.isArray(data.voices)) {
// Kokoro-style format: { "voices": ["af_alloy", "af_aoede", ...] }
return data.voices.filter((v): v is string => typeof v === 'string')
} else if (Array.isArray(data)) {
// Simple array format: ["alloy", "echo", ...] or [{ voice: "alloy" }, ...]
return data.map((item) => {
@@ -165,7 +173,7 @@ async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise<s
}
}
} catch (error) {
logger.debug(`Failed to fetch voices from ${voiceEndpoint}:`, error)
logger.warn(`Failed to fetch voices from ${voiceEndpoint}:`, error)
continue
}
}
@@ -244,7 +252,10 @@ export function createTTSRoutes(db: Database) {
logger.info(`TTS cache miss, calling API: ${cacheKey.substring(0, 8)}...`)
const response = await fetch(endpoint, {
const baseUrl = normalizeToBaseUrl(endpoint)
const speechEndpoint = `${baseUrl}/v1/audio/speech`
const response = await fetch(speechEndpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
@@ -263,7 +274,28 @@ export function createTTSRoutes(db: Database) {
const errorText = await response.text()
logger.error(`TTS API error: ${response.status} - ${errorText}`)
const status = response.status >= 400 && response.status < 600 ? response.status as 400 | 500 : 500
return c.json({ error: 'TTS API request failed', details: errorText }, status)
// Try to parse error details for better frontend display
let errorDetails = errorText
try {
const errorJson = JSON.parse(errorText)
if (errorJson.detail?.error?.message) {
errorDetails = errorJson.detail.error.message
} else if (errorJson.detail?.message) {
errorDetails = errorJson.detail.message
} else if (errorJson.message) {
errorDetails = errorJson.message
}
} catch {
// Use raw error text if parsing fails
}
return c.json({
error: 'TTS API request failed',
details: errorDetails,
voice: voice,
availableVoices: ttsConfig?.availableVoices || []
}, status)
}
const audioBuffer = Buffer.from(await response.arrayBuffer())
@@ -317,6 +349,15 @@ export function createTTSRoutes(db: Database) {
const models = await fetchAvailableModels(ttsConfig.endpoint, ttsConfig.apiKey)
await cacheDiscovery(cacheKey, models)
// Update user preferences with available models
await settingsService.updateSettings({
tts: {
...ttsConfig,
availableModels: models,
lastModelsFetch: Date.now()
}
}, userId)
logger.info(`Fetched ${models.length} TTS models`)
return c.json({ models, cached: false })
} catch (error) {
@@ -356,6 +397,15 @@ export function createTTSRoutes(db: Database) {
const voices = await fetchAvailableVoices(ttsConfig.endpoint, ttsConfig.apiKey)
await cacheDiscovery(cacheKey, voices)
// Update user preferences with available voices
await settingsService.updateSettings({
tts: {
...ttsConfig,
availableVoices: voices,
lastVoicesFetch: Date.now()
}
}, userId)
logger.info(`Fetched ${voices.length} TTS voices`)
return c.json({ voices, cached: false })
} catch (error) {
+1
View File
@@ -9,6 +9,7 @@
"preview": "vite preview"
},
"dependencies": {
"@opencode-manager/shared": "workspace:*",
"@hookform/resolvers": "^5.2.2",
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-checkbox": "^1.3.3",
+5
View File
@@ -117,4 +117,9 @@ export const settingsApi = {
const { data } = await axios.put(`${API_BASE_URL}/api/settings/agents-md`, { content })
return data
},
validateGitToken: async (gitToken: string): Promise<{ valid: boolean; message: string }> => {
const { data } = await axios.post(`${API_BASE_URL}/api/settings/validate-git-token`, { gitToken })
return data
},
}
+10 -58
View File
@@ -1,35 +1,19 @@
import {
DEFAULT_TTS_CONFIG,
DEFAULT_KEYBOARD_SHORTCUTS,
DEFAULT_USER_PREFERENCES,
type TTSConfig,
} from '@opencode-manager/shared'
export type { TTSConfig }
export { DEFAULT_TTS_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES }
export interface CustomCommand {
name: string
description: string
promptTemplate: string
}
export interface TTSConfig {
enabled: boolean
endpoint: string
apiKey: string
voice: string
model: string
speed: number
availableVoices?: string[]
availableModels?: string[]
lastVoicesFetch?: number
lastModelsFetch?: number
}
export const DEFAULT_TTS_CONFIG: TTSConfig = {
enabled: false,
endpoint: 'https://api.openai.com/v1/audio/speech',
apiKey: '',
voice: 'alloy',
model: 'tts-1',
speed: 1.0,
availableVoices: [],
availableModels: [],
lastVoicesFetch: 0,
lastModelsFetch: 0,
}
export interface CustomAgent {
name: string
description: string
@@ -86,35 +70,3 @@ export interface OpenCodeConfigResponse {
configs: OpenCodeConfig[]
defaultConfig: OpenCodeConfig | null
}
const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().indexOf('MAC') >= 0
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
submit: `${CMD_KEY}+Enter`,
abort: 'Escape',
toggleMode: 'Tab',
undo: `${CMD_KEY}+Z`,
redo: `${CMD_KEY}+Shift+Z`,
compact: `${CMD_KEY}+K`,
fork: `${CMD_KEY}+Shift+F`,
settings: `${CMD_KEY}+,`,
sessions: `${CMD_KEY}+S`,
newSession: `${CMD_KEY}+N`,
closeSession: `${CMD_KEY}+W`,
toggleSidebar: `${CMD_KEY}+B`,
selectModel: `${CMD_KEY}+M`,
}
export const DEFAULT_USER_PREFERENCES: UserPreferences = {
theme: 'dark',
mode: 'build',
autoScroll: true,
showReasoning: false,
expandToolCalls: false,
keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
customCommands: [],
customAgents: [],
gitToken: undefined,
tts: DEFAULT_TTS_CONFIG,
}
@@ -1,24 +1,47 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { settingsApi } from '@/api/settings'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { X } from 'lucide-react'
import { TTSSettings } from './TTSSettings'
import { showToast } from '@/lib/toast'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, updateSettingsAsync, isUpdating } = useSettings()
const [gitToken, setGitToken] = useState('')
const [isValidatingToken, setIsValidatingToken] = useState(false)
useEffect(() => {
if (preferences) {
setGitToken(preferences.gitToken || '')
}
}, [preferences])
const validateGitToken = async (token: string): Promise<boolean> => {
if (!token) return true
setIsValidatingToken(true)
try {
const result = await settingsApi.validateGitToken(token)
if (!result.valid) {
showToast.error(result.message, { id: 'validate-token' })
return false
}
showToast.success('GitHub token validated successfully', { id: 'validate-token' })
return true
} catch {
showToast.error('Failed to validate GitHub token - please try again', { id: 'validate-token' })
return false
} finally {
setIsValidatingToken(false)
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
@@ -115,25 +138,61 @@ export function GeneralSettings() {
<div className="space-y-2">
<Label htmlFor="gitToken">GitHub Personal Access Token</Label>
<Input
id="gitToken"
type="password"
placeholder="ghp_..."
value={gitToken}
onChange={(e) => setGitToken(e.target.value)}
onBlur={async () => {
<div className="flex gap-2">
<Input
id="gitToken"
type="password"
placeholder="ghp_..."
value={gitToken}
onChange={(e) => setGitToken(e.target.value)}
disabled={isValidatingToken}
onBlur={async () => {
if (gitToken !== preferences?.gitToken) {
showToast.loading('Validating GitHub token...', { id: 'validate-token' })
const isValid = await validateGitToken(gitToken)
if (!isValid) {
// Reset to previous value if validation failed
setGitToken(preferences?.gitToken || '')
return
}
showToast.loading('Restarting OpenCode server...', { id: 'restart-server' })
try {
await updateSettingsAsync({ gitToken })
showToast.success('GitHub token updated', { id: 'restart-server' })
} catch {
showToast.error('Failed to update GitHub token', { id: 'restart-server' })
setGitToken(preferences?.gitToken || '')
}
}
}}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
{isValidatingToken && (
<div className="flex items-center justify-center w-10">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
)}
<Button
type="button"
variant="outline"
size="icon"
onClick={async () => {
setGitToken('')
showToast.loading('Restarting OpenCode server...', { id: 'restart-server' })
try {
await updateSettingsAsync({ gitToken: '' })
showToast.success('GitHub token cleared', { id: 'restart-server' })
} catch {
showToast.error('Failed to clear GitHub token', { id: 'restart-server' })
}
}}
disabled={!gitToken || isValidatingToken}
>
<X className="h-4 w-4" />
</Button>
</div>
<p className="text-sm text-muted-foreground">
Required for cloning private repos. Get one at github.com/settings/tokens
</p>
@@ -16,6 +16,16 @@ import { DEFAULT_TTS_CONFIG } from '@/api/types/settings'
const TEST_PHRASE = 'Text to speech is working correctly.'
const KOKORO_COMPOSITE_VOICE_SUGGESTIONS = [
{ value: "am_adam+am_echo", label: "Composite: am_adam+am_echo" },
{ value: "af_bella+af_nova", label: "Composite: af_bella+af_nova" },
{ value: "bm_daniel+bm_george", label: "Composite: bm_daniel+bm_george" },
]
function isKokoroStyleVoice(voice: string): boolean {
return /^[a-z]{2}_/.test(voice)
}
const ttsFormSchema = z.object({
enabled: z.boolean(),
endpoint: z.string().url('Must be a valid URL').min(1, 'Endpoint is required'),
@@ -38,7 +48,7 @@ type TTSFormValues = z.infer<typeof ttsFormSchema>
export function TTSSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS()
const { refreshModels, refreshVoices, refreshAll } = useTTSDiscovery()
const { refreshAll } = useTTSDiscovery()
const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle')
const [isRefreshingDiscovery, setIsRefreshingDiscovery] = useState(false)
@@ -48,28 +58,30 @@ export function TTSSettings() {
})
const { reset, formState: { isDirty, isValid } } = form
const watchEnabled = form.watch('enabled')
const watchApiKey = form.watch('apiKey')
const watchEndpoint = form.watch('endpoint')
const canTest = watchEnabled && watchApiKey && !isDirty
// Fetch available models and voices when TTS is configured
const { data: modelsData, isLoading: isLoadingModels, refetch: refetchModels } = useTTSModels(
preferences?.tts?.enabled && preferences?.tts?.apiKey ? undefined : 'default',
watchEnabled && !!watchApiKey && !!watchEndpoint
undefined, // Let the hook use default user
true // Always fetch if endpoint is available
)
const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices(
preferences?.tts?.enabled && preferences?.tts?.apiKey ? undefined : 'default',
watchEnabled && !!watchApiKey && !!watchEndpoint
undefined, // Let the hook use default user
true // Always fetch if endpoint is available
)
const availableModels = modelsData?.models || []
const availableVoices = voicesData?.voices || []
// Use data from API discovery first, fallback to stored preferences
const availableModels = modelsData?.models || preferences?.tts?.availableModels || []
const availableVoices = voicesData?.voices || preferences?.tts?.availableVoices || []
const modelsCached = modelsData?.cached || false
const voicesCached = voicesData?.cached || false
const watchEnabled = form.watch('enabled')
const watchApiKey = form.watch('apiKey')
const watchEndpoint = form.watch('endpoint')
const watchVoice = form.watch('voice')
const canTest = watchEnabled && watchApiKey && !isDirty && watchVoice && availableVoices.length > 0
const handleRefreshDiscovery = async () => {
setIsRefreshingDiscovery(true)
try {
@@ -96,6 +108,18 @@ export function TTSSettings() {
}
}, [preferences?.tts, reset])
// Auto-fetch models and voices when endpoint or API key changes
useEffect(() => {
if (watchEnabled && watchApiKey && watchEndpoint) {
const timer = setTimeout(() => {
refetchModels()
refetchVoices()
}, 1000) // Debounce by 1 second to avoid rapid calls
return () => clearTimeout(timer)
}
}, [watchEndpoint, watchApiKey, watchEnabled, refetchModels, refetchVoices])
const onSubmit = (data: TTSFormValues) => {
updateSettings({ tts: data })
}
@@ -125,10 +149,10 @@ export function TTSSettings() {
}
return (
<div className="bg-card border border-border rounded-lg p-6">
<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">Text-to-Speech</h2>
<Button
<Button
onClick={form.handleSubmit(onSubmit)}
disabled={!isDirty || !isValid || isUpdating}
size="sm"
@@ -174,16 +198,16 @@ export function TTSSettings() {
name="endpoint"
render={({ field }) => (
<FormItem>
<FormLabel>TTS Endpoint</FormLabel>
<FormLabel>TTS Server URL</FormLabel>
<FormControl>
<Input
placeholder="https://api.openai.com/v1/audio/speech"
placeholder="https://api.openai.com"
className="bg-background"
{...field}
/>
</FormControl>
<FormDescription>
OpenAI-compatible TTS API endpoint
Base URL of your TTS service (e.g., https://x.x.x.x:Port)
</FormDescription>
<FormMessage />
</FormItem>
@@ -215,18 +239,29 @@ export function TTSSettings() {
<FormField
control={form.control}
name="voice"
render={({ field }) => (
render={({ field }) => {
const hasKokoroVoices = availableVoices.some(isKokoroStyleVoice)
const voiceOptions = [
...availableVoices.slice(0, 10).map((voice: string) => ({
value: voice,
label: voice
})),
...(hasKokoroVoices ? KOKORO_COMPOSITE_VOICE_SUGGESTIONS : []),
...availableVoices.slice(10).map((voice: string) => ({
value: voice,
label: voice
}))
]
return (
<FormItem>
<FormLabel>Voice</FormLabel>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={availableVoices.map(voice => ({
value: voice,
label: voice
}))}
placeholder="Select a voice or type custom name..."
options={voiceOptions}
placeholder={hasKokoroVoices ? "Select a voice or type custom name (e.g., am_adam+am_echo)..." : "Select a voice..."}
disabled={!watchEnabled || isLoadingVoices}
allowCustomValue={true}
/>
@@ -234,11 +269,14 @@ export function TTSSettings() {
<FormDescription>
{isLoadingVoices ? 'Loading available voices...' :
voicesCached ? `Available voices (${availableVoices.length}) - cached` :
`Available voices (${availableVoices.length})`}
availableVoices.length > 0 ? `Available voices (${availableVoices.length})${hasKokoroVoices ? ' - Support composite voices (e.g., am_adam+am_echo)' : ''}` :
watchEnabled && watchApiKey ? 'No voices available - check endpoint and API key' :
'Configure TTS to discover voices'}
</FormDescription>
<FormMessage />
</FormItem>
)}
)
}}
/>
<FormField
@@ -251,7 +289,7 @@ export function TTSSettings() {
<Combobox
value={field.value}
onChange={field.onChange}
options={availableModels.map(model => ({
options={availableModels.map((model: string) => ({
value: model,
label: model
}))}
@@ -260,11 +298,13 @@ export function TTSSettings() {
allowCustomValue={true}
/>
</FormControl>
<FormDescription>
{isLoadingModels ? 'Loading available models...' :
modelsCached ? `Available models (${availableModels.length}) - cached` :
`Available models (${availableModels.length})`}
</FormDescription>
<FormDescription>
{isLoadingModels ? 'Loading available models...' :
modelsCached ? `Available models (${availableModels.length}) - cached` :
availableModels.length > 0 ? `Available models (${availableModels.length})` :
watchEnabled && watchApiKey ? 'No models available - check endpoint and API key' :
'Configure TTS to discover models'}
</FormDescription>
<FormMessage />
</FormItem>
)}
@@ -339,6 +379,17 @@ export function TTSSettings() {
<p className="text-sm text-destructive flex items-center gap-1">
<XCircle className="h-4 w-4" />
{ttsError}
{ttsError.includes("not found") && availableVoices.length > 0 && (
<span className="text-xs block mt-1">
Try selecting from: {availableVoices.slice(0, 5).join(", ")}
{availableVoices.length > 5 && ` +${availableVoices.length - 5} more`}
</span>
)}
</p>
)}
{!ttsError && watchEnabled && watchApiKey && watchEndpoint && availableVoices.length === 0 && !isLoadingVoices && (
<p className="text-sm text-muted-foreground flex items-center gap-1">
Click "Refresh" to discover available voices, or check your API key and endpoint URL.
</p>
)}
{testStatus === 'success' && (
+64 -26
View File
@@ -5,6 +5,9 @@ import { API_BASE_URL } from '@/config'
const TTS_CACHE_NAME = 'tts-audio-cache'
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const PUNCTUATION_REGEX = /(?<=[.!?;])\s+/
const AUDIO_PLAYBACK_MAX_RETRIES = 3
const AUDIO_PLAYBACK_RETRY_DELAY_MS = 50
const AUDIO_LOAD_TIMEOUT_MS = 5000
function generateCacheKey(text: string, voice: string, model: string, speed: number): string {
const data = `${text}|${voice}|${model}|${speed}`
@@ -158,36 +161,71 @@ export function useTTS() {
if (!audioBlob || !isPlayingChunksRef.current) return
const audioUrl = URL.createObjectURL(audioBlob)
const audio = new Audio(audioUrl)
audioRef.current = audio
audio.onplay = () => setState('playing')
audio.onpause = () => {
if (audio.currentTime < audio.duration) setState('paused')
}
audio.onended = () => {
URL.revokeObjectURL(audioUrl)
playNextChunk()
}
audio.onerror = () => {
const mediaError = audio.error
let errorMessage = 'Audio playback failed'
if (mediaError) {
switch (mediaError.code) {
case MediaError.MEDIA_ERR_ABORTED: errorMessage = 'Audio playback was aborted'; break
case MediaError.MEDIA_ERR_NETWORK: errorMessage = 'Network error during audio playback'; break
case MediaError.MEDIA_ERR_DECODE: errorMessage = 'Audio decoding failed'; break
case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED: errorMessage = 'Audio format not supported'; break
const playAudioBlob = async (blob: Blob, retries = AUDIO_PLAYBACK_MAX_RETRIES): Promise<void> => {
let lastError: Error | null = null
for (let attempt = 1; attempt <= retries; attempt++) {
if (!isPlayingChunksRef.current) return
const typedBlob = new Blob([blob], { type: 'audio/mpeg' })
const audioUrl = URL.createObjectURL(typedBlob)
const audio = new Audio()
try {
await new Promise<void>((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('Audio load timeout'))
}, AUDIO_LOAD_TIMEOUT_MS)
audio.oncanplaythrough = () => {
clearTimeout(timeoutId)
resolve()
}
audio.onerror = () => {
clearTimeout(timeoutId)
reject(new Error(audio.error?.message || 'Audio load failed'))
}
audio.src = audioUrl
audio.load()
})
if (!isPlayingChunksRef.current) {
URL.revokeObjectURL(audioUrl)
return
}
audioRef.current = audio
audio.onplay = () => setState('playing')
audio.onpause = () => {
if (audio.currentTime < audio.duration) setState('paused')
}
audio.onended = () => {
URL.revokeObjectURL(audioUrl)
playNextChunk()
}
audio.onerror = () => {
URL.revokeObjectURL(audioUrl)
}
await audio.play()
return
} catch (err) {
URL.revokeObjectURL(audioUrl)
lastError = err instanceof Error ? err : new Error('Unknown error')
if (attempt < retries) {
await new Promise(r => setTimeout(r, AUDIO_PLAYBACK_RETRY_DELAY_MS * attempt))
}
}
}
setError(errorMessage)
setState('error')
isPlayingChunksRef.current = false
URL.revokeObjectURL(audioUrl)
throw lastError || new Error('Audio playback failed after retries')
}
await audio.play()
await playAudioBlob(audioBlob)
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
setState('idle')
+3
View File
@@ -70,6 +70,9 @@ importers:
'@monaco-editor/react':
specifier: ^4.7.0
version: 4.7.0(monaco-editor@0.55.1)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
'@opencode-manager/shared':
specifier: workspace:*
version: link:../shared
'@radix-ui/react-checkbox':
specifier: ^1.3.3
version: 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
+2 -2
View File
@@ -27,7 +27,7 @@ export const ProviderAuthMethodSchema = z.object({
label: z.string(),
});
export const ProviderAuthMethodsSchema = z.record(z.array(ProviderAuthMethodSchema));
export const ProviderAuthMethodsSchema = z.record(z.string(), z.array(ProviderAuthMethodSchema));
export const OAuthAuthorizeRequestSchema = z.object({
method: z.number(),
@@ -45,5 +45,5 @@ export const OAuthCallbackRequestSchema = z.object({
});
export const ProviderAuthMethodsResponseSchema = z.object({
providers: z.record(z.array(ProviderAuthMethodSchema)),
providers: z.record(z.string(), z.array(ProviderAuthMethodSchema)),
});
+33 -11
View File
@@ -25,15 +25,37 @@ export const CustomAgentSchema = z.object({
config: z.record(z.string(), z.any()),
});
export const DEFAULT_KEYBOARD_SHORTCUTS = {
submit: "shift+Enter",
abort: "Escape",
undo: "ctrl+Z",
redo: "ctrl+R",
compact: "ctrl",
newSession: "ctrl+N",
toggleMode: "Tab",
selectModel: "ctrl+M",
export type TTSConfig = {
enabled: boolean;
endpoint: string;
apiKey: string;
voice: string;
model: string;
speed: number;
availableVoices?: string[];
availableModels?: string[];
lastVoicesFetch?: number;
lastModelsFetch?: number;
};
const isBrowser = typeof navigator !== 'undefined';
const isMac = isBrowser && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl';
export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
submit: `${CMD_KEY}+Enter`,
abort: 'Escape',
toggleMode: 'Tab',
undo: `${CMD_KEY}+Z`,
redo: `${CMD_KEY}+Shift+Z`,
compact: `${CMD_KEY}+K`,
fork: `${CMD_KEY}+Shift+F`,
settings: `${CMD_KEY}+,`,
sessions: `${CMD_KEY}+S`,
newSession: `${CMD_KEY}+N`,
closeSession: `${CMD_KEY}+W`,
toggleSidebar: `${CMD_KEY}+B`,
selectModel: `${CMD_KEY}+M`,
};
export const UserPreferencesSchema = z.object({
@@ -51,9 +73,9 @@ export const UserPreferencesSchema = z.object({
tts: TTSConfigSchema.optional(),
});
export const DEFAULT_TTS_CONFIG = {
export const DEFAULT_TTS_CONFIG: TTSConfig = {
enabled: false,
endpoint: "https://api.openai.com/v1/audio/speech",
endpoint: "https://api.openai.com",
apiKey: "",
voice: "alloy",
model: "tts-1",