diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 8250d058..c74bc651 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import * as db from '../db/queries' import * as repoService from '../services/repo' +import { GitAuthenticationError } from '../services/repo' import * as gitOperations from '../services/git-operations' import * as archiveService from '../services/archive' import { SettingsService } from '../services/settings' @@ -191,6 +192,40 @@ export function createRepoRoutes(database: Database) { return c.json({ ...updatedRepo, currentBranch }) } catch (error: any) { logger.error('Failed to switch branch:', error) + if (error instanceof GitAuthenticationError) { + return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401) + } + return c.json({ error: error.message }, 500) + } + }) + + app.post('/:id/branch/create', async (c) => { + try { + const id = parseInt(c.req.param('id')) + const repo = db.getRepoById(database, id) + + if (!repo) { + return c.json({ error: 'Repo not found' }, 404) + } + + const body = await c.req.json() + const { branch } = body + + if (!branch) { + return c.json({ error: 'branch is required' }, 400) + } + + await repoService.createBranch(database, id, branch) + + const updatedRepo = db.getRepoById(database, id) + const currentBranch = await repoService.getCurrentBranch(updatedRepo!) + + return c.json({ ...updatedRepo, currentBranch }) + } catch (error: any) { + logger.error('Failed to create branch:', error) + if (error instanceof GitAuthenticationError) { + return c.json({ error: error.message, code: 'AUTH_FAILED' }, 401) + } return c.json({ error: error.message }, 500) } }) diff --git a/backend/src/routes/tts.ts b/backend/src/routes/tts.ts index 571e0e09..b0119724 100644 --- a/backend/src/routes/tts.ts +++ b/backend/src/routes/tts.ts @@ -11,7 +11,9 @@ import { getWorkspacePath } from '@opencode-manager/shared' const TTS_CACHE_DIR = join(getWorkspacePath(), 'cache', 'tts') const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'discovery') const CACHE_TTL_MS = 24 * 60 * 60 * 1000 -const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour for discovery cache +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 const TTSRequestSchema = z.object({ text: z.string().min(1).max(4096), @@ -54,8 +56,64 @@ async function getCachedAudio(cacheKey: string): Promise { } } +async function getCacheSize(): Promise { + try { + const files = await readdir(TTS_CACHE_DIR) + let totalSize = 0 + + for (const file of files) { + if (!file.endsWith('.mp3')) continue + + const filePath = join(TTS_CACHE_DIR, file) + const fileStat = await stat(filePath) + totalSize += fileStat.size + } + + return totalSize + } catch { + return 0 + } +} + +async function cleanupOldestFiles(requiredSpace: number): Promise { + try { + const files = await readdir(TTS_CACHE_DIR) + const fileInfos = [] + + for (const file of files) { + if (!file.endsWith('.mp3')) continue + + const filePath = join(TTS_CACHE_DIR, file) + const fileStat = await stat(filePath) + fileInfos.push({ path: filePath, mtimeMs: fileStat.mtimeMs, size: fileStat.size }) + } + + fileInfos.sort((a, b) => a.mtimeMs - b.mtimeMs) + + let freedSpace = 0 + for (const fileInfo of fileInfos) { + await unlink(fileInfo.path) + freedSpace += fileInfo.size + + if (freedSpace >= requiredSpace) break + } + + logger.info(`TTS cache freed ${freedSpace} bytes by removing old files`) + } catch (error) { + logger.error('TTS cache cleanup failed:', error) + } +} + async function cacheAudio(cacheKey: string, audioData: Buffer): Promise { const filePath = join(TTS_CACHE_DIR, `${cacheKey}.mp3`) + + await ensureCacheDir() + const currentCacheSize = await getCacheSize() + + if (currentCacheSize + audioData.length > MAX_CACHE_SIZE_BYTES) { + await cleanupOldestFiles(audioData.length) + } + await writeFile(filePath, audioData) } @@ -213,10 +271,48 @@ export async function cleanupExpiredCache(): Promise { } } +export async function getCacheStats(): Promise<{ count: number; sizeBytes: number; sizeMB: number }> { + try { + await ensureCacheDir() + const files = await readdir(TTS_CACHE_DIR) + let count = 0 + let totalSize = 0 + + for (const file of files) { + if (!file.endsWith('.mp3')) continue + + const filePath = join(TTS_CACHE_DIR, file) + const fileStat = await stat(filePath) + + if (Date.now() - fileStat.mtimeMs <= CACHE_TTL_MS) { + count++ + totalSize += fileStat.size + } + } + + return { + count, + sizeBytes: totalSize, + sizeMB: Math.round(totalSize / (1024 * 1024) * 100) / 100 + } + } catch { + return { count: 0, sizeBytes: 0, sizeMB: 0 } + } +} + +export { generateCacheKey, ensureCacheDir, getCachedAudio, cacheAudio, getCacheSize, cleanupOldestFiles } + export function createTTSRoutes(db: Database) { const app = new Hono() app.post('/synthesize', async (c) => { + const abortController = new AbortController() + + c.req.raw.signal.addEventListener('abort', () => { + logger.info('TTS request aborted by client') + abortController.abort() + }) + try { const body = await c.req.json() const { text } = TTSRequestSchema.parse(body) @@ -250,6 +346,10 @@ export function createTTSRoutes(db: Database) { }) } + if (abortController.signal.aborted) { + return new Response(null, { status: 499 }) + } + logger.info(`TTS cache miss, calling API: ${cacheKey.substring(0, 8)}...`) const baseUrl = normalizeToBaseUrl(endpoint) @@ -268,6 +368,7 @@ export function createTTSRoutes(db: Database) { speed, response_format: 'mp3', }), + signal: abortController.signal, }) if (!response.ok) { @@ -310,6 +411,9 @@ export function createTTSRoutes(db: Database) { }, }) } catch (error) { + if (error instanceof Error && error.name === 'AbortError') { + return new Response(null, { status: 499 }) + } logger.error('TTS synthesis failed:', error) if (error instanceof z.ZodError) { return c.json({ error: 'Invalid request', details: error.issues }, 400) @@ -419,10 +523,16 @@ export function createTTSRoutes(db: Database) { const settingsService = new SettingsService(db) const settings = settingsService.getSettings(userId) const ttsConfig = settings.preferences.tts + const cacheStats = await getCacheStats() return c.json({ enabled: ttsConfig?.enabled || false, configured: !!(ttsConfig?.apiKey), + cache: { + ...cacheStats, + maxSizeMB: MAX_CACHE_SIZE_MB, + ttlHours: CACHE_TTL_MS / (60 * 60 * 1000) + } }) }) diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index de446a01..be62e726 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -5,10 +5,59 @@ import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' import { SettingsService } from './settings' -import { createGitEnvForRepoUrl, createNoPromptGitEnv } from '../utils/git-auth' +import { createGitEnvForRepoUrl, createNoPromptGitEnv, createGitHubGitEnv } from '../utils/git-auth' import { getReposPath } from '@opencode-manager/shared' import path from 'path' +export class GitAuthenticationError extends Error { + constructor(message: string) { + super(message) + this.name = 'GitAuthenticationError' + } +} + +function isAuthenticationError(error: any): boolean { + const message = error?.message?.toLowerCase() || '' + return message.includes('authentication failed') || + message.includes('invalid username or token') || + message.includes('could not read username') +} + +interface GitCommandOptions { + cwd?: string + env?: Record + silent?: boolean +} + +async function executeGitWithFallback( + cmd: string[], + options: GitCommandOptions = {} +): Promise { + const { cwd, env = createNoPromptGitEnv(), silent } = options + + try { + return await executeCommand(cmd, { cwd, env, silent }) + } catch (error: any) { + if (!isAuthenticationError(error)) { + throw error + } + + logger.warn(`Git command failed with auth, trying gh auth fallback`) + try { + const ghToken = (await executeCommand(['gh', 'auth', 'token'])).trim() + const ghEnv = createGitHubGitEnv(ghToken) + return await executeCommand(cmd, { cwd, env: ghEnv, silent }) + } catch (ghError: any) { + if (!isAuthenticationError(ghError)) { + throw ghError + } + + logger.warn(`Git command failed with gh auth, trying without auth (public repo)`) + return await executeCommand(cmd, { cwd, env: createNoPromptGitEnv(), silent }) + } + } +} + async function hasCommits(repoPath: string): Promise { try { await executeCommand(['git', '-C', repoPath, 'rev-parse', 'HEAD'], { silent: true }) @@ -182,7 +231,7 @@ export async function cloneRepo( const baseRepoPath = path.resolve(getReposPath(), baseRepoDirName) const worktreePath = path.resolve(getReposPath(), worktreeDirName) - await executeCommand(['git', '-C', baseRepoPath, 'fetch', '--all'], { env }) + await executeGitWithFallback(['git', '-C', baseRepoPath, 'fetch', '--all'], { cwd: getReposPath(), env }) await createWorktreeSafely(baseRepoPath, worktreePath, branch) @@ -216,8 +265,7 @@ export async function cloneRepo( } try { - const cloneCmd = ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(['git', 'clone', '-b', branch, repoUrl, worktreeDirName], { cwd: getReposPath(), env }) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { logger.error(`Clone failed: directory still exists after cleanup attempt`) @@ -225,8 +273,7 @@ export async function cloneRepo( } logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`) - const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(['git', 'clone', repoUrl, worktreeDirName], { cwd: getReposPath(), env }) let localBranchExists = 'missing' try { await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`]) @@ -250,7 +297,7 @@ export async function cloneRepo( if (branch) { logger.info(`Switching to branch: ${branch}`) - await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'], { env }) + await executeGitWithFallback(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'], { cwd: getReposPath(), env }) let remoteBranchExists = false @@ -311,7 +358,7 @@ export async function cloneRepo( ? ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] : ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(cloneCmd, { cwd: getReposPath(), env }) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { logger.error(`Clone failed: directory still exists after cleanup attempt`) @@ -320,8 +367,7 @@ export async function cloneRepo( if (branch && (error.message.includes('Remote branch') || error.message.includes('not found'))) { logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`) -const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, { cwd: getReposPath(), env }) + await executeGitWithFallback(['git', 'clone', repoUrl, worktreeDirName], { cwd: getReposPath(), env }) let localBranchExists = 'missing' try { await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`]) @@ -357,38 +403,42 @@ export async function getCurrentBranch(repo: Repo): Promise { return branch || repo.branch || repo.defaultBranch || null } -export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], remote: string[], current: string | null }> { +export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], all: string[], current: string | null }> { try { const repoPath = path.resolve(getReposPath(), repo.localPath) const env = getGitEnv(database, repo.repoUrl) if (!repo.isLocal) { - await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env }) + try { + await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env }) + } catch (error) { + logger.warn(`Failed to fetch remote for repo ${repo.id}, using cached branch info:`, error) + } } const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)']) const localBranches = localBranchesOutput.trim().split('\n').filter(b => b.trim()) let remoteBranches: string[] = [] - if (!repo.isLocal) { - try { - const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)']) - remoteBranches = remoteBranchesOutput.trim().split('\n') - .filter(b => b.trim() && !b.includes('HEAD')) - .map(b => b.replace('origin/', '')) - } catch (error) { - logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error) - remoteBranches = [] - } + try { + const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)']) + remoteBranches = remoteBranchesOutput.trim().split('\n') + .filter(b => b.trim() && !b.includes('HEAD') && b.includes('/')) + } catch (error) { + logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error) } const current = await getCurrentBranch(repo) - const allBranches = new Set([...localBranches, ...remoteBranches]) + const remoteOnlyBranches = remoteBranches + .map(b => b.replace(/^[^/]+\//, '')) + .filter(b => !localBranches.includes(b)) + + const allBranches = [...localBranches, ...remoteOnlyBranches] return { local: localBranches, - remote: Array.from(allBranches), + all: allBranches, current } } catch (error: any) { @@ -407,13 +457,18 @@ export async function switchBranch(database: Database, repoId: number, branch: s const repoPath = path.resolve(getReposPath(), repo.localPath) const env = getGitEnv(database, repo.repoUrl) - logger.info(`Switching to branch: ${branch} in ${repo.localPath}`) + const sanitizedBranch = branch + .replace(/^refs\/heads\//, '') + .replace(/^refs\/remotes\//, '') + .replace(/^origin\//, '') - await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env }) + logger.info(`Switching to branch: ${sanitizedBranch} in ${repo.localPath}`) + + await executeGitWithFallback(['git', '-C', repoPath, 'fetch', '--all'], { env }) let localBranchExists = false try { - await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${branch}`]) + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/heads/${sanitizedBranch}`]) localBranchExists = true } catch { localBranchExists = false @@ -421,30 +476,53 @@ export async function switchBranch(database: Database, repoId: number, branch: s let remoteBranchExists = false try { - await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${branch}`]) + await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', `refs/remotes/origin/${sanitizedBranch}`]) remoteBranchExists = true } catch { remoteBranchExists = false } if (localBranchExists) { - logger.info(`Checking out existing local branch: ${branch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', branch]) + logger.info(`Checking out existing local branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', sanitizedBranch]) } else if (remoteBranchExists) { - logger.info(`Checking out remote branch: ${branch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', '-b', branch, `origin/${branch}`]) + logger.info(`Checking out remote branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch, `origin/${sanitizedBranch}`]) } else { - logger.info(`Creating new branch: ${branch}`) - await executeCommand(['git', '-C', repoPath, 'checkout', '-b', branch]) + logger.info(`Creating new branch: ${sanitizedBranch}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch]) } - logger.info(`Successfully switched to branch: ${branch}`) + logger.info(`Successfully switched to branch: ${sanitizedBranch}`) } catch (error: any) { logger.error(`Failed to switch branch for repo ${repoId}:`, error) throw error } } +export async function createBranch(database: Database, repoId: number, branch: string): Promise { + const repo = db.getRepoById(database, repoId) + if (!repo) { + throw new Error(`Repo not found: ${repoId}`) + } + + try { + const repoPath = path.resolve(getReposPath(), repo.localPath) + + const sanitizedBranch = branch + .replace(/^refs\/heads\//, '') + .replace(/^refs\/remotes\//, '') + .replace(/^origin\//, '') + + logger.info(`Creating new branch: ${sanitizedBranch} in ${repo.localPath}`) + await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch]) + logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`) + } catch (error: any) { + logger.error(`Failed to create branch for repo ${repoId}:`, error) + throw error + } +} + export async function pullRepo(database: Database, repoId: number): Promise { const repo = db.getRepoById(database, repoId) if (!repo) { diff --git a/backend/test/routes/tts.test.ts b/backend/test/routes/tts.test.ts new file mode 100644 index 00000000..19d546b7 --- /dev/null +++ b/backend/test/routes/tts.test.ts @@ -0,0 +1,225 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +const mockMkdir = vi.fn() +const mockReadFile = vi.fn() +const mockWriteFile = vi.fn() +const mockReaddir = vi.fn() +const mockStat = vi.fn() +const mockUnlink = vi.fn() + +const mockLogger = { + info: vi.fn(), + error: vi.fn(), + warn: vi.fn(), +} + +vi.mock('fs/promises', async () => { + return { + mkdir: mockMkdir, + readFile: mockReadFile, + writeFile: mockWriteFile, + readdir: mockReaddir, + stat: mockStat, + unlink: mockUnlink, + } +}) + +vi.mock('bun:sqlite', () => ({ + Database: vi.fn(), +})) +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn(), +})) +vi.mock('../../src/utils/logger', async () => { + return { + logger: mockLogger, + } +}) + +import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, ensureCacheDir, getCachedAudio, getCacheSize, cleanupOldestFiles } from '../../src/routes/tts' + +describe('TTS Routes', () => { + let mockDb: any + let ttsApp: any + let mockSettingsService: any + + beforeEach(() => { + vi.clearAllMocks() + + mockDb = {} as any + mockSettingsService = { + getSettings: vi.fn().mockReturnValue({ + preferences: { + tts: { + enabled: true, + apiKey: 'test-key', + endpoint: 'https://api.openai.com/v1/audio/speech', + voice: 'alloy', + model: 'tts-1', + speed: 1.0, + }, + }, + }), + } + + ttsApp = createTTSRoutes(mockDb) + }) + + describe('generateCacheKey', () => { + it('should generate consistent cache keys for identical inputs', () => { + const text = 'Hello world' + const voice = 'alloy' + const model = 'tts-1' + const speed = 1.0 + + const key1 = generateCacheKey(text, voice, model, speed) + const key2 = generateCacheKey(text, voice, model, speed) + + expect(key1).toBe(key2) + expect(key1).toMatch(/^[a-f0-9]{64}$/) + }) + + it('should generate different cache keys for different inputs', () => { + const key1 = generateCacheKey('Hello', 'alloy', 'tts-1', 1.0) + const key2 = generateCacheKey('World', 'alloy', 'tts-1', 1.0) + + expect(key1).not.toBe(key2) + }) + }) + + describe('ensureCacheDir', () => { + it('should create cache directory when it does not exist', async () => { + mockMkdir.mockResolvedValue(undefined) + + await ensureCacheDir() + + expect(mockMkdir).toHaveBeenCalledWith( + expect.stringContaining('cache/tts'), + { recursive: true } + ) + }) + }) + + describe('getCachedAudio', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + +beforeEach(() => { + vi.useFakeTimers() + }) + + it('should return cached audio when file exists and is not expired', async () => { + const cacheKey = 'test-key' + const audioBuffer = Buffer.from('audio data') + + mockStat.mockResolvedValue({ + mtimeMs: Date.now() - 1000, // 1 second ago (not expired) + size: 1024, + }) + mockReadFile.mockResolvedValue(audioBuffer) + + const result = await getCachedAudio(cacheKey) + + expect(result).toBe(audioBuffer) + expect(mockReadFile).toHaveBeenCalledWith( + expect.stringContaining(`${cacheKey}.mp3`) + ) + }) + + it('should return null when cached file has expired', async () => { + const cacheKey = 'test-key' + + mockStat.mockResolvedValue({ + mtimeMs: Date.now() - 25 * 60 * 60 * 1000, // 25 hours ago (expired) + size: 1024, + }) + mockUnlink.mockResolvedValue(undefined) + + const result = await getCachedAudio(cacheKey) + + expect(result).toBeNull() + expect(mockUnlink).toHaveBeenCalledWith( + expect.stringContaining(`${cacheKey}.mp3`) + ) + }) + + it('should return null when cached file does not exist', async () => { + const cacheKey = 'nonexistent-key' + + mockStat.mockRejectedValue(new Error('File not found')) + + const result = await getCachedAudio(cacheKey) + + expect(result).toBeNull() + }) + }) + + describe('getCacheSize', () => { + it('should calculate correct cache size', async () => { + mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'readme.txt']) + mockStat + .mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() }) + .mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() }) + + const size = await getCacheSize() + + expect(size).toBe(3072) // 1024 + 2048 + }) + + it('should handle cache directory errors gracefully', async () => { + mockReaddir.mockRejectedValue(new Error('Permission denied')) + + const size = await getCacheSize() + + expect(size).toBe(0) + }) + }) + + describe('cleanupMethods', () => { + it('should remove oldest files when cache size limit exceeded', async () => { + mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'file3.mp3']) + mockStat + .mockResolvedValueOnce({ size: 1024, mtimeMs: 1000 }) + .mockResolvedValueOnce({ size: 2048, mtimeMs: 2000 }) + .mockResolvedValueOnce({ size: 1536, mtimeMs: 3000 }) + mockUnlink.mockResolvedValue(undefined) + + await cleanupOldestFiles(1500) // Need 1500 bytes freed + + expect(mockUnlink).toHaveBeenCalledWith( + expect.stringContaining('file1.mp3') + ) + }) + + it('should return cache statistics for files', async () => { + const currentTime = Date.now() + mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3']) + mockStat + .mockResolvedValueOnce({ size: 1024, mtimeMs: currentTime }) + .mockResolvedValueOnce({ size: 2048, mtimeMs: currentTime }) + + const stats = await getCacheStats() + + expect(stats.count).toBe(2) + expect(stats.sizeBytes).toBe(3072) + expect(stats.sizeMB).toBeCloseTo(0, 1) + }) + + it('should cleanup expired cache files', async () => { + mockReaddir.mockResolvedValue(['file1.mp3', 'file2.mp3', 'expired.mp3']) + mockStat + .mockResolvedValueOnce({ size: 1024, mtimeMs: Date.now() }) + .mockResolvedValueOnce({ size: 2048, mtimeMs: Date.now() }) + .mockResolvedValueOnce({ size: 1536, mtimeMs: Date.now() - 25 * 60 * 60 * 1000 }) + mockUnlink.mockResolvedValue(undefined) + + const cleaned = await cleanupExpiredCache() + + expect(cleaned).toBe(1) + expect(mockUnlink).toHaveBeenCalledWith( + expect.stringContaining('expired.mp3') + ) + }) + }) +}) \ No newline at end of file diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index b19330b1..1e49644b 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -20,4 +20,10 @@ export default defineConfig([ globals: globals.browser, }, }, + { + files: ['src/components/ui/**/*.{ts,tsx}'], + rules: { + 'react-refresh/only-export-components': 'off', + }, + }, ]) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f6a3d13a..96a661c5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,6 +7,7 @@ import { SessionDetail } from './pages/SessionDetail' import { SettingsDialog } from './components/settings/SettingsDialog' import { useSettingsDialog } from './hooks/useSettingsDialog' import { useTheme } from './hooks/useTheme' +import { TTSProvider } from './contexts/TTSContext' const queryClient = new QueryClient({ defaultOptions: { @@ -44,7 +45,9 @@ function App() { return ( - + + + ) } diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index 0bde92a6..bbf7c923 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -115,6 +115,15 @@ export async function switchRepoConfig(id: number, configName: string): Promise< return response.json() } +export class GitAuthError extends Error { + code: string + constructor(message: string, code: string) { + super(message) + this.name = 'GitAuthError' + this.code = code + } +} + export async function switchBranch(id: number, branch: string): Promise { const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/switch`, { method: 'POST', @@ -124,13 +133,16 @@ export async function switchBranch(id: number, branch: string): Promise { if (!response.ok) { const error = await response.json() + if (error.code === 'AUTH_FAILED') { + throw new GitAuthError(error.error || 'Git authentication failed', error.code) + } throw new Error(error.error || 'Failed to switch branch') } return response.json() } -export async function listBranches(id: number): Promise<{ local: string[], remote: string[], current: string | null }> { +export async function listBranches(id: number): Promise<{ local: string[], all: string[], current: string | null }> { const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branches`) if (!response.ok) { @@ -140,6 +152,24 @@ export async function listBranches(id: number): Promise<{ local: string[], remot return response.json() } +export async function createBranch(id: number, branch: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/create`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ branch }), + }) + + if (!response.ok) { + const error = await response.json() + if (error.code === 'AUTH_FAILED') { + throw new GitAuthError(error.error || 'Git authentication failed', error.code) + } + throw new Error(error.error || 'Failed to create branch') + } + + return response.json() +} + export async function downloadRepo(id: number, repoName: string): Promise { const response = await fetch(`${API_BASE_URL}/api/repos/${id}/download`) diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 18eda291..18a0acf5 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -15,15 +15,11 @@ import { CommandSuggestions } from '@/components/command/CommandSuggestions' import { MentionSuggestions, type MentionItem } from './MentionSuggestions' import { SessionStatusIndicator } from '@/components/ui/session-status-indicator' import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQuery } from '@/lib/promptParser' -import { getModel, formatModelName } from '@/api/providers' + + import type { components } from '@/api/opencode-types' import type { MessageWithParts, FileInfo } from '@/api/types' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from '@/components/ui/dropdown-menu' + type CommandType = components['schemas']['Command'] @@ -55,7 +51,7 @@ export function PromptInput({ onExportSession }: PromptInputProps) { const [prompt, setPrompt] = useState('') - const [modelName, setModelName] = useState('') + const [isBashMode, setIsBashMode] = useState(false) const [showSuggestions, setShowSuggestions] = useState(false) const [suggestionQuery, setSuggestionQuery] = useState('') @@ -452,33 +448,16 @@ export function PromptInput({ const modeColor = currentMode === 'plan' ? 'text-yellow-600 dark:text-yellow-500' : 'text-green-600 dark:text-green-500' const modeBg = currentMode === 'plan' ? 'bg-yellow-500/10 border-yellow-500/30' : 'bg-green-500/10 border-green-500/30' - const { model: selectedModel, modelString } = useModelSelection(opcodeUrl, directory) + const { modelString } = useModelSelection(opcodeUrl, directory) const currentModel = modelString || '' const isMobile = useMobile() const sessionStatus = useSessionStatusForSession(sessionID) const showStopButton = hasActiveStream && (sessionStatus.type === 'busy' || sessionStatus.type === 'retry') const hideSecondaryButtons = isMobile && hasActiveStream - useEffect(() => { - const loadModelName = async () => { - if (selectedModel) { - try { - const model = await getModel(selectedModel.providerID, selectedModel.modelID) - if (model) { - setModelName(formatModelName(model)) - } else { - setModelName(currentModel) - } - } catch { - setModelName(currentModel) - } - } else { - setModelName('No model selected') - } - } + - loadModelName() - }, [selectedModel, currentModel]) + useEffect(() => { if (textareaRef.current && !disabled) { @@ -490,11 +469,7 @@ export function PromptInput({ return (
- {hasActiveStream && ( -
- -
- )} +