Merge pull request #26 from chriswritescode-dev/feature/TTS

Feature/tts
This commit is contained in:
Chris Scott authored and GitHub committed 2025-12-15 14:51:05 -05:00
commit f962c0fe09
14 files changed
+802 -129

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
}
+257 -2
View File
@@ -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<void> {
await mkdir(TTS_CACHE_DIR, { recursive: true })
}
async function ensureDiscoveryCacheDir(): Promise<void> {
await mkdir(DISCOVERY_CACHE_DIR, { recursive: true })
}
async function getCachedAudio(cacheKey: string): Promise<Buffer | null> {
try {
const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`)
@@ -104,6 +117,128 @@ async function cacheAudio(cacheKey: string, audioData: Buffer): Promise<void> {
await writeFile(filePath, audioData)
}
async function getCachedDiscovery(cacheKey: string): Promise<string[] | null> {
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<void> {
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<string[]> {
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<string[]> {
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<number> {
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)
+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
},
}
+104
View File
@@ -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] })
}
}
}
+10 -50
View File
@@ -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<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,
}
+2 -2
View File
@@ -49,7 +49,7 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) {
return (
<div className="relative">
<pre className={`bg-accent p-1 rounded-lg overflow-x-auto border border-border my-4 ${className || ''}`} {...props}>
<pre className={`bg-accent p-1 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
{children}
</pre>
<button
@@ -82,7 +82,7 @@ export function TextPart({ part }: TextPartProps) {
const isInline = !className || !className.includes('language-')
if (isInline) {
return (
<code className={className || "bg-accent px-1.5 py-0.5 rounded text-sm text-foreground"} {...props}>
<code className={className || "bg-accent px-1.5 py-0.5 rounded text-sm text-foreground break-all"} {...props}>
{children}
</code>
)
@@ -19,7 +19,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
const references = detectFileReferences(jsonString)
if (references.length === 0) {
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{jsonString}</pre>
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{jsonString}</pre>
}
const parts: React.ReactNode[] = []
@@ -51,7 +51,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
parts.push(jsonString.slice(lastIndex))
}
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{parts}</pre>
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
}
export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
@@ -224,10 +224,35 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
)}
{part.state.status === 'running' && (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
<>
{part.tool === 'bash' ? (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
<div className="text-muted-foreground">Command:</div>
<CopyButton
content={typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
title="Copy command"
/>
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
<span className="text-green-600 dark:text-green-400">$</span> {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
</div>
<div className="flex items-center gap-2 mt-2 text-xs text-yellow-600 dark:text-yellow-400">
<Loader2 className="w-3 h-3 animate-spin" />
<span>Running...</span>
</div>
</div>
) : (
<div className="text-sm">
<div className="text-muted-foreground mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
<div className="flex items-center gap-2 mt-2 text-xs text-yellow-600 dark:text-yellow-400">
<Loader2 className="w-3 h-3 animate-spin" />
<span>Running...</span>
</div>
</div>
)}
</>
)}
{part.state.status === 'completed' && (
@@ -241,7 +266,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
title="Copy command"
/>
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto">
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
<span className="text-green-600 dark:text-green-400">$</span> {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
</div>
</div>
@@ -253,7 +278,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
)}
<div className="text-sm">
<div className="text-muted-foreground mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap cursor-pointer hover:bg-accent/80 transition-colors"
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => 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' && (
<div className="text-sm">
<div className="text-red-600 dark:text-red-400 mb-1">Error:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto text-red-600 dark:text-red-300">
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words text-red-600 dark:text-red-300">
{part.state.error}
</pre>
</div>
@@ -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>
+158 -42
View File
@@ -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<typeof ttsFormSchema>
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<TTSFormValues>({
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 (
<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"
@@ -132,16 +189,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>
@@ -170,33 +227,47 @@ export function TTSSettings() {
)}
/>
<FormField
<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>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a voice" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="alloy">Alloy</SelectItem>
<SelectItem value="echo">Echo</SelectItem>
<SelectItem value="fable">Fable</SelectItem>
<SelectItem value="onyx">Onyx</SelectItem>
<SelectItem value="nova">Nova</SelectItem>
<SelectItem value="shimmer">Shimmer</SelectItem>
</SelectContent>
</Select>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
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}
/>
</FormControl>
<FormDescription>
Voice for text-to-speech output
{isLoadingVoices ? 'Loading available voices...' :
voicesCached ? `Available voices (${availableVoices.length}) - cached` :
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
@@ -205,20 +276,26 @@ export function TTSSettings() {
render={({ field }) => (
<FormItem>
<FormLabel>Model</FormLabel>
<Select onValueChange={field.onChange} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a model" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="tts-1">TTS-1 (faster)</SelectItem>
<SelectItem value="tts-1-hd">TTS-1-HD (higher quality)</SelectItem>
</SelectContent>
</Select>
<FormDescription>
TTS model quality
</FormDescription>
<FormControl>
<Combobox
value={field.value}
onChange={field.onChange}
options={availableModels.map((model: string) => ({
value: model,
label: model
}))}
placeholder="Select a model or type custom name..."
disabled={!watchEnabled || isLoadingModels}
allowCustomValue={true}
/>
</FormControl>
<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>
)}
@@ -253,6 +330,34 @@ export function TTSSettings() {
)}
/>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<div className="text-base font-medium">Refresh Discovery Data</div>
<p className="text-sm text-muted-foreground">
Force refresh available models and voices from the endpoint
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleRefreshDiscovery}
disabled={!watchEnabled || !watchApiKey || isRefreshingDiscovery}
>
{isRefreshingDiscovery ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Refreshing...
</>
) : (
<>
<RefreshCw className="h-4 w-4 mr-2" />
Refresh
</>
)}
</Button>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<div className="text-base font-medium">Test TTS</div>
@@ -265,6 +370,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>
)}
</div>
+25 -2
View File
@@ -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<string, unknown> }).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
}
})
+17
View File
@@ -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 {
+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)
+41 -11
View File
@@ -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<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({
@@ -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 = {