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 d4ffd59f..b0119724 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 const MAX_CACHE_SIZE_MB = 200 const MAX_CACHE_SIZE_BYTES = MAX_CACHE_SIZE_MB * 1024 * 1024 @@ -23,10 +25,21 @@ 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 }) } +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`) @@ -104,6 +117,128 @@ 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 { + const baseUrl = normalizeToBaseUrl(endpoint) + const endpointVariations = [ + `${baseUrl}/v1/models`, + `${baseUrl}/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.warn(`Failed to fetch models from ${modelEndpoint}:`, error) + continue + } + } + + return ['tts-1', 'tts-1-hd'] +} + +async function fetchAvailableVoices(endpoint: string, apiKey: string): Promise { + const baseUrl = normalizeToBaseUrl(endpoint) + const endpointVariations = [ + `${baseUrl}/v1/audio/voices`, + `${baseUrl}/voices`, + `${baseUrl}/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[]; voices?: string[] } | (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 ('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) => { + if (typeof item === 'string') return item + return item.name || item.voice || item.id + }).filter((v): v is string => typeof v === 'string') + } + } + } catch (error) { + logger.warn(`Failed to fetch voices from ${voiceEndpoint}:`, error) + continue + } + } + + return ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'] +} + export async function cleanupExpiredCache(): Promise { try { await ensureCacheDir() @@ -217,7 +352,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}`, @@ -237,7 +375,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()) @@ -263,6 +422,102 @@ 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) + + // 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) { + 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) + + // 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) { + 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/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/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..0de444e5 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -1,27 +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 -} - -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, -} - export interface CustomAgent { name: string description: string @@ -78,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/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 : ''}
@@ -253,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 : ''}
@@ -270,7 +295,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
           {part.state.status === 'error' && (
             
Error:
-
+              
                 {part.state.error}
               
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 5cdb8e17..4b8a2cbe 100644 --- a/frontend/src/components/settings/TTSSettings.tsx +++ b/frontend/src/components/settings/TTSSettings.tsx @@ -1,20 +1,31 @@ -import { useEffect } from 'react' +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 { useTTS } from '@/hooks/useTTS' -import { Loader2, Volume2, Square, XCircle } from 'lucide-react' +import { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/api/tts' +import { Loader2, Volume2, Square, 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.' +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'), @@ -37,6 +48,8 @@ type TTSFormValues = z.infer export function TTSSettings() { const { preferences, isLoading, updateSettings, isUpdating } = useSettings() const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS() + const { refreshAll } = useTTSDiscovery() + const [isRefreshingDiscovery, setIsRefreshingDiscovery] = useState(false) const form = useForm({ resolver: zodResolver(ttsFormSchema), @@ -44,10 +57,42 @@ export function TTSSettings() { }) const { reset, formState: { isDirty, isValid } } = form + // Fetch available models and voices when TTS is configured + const { data: modelsData, isLoading: isLoadingModels, refetch: refetchModels } = useTTSModels( + undefined, // Let the hook use default user + true // Always fetch if endpoint is available + ) + + const { data: voicesData, isLoading: isLoadingVoices, refetch: refetchVoices } = useTTSVoices( + undefined, // Let the hook use default user + true // Always fetch if endpoint is available + ) + + // 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 + const canTest = watchEnabled && watchApiKey && !isDirty && watchVoice && availableVoices.length > 0 + + const handleRefreshDiscovery = async () => { + setIsRefreshingDiscovery(true) + try { + await refreshAll() + await Promise.all([ + refetchModels(), + refetchVoices() + ]) + } finally { + setIsRefreshingDiscovery(false) + } + } useEffect(() => { if (preferences?.tts) { @@ -62,6 +107,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 }) } @@ -83,10 +140,10 @@ export function TTSSettings() { } return ( -
+

Text-to-Speech

- +
+
Test TTS
@@ -265,6 +370,17 @@ export function TTSSettings() {

{ttsError} + {ttsError.includes("not found") && availableVoices.length > 0 && ( + + Try selecting from: {availableVoices.slice(0, 5).join(", ")} + {availableVoices.length > 5 && ` +${availableVoices.length - 5} more`} + + )} +

+ )} + {!ttsError && watchEnabled && watchApiKey && watchEndpoint && availableVoices.length === 0 && !isLoadingVoices && ( +

+ Click "Refresh" to discover available voices, or check your API key and endpoint URL.

)}
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 { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d9a3cfb9..276fcd58 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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) diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 5abaccec..875cbda5 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({ @@ -21,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 = { + 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({ @@ -47,13 +73,17 @@ 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", speed: 1.0, + availableVoices: [], + availableModels: [], + lastVoicesFetch: 0, + lastModelsFetch: 0, }; export const DEFAULT_USER_PREFERENCES = {