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

-