From 9975be955e27ed5a4512810affa1f2eb11f436fe Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 24 Mar 2026 11:39:11 -0400 Subject: [PATCH] Refactor routes to use shared route-helpers utility Extracts parseId and handleServiceError into reusable helpers for consistent error handling and ID parsing across all routes. --- backend/src/routes/mcp-oauth-proxy.ts | 5 +- backend/src/routes/oauth.ts | 5 +- backend/src/routes/prompt-templates.ts | 35 +++----- backend/src/routes/schedules.ts | 82 +++++++---------- backend/src/routes/stt.ts | 118 ++++--------------------- backend/src/routes/title.ts | 4 +- backend/src/routes/tts.ts | 105 ++++------------------ backend/src/services/proxy.ts | 2 +- backend/src/utils/discovery-cache.ts | 105 ++++++++++++++++++++++ backend/src/utils/route-helpers.ts | 42 +++++++++ backend/test/routes/title.test.ts | 2 +- 11 files changed, 225 insertions(+), 280 deletions(-) create mode 100644 backend/src/utils/discovery-cache.ts create mode 100644 backend/src/utils/route-helpers.ts diff --git a/backend/src/routes/mcp-oauth-proxy.ts b/backend/src/routes/mcp-oauth-proxy.ts index e7a1ea37..9850f6dd 100644 --- a/backend/src/routes/mcp-oauth-proxy.ts +++ b/backend/src/routes/mcp-oauth-proxy.ts @@ -5,9 +5,8 @@ import path from 'path' import { readFile, writeFile, mkdir } from 'fs/promises' import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state' import { logger } from '../utils/logger' -import { getWorkspacePath, ENV } from '@opencode-manager/shared/config/env' - -const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` +import { getWorkspacePath } from '@opencode-manager/shared/config/env' +import { OPENCODE_SERVER_URL } from '../services/proxy' const StartSchema = z.object({ serverName: z.string(), diff --git a/backend/src/routes/oauth.ts b/backend/src/routes/oauth.ts index 16119dbf..83831582 100644 --- a/backend/src/routes/oauth.ts +++ b/backend/src/routes/oauth.ts @@ -1,8 +1,7 @@ import { Hono } from 'hono' import { z } from 'zod' -import { proxyRequest } from '../services/proxy' +import { proxyRequest, OPENCODE_SERVER_URL } from '../services/proxy' import { logger } from '../utils/logger' -import { ENV } from '@opencode-manager/shared/config/env' import { OAuthAuthorizeRequestSchema, OAuthAuthorizeResponseSchema, @@ -10,8 +9,6 @@ import { } from '../../../shared/src/schemas/auth' import { opencodeServerManager } from '../services/opencode-single-server' -const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` - export function createOAuthRoutes() { const app = new Hono() diff --git a/backend/src/routes/prompt-templates.ts b/backend/src/routes/prompt-templates.ts index 47080c3b..2b57b514 100644 --- a/backend/src/routes/prompt-templates.ts +++ b/backend/src/routes/prompt-templates.ts @@ -1,26 +1,11 @@ -import { Hono, type Context } from 'hono' +import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import { CreatePromptTemplateRequestSchema, UpdatePromptTemplateRequestSchema, } from '@opencode-manager/shared/schemas' import { PromptTemplateService, PromptTemplateServiceError } from '../services/prompt-templates' -import { getErrorMessage } from '../utils/error-utils' -import { logger } from '../utils/logger' - -function parseId(value: string | undefined): number { - const parsed = Number.parseInt(value ?? '', 10) - if (Number.isNaN(parsed)) throw new PromptTemplateServiceError('Invalid id', 400) - return parsed -} - -function handleTemplateError(c: Context, error: unknown, fallback: string) { - if (error instanceof PromptTemplateServiceError) { - return c.json({ error: error.message }, error.statusCode as 400 | 404 | 500) - } - logger.error(fallback, error) - return c.json({ error: getErrorMessage(error) }, 500) -} +import { parseId, handleServiceError } from '../utils/route-helpers' export function createPromptTemplateRoutes(database: Database) { const app = new Hono() @@ -30,7 +15,7 @@ export function createPromptTemplateRoutes(database: Database) { try { return c.json({ templates: service.list() }) } catch (error) { - return handleTemplateError(c, error, 'Failed to list templates') + return handleServiceError(c, error, 'Failed to list templates', PromptTemplateServiceError) } }) @@ -41,38 +26,38 @@ export function createPromptTemplateRoutes(database: Database) { const template = service.create(input) return c.json({ template }, 201) } catch (error) { - return handleTemplateError(c, error, 'Failed to create template') + return handleServiceError(c, error, 'Failed to create template', PromptTemplateServiceError) } }) app.get('/:id', (c) => { try { - const id = parseId(c.req.param('id')) + const id = parseId(c.req.param('id'), 'id', PromptTemplateServiceError) return c.json({ template: service.getById(id) }) } catch (error) { - return handleTemplateError(c, error, 'Failed to get template') + return handleServiceError(c, error, 'Failed to get template', PromptTemplateServiceError) } }) app.patch('/:id', async (c) => { try { - const id = parseId(c.req.param('id')) + const id = parseId(c.req.param('id'), 'id', PromptTemplateServiceError) const body = await c.req.json() const input = UpdatePromptTemplateRequestSchema.parse(body) const template = service.update(id, input) return c.json({ template }) } catch (error) { - return handleTemplateError(c, error, 'Failed to update template') + return handleServiceError(c, error, 'Failed to update template', PromptTemplateServiceError) } }) app.delete('/:id', (c) => { try { - const id = parseId(c.req.param('id')) + const id = parseId(c.req.param('id'), 'id', PromptTemplateServiceError) service.delete(id) return c.body(null, 204) } catch (error) { - return handleTemplateError(c, error, 'Failed to delete template') + return handleServiceError(c, error, 'Failed to delete template', PromptTemplateServiceError) } }) diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index 8d44d822..8c968338 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -1,30 +1,17 @@ -import { Hono, type Context } from 'hono' +import { Hono } from 'hono' import { CreateScheduleJobRequestSchema, UpdateScheduleJobRequestSchema, } from '@opencode-manager/shared/schemas' import { ScheduleService, ScheduleServiceError } from '../services/schedules' -import { getErrorMessage } from '../utils/error-utils' -import { logger } from '../utils/logger' - -function parseId(value: string | undefined, label: string): number { - if (!value) { - throw new ScheduleServiceError(`Missing ${label}`, 400) - } - - const parsed = Number.parseInt(value, 10) - if (Number.isNaN(parsed)) { - throw new ScheduleServiceError(`Invalid ${label}`, 400) - } - return parsed -} +import { parseId, handleServiceError } from '../utils/route-helpers' function parseRunListLimit(value: string | undefined): number { if (value === undefined) { return 20 } - const parsed = parseId(value, 'limit') + const parsed = parseId(value, 'limit', ScheduleServiceError) if (parsed < 1) { throw new ScheduleServiceError('Limit must be greater than 0', 400) } @@ -40,122 +27,115 @@ export function createScheduleRoutes(scheduleService: ScheduleService) { const jobs = scheduleService.listAllJobsWithRepos() return c.json({ jobs }) } catch (error) { - return handleScheduleError(c, error, 'Failed to list all schedules') + return handleServiceError(c, error, 'Failed to list all schedules', ScheduleServiceError) } }) app.get('/', (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) return c.json({ jobs: scheduleService.listJobs(repoId) }) } catch (error) { - return handleScheduleError(c, error, 'Failed to list schedules') + return handleServiceError(c, error, 'Failed to list schedules', ScheduleServiceError) } }) app.post('/', async (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) const body = await c.req.json() const input = CreateScheduleJobRequestSchema.parse(body) const job = scheduleService.createJob(repoId, input) return c.json({ job }, 201) } catch (error) { - return handleScheduleError(c, error, 'Failed to create schedule') + return handleServiceError(c, error, 'Failed to create schedule', ScheduleServiceError) } }) app.get('/:jobId', (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) const job = scheduleService.getJob(repoId, jobId) if (!job) { return c.json({ error: 'Schedule not found' }, 404) } return c.json({ job }) } catch (error) { - return handleScheduleError(c, error, 'Failed to get schedule') + return handleServiceError(c, error, 'Failed to get schedule', ScheduleServiceError) } }) app.patch('/:jobId', async (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) const body = await c.req.json() const input = UpdateScheduleJobRequestSchema.parse(body) const job = scheduleService.updateJob(repoId, jobId, input) return c.json({ job }) } catch (error) { - return handleScheduleError(c, error, 'Failed to update schedule') + return handleServiceError(c, error, 'Failed to update schedule', ScheduleServiceError) } }) app.delete('/:jobId', (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) scheduleService.deleteJob(repoId, jobId) return c.json({ success: true }) } catch (error) { - return handleScheduleError(c, error, 'Failed to delete schedule') + return handleServiceError(c, error, 'Failed to delete schedule', ScheduleServiceError) } }) app.post('/:jobId/run', async (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) const run = await scheduleService.runJob(repoId, jobId, 'manual') return c.json({ run }) } catch (error) { - return handleScheduleError(c, error, 'Failed to run schedule') + return handleServiceError(c, error, 'Failed to run schedule', ScheduleServiceError) } }) app.get('/:jobId/runs', (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) const limit = parseRunListLimit(c.req.query('limit')) return c.json({ runs: scheduleService.listRuns(repoId, jobId, limit) }) } catch (error) { - return handleScheduleError(c, error, 'Failed to list schedule runs') + return handleServiceError(c, error, 'Failed to list schedule runs', ScheduleServiceError) } }) app.get('/:jobId/runs/:runId', (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') - const runId = parseId(c.req.param('runId'), 'run id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) + const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError) return c.json({ run: scheduleService.getRun(repoId, jobId, runId) }) } catch (error) { - return handleScheduleError(c, error, 'Failed to get schedule run') + return handleServiceError(c, error, 'Failed to get schedule run', ScheduleServiceError) } }) app.post('/:jobId/runs/:runId/cancel', async (c) => { try { - const repoId = parseId(c.req.param('id'), 'repo id') - const jobId = parseId(c.req.param('jobId'), 'schedule id') - const runId = parseId(c.req.param('runId'), 'run id') + const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) + const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) + const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError) const run = await scheduleService.cancelRun(repoId, jobId, runId) return c.json({ run }) } catch (error) { - return handleScheduleError(c, error, 'Failed to cancel schedule run') + return handleServiceError(c, error, 'Failed to cancel schedule run', ScheduleServiceError) } }) return app } -function handleScheduleError(c: Context, error: unknown, fallbackMessage: string) { - if (error instanceof ScheduleServiceError) { - return c.json({ error: error.message }, error.status as 400 | 404 | 409 | 500 | 502) - } - logger.error(fallbackMessage + ':', error) - return c.json({ error: getErrorMessage(error) }, 500) -} diff --git a/backend/src/routes/stt.ts b/backend/src/routes/stt.ts index f94410df..f891c9a5 100644 --- a/backend/src/routes/stt.ts +++ b/backend/src/routes/stt.ts @@ -1,11 +1,15 @@ import { Hono } from 'hono' import { Database } from 'bun:sqlite' -import { createHash } from 'crypto' -import { mkdir, readFile, writeFile, stat, unlink } from 'fs/promises' -import { join } from 'path' import { SettingsService } from '../services/settings' import { logger } from '../utils/logger' -import { getWorkspacePath } from '@opencode-manager/shared/config/env' +import { + normalizeToBaseUrl, + ensureDiscoveryCacheDir, + getCachedDiscovery, + cacheDiscovery, + generateDiscoveryCacheKey, + fetchAvailableModels, +} from '../utils/discovery-cache' type STTConfigExtended = { enabled: boolean @@ -18,103 +22,6 @@ type STTConfigExtended = { lastModelsFetch?: number } -const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'stt-discovery') -const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 - -function normalizeToBaseUrl(endpoint: string): string { - return endpoint - .replace(/\/v1\/audio\/transcriptions$/, '') - .replace(/\/audio\/transcriptions$/, '') - .replace(/\/$/, '') -} - -async function ensureDiscoveryCacheDir(): Promise { - await mkdir(DISCOVERY_CACHE_DIR, { recursive: true }) -} - -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 { - await ensureDiscoveryCacheDir() - const filePath = join(DISCOVERY_CACHE_DIR, `${cacheKey}.json`) - await writeFile(filePath, JSON.stringify(data)) - } catch (error) { - logger.error(`Failed to cache STT discovery data for ${cacheKey}:`, error) - } -} - -function generateDiscoveryCacheKey(endpoint: string, apiKey: string, type: 'models'): string { - const hash = createHash('sha256') - hash.update(`stt|${endpoint}|${apiKey ? apiKey.substring(0, 8) : 'no-key'}|${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: { - ...(apiKey && { 'Authorization': `Bearer ${apiKey}` }), - 'Content-Type': 'application/json', - }, - }) - - if (response.ok) { - const data = await response.json() as { data?: { id?: string }[] } | unknown[] - - if ('data' in data && Array.isArray(data.data)) { - const sttModels = data.data - .filter((model) => model.id && typeof model.id === 'string') - .filter((model) => - model.id!.toLowerCase().includes('whisper') || - model.id!.toLowerCase().includes('transcri') - ) - .map((model) => model.id!) - - if (sttModels.length > 0) { - return sttModels - } - } else if (Array.isArray(data)) { - const filtered = data.filter((item): item is string => - typeof item === 'string' && - (item.toLowerCase().includes('whisper') || item.toLowerCase().includes('transcri')) - ) - if (filtered.length > 0) { - return filtered - } - } - } - } catch (error) { - logger.warn(`Failed to fetch STT models from ${modelEndpoint}:`, error) - continue - } - } - - return ['whisper-1'] -} - export function createSTTRoutes(db: Database) { const app = new Hono() @@ -248,7 +155,7 @@ export function createSTTRoutes(db: Database) { const cacheKey = generateDiscoveryCacheKey(sttConfig.endpoint, sttConfig.apiKey, 'models') if (!forceRefresh) { - const cachedModels = await getCachedDiscovery(cacheKey) + const cachedModels = await getCachedDiscovery(cacheKey) if (cachedModels) { logger.info(`STT models cache hit for user ${userId}`) return c.json({ models: cachedModels, cached: true }) @@ -258,7 +165,12 @@ export function createSTTRoutes(db: Database) { await ensureDiscoveryCacheDir() logger.info(`Fetching STT models for user ${userId}`) - const models = await fetchAvailableModels(sttConfig.endpoint, sttConfig.apiKey) + const models = await fetchAvailableModels( + sttConfig.endpoint, + sttConfig.apiKey, + /whisper|transcri/, + ['whisper-1'], + ) await cacheDiscovery(cacheKey, models) await settingsService.updateSettings({ diff --git a/backend/src/routes/title.ts b/backend/src/routes/title.ts index cb75f2f0..25c17f10 100644 --- a/backend/src/routes/title.ts +++ b/backend/src/routes/title.ts @@ -1,15 +1,13 @@ import { Hono } from 'hono' import { z } from 'zod' import { logger } from '../utils/logger' -import { ENV } from '@opencode-manager/shared/config/env' import { resolveOpenCodeModel } from '../services/opencode-models' +import { OPENCODE_SERVER_URL } from '../services/proxy' const TitleRequestSchema = z.object({ text: z.string().min(1).max(5000), sessionID: z.string().min(1) }) - -const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}` const TITLE_POLL_INTERVAL_MS = 1_000 const TITLE_POLL_TIMEOUT_MS = 30_000 diff --git a/backend/src/routes/tts.ts b/backend/src/routes/tts.ts index cdad1e6a..52df769c 100644 --- a/backend/src/routes/tts.ts +++ b/backend/src/routes/tts.ts @@ -7,11 +7,17 @@ import { join } from 'path' import { SettingsService } from '../services/settings' import { logger } from '../utils/logger' import { getWorkspacePath } from '@opencode-manager/shared/config/env' +import { + normalizeToBaseUrl, + ensureDiscoveryCacheDir, + getCachedDiscovery, + cacheDiscovery, + generateDiscoveryCacheKey, + fetchAvailableModels, +} from '../utils/discovery-cache' 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 @@ -25,21 +31,10 @@ 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`) @@ -117,80 +112,7 @@ 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) @@ -439,7 +361,7 @@ export function createTTSRoutes(db: Database) { // Check cache first (unless force refresh) if (!forceRefresh) { - const cachedModels = await getCachedDiscovery(cacheKey) + const cachedModels = await getCachedDiscovery(cacheKey) if (cachedModels) { logger.info(`Models cache hit for user ${userId}`) return c.json({ models: cachedModels, cached: true }) @@ -450,7 +372,12 @@ export function createTTSRoutes(db: Database) { await ensureDiscoveryCacheDir() logger.info(`Fetching TTS models for user ${userId}`) - const models = await fetchAvailableModels(ttsConfig.endpoint, ttsConfig.apiKey) + const models = await fetchAvailableModels( + ttsConfig.endpoint, + ttsConfig.apiKey, + /tts|audio|speech/, + ['tts-1', 'tts-1-hd'], + ) await cacheDiscovery(cacheKey, models) // Update user preferences with available models @@ -487,7 +414,7 @@ export function createTTSRoutes(db: Database) { // Check cache first (unless force refresh) if (!forceRefresh) { - const cachedVoices = await getCachedDiscovery(cacheKey) + const cachedVoices = await getCachedDiscovery(cacheKey) if (cachedVoices) { logger.info(`Voices cache hit for user ${userId}`) return c.json({ voices: cachedVoices, cached: true }) diff --git a/backend/src/services/proxy.ts b/backend/src/services/proxy.ts index 354f13ff..d7bfb3ba 100644 --- a/backend/src/services/proxy.ts +++ b/backend/src/services/proxy.ts @@ -1,7 +1,7 @@ import { logger } from '../utils/logger' import { ENV } from '@opencode-manager/shared/config/env' -const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` +export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}` export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise { try { diff --git a/backend/src/utils/discovery-cache.ts b/backend/src/utils/discovery-cache.ts new file mode 100644 index 00000000..4c76c40f --- /dev/null +++ b/backend/src/utils/discovery-cache.ts @@ -0,0 +1,105 @@ +import { createHash } from 'crypto' +import { mkdir, readFile, writeFile, stat, unlink } from 'fs/promises' +import { join } from 'path' +import { logger } from './logger' +import { getWorkspacePath } from '@opencode-manager/shared/config/env' + +const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'discovery') +const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 + +export function normalizeToBaseUrl(endpoint: string): string { + return endpoint + .replace(/\/v1\/audio\/speech$/, '') + .replace(/\/audio\/speech$/, '') + .replace(/\/v1\/audio\/transcriptions$/, '') + .replace(/\/audio\/transcriptions$/, '') + .replace(/\/$/, '') +} + +export async function ensureDiscoveryCacheDir(): Promise { + await mkdir(DISCOVERY_CACHE_DIR, { recursive: true }) +} + +export 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) as T + } catch { + return null + } +} + +export async function cacheDiscovery(cacheKey: string, data: T): Promise { + try { + await ensureDiscoveryCacheDir() + 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) + } +} + +export function generateDiscoveryCacheKey(baseUrl: string, apiKey: string, type: string): string { + const hash = createHash('sha256') + hash.update(`${baseUrl}|${apiKey}|${type}`) + return hash.digest('hex') +} + +export async function fetchAvailableModels( + baseUrl: string, + apiKey: string, + filterPattern: RegExp, + defaultModels: string[], +): Promise { + const normalizedUrl = normalizeToBaseUrl(baseUrl) + const endpointVariations = [ + `${normalizedUrl}/v1/models`, + `${normalizedUrl}/models`, + ] + + for (const modelEndpoint of endpointVariations) { + try { + const response = await fetch(modelEndpoint, { + headers: { + ...(apiKey && { 'Authorization': `Bearer ${apiKey}` }), + 'Content-Type': 'application/json', + }, + }) + + if (response.ok) { + const data = await response.json() as { data?: { id?: string }[] } | unknown[] + + if ('data' in data && Array.isArray(data.data)) { + const filtered = data.data + .filter((model) => model.id && typeof model.id === 'string') + .filter((model) => filterPattern.test(model.id!.toLowerCase())) + .map((model) => model.id!) + + if (filtered.length > 0) { + return filtered + } + } else if (Array.isArray(data)) { + const filtered = data.filter((item): item is string => + typeof item === 'string' && filterPattern.test(item.toLowerCase()) + ) + if (filtered.length > 0) { + return filtered + } + } + } + } catch (error) { + logger.warn(`Failed to fetch models from ${modelEndpoint}:`, error) + continue + } + } + + return defaultModels +} diff --git a/backend/src/utils/route-helpers.ts b/backend/src/utils/route-helpers.ts new file mode 100644 index 00000000..8e2ac000 --- /dev/null +++ b/backend/src/utils/route-helpers.ts @@ -0,0 +1,42 @@ +import type { Context } from 'hono' +import type { ContentfulStatusCode } from 'hono/utils/http-status' +import { getErrorMessage } from './error-utils' +import { logger } from './logger' + +export function parseId(value: string | undefined, label?: string, ErrorClass?: new (message: string, status: number) => Error): number { + if (!value) { + throw ErrorClass + ? new ErrorClass(`Missing ${label || 'id'}`, 400) + : new Error(`Missing ${label || 'id'}`) + } + + const parsed = Number.parseInt(value, 10) + if (Number.isNaN(parsed)) { + throw ErrorClass + ? new ErrorClass(`Invalid ${label || 'id'}`, 400) + : new Error(`Invalid ${label || 'id'}`) + } + return parsed +} + +interface ServiceError { + message: string + statusCode?: number + status?: number +} + +type ServiceErrorConstructor = new (message: string, statusOrStatusCode: number) => ServiceError + +export function handleServiceError( + c: Context, + error: unknown, + fallback: string, + ErrorClass: ServiceErrorConstructor, +) { + if (error instanceof ErrorClass) { + const status = (error as ServiceError).statusCode ?? (error as ServiceError).status ?? 500 + return c.json({ error: error.message }, status as ContentfulStatusCode) + } + logger.error(fallback, error) + return c.json({ error: getErrorMessage(error) }, 500) +} diff --git a/backend/test/routes/title.test.ts b/backend/test/routes/title.test.ts index 99275cd7..4bcc4761 100644 --- a/backend/test/routes/title.test.ts +++ b/backend/test/routes/title.test.ts @@ -20,7 +20,7 @@ vi.mock('../../src/utils/logger', () => ({ vi.mock('@opencode-manager/shared/config/env', () => ({ ENV: { - OPENCODE: { PORT: 5551 }, + OPENCODE: { PORT: 5551, HOST: '127.0.0.1' }, }, }))