From cb1714a4e086f704597a2eb903cccdd6ea4ecab8 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 26 Jan 2026 13:03:02 -0500 Subject: [PATCH] Merge dev: STT feature, git date fixes, and session improvements (#82) * fix session last active * Feature/sst (#81) * Use CSS field-sizing for textarea auto-height and abort STT recording on clear * Fix invalid date display in git commits * Use Unix timestamps for git log dates --- backend/src/index.ts | 2 + backend/src/routes/stt.ts | 292 ++++++++++ backend/src/services/git/GitLogService.ts | 12 +- backend/test/routes/stt.test.ts | 529 ++++++++++++++++++ .../test/services/git/GitLogService.test.ts | 82 ++- frontend/src/api/stt.ts | 65 +++ frontend/src/api/types/settings.ts | 7 +- .../src/components/message/PromptInput.tsx | 134 +++-- .../components/message/RecordingOverlay.tsx | 53 ++ .../components/settings/GeneralSettings.tsx | 5 + .../src/components/settings/STTSettings.tsx | 502 +++++++++++++++++ .../components/source-control/CommitsTab.tsx | 5 +- frontend/src/components/ui/combobox.tsx | 24 +- frontend/src/hooks/useSTT.ts | 290 ++++++++++ frontend/src/lib/audioRecorder.ts | 188 +++++++ frontend/src/lib/webSpeechRecognizer.ts | 323 +++++++++++ shared/src/schemas/settings.ts | 38 ++ 17 files changed, 2475 insertions(+), 76 deletions(-) create mode 100644 backend/src/routes/stt.ts create mode 100644 backend/test/routes/stt.test.ts create mode 100644 frontend/src/api/stt.ts create mode 100644 frontend/src/components/message/RecordingOverlay.tsx create mode 100644 frontend/src/components/settings/STTSettings.tsx create mode 100644 frontend/src/hooks/useSTT.ts create mode 100644 frontend/src/lib/audioRecorder.ts create mode 100644 frontend/src/lib/webSpeechRecognizer.ts diff --git a/backend/src/index.ts b/backend/src/index.ts index 889f3e75..e1a09568 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -11,6 +11,7 @@ import { GitAuthService } from './services/git-auth' import { createSettingsRoutes } from './routes/settings' import { createHealthRoutes } from './routes/health' import { createTTSRoutes, cleanupExpiredCache } from './routes/tts' +import { createSTTRoutes } from './routes/stt' import { createFileRoutes } from './routes/files' import { createProvidersRoutes } from './routes/providers' import { createOAuthRoutes } from './routes/oauth' @@ -269,6 +270,7 @@ protectedApi.route('/files', createFileRoutes()) protectedApi.route('/providers', createProvidersRoutes()) protectedApi.route('/oauth', createOAuthRoutes()) protectedApi.route('/tts', createTTSRoutes(db)) +protectedApi.route('/stt', createSTTRoutes(db)) protectedApi.route('/generate-title', createTitleRoutes()) protectedApi.route('/sse', createSSERoutes()) diff --git a/backend/src/routes/stt.ts b/backend/src/routes/stt.ts new file mode 100644 index 00000000..711c9563 --- /dev/null +++ b/backend/src/routes/stt.ts @@ -0,0 +1,292 @@ +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' + +type STTConfigExtended = { + enabled: boolean + provider: 'external' | 'builtin' + endpoint: string + apiKey: string + model: string + language: string + continuous: boolean + availableModels?: string[] + 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.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[] + + 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() + + app.post('/transcribe', async (c) => { + const abortController = new AbortController() + + c.req.raw.signal.addEventListener('abort', () => { + logger.info('STT request aborted by client') + abortController.abort() + }) + + try { + const userId = c.req.query('userId') || 'default' + + const settingsService = new SettingsService(db) + const settings = settingsService.getSettings(userId) + const sttConfig = settings.preferences.stt as STTConfigExtended | undefined + + if (!sttConfig?.enabled) { + return c.json({ error: 'STT is not enabled' }, 400) + } + + if (sttConfig.provider !== 'external') { + return c.json({ error: 'External STT provider is not selected' }, 400) + } + + if (!sttConfig.apiKey) { + return c.json({ error: 'STT API key is not configured' }, 400) + } + + if (!sttConfig.endpoint) { + return c.json({ error: 'STT endpoint is not configured' }, 400) + } + + const formData = await c.req.formData() + const audioFile = formData.get('audio') + + if (!audioFile || !(audioFile instanceof File)) { + return c.json({ error: 'No audio file provided' }, 400) + } + + const endpoint = sttConfig.endpoint + const apiKey = sttConfig.apiKey + const model = sttConfig.model || 'whisper-1' + const language = sttConfig.language + + if (abortController.signal.aborted) { + return new Response(null, { status: 499 }) + } + + logger.info(`STT transcription request: model=${model}, language=${language}, size=${audioFile.size}`) + + const baseUrl = normalizeToBaseUrl(endpoint) + const transcriptionEndpoint = `${baseUrl}/v1/audio/transcriptions` + + const apiFormData = new FormData() + apiFormData.append('file', audioFile, audioFile.name || 'audio.webm') + apiFormData.append('model', model) + + if (language && language !== 'auto') { + const langCode = language.split('-')[0] + if (langCode) { + apiFormData.append('language', langCode) + } + } + + const response = await fetch(transcriptionEndpoint, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiKey}`, + }, + body: apiFormData, + signal: abortController.signal, + }) + + if (!response.ok) { + const errorText = await response.text() + logger.error(`STT API error: ${response.status} - ${errorText}`) + const status = response.status >= 400 && response.status < 600 ? response.status as 400 | 500 : 500 + + let errorDetails = errorText + try { + const errorJson = JSON.parse(errorText) + if (errorJson.error?.message) { + errorDetails = errorJson.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: 'STT API request failed', + details: errorDetails, + }, status) + } + + const result = await response.json() as { text: string } + logger.info(`STT transcription successful: ${result.text.substring(0, 50)}...`) + + return c.json({ text: result.text }) + } catch (error) { + if (error instanceof Error && error.name === 'AbortError') { + return new Response(null, { status: 499 }) + } + logger.error('STT transcription failed:', error) + return c.json({ error: 'STT transcription failed' }, 500) + } + }) + + 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 sttConfig = settings.preferences.stt as STTConfigExtended | undefined + + if (!sttConfig?.apiKey || !sttConfig?.endpoint) { + return c.json({ error: 'STT not configured' }, 400) + } + + const cacheKey = generateDiscoveryCacheKey(sttConfig.endpoint, sttConfig.apiKey, 'models') + + if (!forceRefresh) { + const cachedModels = await getCachedDiscovery(cacheKey) + if (cachedModels) { + logger.info(`STT models cache hit for user ${userId}`) + return c.json({ models: cachedModels, cached: true }) + } + } + + await ensureDiscoveryCacheDir() + logger.info(`Fetching STT models for user ${userId}`) + + const models = await fetchAvailableModels(sttConfig.endpoint, sttConfig.apiKey) + await cacheDiscovery(cacheKey, models) + + await settingsService.updateSettings({ + stt: { + ...sttConfig, + availableModels: models, + lastModelsFetch: Date.now() + } as STTConfigExtended + }, userId) + + logger.info(`Fetched ${models.length} STT models`) + return c.json({ models, cached: false }) + } catch (error) { + logger.error('Failed to fetch STT models:', error) + return c.json({ error: 'Failed to fetch models' }, 500) + } + }) + + app.get('/status', async (c) => { + const userId = c.req.query('userId') || 'default' + const settingsService = new SettingsService(db) + const settings = settingsService.getSettings(userId) + const sttConfig = settings.preferences.stt as STTConfigExtended | undefined + + return c.json({ + enabled: sttConfig?.enabled || false, + configured: !!(sttConfig?.apiKey && sttConfig?.endpoint), + provider: sttConfig?.provider || 'builtin', + model: sttConfig?.model || 'whisper-1', + }) + }) + + return app +} diff --git a/backend/src/services/git/GitLogService.ts b/backend/src/services/git/GitLogService.ts index 3b2d2c5f..a655dc96 100644 --- a/backend/src/services/git/GitLogService.ts +++ b/backend/src/services/git/GitLogService.ts @@ -35,7 +35,7 @@ export class GitLogService { `--all`, `-n`, String(limit), - '--format=%H|%an|%ae|%ai|%s' + '--format=%H|%an|%ae|%at|%s' ] const logEnv = this.gitAuthService.getGitEnvironment(true) const output = await executeCommand(logArgs, { env: logEnv }) @@ -47,7 +47,7 @@ export class GitLogService { if (!line.trim()) continue const parts = line.split('|') - const [hash, authorName, authorEmail, date, ...messageParts] = parts + const [hash, authorName, authorEmail, timestamp, ...messageParts] = parts const message = messageParts.join('|') if (hash) { @@ -55,7 +55,7 @@ export class GitLogService { hash, authorName: authorName || '', authorEmail: authorEmail || '', - date: date || '', + date: timestamp || '', message: message || '' }) } @@ -99,7 +99,7 @@ export class GitLogService { '-C', repoPath, 'log', - '--format=%H|%an|%ae|%ai|%s', + '--format=%H|%an|%ae|%at|%s', hash, '-1' ] @@ -112,7 +112,7 @@ export class GitLogService { } const parts = output.trim().split('|') - const [commitHash, authorName, authorEmail, date, ...messageParts] = parts + const [commitHash, authorName, authorEmail, timestamp, ...messageParts] = parts const message = messageParts.join('|') if (!commitHash) { @@ -123,7 +123,7 @@ export class GitLogService { hash: commitHash, authorName: authorName || '', authorEmail: authorEmail || '', - date: date || '', + date: timestamp || '', message: message || '' } } catch (error: unknown) { diff --git a/backend/test/routes/stt.test.ts b/backend/test/routes/stt.test.ts new file mode 100644 index 00000000..275f86c7 --- /dev/null +++ b/backend/test/routes/stt.test.ts @@ -0,0 +1,529 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import * as fs from 'fs/promises' + +vi.mock('fs/promises', () => ({ + mkdir: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + stat: vi.fn(), + unlink: vi.fn(), +})) + +vi.mock('bun:sqlite', () => ({ + Database: vi.fn(), +})) + +const mockGetSettings = vi.fn() +const mockUpdateSettings = vi.fn() + +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn().mockImplementation(() => ({ + getSettings: mockGetSettings, + updateSettings: mockUpdateSettings, + })), +})) + +vi.mock('../../src/utils/logger', () => ({ + logger: { + info: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})) + +vi.mock('@opencode-manager/shared/config/env', () => ({ + getWorkspacePath: () => '/test/workspace', + ENV: { + WORKSPACE: { + BASE_PATH: '/test/workspace', + }, + }, +})) + +const mockMkdir = fs.mkdir as any +const mockReadFile = fs.readFile as any +const mockWriteFile = fs.writeFile as any +const mockStat = fs.stat as any +const mockUnlink = fs.unlink as any + +import { createSTTRoutes } from '../../src/routes/stt' + +describe('STT Routes', () => { + let mockDb: any + let sttApp: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + mockDb = {} as any + + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'external', + apiKey: 'test-api-key', + endpoint: 'https://api.openai.com', + model: 'whisper-1', + language: 'en-US', + continuous: false, + }, + }, + }) + + sttApp = createSTTRoutes(mockDb) + }) + + describe('createSTTRoutes', () => { + it('should create a Hono app with routes', () => { + expect(sttApp).toBeDefined() + expect(typeof sttApp.fetch).toBe('function') + }) + }) + + describe('GET /status', () => { + it('should return status with correct structure', async () => { + const req = new Request('http://localhost/status?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json).toHaveProperty('enabled') + expect(json).toHaveProperty('configured') + expect(json).toHaveProperty('provider') + expect(json).toHaveProperty('model') + }) + + it('should return enabled true when STT is enabled', async () => { + const req = new Request('http://localhost/status?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(json.enabled).toBe(true) + expect(json.configured).toBe(true) + expect(json.provider).toBe('external') + expect(json.model).toBe('whisper-1') + }) + + it('should return enabled false when STT is disabled', async () => { + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: false, + provider: 'builtin', + apiKey: '', + endpoint: '', + model: '', + language: 'en-US', + }, + }, + }) + + const req = new Request('http://localhost/status?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(json.enabled).toBe(false) + expect(json.configured).toBe(false) + }) + + it('should handle missing STT config gracefully', async () => { + mockGetSettings.mockReturnValue({ + preferences: {}, + }) + + const req = new Request('http://localhost/status?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.enabled).toBe(false) + expect(json.provider).toBe('builtin') + }) + }) + + describe('POST /transcribe', () => { + it('should reject when STT is disabled', async () => { + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: false, + provider: 'external', + apiKey: 'test-key', + endpoint: 'https://api.openai.com', + model: 'whisper-1', + }, + }, + }) + + const audioBlob = new Blob(['fake audio'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'test.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('STT is not enabled') + }) + + it('should reject when provider is builtin', async () => { + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'builtin', + apiKey: 'test-key', + endpoint: 'https://api.openai.com', + model: 'whisper-1', + }, + }, + }) + + const audioBlob = new Blob(['fake audio'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'test.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('External STT provider is not selected') + }) + + it('should reject when API key is missing', async () => { + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'external', + apiKey: '', + endpoint: 'https://api.openai.com', + model: 'whisper-1', + }, + }, + }) + + const audioBlob = new Blob(['fake audio'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'test.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('STT API key is not configured') + }) + + it('should reject when endpoint is missing', async () => { + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'external', + apiKey: 'test-key', + endpoint: '', + model: 'whisper-1', + }, + }, + }) + + const audioBlob = new Blob(['fake audio'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'test.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('STT endpoint is not configured') + }) + + it('should reject when no audio file provided', async () => { + const formData = new FormData() + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('No audio file provided') + }) + + it('should successfully transcribe when API returns success', async () => { + const originalFetch = globalThis.fetch + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ text: 'Hello, world!' }), + }) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const audioBlob = new Blob(['fake audio data'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'audio.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.text).toBe('Hello, world!') + expect(mockFetch).toHaveBeenCalledWith( + 'https://api.openai.com/v1/audio/transcriptions', + expect.objectContaining({ + method: 'POST', + headers: { + 'Authorization': 'Bearer test-api-key', + }, + }) + ) + + globalThis.fetch = originalFetch + }) + + it('should handle API errors gracefully', async () => { + const originalFetch = globalThis.fetch + const mockFetch = vi.fn().mockResolvedValue({ + ok: false, + status: 401, + text: async () => JSON.stringify({ error: { message: 'Invalid API key' } }), + }) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const audioBlob = new Blob(['fake audio data'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'audio.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(401) + expect(json.error).toBe('STT API request failed') + expect(json.details).toBe('Invalid API key') + + globalThis.fetch = originalFetch + }) + }) + + describe('GET /models', () => { + it('should reject when STT not configured', async () => { + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'external', + apiKey: '', + endpoint: '', + model: '', + }, + }, + }) + + const req = new Request('http://localhost/models?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.error).toBe('STT not configured') + }) + + it('should return cached models when available', async () => { + mockStat.mockResolvedValue({ + mtimeMs: Date.now() - 1000, + }) + mockReadFile.mockResolvedValue(JSON.stringify(['whisper-1', 'whisper-large'])) + + const req = new Request('http://localhost/models?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.models).toEqual(['whisper-1', 'whisper-large']) + expect(json.cached).toBe(true) + }) + + it('should fetch models from API when cache is expired', async () => { + const originalFetch = globalThis.fetch + mockStat.mockResolvedValue({ + mtimeMs: Date.now() - 2 * 60 * 60 * 1000, + }) + mockUnlink.mockResolvedValue(undefined) + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + data: [ + { id: 'whisper-1' }, + { id: 'gpt-4' }, + { id: 'whisper-large-v3' }, + ], + }), + }) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const req = new Request('http://localhost/models?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.models).toEqual(['whisper-1', 'whisper-large-v3']) + expect(json.cached).toBe(false) + + globalThis.fetch = originalFetch + }) + + it('should return default model when API fetch fails', async () => { + const originalFetch = globalThis.fetch + mockStat.mockRejectedValue(new Error('File not found')) + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + + const mockFetch = vi.fn().mockRejectedValue(new Error('Network error')) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const req = new Request('http://localhost/models?userId=test') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.models).toEqual(['whisper-1']) + + globalThis.fetch = originalFetch + }) + + it('should force refresh when refresh=true', async () => { + const originalFetch = globalThis.fetch + mockMkdir.mockResolvedValue(undefined) + mockWriteFile.mockResolvedValue(undefined) + + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + data: [{ id: 'whisper-1' }], + }), + }) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const req = new Request('http://localhost/models?userId=test&refresh=true') + const res = await sttApp.fetch(req) + const json = await res.json() as Record + + expect(res.status).toBe(200) + expect(json.cached).toBe(false) + expect(mockFetch).toHaveBeenCalled() + + globalThis.fetch = originalFetch + }) + }) + + describe('URL normalization', () => { + it('should normalize endpoint with trailing path', async () => { + const originalFetch = globalThis.fetch + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'external', + apiKey: 'test-api-key', + endpoint: 'https://api.openai.com/v1/audio/transcriptions', + model: 'whisper-1', + language: 'en-US', + }, + }, + }) + + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ text: 'Test' }), + }) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const audioBlob = new Blob(['fake audio data'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'audio.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + + await sttApp.fetch(req) + + expect(mockFetch).toHaveBeenCalledWith( + 'https://api.openai.com/v1/audio/transcriptions', + expect.anything() + ) + + globalThis.fetch = originalFetch + }) + + it('should handle endpoint with trailing slash', async () => { + const originalFetch = globalThis.fetch + mockGetSettings.mockReturnValue({ + preferences: { + stt: { + enabled: true, + provider: 'external', + apiKey: 'test-api-key', + endpoint: 'https://api.openai.com/', + model: 'whisper-1', + language: 'en-US', + }, + }, + }) + + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ text: 'Test' }), + }) + globalThis.fetch = mockFetch as unknown as typeof fetch + + const audioBlob = new Blob(['fake audio data'], { type: 'audio/webm' }) + const formData = new FormData() + formData.append('audio', audioBlob, 'audio.webm') + + const req = new Request('http://localhost/transcribe?userId=test', { + method: 'POST', + body: formData, + }) + + await sttApp.fetch(req) + + expect(mockFetch).toHaveBeenCalledWith( + 'https://api.openai.com/v1/audio/transcriptions', + expect.anything() + ) + + globalThis.fetch = originalFetch + }) + }) +}) diff --git a/backend/test/services/git/GitLogService.test.ts b/backend/test/services/git/GitLogService.test.ts index f06b22dd..8fb96751 100644 --- a/backend/test/services/git/GitLogService.test.ts +++ b/backend/test/services/git/GitLogService.test.ts @@ -61,8 +61,8 @@ describe('GitLogService', () => { getRepoByIdMock.mockReturnValue(mockRepo as any) executeCommandMock .mockResolvedValueOnce( - 'abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|First commit\n' + - 'def456|Jane Smith|jane@example.com|2024-01-02 13:00:00 +0000|Second commit' + 'abc123|John Doe|john@example.com|1704110400|First commit\n' + + 'def456|Jane Smith|jane@example.com|1704200400|Second commit' ) .mockResolvedValueOnce('') @@ -70,7 +70,7 @@ describe('GitLogService', () => { expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1) expect(executeCommandMock).toHaveBeenCalledWith( - ['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '10', '--format=%H|%an|%ae|%ai|%s'], + ['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '10', '--format=%H|%an|%ae|%at|%s'], { env: expect.any(Object) } ) expect(result).toHaveLength(2) @@ -78,7 +78,7 @@ describe('GitLogService', () => { hash: 'abc123', authorName: 'John Doe', authorEmail: 'john@example.com', - date: '2024-01-01 12:00:00 +0000', + date: '1704110400', message: 'First commit', unpushed: false, }) @@ -86,7 +86,7 @@ describe('GitLogService', () => { hash: 'def456', authorName: 'Jane Smith', authorEmail: 'jane@example.com', - date: '2024-01-02 13:00:00 +0000', + date: '1704200400', message: 'Second commit', unpushed: false, }) @@ -99,13 +99,13 @@ describe('GitLogService', () => { } getRepoByIdMock.mockReturnValue(mockRepo as any) executeCommandMock - .mockResolvedValueOnce('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|First commit') + .mockResolvedValueOnce('abc123|John Doe|john@example.com|1704110400|First commit') .mockResolvedValueOnce('') await service.getLog(1, database, 5) expect(executeCommandMock).toHaveBeenCalledWith( - ['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '5', '--format=%H|%an|%ae|%ai|%s'], + ['git', '-C', '/repos/test-repo', 'log', '--all', '-n', '5', '--format=%H|%an|%ae|%at|%s'], { env: expect.any(Object) } ) }) @@ -117,7 +117,7 @@ describe('GitLogService', () => { } getRepoByIdMock.mockReturnValue(mockRepo as any) executeCommandMock - .mockResolvedValueOnce('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|') + .mockResolvedValueOnce('abc123|John Doe|john@example.com|1704110400|') .mockResolvedValueOnce('') const result = await service.getLog(1, database, 10) @@ -133,7 +133,7 @@ describe('GitLogService', () => { } getRepoByIdMock.mockReturnValue(mockRepo as any) executeCommandMock - .mockResolvedValueOnce('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Multi|line commit') + .mockResolvedValueOnce('abc123|John Doe|john@example.com|1704110400|Multi|line commit') .mockResolvedValueOnce('') const result = await service.getLog(1, database, 10) @@ -164,7 +164,7 @@ describe('GitLogService', () => { } getRepoByIdMock.mockReturnValue(mockRepo as any) executeCommandMock - .mockResolvedValueOnce('\n\nabc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Test\n\n') + .mockResolvedValueOnce('\n\nabc123|John Doe|john@example.com|1704110400|Test\n\n') .mockResolvedValueOnce('') const result = await service.getLog(1, database, 10) @@ -180,7 +180,7 @@ describe('GitLogService', () => { } getRepoByIdMock.mockReturnValue(mockRepo as any) executeCommandMock - .mockResolvedValueOnce('|John Doe|john@example.com|2024-01-01 12:00:00 +0000|No hash') + .mockResolvedValueOnce('|John Doe|john@example.com|1704110400|No hash') .mockResolvedValueOnce('') const result = await service.getLog(1, database, 10) @@ -204,6 +204,56 @@ describe('GitLogService', () => { await expect(service.getLog(1, database, 10)).rejects.toThrow('Failed to get git log') }) + + it('handles commits with empty timestamps', async () => { + const mockRepo = { + id: 1, + localPath: 'test-repo', + } + getRepoByIdMock.mockReturnValue(mockRepo as any) + executeCommandMock + .mockResolvedValueOnce( + 'abc123|John Doe|john@example.com|1704110400|Valid commit\n' + + 'def456|Jane Smith|jane@example.com||Empty timestamp\n' + ) + .mockResolvedValueOnce('') + + const result = await service.getLog(1, database, 10) + + expect(result).toHaveLength(2) + expect(result[0]).toEqual({ + hash: 'abc123', + authorName: 'John Doe', + authorEmail: 'john@example.com', + date: '1704110400', + message: 'Valid commit', + unpushed: false, + }) + expect(result[1]?.date).toBe('') + }) + + it('handles commits with missing date field', async () => { + const mockRepo = { + id: 1, + localPath: 'test-repo', + } + getRepoByIdMock.mockReturnValue(mockRepo as any) + executeCommandMock + .mockResolvedValueOnce('abc123|John Doe|john@example.com') + .mockResolvedValueOnce('') + + const result = await service.getLog(1, database, 10) + + expect(result).toHaveLength(1) + expect(result[0]).toEqual({ + hash: 'abc123', + authorName: 'John Doe', + authorEmail: 'john@example.com', + date: '', + message: '', + unpushed: false, + }) + }) }) describe('getCommit', () => { @@ -213,20 +263,20 @@ describe('GitLogService', () => { localPath: 'test-repo', } getRepoByIdMock.mockReturnValue(mockRepo as any) - executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Test commit') + executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|1704110400|Test commit') const result = await service.getCommit(1, 'abc123', database) expect(getRepoByIdMock).toHaveBeenCalledWith(database, 1) expect(executeCommandMock).toHaveBeenCalledWith( - ['git', '-C', '/repos/test-repo', 'log', '--format=%H|%an|%ae|%ai|%s', 'abc123', '-1'], + ['git', '-C', '/repos/test-repo', 'log', '--format=%H|%an|%ae|%at|%s', 'abc123', '-1'], { env: expect.any(Object) } ) expect(result).toEqual({ hash: 'abc123', authorName: 'John Doe', authorEmail: 'john@example.com', - date: '2024-01-01 12:00:00 +0000', + date: '1704110400', message: 'Test commit', }) }) @@ -263,7 +313,7 @@ describe('GitLogService', () => { localPath: 'test-repo', } getRepoByIdMock.mockReturnValue(mockRepo as any) - executeCommandMock.mockResolvedValue('|John Doe|john@example.com|2024-01-01 12:00:00 +0000|Test') + executeCommandMock.mockResolvedValue('|John Doe|john@example.com|1704110400|Test') const result = await service.getCommit(1, 'abc123', database) @@ -276,7 +326,7 @@ describe('GitLogService', () => { localPath: 'test-repo', } getRepoByIdMock.mockReturnValue(mockRepo as any) - executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|2024-01-01 12:00:00 +0000|') + executeCommandMock.mockResolvedValue('abc123|John Doe|john@example.com|1704110400|') const result = await service.getCommit(1, 'abc123', database) diff --git a/frontend/src/api/stt.ts b/frontend/src/api/stt.ts new file mode 100644 index 00000000..f042872f --- /dev/null +++ b/frontend/src/api/stt.ts @@ -0,0 +1,65 @@ +import axios from 'axios' +import { API_BASE_URL } from '@/config' + +export interface STTModelsResponse { + models: string[] + cached: boolean +} + +export interface STTStatusResponse { + enabled: boolean + configured: boolean + provider: 'external' | 'builtin' + model: string +} + +export interface STTTranscribeResponse { + text: string +} + +export interface STTErrorResponse { + error: string + details?: string +} + +export const sttApi = { + getModels: async (userId = 'default', forceRefresh = false): Promise => { + const { data } = await axios.get(`${API_BASE_URL}/api/stt/models`, { + params: { userId, ...(forceRefresh && { refresh: 'true' }) }, + }) + return data + }, + + getStatus: async (userId = 'default'): Promise => { + const { data } = await axios.get(`${API_BASE_URL}/api/stt/status`, { + params: { userId }, + }) + return data + }, + + transcribe: async ( + audioBlob: Blob, + userId = 'default', + signal?: AbortSignal + ): Promise => { + const formData = new FormData() + + const extension = audioBlob.type.includes('webm') ? 'webm' : + audioBlob.type.includes('ogg') ? 'ogg' : + audioBlob.type.includes('mp4') ? 'm4a' : 'webm' + formData.append('audio', audioBlob, `recording.${extension}`) + + const { data } = await axios.post( + `${API_BASE_URL}/api/stt/transcribe`, + formData, + { + params: { userId }, + headers: { + 'Content-Type': 'multipart/form-data', + }, + signal, + } + ) + return data + }, +} diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 7bfab0af..76f00d20 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -1,14 +1,16 @@ import { DEFAULT_TTS_CONFIG, + DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, type TTSConfig, + type STTConfig, type OpenCodeConfigContent, } from '@opencode-manager/shared' -export type { TTSConfig, OpenCodeConfigContent } -export { DEFAULT_TTS_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY } +export type { TTSConfig, STTConfig, OpenCodeConfigContent } +export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY } export interface CustomCommand { name: string @@ -51,6 +53,7 @@ export interface UserPreferences { gitCredentials?: GitCredential[] gitIdentity?: GitIdentity tts?: TTSConfig + stt?: STTConfig repoOrder?: number[] } diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 19643c49..afe7b868 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -6,12 +6,13 @@ import { useFileSearch } from '@/hooks/useFileSearch' import { useModelSelection } from '@/hooks/useModelSelection' import { useVariants } from '@/hooks/useVariants' import { useSessionAgent } from '@/hooks/useSessionAgent' +import { useSTT } from '@/hooks/useSTT' import { useUserBash } from '@/stores/userBashStore' import { useMobile } from '@/hooks/useMobile' import { useSessionStatusForSession } from '@/stores/sessionStatusStore' import { usePermissions } from '@/contexts/EventContext' -import { ChevronDown, Upload, X } from 'lucide-react' +import { ChevronDown, Upload, X, Mic } from 'lucide-react' import { CommandSuggestions } from '@/components/command/CommandSuggestions' import { SquareFill } from '@/components/ui/square-fill' @@ -91,6 +92,18 @@ export const PromptInput = forwardRef(funct const [selectedAgent, setSelectedAgent] = useState(null) const [localMode, setLocalMode] = useState(null) const [isFocused, setIsFocused] = useState(false) + + const { + isRecording, + startRecording, + stopRecording, + abortRecording, + isSupported: sttSupported, + isEnabled: sttEnabled, + interimTranscript, + transcript, + clear: clearSTT, + } = useSTT() const textareaRef = useRef(null) const fileInputRef = useRef(null) @@ -98,11 +111,7 @@ export const PromptInput = forwardRef(funct useImperativeHandle(ref, () => ({ setPromptValue: (value: string) => { setPrompt(value) - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px` - textareaRef.current.focus() - } + textareaRef.current?.focus() }, clearPrompt: () => { setPrompt('') @@ -110,15 +119,17 @@ export const PromptInput = forwardRef(funct revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - textareaRef.current.focus() + if (isRecording) { + abortRecording() + } else { + clearSTT() } + textareaRef.current?.focus() }, triggerFileUpload: () => { fileInputRef.current?.click() } - }), [imageAttachments]) + }), [imageAttachments, clearSTT, isRecording, abortRecording]) const sendPrompt = useSendPrompt(opcodeUrl, directory) const sendShell = useSendShell(opcodeUrl, directory) const abortSession = useAbortSession(opcodeUrl, directory, sessionID) @@ -188,9 +199,7 @@ export const PromptInput = forwardRef(funct revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - } + clearSTT() return } @@ -204,9 +213,7 @@ export const PromptInput = forwardRef(funct }) setPrompt('') setIsBashMode(false) - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - } + clearSTT() return } @@ -220,9 +227,7 @@ export const PromptInput = forwardRef(funct if (command) { executeCommand(command, commandArgs?.trim() || '') setPrompt('') - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - } + clearSTT() return } } @@ -242,9 +247,7 @@ export const PromptInput = forwardRef(funct revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - } + clearSTT() } const handleStop = () => { @@ -269,8 +272,6 @@ export const PromptInput = forwardRef(funct if (textareaRef.current) { textareaRef.current.focus() textareaRef.current.setSelectionRange(cleanedTemplate.length, cleanedTemplate.length) - textareaRef.current.style.height = 'auto' - textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px` } }, 0) } else { @@ -351,6 +352,28 @@ export const PromptInput = forwardRef(funct setLocalMode(agent) } + const handleVoiceToggle = async () => { + if (isRecording) { + stopRecording() + } else { + await startRecording() + if (textareaRef.current) { + textareaRef.current.blur() + } + } + } + + useEffect(() => { + const textToUse = transcript || interimTranscript + if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') { + const trimmedTranscript = textToUse.trim() + if (trimmedTranscript && (prompt === '' || prompt === 'Processing...' || prompt === 'Recording...')) { + setPrompt(trimmedTranscript) + textareaRef.current?.focus() + } + } + }, [isRecording, interimTranscript, transcript, prompt]) + const addImageAttachment = (file: File) => { const generateId = () => { if (typeof crypto !== 'undefined' && crypto.randomUUID) { @@ -607,9 +630,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) setPrompt('') revokeBlobUrls(imageAttachments) setImageAttachments([]) - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - } + clearSTT() } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') { e.preventDefault() if (hasVariants) { @@ -632,11 +653,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) } setPrompt(value) - - if (textareaRef.current) { - textareaRef.current.style.height = 'auto' - textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px` - } if (isBashMode) { return @@ -744,7 +760,7 @@ return ( disabled={disabled} onFocus={() => setIsFocused(true)} onBlur={() => setIsFocused(false)} - className={`w-full bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg ${ + className={`w-full bg-muted/50 pl-2 md:pl-3 pr-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:bg-muted/70 resize-none min-h-[40px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg [field-sizing:content] ${ isBashMode ? 'border-purple-500/50 bg-purple-500/5 focus:bg-purple-500/10' : isDragging ? 'border-blue-500/50 border-dashed bg-blue-500/5' : '' @@ -839,19 +855,49 @@ return ( > + {sttEnabled && sttSupported && ( + )} + {isMobile && !prompt.trim() && imageAttachments.length === 0 && sttEnabled && sttSupported && !hasPendingPermissionForSession ? ( + + ) : ( + + )} diff --git a/frontend/src/components/message/RecordingOverlay.tsx b/frontend/src/components/message/RecordingOverlay.tsx new file mode 100644 index 00000000..da266ed7 --- /dev/null +++ b/frontend/src/components/message/RecordingOverlay.tsx @@ -0,0 +1,53 @@ +import { X, Mic } from 'lucide-react' +import { SquareFill } from '@/components/ui/square-fill' + +interface RecordingOverlayProps { + interimTranscript: string + onStop: () => void + onCancel: () => void +} + +export function RecordingOverlay({ + interimTranscript, + onStop, + onCancel +}: RecordingOverlayProps) { + return ( +
+
+
+ + Recording... +
+
+ +
+ {interimTranscript ? ( +

{interimTranscript}

+ ) : ( +

Listening...

+ )} +
+ +
+ + + +
+
+ ) +} diff --git a/frontend/src/components/settings/GeneralSettings.tsx b/frontend/src/components/settings/GeneralSettings.tsx index 66af8e6c..40162a9c 100644 --- a/frontend/src/components/settings/GeneralSettings.tsx +++ b/frontend/src/components/settings/GeneralSettings.tsx @@ -4,6 +4,7 @@ import { Label } from '@/components/ui/label' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Switch } from '@/components/ui/switch' import { TTSSettings } from './TTSSettings' +import { STTSettings } from './STTSettings' export function GeneralSettings() { const { preferences, isLoading, updateSettings, isUpdating } = useSettings() @@ -108,6 +109,10 @@ export function GeneralSettings() {
+ +
+ +
) } diff --git a/frontend/src/components/settings/STTSettings.tsx b/frontend/src/components/settings/STTSettings.tsx new file mode 100644 index 00000000..5e629a85 --- /dev/null +++ b/frontend/src/components/settings/STTSettings.tsx @@ -0,0 +1,502 @@ +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 { useSTT } from '@/hooks/useSTT' +import { isWebRecognitionSupported, getAvailableLanguages } from '@/lib/webSpeechRecognizer' +import { sttApi } from '@/api/stt' +import { Mic, Loader2, XCircle, CheckCircle2, RefreshCw, Eye, EyeOff } from 'lucide-react' +import { Switch } from '@/components/ui/switch' +import { SquareFill } from '@/components/ui/square-fill' +import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form' +import { Combobox } from '@/components/ui/combobox' +import { DEFAULT_STT_CONFIG } from '@/api/types/settings' + +const sttFormSchema = z.object({ + enabled: z.boolean(), + provider: z.enum(['external', 'builtin']), + endpoint: z.string(), + apiKey: z.string(), + model: z.string(), + language: z.string(), + continuous: z.boolean(), +}).superRefine((data, ctx) => { + if (!data.enabled) return + + if (data.provider === 'external') { + if (!data.endpoint || data.endpoint.trim().length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['endpoint'], + message: 'Endpoint is required for external provider', + }) + } + if (!data.apiKey || data.apiKey.trim().length === 0) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['apiKey'], + message: 'API key is required for external provider', + }) + } + } +}) + +type STTFormValues = z.infer + +export function STTSettings() { + const { preferences, updateSettings } = useSettings() + const { startRecording, stopRecording, abortRecording, isRecording, isProcessing, transcript, interimTranscript, error: sttError, isExternalProvider } = useSTT() + + const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle') + const [isTesting, setIsTesting] = useState(false) + const [testTranscript, setTestTranscript] = useState('') + const [testResult, setTestResult] = useState<'idle' | 'success' | 'failed'>('idle') + const [showApiKey, setShowApiKey] = useState(false) + const [availableModels, setAvailableModels] = useState(['whisper-1']) + const [isLoadingModels, setIsLoadingModels] = useState(false) + + const isWebSpeechAvailable = isWebRecognitionSupported() + + const form = useForm({ + resolver: zodResolver(sttFormSchema), + defaultValues: { + ...DEFAULT_STT_CONFIG, + model: DEFAULT_STT_CONFIG.model || 'whisper-1', + }, + }) + + const { reset, formState: { isDirty, isValid }, getValues, setValue } = form + + const availableLanguages = getAvailableLanguages() + + const watchEnabled = form.watch('enabled') + const watchProvider = form.watch('provider') + const watchLanguage = form.watch('language') + const watchContinuous = form.watch('continuous') + const watchEndpoint = form.watch('endpoint') + const watchApiKey = form.watch('apiKey') + const watchModel = form.watch('model') + + const fetchModels = async (forceRefresh = false) => { + if (!watchEndpoint || !watchApiKey) return + + setIsLoadingModels(true) + try { + const response = await sttApi.getModels('default', forceRefresh) + setAvailableModels(response.models.length > 0 ? response.models : ['whisper-1']) + + if (!watchModel && response.models.length > 0) { + setValue('model', response.models[0]) + } + } catch { + setAvailableModels(['whisper-1']) + } finally { + setIsLoadingModels(false) + } + } + + useEffect(() => { + if (watchProvider === 'external' && watchEndpoint && watchApiKey) { + const timer = setTimeout(() => { + fetchModels() + }, 500) + return () => clearTimeout(timer) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [watchProvider, watchEndpoint, watchApiKey]) + + const handleTest = async () => { + if (isTesting || isRecording) { + if (isExternalProvider) { + stopRecording() + } else { + abortRecording() + setIsTesting(false) + if (testTranscript) { + setTestResult('success') + } + } + return + } + + setTestTranscript('') + setTestResult('idle') + setIsTesting(true) + await startRecording() + } + + useEffect(() => { + if (isTesting && !isRecording && !isProcessing) { + if (transcript) { + setTestTranscript(transcript) + setTestResult('success') + setTimeout(() => { + setIsTesting(false) + }, 1000) + } else if (sttError) { + setTestResult('failed') + setIsTesting(false) + } + } + }, [isTesting, isRecording, isProcessing, transcript, sttError]) + + useEffect(() => { + if (isTesting && interimTranscript && interimTranscript !== 'Processing...' && interimTranscript !== 'Recording...') { + setTestTranscript(interimTranscript) + } + }, [isTesting, interimTranscript]) + + useEffect(() => { + if (preferences?.stt) { + const sttPrefs = preferences.stt as typeof preferences.stt & { model?: string; availableModels?: string[] } + reset({ + enabled: sttPrefs.enabled ?? DEFAULT_STT_CONFIG.enabled, + provider: sttPrefs.provider ?? DEFAULT_STT_CONFIG.provider, + endpoint: sttPrefs.endpoint ?? DEFAULT_STT_CONFIG.endpoint, + apiKey: sttPrefs.apiKey ?? DEFAULT_STT_CONFIG.apiKey, + model: sttPrefs.model ?? 'whisper-1', + language: sttPrefs.language ?? DEFAULT_STT_CONFIG.language, + continuous: sttPrefs.continuous ?? DEFAULT_STT_CONFIG.continuous, + }) + + if (sttPrefs.availableModels && sttPrefs.availableModels.length > 0) { + setAvailableModels(sttPrefs.availableModels) + } + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [preferences?.stt]) + + useEffect(() => { + const timer = setTimeout(() => { + if (isDirty && isValid) { + const formData = getValues() + updateSettings({ stt: formData }) + setSaveStatus('saved') + setTimeout(() => setSaveStatus('idle'), 1500) + } + }, 800) + + return () => clearTimeout(timer) + }, [watchEnabled, watchProvider, watchLanguage, watchContinuous, watchEndpoint, watchApiKey, watchModel, isDirty, isValid, getValues, updateSettings]) + + const canTestBuiltin = watchEnabled && watchProvider === 'builtin' && isWebSpeechAvailable + const canTestExternal = watchEnabled && watchProvider === 'external' && watchEndpoint && watchApiKey + const canTest = canTestBuiltin || canTestExternal + + return ( +
+
+

Speech-to-Text

+
+ {saveStatus === 'saved' && ( + <> + + Saved + + )} + {saveStatus === 'idle' && isDirty && isValid && ( + Unsaved changes + )} + {saveStatus === 'idle' && !isDirty && ( + All changes saved + )} +
+
+ +
+ + ( + +
+ Enable STT + + Allow speech-to-text input for voice messages + +
+ + + +
+ )} + /> + + + + {watchEnabled && ( + <> + ( + + Provider + + + + + {watchProvider === 'builtin' + ? "Uses browser's built-in speech recognition (free, requires Chrome/Safari/Edge)" + : "Uses OpenAI Whisper API or compatible endpoint (requires API key)" + } + + + + )} + /> + + {watchProvider === 'external' && ( + <> + ( + + API Endpoint + + + + + Base URL for the Whisper-compatible API (e.g., OpenAI, local Whisper server) + + + + )} + /> + + ( + + API Key + +
+ + +
+
+ + Your API key for the speech-to-text service + + +
+ )} + /> + + ( + +
+ Model + +
+ + ({ + value: model, + label: model, + }))} + placeholder="Select model..." + disabled={isLoadingModels} + allowCustomValue={true} + /> + + + The speech-to-text model to use (e.g., whisper-1) + + +
+ )} + /> + + )} + + {watchProvider === 'builtin' && ( + <> + ( + + Language + + ({ + value: lang, + label: lang.replace('-', ' - ') + }))} + placeholder="Select language..." + disabled={!isWebSpeechAvailable} + allowCustomValue={false} + /> + + + Select the language for speech recognition + + + + )} + /> + + ( + +
+ Continuous Mode + + Keep listening after a pause (experimental) + +
+ + + +
+ )} + /> + + )} + + {sttError && ( +
+
+ +
{sttError}
+
+
+ )} + +
+
+
Test STT
+

