From 873321b0889119f58b93f5b3fca12761d488608c Mon Sep 17 00:00:00 2001 From: OpenCode Date: Sun, 14 Dec 2025 20:30:07 +0000 Subject: [PATCH 1/4] Fix tool call status stuck on running and improve mobile code block word-wrap --- frontend/src/components/message/TextPart.tsx | 4 +- .../src/components/message/ToolCallPart.tsx | 41 +++++++++++++++---- frontend/src/hooks/useSSE.ts | 27 +++++++++++- frontend/src/index.css | 17 ++++++++ 4 files changed, 77 insertions(+), 12 deletions(-) diff --git a/frontend/src/components/message/TextPart.tsx b/frontend/src/components/message/TextPart.tsx index bc13285d..c37e44f0 100644 --- a/frontend/src/components/message/TextPart.tsx +++ b/frontend/src/components/message/TextPart.tsx @@ -49,7 +49,7 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) { return (
-
+      
         {children}
       
-
+
$ {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
@@ -270,7 +295,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal {part.state.status === 'error' && (
Error:
-
+              
                 {part.state.error}
               
diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 1e9d37aa..e3402ba3 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -272,13 +272,36 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string) const now = Date.now() const updated = currentData.map(msg => { if (msg.info.role !== 'assistant') return msg - if ('completed' in msg.info.time && msg.info.time.completed) return msg + + const updatedParts = msg.parts.map(part => { + if (part.type !== 'tool') return part + if (part.state.status !== 'running' && part.state.status !== 'pending') return part + return { + ...part, + state: { + ...part.state, + status: 'completed' as const, + output: part.state.status === 'running' ? '[Session ended - output not captured]' : '[Tool was pending when session ended]', + title: part.state.status === 'running' ? (part.state as { title?: string }).title || '' : '', + metadata: (part.state as { metadata?: Record }).metadata || {}, + time: { + start: (part.state as { time?: { start: number } }).time?.start || now, + end: now + } + } + } + }) + + const msgUpdated = updatedParts !== msg.parts + if ('completed' in msg.info.time && msg.info.time.completed && !msgUpdated) return msg + return { ...msg, info: { ...msg.info, time: { ...msg.info.time, completed: now } - } + }, + parts: updatedParts } }) diff --git a/frontend/src/index.css b/frontend/src/index.css index eda914cc..87445b35 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -217,6 +217,23 @@ body { .prose-enhanced pre { margin-top: 1.5em; margin-bottom: 1.5em; + white-space: pre-wrap; + word-break: break-word; +} + +.prose-enhanced code { + word-break: break-all; +} + +@media (max-width: 640px) { + .prose-enhanced pre { + padding: 0.5rem; + font-size: 0.75rem; + } + + .prose-enhanced code { + font-size: 0.75rem; + } } .prose-enhanced :first-child { From 722c62f61e0b68776898dc033b5f8a2104a86c98 Mon Sep 17 00:00:00 2001 From: OpenCode Date: Sun, 14 Dec 2025 21:11:21 +0000 Subject: [PATCH 2/4] Add break-all to tool output for better mobile wrapping --- frontend/src/components/message/ToolCallPart.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index 176df82e..10faca17 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -278,7 +278,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal )}
Output:
-
 part.state.status === 'completed' && navigator.clipboard.writeText(part.state.output)}
                      title="Click to copy output">
                   {part.state.status === 'completed' ? part.state.output : ''}

From 406ff8fd4a1edfbbbc1230561b65bbc21eae9bcf Mon Sep 17 00:00:00 2001
From: OpenCode 
Date: Mon, 15 Dec 2025 17:43:05 +0000
Subject: [PATCH 3/4] Add TTS model and voice discovery with caching

---
 backend/src/routes/tts.ts                     | 205 ++++++++++++++++++
 frontend/src/api/tts.ts                       | 104 +++++++++
 frontend/src/api/types/settings.ts            |   8 +
 .../src/components/settings/TTSSettings.tsx   | 127 ++++++++---
 shared/src/schemas/settings.ts                |   8 +
 5 files changed, 421 insertions(+), 31 deletions(-)
 create mode 100644 frontend/src/api/tts.ts

diff --git a/backend/src/routes/tts.ts b/backend/src/routes/tts.ts
index bdb0f1d0..1bc00666 100644
--- a/backend/src/routes/tts.ts
+++ b/backend/src/routes/tts.ts
@@ -9,7 +9,9 @@ import { logger } from '../utils/logger'
 import { getWorkspacePath } from '@opencode-manager/shared'
 
 const TTS_CACHE_DIR = join(getWorkspacePath(), 'cache', 'tts')
+const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'discovery')
 const CACHE_TTL_MS = 24 * 60 * 60 * 1000
+const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour for discovery cache
 
 const TTSRequestSchema = z.object({
   text: z.string().min(1).max(4096),
@@ -25,6 +27,10 @@ async function ensureCacheDir(): Promise {
   await mkdir(TTS_CACHE_DIR, { recursive: true })
 }
 
+async function ensureDiscoveryCacheDir(): Promise {
+  await mkdir(DISCOVERY_CACHE_DIR, { recursive: true })
+}
+
 async function getCachedAudio(cacheKey: string): Promise {
   try {
     const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`)
@@ -46,6 +52,127 @@ async function cacheAudio(cacheKey: string, audioData: Buffer): Promise {
   await writeFile(filePath, audioData)
 }
 
+async function getCachedDiscovery(cacheKey: string): Promise {
+  try {
+    const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`)
+    const fileStat = await stat(filePath)
+    
+    if (Date.now() - fileStat.mtimeMs > DISCOVERY_CACHE_TTL_MS) {
+      await unlink(filePath)
+      return null
+    }
+    
+    const content = await readFile(filePath, 'utf-8')
+    return JSON.parse(content)
+  } catch {
+    return null
+  }
+}
+
+async function cacheDiscovery(cacheKey: string, data: string[]): Promise {
+  try {
+    const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`)
+    await writeFile(filePath, JSON.stringify(data))
+  } catch (error) {
+    logger.error(`Failed to cache discovery data for ${cacheKey}:`, error)
+  }
+}
+
+function generateDiscoveryCacheKey(endpoint: string, apiKey: string, type: 'models' | 'voices'): string {
+  const hash = createHash('sha256')
+  hash.update(`${endpoint}|${apiKey.substring(0, 8)}|${type}`)
+  return hash.digest('hex')
+}
+
+async function fetchAvailableModels(endpoint: string, apiKey: string): Promise {
+  // Try different endpoint formats for models
+  const endpointVariations = [
+    `${endpoint.replace(/\/audio\/speech$/, '')}/v1/models`,
+    `${endpoint.replace(/\/audio\/speech$/, '')}/models`,
+    `${endpoint.replace(/\/v1\/audio\/speech$/, '')}/v1/models`,
+  ]
+  
+  for (const modelEndpoint of endpointVariations) {
+    try {
+      const response = await fetch(modelEndpoint, {
+        headers: {
+          'Authorization': `Bearer ${apiKey}`,
+          'Content-Type': 'application/json',
+        },
+      })
+      
+      if (response.ok) {
+        const data = await response.json() as { data?: { id?: string }[] } | unknown[]
+        
+        // Handle different response formats
+        if ('data' in data && Array.isArray(data.data)) {
+          // OpenAI format: { data: [{ id: "gpt-4" }, ...] }
+          return data.data
+            .filter((model) => model.id && typeof model.id === 'string')
+            .filter((model) => 
+              model.id!.toLowerCase().includes('tts') || 
+              model.id!.toLowerCase().includes('audio') ||
+              model.id!.toLowerCase().includes('speech')
+            )
+            .map((model) => model.id!)
+        } else if (Array.isArray(data)) {
+          return data.filter((item): item is string => typeof item === 'string')
+        }
+      }
+    } catch (error) {
+      logger.debug(`Failed to fetch models from ${modelEndpoint}:`, error)
+      continue
+    }
+  }
+  
+  return ['tts-1', 'tts-1-hd']
+}
+
+async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise {
+  // Try different endpoint formats for voices
+  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`,
+  ]
+  
+  for (const voiceEndpoint of endpointVariations) {
+    try {
+      const response = await fetch(voiceEndpoint, {
+        headers: {
+          'Authorization': `Bearer ${apiKey}`,
+          'Content-Type': 'application/json',
+        },
+      })
+      
+      if (response.ok) {
+        type VoiceItem = { id?: string; name?: string; voice?: string }
+        const data = await response.json() as { data?: VoiceItem[] } | (string | VoiceItem)[]
+        
+        // Handle different response formats
+        if ('data' in data && Array.isArray(data.data)) {
+          // OpenAI-style format: { data: [{ name: "alloy" }, ...] }
+          return data.data
+            .filter((voice) => voice.id || voice.name)
+            .map((voice) => (voice.id || voice.name)!)
+        } else if (Array.isArray(data)) {
+          // Simple array format: ["alloy", "echo", ...] or [{ voice: "alloy" }, ...]
+          return data.map((item) => {
+            if (typeof item === 'string') return item
+            return item.name || item.voice || item.id
+          }).filter((v): v is string => typeof v === 'string')
+        }
+      }
+    } catch (error) {
+      logger.debug(`Failed to fetch voices from ${voiceEndpoint}:`, error)
+      continue
+    }
+  }
+  
+  return ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']
+}
+
 export async function cleanupExpiredCache(): Promise {
   try {
     await ensureCacheDir()
@@ -159,6 +286,84 @@ export function createTTSRoutes(db: Database) {
     }
   })
 
+  app.get('/models', async (c) => {
+    try {
+      const userId = c.req.query('userId') || 'default'
+      const forceRefresh = c.req.query('refresh') === 'true'
+      
+      const settingsService = new SettingsService(db)
+      const settings = settingsService.getSettings(userId)
+      const ttsConfig = settings.preferences.tts
+      
+      if (!ttsConfig?.apiKey || !ttsConfig?.endpoint) {
+        return c.json({ error: 'TTS not configured' }, 400)
+      }
+      
+      const cacheKey = generateDiscoveryCacheKey(ttsConfig.endpoint, ttsConfig.apiKey, 'models')
+      
+      // Check cache first (unless force refresh)
+      if (!forceRefresh) {
+        const cachedModels = await getCachedDiscovery(cacheKey)
+        if (cachedModels) {
+          logger.info(`Models cache hit for user ${userId}`)
+          return c.json({ models: cachedModels, cached: true })
+        }
+      }
+      
+      // Fetch from API
+      await ensureDiscoveryCacheDir()
+      logger.info(`Fetching TTS models for user ${userId}`)
+      
+      const models = await fetchAvailableModels(ttsConfig.endpoint, ttsConfig.apiKey)
+      await cacheDiscovery(cacheKey, models)
+      
+      logger.info(`Fetched ${models.length} TTS models`)
+      return c.json({ models, cached: false })
+    } catch (error) {
+      logger.error('Failed to fetch TTS models:', error)
+      return c.json({ error: 'Failed to fetch models' }, 500)
+    }
+  })
+
+  app.get('/voices', async (c) => {
+    try {
+      const userId = c.req.query('userId') || 'default'
+      const forceRefresh = c.req.query('refresh') === 'true'
+      
+      const settingsService = new SettingsService(db)
+      const settings = settingsService.getSettings(userId)
+      const ttsConfig = settings.preferences.tts
+      
+      if (!ttsConfig?.apiKey || !ttsConfig?.endpoint) {
+        return c.json({ error: 'TTS not configured' }, 400)
+      }
+      
+      const cacheKey = generateDiscoveryCacheKey(ttsConfig.endpoint, ttsConfig.apiKey, 'voices')
+      
+      // Check cache first (unless force refresh)
+      if (!forceRefresh) {
+        const cachedVoices = await getCachedDiscovery(cacheKey)
+        if (cachedVoices) {
+          logger.info(`Voices cache hit for user ${userId}`)
+          return c.json({ voices: cachedVoices, cached: true })
+        }
+      }
+      
+      // Fetch from API
+      await ensureDiscoveryCacheDir()
+      logger.info(`Fetching TTS voices for user ${userId}`)
+      
+      const voices = await fetchAvailableVoices(ttsConfig.endpoint, ttsConfig.apiKey)
+      await cacheDiscovery(cacheKey, voices)
+      
+      logger.info(`Fetched ${voices.length} TTS voices`)
+      return c.json({ voices, cached: false })
+    } catch (error) {
+      logger.error('Failed to fetch TTS voices:', error)
+      return c.json({ error: 'Failed to fetch voices' }, 500)
+    }
+  })
+
   app.get('/status', async (c) => {
     const userId = c.req.query('userId') || 'default'
     const settingsService = new SettingsService(db)
diff --git a/frontend/src/api/tts.ts b/frontend/src/api/tts.ts
new file mode 100644
index 00000000..8a0adc66
--- /dev/null
+++ b/frontend/src/api/tts.ts
@@ -0,0 +1,104 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { API_BASE_URL } from '@/config'
+
+async function fetchTTSModels(userId?: string, forceRefresh = false): Promise<{ models: string[]; cached: boolean }> {
+  const url = new URL(`${API_BASE_URL}/api/tts/models`)
+  if (userId) url.searchParams.set('userId', userId)
+  if (forceRefresh) url.searchParams.set('refresh', 'true')
+
+  const response = await fetch(url.toString())
+
+  if (!response.ok) {
+    let errorMessage = 'Failed to fetch TTS models'
+    try {
+      const errorData = await response.json()
+      errorMessage = errorData.error || errorMessage
+    } catch {
+      if (response.status === 400) errorMessage = 'TTS not configured'
+      else if (response.status === 401) errorMessage = 'Invalid TTS API key'
+      else if (response.status === 500) errorMessage = 'TTS service unavailable'
+    }
+    throw new Error(errorMessage)
+  }
+
+  return response.json()
+}
+
+async function fetchTTSVoices(userId?: string, forceRefresh = false): Promise<{ voices: string[]; cached: boolean }> {
+  const url = new URL(`${API_BASE_URL}/api/tts/voices`)
+  if (userId) url.searchParams.set('userId', userId)
+  if (forceRefresh) url.searchParams.set('refresh', 'true')
+
+  const response = await fetch(url.toString())
+
+  if (!response.ok) {
+    let errorMessage = 'Failed to fetch TTS voices'
+    try {
+      const errorData = await response.json()
+      errorMessage = errorData.error || errorMessage
+    } catch {
+      if (response.status === 400) errorMessage = 'TTS not configured'
+      else if (response.status === 401) errorMessage = 'Invalid TTS API key'
+      else if (response.status === 500) errorMessage = 'TTS service unavailable'
+    }
+    throw new Error(errorMessage)
+  }
+
+  return response.json()
+}
+
+export function useTTSModels(userId?: string, enabled = true) {
+  return useQuery({
+    queryKey: ['tts-models', userId],
+    queryFn: () => fetchTTSModels(userId),
+    enabled,
+    staleTime: 60 * 60 * 1000, // 1 hour
+    gcTime: 2 * 60 * 60 * 1000, // 2 hours
+  })
+}
+
+export function useTTSVoices(userId?: string, enabled = true) {
+  return useQuery({
+    queryKey: ['tts-voices', userId],
+    queryFn: () => fetchTTSVoices(userId),
+    enabled,
+    staleTime: 60 * 60 * 1000, // 1 hour
+    gcTime: 2 * 60 * 60 * 1000, // 2 hours
+  })
+}
+
+export function useTTSDiscovery(userId?: string) {
+  const queryClient = useQueryClient()
+
+  const refreshModels = async () => {
+    const result = await fetchTTSModels(userId, true)
+    queryClient.setQueryData(['tts-models', userId], result)
+    return result
+  }
+
+  const refreshVoices = async () => {
+    const result = await fetchTTSVoices(userId, true)
+    queryClient.setQueryData(['tts-voices', userId], result)
+    return result
+  }
+
+  const refreshAll = async () => {
+    const [models, voices] = await Promise.all([
+      refreshModels(),
+      refreshVoices()
+    ])
+    return { models, voices }
+  }
+
+  return {
+    refreshModels,
+    refreshVoices,
+    refreshAll,
+    invalidateModels: () => queryClient.invalidateQueries({ queryKey: ['tts-models', userId] }),
+    invalidateVoices: () => queryClient.invalidateQueries({ queryKey: ['tts-voices', userId] }),
+    invalidateAll: () => {
+      queryClient.invalidateQueries({ queryKey: ['tts-models', userId] })
+      queryClient.invalidateQueries({ queryKey: ['tts-voices', userId] })
+    }
+  }
+}
\ No newline at end of file
diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts
index 94e7ce24..9f87f902 100644
--- a/frontend/src/api/types/settings.ts
+++ b/frontend/src/api/types/settings.ts
@@ -11,6 +11,10 @@ export interface TTSConfig {
   voice: string
   model: string
   speed: number
+  availableVoices?: string[]
+  availableModels?: string[]
+  lastVoicesFetch?: number
+  lastModelsFetch?: number
 }
 
 export const DEFAULT_TTS_CONFIG: TTSConfig = {
@@ -20,6 +24,10 @@ export const DEFAULT_TTS_CONFIG: TTSConfig = {
   voice: 'alloy',
   model: 'tts-1',
   speed: 1.0,
+  availableVoices: [],
+  availableModels: [],
+  lastVoicesFetch: 0,
+  lastModelsFetch: 0,
 }
 
 export interface CustomAgent {
diff --git a/frontend/src/components/settings/TTSSettings.tsx b/frontend/src/components/settings/TTSSettings.tsx
index 7d507e20..8d8b5c64 100644
--- a/frontend/src/components/settings/TTSSettings.tsx
+++ b/frontend/src/components/settings/TTSSettings.tsx
@@ -4,13 +4,14 @@ import { zodResolver } from '@hookform/resolvers/zod'
 import { z } from 'zod'
 import { useSettings } from '@/hooks/useSettings'
 import { useTTS } from '@/hooks/useTTS'
-import { Loader2, Volume2, Square, CheckCircle, XCircle } from 'lucide-react'
+import { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/api/tts'
+import { Loader2, Volume2, Square, CheckCircle, XCircle, RefreshCw } from 'lucide-react'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Switch } from '@/components/ui/switch'
 import { Slider } from '@/components/ui/slider'
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
 import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
+import { Combobox } from '@/components/ui/combobox'
 import { DEFAULT_TTS_CONFIG } from '@/api/types/settings'
 
 const TEST_PHRASE = 'Text to speech is working correctly.'
@@ -37,7 +38,9 @@ type TTSFormValues = z.infer
 export function TTSSettings() {
   const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
   const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS()
+  const { refreshModels, refreshVoices, refreshAll } = useTTSDiscovery()
   const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle')
+  const [isRefreshingDiscovery, setIsRefreshingDiscovery] = useState(false)
   
   const form = useForm({
     resolver: zodResolver(ttsFormSchema),
@@ -47,9 +50,39 @@ 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
+  )
+  
+  const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices(
+    preferences?.tts?.enabled && preferences?.tts?.apiKey ? undefined : 'default',
+    watchEnabled && !!watchApiKey && !!watchEndpoint
+  )
+  
+  const availableModels = modelsData?.models || []
+  const availableVoices = voicesData?.voices || []
+  const modelsCached = modelsData?.cached || false
+  const voicesCached = voicesData?.cached || false
+  
+  const handleRefreshDiscovery = async () => {
+    setIsRefreshingDiscovery(true)
+    try {
+      await refreshAll()
+      await Promise.all([
+        refetchModels(),
+        refetchVoices()
+      ])
+    } finally {
+      setIsRefreshingDiscovery(false)
+    }
+  }
+  
   useEffect(() => {
     if (preferences?.tts) {
       reset({
@@ -179,29 +212,29 @@ export function TTSSettings() {
                 )}
               />
 
-               (
                   
                     Voice
-                    
+                    
+                       ({
+                          value: voice,
+                          label: voice
+                        }))}
+                        placeholder="Select a voice or type custom name..."
+                        disabled={!watchEnabled || isLoadingVoices}
+                        allowCustomValue={true}
+                      />
+                    
                     
-                      Voice for text-to-speech output
+                      {isLoadingVoices ? 'Loading available voices...' : 
+                       voicesCached ? `Available voices (${availableVoices.length}) - cached` :
+                       `Available voices (${availableVoices.length})`}
                     
                     
                   
@@ -214,19 +247,23 @@ export function TTSSettings() {
                 render={({ field }) => (
                   
                     Model
-                    
+                    
+                       ({
+                          value: model,
+                          label: model
+                        }))}
+                        placeholder="Select a model or type custom name..."
+                        disabled={!watchEnabled || isLoadingModels}
+                        allowCustomValue={true}
+                      />
+                    
                     
-                      TTS model quality
+                      {isLoadingModels ? 'Loading available models...' : 
+                       modelsCached ? `Available models (${availableModels.length}) - cached` :
+                       `Available models (${availableModels.length})`}
                     
                     
                   
@@ -262,6 +299,34 @@ export function TTSSettings() {
                 )}
               />
 
+              
+
+
Refresh Discovery Data
+

+ Force refresh available models and voices from the endpoint +

+
+ +
+
Test TTS
diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 5abaccec..22013f99 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -13,6 +13,10 @@ export const TTSConfigSchema = z.object({ voice: z.string(), model: z.string(), speed: z.number().min(0.25).max(4.0), + availableVoices: z.array(z.string()).optional(), + availableModels: z.array(z.string()).optional(), + lastVoicesFetch: z.number().optional(), + lastModelsFetch: z.number().optional(), }); export const CustomAgentSchema = z.object({ @@ -54,6 +58,10 @@ export const DEFAULT_TTS_CONFIG = { voice: "alloy", model: "tts-1", speed: 1.0, + availableVoices: [], + availableModels: [], + lastVoicesFetch: 0, + lastModelsFetch: 0, }; export const DEFAULT_USER_PREFERENCES = { From c7de65290a71b6fc7d9588bae9b0d716097513b4 Mon Sep 17 00:00:00 2001 From: Chris Scott Date: Mon, 15 Dec 2025 14:43:03 -0500 Subject: [PATCH 4/4] 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 --- backend/src/routes/settings.ts | 75 ++++++++++++ backend/src/routes/tts.ts | 78 +++++++++--- frontend/package.json | 1 + frontend/src/api/settings.ts | 5 + frontend/src/api/types/settings.ts | 68 ++--------- .../components/settings/GeneralSettings.tsx | 81 ++++++++++-- .../src/components/settings/TTSSettings.tsx | 115 +++++++++++++----- frontend/src/hooks/useTTS.ts | 90 ++++++++++---- pnpm-lock.yaml | 3 + shared/src/schemas/auth.ts | 4 +- shared/src/schemas/settings.ts | 44 +++++-- 11 files changed, 410 insertions(+), 154 deletions(-) diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index d759c0ea..154bb476 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -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 } diff --git a/backend/src/routes/tts.ts b/backend/src/routes/tts.ts index 1bc00666..571e0e09 100644 --- a/backend/src/routes/tts.ts +++ b/backend/src/routes/tts.ts @@ -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 { 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 { - // 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 { - // 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 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= 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) { diff --git a/frontend/package.json b/frontend/package.json index ece9f10b..c06f39d5 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 01c164fe..8bbd1328 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -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 + }, } diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 9f87f902..0de444e5 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -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 = { - 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, -} diff --git a/frontend/src/components/settings/GeneralSettings.tsx b/frontend/src/components/settings/GeneralSettings.tsx index 8186237a..69fbaef9 100644 --- a/frontend/src/components/settings/GeneralSettings.tsx +++ b/frontend/src/components/settings/GeneralSettings.tsx @@ -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 => { + 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 (
@@ -115,25 +138,61 @@ export function GeneralSettings() {
- setGitToken(e.target.value)} - onBlur={async () => { +
+ 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 && ( +
+ +
+ )} + +

Required for cloning private repos. Get one at github.com/settings/tokens

diff --git a/frontend/src/components/settings/TTSSettings.tsx b/frontend/src/components/settings/TTSSettings.tsx index 8d8b5c64..d5a7079f 100644 --- a/frontend/src/components/settings/TTSSettings.tsx +++ b/frontend/src/components/settings/TTSSettings.tsx @@ -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 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 ( -
+

Text-to-Speech

-