+ {watchProvider === 'external' + ? 'Record audio, then click Stop to transcribe' + : 'Verify your speech recognition is working' + } +

+ {(isTesting || isProcessing) && ( +
+

{testTranscript || (isProcessing ? 'Processing...' : 'Listening...')}

+ {isRecording && ( +
+ + Recording... +
+ )} + {isProcessing && !isRecording && ( +
+ + Transcribing... +
+ )} +
+ )} + {!isTesting && !isProcessing && testResult === 'success' && testTranscript && ( +
+
+ + Test successful +
+

{testTranscript}

+
+ )} + {!isTesting && !isProcessing && testResult === 'failed' && ( +
+
+ + Test failed - {sttError || 'no speech detected'} +
+
+ )} +
+ +
+ + )} + + +
+ ) +} diff --git a/frontend/src/components/source-control/CommitsTab.tsx b/frontend/src/components/source-control/CommitsTab.tsx index 71025a19..2e6718e3 100644 --- a/frontend/src/components/source-control/CommitsTab.tsx +++ b/frontend/src/components/source-control/CommitsTab.tsx @@ -8,8 +8,9 @@ interface CommitsTabProps { onSelectCommit?: (hash: string) => void } -function formatRelativeTime(dateString: string): string { - const date = new Date(dateString) +function formatRelativeTime(timestamp: string): string { + const date = new Date(parseInt(timestamp, 10) * 1000) + const now = new Date() const diffMs = now.getTime() - date.getTime() const diffSeconds = Math.floor(diffMs / 1000) diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx index adc674d3..1b92fb24 100644 --- a/frontend/src/components/ui/combobox.tsx +++ b/frontend/src/components/ui/combobox.tsx @@ -29,17 +29,26 @@ export function Combobox({ allowCustomValue = true, }: ComboboxProps) { const [isOpen, setIsOpen] = useState(false) - const [inputValue, setInputValue] = useState(value) + const [inputValue, setInputValue] = useState(() => { + const selectedOption = options.find(o => o.value === value) + return selectedOption?.label || value + }) const [selectedIndex, setSelectedIndex] = useState(0) + const [isUserTyping, setIsUserTyping] = useState(false) const inputRef = useRef(null) const listRef = useRef(null) const containerRef = useRef(null) useEffect(() => { - setInputValue(value) - }, [value]) + if (!isUserTyping) { + const selectedOption = options.find(o => o.value === value) + setInputValue(selectedOption?.label || value) + } + }, [value, options, isUserTyping]) - const filteredOptions = options.filter(option => + const isExactMatch = options.some(o => o.value === value || o.label === inputValue) + + const filteredOptions = (isExactMatch && !isUserTyping) ? options : options.filter(option => option.value.toLowerCase().includes(inputValue.toLowerCase()) || option.label.toLowerCase().includes(inputValue.toLowerCase()) || (option.description?.toLowerCase().includes(inputValue.toLowerCase())) @@ -87,11 +96,13 @@ export function Combobox({ }, [selectedIndex, isOpen]) const handleSelect = useCallback((optionValue: string) => { - setInputValue(optionValue) + const selectedOption = options.find(o => o.value === optionValue) + setInputValue(selectedOption?.label || optionValue) onChange(optionValue) setIsOpen(false) + setIsUserTyping(false) inputRef.current?.blur() - }, [onChange]) + }, [onChange, options]) const handleKeyDown = useCallback((e: React.KeyboardEvent) => { if (!isOpen) { @@ -137,6 +148,7 @@ export function Combobox({ const newValue = e.target.value setInputValue(newValue) setIsOpen(true) + setIsUserTyping(true) if (allowCustomValue) { onChange(newValue) } diff --git a/frontend/src/hooks/useSTT.ts b/frontend/src/hooks/useSTT.ts new file mode 100644 index 00000000..f6cf84a0 --- /dev/null +++ b/frontend/src/hooks/useSTT.ts @@ -0,0 +1,290 @@ +import { useState, useEffect, useRef, useCallback } from 'react' +import { useSettings } from '@/hooks/useSettings' +import { getWebSpeechRecognizer, isWebRecognitionSupported, type SpeechRecognitionOptions, type SpeechRecognitionResult, type RecognitionState } from '@/lib/webSpeechRecognizer' +import { AudioRecorder } from '@/lib/audioRecorder' +import { sttApi } from '@/api/stt' +import { DEFAULT_STT_CONFIG } from '@/api/types/settings' + +export function useSTT(userId = 'default') { + const { preferences } = useSettings(userId) + const [isRecording, setIsRecording] = useState(false) + const [isProcessing, setIsProcessing] = useState(false) + const [isError, setIsError] = useState(false) + const [error, setError] = useState(null) + const [transcript, setTranscript] = useState('') + const [interimTranscript, setInterimTranscript] = useState('') + const [state, setState] = useState('idle') + + const recognizer = useRef(getWebSpeechRecognizer()) + const audioRecorder = useRef(null) + const hasShownPermissionError = useRef(false) + const abortControllerRef = useRef(null) + const userIdRef = useRef(userId) + + useEffect(() => { + userIdRef.current = userId + }, [userId]) + + const isEnabled = preferences?.stt?.enabled ?? false + const config = preferences?.stt ?? DEFAULT_STT_CONFIG + const isExternalProvider = config.provider === 'external' + + const isSupported = isExternalProvider + ? true + : isWebRecognitionSupported() + + useEffect(() => { + if (!isEnabled || isExternalProvider) { + return + } + + if (!isWebRecognitionSupported()) { + return + } + + const rec = recognizer.current + + rec.onResult((result: SpeechRecognitionResult) => { + setIsProcessing(false) + setTranscript((prev) => prev + ' ' + result.transcript) + setIsRecording(false) + }) + + rec.onInterimResult((interim: string) => { + setInterimTranscript(interim.trim()) + }) + + rec.onError((errorMessage: string) => { + setIsProcessing(false) + setIsRecording(false) + setIsError(true) + setError(errorMessage) + + if (!hasShownPermissionError.current && errorMessage.includes('denied')) { + hasShownPermissionError.current = true + } + + setTimeout(() => { + setIsError(false) + setError(null) + }, 3000) + }) + + rec.onEnd(() => { + setIsRecording(false) + setIsProcessing(false) + setState('idle') + }) + + rec.onStart(() => { + setIsRecording(true) + setState('listening') + setInterimTranscript('') + }) + + return () => { + rec.clearCallbacks() + } + }, [isEnabled, isExternalProvider]) + + const setupAudioRecorder = useCallback((recorder: AudioRecorder) => { + recorder.setOnStateChange((recState) => { + if (recState === 'recording') { + setIsRecording(true) + setState('listening') + setInterimTranscript('Recording...') + } else if (recState === 'stopped') { + setIsRecording(false) + } else if (recState === 'error') { + setIsRecording(false) + setIsProcessing(false) + setState('idle') + } else if (recState === 'idle') { + setState('idle') + } + }) + + recorder.setOnError((errorMessage) => { + setIsProcessing(false) + setIsRecording(false) + setIsError(true) + setError(errorMessage) + + setTimeout(() => { + setIsError(false) + setError(null) + }, 3000) + }) + + recorder.setOnDataAvailable(async (blob) => { + setInterimTranscript('Processing...') + setIsProcessing(true) + + try { + abortControllerRef.current = new AbortController() + const result = await sttApi.transcribe( + blob, + userIdRef.current || 'default', + abortControllerRef.current.signal + ) + + setTranscript((prev) => { + const prevTrimmed = prev.trim() + const newText = result.text.trim() + return prevTrimmed ? `${prevTrimmed} ${newText}` : newText + }) + setInterimTranscript('') + } catch (err) { + if (err instanceof Error && err.name === 'CanceledError') { + return + } + + setIsError(true) + const errorMessage = err instanceof Error ? err.message : 'Transcription failed' + setError(errorMessage) + + setTimeout(() => { + setIsError(false) + setError(null) + }, 3000) + } finally { + setIsProcessing(false) + setState('idle') + abortControllerRef.current = null + } + }) + }, []) + + useEffect(() => { + if (!isEnabled || !isExternalProvider) { + return + } + + if (!audioRecorder.current) { + audioRecorder.current = new AudioRecorder() + } + + setupAudioRecorder(audioRecorder.current) + + return () => { + if (audioRecorder.current) { + audioRecorder.current.abort() + } + } + }, [isEnabled, isExternalProvider, setupAudioRecorder]) + + const startRecording = useCallback(async () => { + if (!isSupported) { + setError('Speech recognition is not supported in this browser') + setIsError(true) + return + } + + if (!isEnabled) { + setError('Speech recognition is not enabled') + setIsError(true) + return + } + + setTranscript('') + setInterimTranscript('') + setIsError(false) + setError(null) + hasShownPermissionError.current = false + + if (isExternalProvider) { + if (!audioRecorder.current) { + audioRecorder.current = new AudioRecorder() + setupAudioRecorder(audioRecorder.current) + } + + try { + setIsProcessing(true) + await audioRecorder.current.start() + setIsProcessing(false) + } catch (err) { + setIsProcessing(false) + setIsError(true) + setError(err instanceof Error ? err.message : 'Failed to start recording') + } + } else { + const options: SpeechRecognitionOptions = { + language: config.language, + continuous: config.continuous, + interimResults: true, + maxAlternatives: 1, + } + + try { + setIsProcessing(true) + await recognizer.current.start(options) + } catch (err) { + setIsProcessing(false) + setIsError(true) + setError(err instanceof Error ? err.message : 'Failed to start recording') + } + } + }, [isSupported, isEnabled, isExternalProvider, config.language, config.continuous, setupAudioRecorder]) + + const stopRecording = useCallback(() => { + if (isExternalProvider && audioRecorder.current) { + audioRecorder.current.stop() + setIsProcessing(true) + } else { + recognizer.current.stop() + setIsProcessing(true) + } + }, [isExternalProvider]) + + const abortRecording = useCallback(() => { + if (isExternalProvider && audioRecorder.current) { + audioRecorder.current.abort() + } else { + recognizer.current.abort() + } + + if (abortControllerRef.current) { + abortControllerRef.current.abort() + abortControllerRef.current = null + } + + setTranscript('') + setInterimTranscript('') + setIsRecording(false) + setIsProcessing(false) + setState('idle') + }, [isExternalProvider]) + + const reset = useCallback(() => { + setTranscript('') + setInterimTranscript('') + setIsError(false) + setError(null) + setIsRecording(false) + setIsProcessing(false) + setState('idle') + }, []) + + const clear = useCallback(() => { + setTranscript('') + setInterimTranscript('') + }, []) + + return { + isRecording, + isProcessing, + isError, + error, + transcript, + interimTranscript, + state, + isSupported, + isEnabled, + isExternalProvider, + startRecording, + stopRecording, + abortRecording, + reset, + clear, + } +} diff --git a/frontend/src/lib/audioRecorder.ts b/frontend/src/lib/audioRecorder.ts new file mode 100644 index 00000000..5f566fe8 --- /dev/null +++ b/frontend/src/lib/audioRecorder.ts @@ -0,0 +1,188 @@ +export type AudioRecorderState = 'idle' | 'recording' | 'stopped' | 'error' + +export interface AudioRecorderOptions { + mimeType?: string + audioBitsPerSecond?: number +} + +const DEFAULT_OPTIONS: AudioRecorderOptions = { + mimeType: 'audio/webm;codecs=opus', + audioBitsPerSecond: 128000, +} + +function getSupportedMimeType(): string { + const mimeTypes = [ + 'audio/webm;codecs=opus', + 'audio/webm', + 'audio/ogg;codecs=opus', + 'audio/mp4', + ] + + for (const mimeType of mimeTypes) { + if (MediaRecorder.isTypeSupported(mimeType)) { + return mimeType + } + } + + return 'audio/webm' +} + +export class AudioRecorder { + private mediaRecorder: MediaRecorder | null = null + private audioChunks: Blob[] = [] + private stream: MediaStream | null = null + private state: AudioRecorderState = 'idle' + private options: AudioRecorderOptions + private isAborted: boolean = false + + private onStateChange?: (state: AudioRecorderState) => void + private onError?: (error: string) => void + private onDataAvailable?: (blob: Blob) => void + + constructor(options: AudioRecorderOptions = {}) { + this.options = { ...DEFAULT_OPTIONS, ...options } + } + + static isSupported(): boolean { + return !!( + typeof navigator !== 'undefined' && + navigator.mediaDevices && + typeof navigator.mediaDevices.getUserMedia === 'function' && + typeof window !== 'undefined' && + typeof window.MediaRecorder === 'function' + ) + } + + getState(): AudioRecorderState { + return this.state + } + + setOnStateChange(callback: (state: AudioRecorderState) => void): void { + this.onStateChange = callback + } + + setOnError(callback: (error: string) => void): void { + this.onError = callback + } + + setOnDataAvailable(callback: (blob: Blob) => void): void { + this.onDataAvailable = callback + } + + private setState(newState: AudioRecorderState): void { + this.state = newState + this.onStateChange?.(newState) + } + + async start(): Promise { + if (!AudioRecorder.isSupported()) { + this.setState('error') + this.onError?.('Audio recording is not supported in this browser') + throw new Error('Audio recording is not supported in this browser') + } + + try { + this.audioChunks = [] + this.isAborted = false + + this.stream = await navigator.mediaDevices.getUserMedia({ + audio: { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + }, + }) + + const mimeType = getSupportedMimeType() + this.mediaRecorder = new MediaRecorder(this.stream, { + mimeType, + audioBitsPerSecond: this.options.audioBitsPerSecond, + }) + + this.mediaRecorder.ondataavailable = (event) => { + if (event.data.size > 0) { + this.audioChunks.push(event.data) + } + } + + this.mediaRecorder.onstop = () => { + if (!this.isAborted) { + const mimeType = this.mediaRecorder?.mimeType || 'audio/webm' + const audioBlob = new Blob(this.audioChunks, { type: mimeType }) + this.onDataAvailable?.(audioBlob) + this.setState('stopped') + } + this.cleanup() + } + + this.mediaRecorder.onerror = () => { + this.setState('error') + this.onError?.('Recording error occurred') + this.cleanup() + } + + this.mediaRecorder.start(100) + this.setState('recording') + } catch (error) { + this.setState('error') + + if (error instanceof DOMException) { + if (error.name === 'NotAllowedError') { + this.onError?.('Microphone permission denied') + } else if (error.name === 'NotFoundError') { + this.onError?.('No microphone found') + } else { + this.onError?.(`Microphone error: ${error.message}`) + } + } else { + this.onError?.('Failed to start recording') + } + + throw error + } + } + + stop(): void { + if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') { + this.mediaRecorder.stop() + } + } + + abort(): void { + this.isAborted = true + this.audioChunks = [] + if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') { + this.mediaRecorder.stop() + } + this.setState('idle') + } + + private cleanup(): void { + if (this.stream) { + this.stream.getTracks().forEach(track => track.stop()) + this.stream = null + } + this.mediaRecorder = null + } + + getRecordingBlob(): Blob | null { + if (this.audioChunks.length === 0) { + return null + } + const mimeType = this.mediaRecorder?.mimeType || 'audio/webm' + return new Blob(this.audioChunks, { type: mimeType }) + } +} + +let recorderInstance: AudioRecorder | null = null + +export function getAudioRecorder(): AudioRecorder { + if (!recorderInstance) { + recorderInstance = new AudioRecorder() + } + return recorderInstance +} + +export function isAudioRecordingSupported(): boolean { + return AudioRecorder.isSupported() +} diff --git a/frontend/src/lib/webSpeechRecognizer.ts b/frontend/src/lib/webSpeechRecognizer.ts new file mode 100644 index 00000000..ece176f2 --- /dev/null +++ b/frontend/src/lib/webSpeechRecognizer.ts @@ -0,0 +1,323 @@ +/** + * Web Speech API recognizer - Browser-native STT without external dependencies + */ + +export interface SpeechRecognitionResult { + transcript: string; + isFinal: boolean; + confidence: number; +} + +export interface SpeechRecognitionOptions { + language?: string; + continuous?: boolean; + interimResults?: boolean; + maxAlternatives?: number; +} + +export type RecognitionState = 'idle' | 'listening' | 'processing' | 'error'; + +interface SpeechRecognition extends EventTarget { + continuous: boolean; + interimResults: boolean; + lang: string; + maxAlternatives: number; + onstart: (event: Event) => void; + onend: (event: Event) => void; + onerror: (event: SpeechRecognitionErrorEvent) => void; + onresult: (event: SpeechRecognitionEvent) => void; + start: () => void; + stop: () => void; + abort: () => void; +} + +interface SpeechRecognitionEvent extends Event { + resultIndex: number; + results: SpeechRecognitionResultList; +} + +interface SpeechRecognitionResultList { + length: number; + item(index: number): SpeechRecognitionAlternativeList; + [index: number]: SpeechRecognitionAlternativeList; +} + +interface SpeechRecognitionAlternativeList { + length: number; + item(index: number): SpeechRecognitionAlternative; + isFinal: boolean; + [index: number]: SpeechRecognitionAlternative; +} + +interface SpeechRecognitionAlternative { + transcript: string; + confidence: number; +} + +interface SpeechRecognitionErrorEvent extends Event { + error: string; + message?: string; +} + +declare global { + interface Window { + SpeechRecognition?: { + new (): SpeechRecognition; + }; + webkitSpeechRecognition?: { + new (): SpeechRecognition; + }; + } +} + +export class WebSpeechRecognizer { + private recognition: SpeechRecognition | null = null; + private isListening = false; + private state: RecognitionState = 'idle'; + private onResultCallbacks: ((result: SpeechRecognitionResult) => void)[] = []; + private onInterimResultCallbacks: ((transcript: string) => void)[] = []; + private onErrorCallbacks: ((error: string) => void)[] = []; + private onEndCallbacks: (() => void)[] = []; + private onStartCallbacks: (() => void)[] = []; + private finalTranscript = ''; + + constructor() { + if (typeof window === 'undefined') return; + + const RecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition; + + if (RecognitionClass) { + this.recognition = new RecognitionClass(); + this.recognition.continuous = false; + this.recognition.interimResults = true; + this.recognition.maxAlternatives = 1; + + this.recognition.onstart = () => { + this.isListening = true; + this.state = 'listening'; + this.onStartCallbacks.forEach((cb) => cb()); + }; + + this.recognition.onresult = (event: SpeechRecognitionEvent) => { + let interimTranscript = ''; + + for (let i = event.resultIndex; i < event.results.length; i++) { + const result = event.results[i]; + + if (result.isFinal) { + const finalResult: SpeechRecognitionResult = { + transcript: result[0].transcript, + isFinal: true, + confidence: result[0].confidence || 1.0, + }; + + this.finalTranscript = result[0].transcript; + this.onResultCallbacks.forEach((cb) => cb(finalResult)); + } else { + interimTranscript += result[0].transcript; + } + } + + if (interimTranscript) { + this.onInterimResultCallbacks.forEach((cb) => cb(this.finalTranscript + ' ' + interimTranscript)); + } + }; + + this.recognition.onerror = (event: SpeechRecognitionErrorEvent) => { + this.state = 'error'; + this.isListening = false; + + let errorMsg = event.error || 'Unknown error'; + + switch (event.error) { + case 'no-speech': + errorMsg = 'No speech detected. Please try again.'; + break; + case 'audio-capture': + errorMsg = 'No microphone found. Please check your audio input.'; + break; + case 'not-allowed': + errorMsg = 'Microphone access denied. Please allow microphone permissions.'; + break; + case 'network': + errorMsg = 'Network error occurred.'; + break; + case 'aborted': + errorMsg = 'Recording was aborted.'; + break; + } + + this.onErrorCallbacks.forEach((cb) => cb(errorMsg)); + }; + + this.recognition.onend = () => { + this.isListening = false; + + if (this.state !== 'error') { + this.state = 'idle'; + } + + this.onEndCallbacks.forEach((cb) => cb()); + }; + } + } + + isSupported(): boolean { + if (typeof window === 'undefined') return false; + return !!(window.SpeechRecognition || window.webkitSpeechRecognition); + } + + start(options: SpeechRecognitionOptions = {}): Promise { + return new Promise((resolve, reject) => { + if (!this.isSupported()) { + reject(new Error('Web Speech API is not supported in this browser')); + return; + } + + if (this.isListening) { + reject(new Error('Already listening')); + return; + } + + if (!this.recognition) { + reject(new Error('Recognition not initialized')); + return; + } + + this.finalTranscript = ''; + this.state = 'listening'; + + if (options.language) { + this.recognition.lang = options.language; + } + + if (typeof options.continuous === 'boolean') { + this.recognition.continuous = options.continuous; + } + + if (typeof options.interimResults === 'boolean') { + this.recognition.interimResults = options.interimResults; + } + + if (options.maxAlternatives) { + this.recognition.maxAlternatives = options.maxAlternatives; + } + + const onStartOnce = () => { + this.onStartCallbacks = this.onStartCallbacks.filter(cb => cb !== onStartOnce); + resolve(); + }; + + const onErrorOnce = (error: string) => { + this.onErrorCallbacks = this.onErrorCallbacks.filter(cb => cb !== onErrorOnce); + reject(new Error(error)); + }; + + this.onStartCallbacks.push(onStartOnce); + this.onErrorCallbacks.push(onErrorOnce); + + try { + this.recognition.start(); + } catch (error) { + this.state = 'error'; + reject(error || new Error('Failed to start recognition')); + } + }); + } + + stop(): void { + if (this.recognition) { + try { + this.recognition.stop(); + } catch { + this.isListening = false; + this.state = 'idle'; + } + } + } + + abort(): void { + if (this.recognition) { + try { + this.recognition.abort(); + } catch { + // Ignore abort errors + } + this.state = 'idle'; + this.isListening = false; + this.finalTranscript = ''; + } + } + + isCurrentlyListening(): boolean { + return this.isListening; + } + + getState(): RecognitionState { + return this.state; + } + + onResult(callback: (result: SpeechRecognitionResult) => void): void { + this.onResultCallbacks.push(callback); + } + + onInterimResult(callback: (transcript: string) => void): void { + this.onInterimResultCallbacks.push(callback); + } + + onError(callback: (error: string) => void): void { + this.onErrorCallbacks.push(callback); + } + + onEnd(callback: () => void): void { + this.onEndCallbacks.push(callback); + } + + onStart(callback: () => void): void { + this.onStartCallbacks.push(callback); + } + + clearCallbacks(): void { + this.onResultCallbacks = []; + this.onInterimResultCallbacks = []; + this.onErrorCallbacks = []; + this.onEndCallbacks = []; + this.onStartCallbacks = []; + } + + getFinalTranscript(): string { + return this.finalTranscript; + } +} + +let recognizerInstance: WebSpeechRecognizer | null = null; + +export function getWebSpeechRecognizer(): WebSpeechRecognizer { + if (!recognizerInstance) { + recognizerInstance = new WebSpeechRecognizer(); + } + return recognizerInstance; +} + +export function isWebRecognitionSupported(): boolean { + if (typeof window === 'undefined') return false; + return !!(window.SpeechRecognition || window.webkitSpeechRecognition); +} + +export function getAvailableLanguages(): string[] { + if (typeof window === 'undefined' || !isWebRecognitionSupported()) { + return ['en-US']; + } + + const commonLanguages = [ + 'en-US', 'en-GB', 'en-AU', 'en-CA', 'en-IN', + 'es-ES', 'es-MX', 'es-AR', 'es-CO', + 'fr-FR', 'fr-CA', 'fr-BE', + 'de-DE', 'de-AT', 'de-CH', + 'it-IT', 'pt-BR', 'pt-PT', + 'zh-CN', 'zh-TW', 'ja-JP', 'ko-KR', + 'ru-RU', 'ar-SA', 'hi-IN', + ]; + + return commonLanguages; +} diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index b968ba05..51ae6dd2 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -20,6 +20,18 @@ export const TTSConfigSchema = z.object({ lastModelsFetch: z.number().optional(), }); +export const STTConfigSchema = z.object({ + enabled: z.boolean(), + provider: z.enum(['external', 'builtin']).default('builtin'), + endpoint: z.string(), + apiKey: z.string(), + model: z.string(), + language: z.string().default('en-US'), + continuous: z.boolean().default(false), + availableModels: z.array(z.string()).optional(), + lastModelsFetch: z.number().optional(), +}); + export const CustomAgentSchema = z.object({ name: z.string(), description: z.string(), @@ -40,6 +52,18 @@ export type TTSConfig = { lastModelsFetch?: number; }; +export type STTConfig = { + enabled: boolean; + provider: 'external' | 'builtin'; + endpoint: string; + apiKey: string; + model: string; + language: string; + continuous: boolean; + availableModels?: string[]; + lastModelsFetch?: number; +}; + const isBrowser = typeof navigator !== 'undefined'; const isMac = isBrowser && navigator.platform.toUpperCase().indexOf('MAC') >= 0; const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'; @@ -101,6 +125,7 @@ export const UserPreferencesSchema = z.object({ gitCredentials: z.array(GitCredentialSchema).optional(), gitIdentity: GitIdentitySchema.optional(), tts: TTSConfigSchema.optional(), + stt: STTConfigSchema.optional(), lastKnownGoodConfig: z.string().optional(), repoOrder: z.array(z.number()).optional(), }); @@ -119,6 +144,18 @@ export const DEFAULT_TTS_CONFIG: TTSConfig = { lastModelsFetch: 0, }; +export const DEFAULT_STT_CONFIG: STTConfig = { + enabled: false, + provider: 'builtin', + endpoint: "https://api.openai.com", + apiKey: "", + model: '', + language: 'en-US', + continuous: false, + availableModels: [], + lastModelsFetch: 0, +}; + export const DEFAULT_USER_PREFERENCES = { theme: "dark" as const, mode: "build" as const, @@ -134,6 +171,7 @@ export const DEFAULT_USER_PREFERENCES = { gitCredentials: [] as GitCredential[], gitIdentity: DEFAULT_GIT_IDENTITY, tts: DEFAULT_TTS_CONFIG, + stt: DEFAULT_STT_CONFIG, }; export const SettingsResponseSchema = z.object({