Merge main into feature/TTS and resolve conflicts

This commit is contained in:
Chris Scott committed 2025-12-15 14:50:04 -05:00
commit 67cb729ca7
19 files changed
+963 -524

No files matched your search

+35
View File
@@ -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)
}
})
+111 -1
View File
@@ -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<Buffer | null> {
}
}
async function getCacheSize(): Promise<number> {
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<void> {
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<void> {
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<number> {
}
}
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)
}
})
})
+113 -35
View File
@@ -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<string, string>
silent?: boolean
}
async function executeGitWithFallback(
cmd: string[],
options: GitCommandOptions = {}
): Promise<string> {
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<boolean> {
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<string | null> {
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<void> {
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<void> {
const repo = db.getRepoById(database, repoId)
if (!repo) {
+225
View File
@@ -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')
)
})
})
})
+6
View File
@@ -20,4 +20,10 @@ export default defineConfig([
globals: globals.browser,
},
},
{
files: ['src/components/ui/**/*.{ts,tsx}'],
rules: {
'react-refresh/only-export-components': 'off',
},
},
])
+4 -1
View File
@@ -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 (
<QueryClientProvider client={queryClient}>
<AppContent />
<TTSProvider>
<AppContent />
</TTSProvider>
</QueryClientProvider>
)
}
+31 -1
View File
@@ -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<Repo> {
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<Repo> {
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<Repo> {
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<void> {
const response = await fetch(`${API_BASE_URL}/api/repos/${id}/download`)
+20 -64
View File
@@ -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<string>('')
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 (
<div className="relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-white/30 rounded-xl p-2 md:p-3 md:mx-4 mb-4 md:mb-1 w-[94%] md:max-w-4xl">
{hasActiveStream && (
<div className="pb-1">
<SessionStatusIndicator sessionID={sessionID} />
</div>
)}
<textarea
ref={textareaRef}
@@ -527,40 +502,21 @@ export function PromptInput({
>
{isBashMode ? 'BASH' : currentMode.toUpperCase()}
</button>
{!hideSecondaryButtons && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer max-w-[120px] md:max-w-[180px] truncate"
>
{modelName.length > 12 ? modelName.substring(0, 10) + '...' : modelName || 'Select model'}
</button>
)}
{!hideSecondaryButtons && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
{hasActiveStream ? (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground max-w-[120px] md:max-w-[180px] truncate">
<SessionStatusIndicator sessionID={sessionID} />
</div>
) : (
!hideSecondaryButtons && (
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium flex-shrink-0"
title="Help"
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer max-w-[120px] md:max-w-[180px] truncate"
>
?
{currentModel.length > 12 ? currentModel.substring(0, 10) + '...' : currentModel || 'Select model'}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files or agents
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
)
)}
</div>
<div className="flex items-center gap-1.5 md:gap-2 flex-shrink-0">
<button
@@ -1,6 +1,6 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createRepo } from "@/api/repos";
import { createRepo, createBranch } from "@/api/repos";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
@@ -15,24 +15,32 @@ interface AddBranchWorkspaceDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoUrl: string;
repoId: number;
}
export function AddBranchWorkspaceDialog({
open,
onOpenChange,
repoUrl,
repoId,
}: AddBranchWorkspaceDialogProps) {
const [branch, setBranch] = useState("");
const [useWorktree, setUseWorktree] = useState(true);
const [useWorktree, setUseWorktree] = useState(false);
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: () =>
createRepo(repoUrl, undefined, branch || undefined, undefined, useWorktree),
mutationFn: () => {
if (useWorktree) {
return createRepo(repoUrl, undefined, branch || undefined, undefined, true)
}
return createBranch(repoId, branch)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
queryClient.invalidateQueries({ queryKey: ["branches", repoId] });
queryClient.invalidateQueries({ queryKey: ["repo", repoId] });
setBranch("");
setUseWorktree(true);
setUseWorktree(false);
onOpenChange(false);
},
});
@@ -54,10 +62,10 @@ export function AddBranchWorkspaceDialog({
<DialogContent className="max-w-[90%] sm:max-w-[500px] bg-[#141414] border-[#2a2a2a]">
<DialogHeader>
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
Add Branch Workspace
Add Branch
</DialogTitle>
<p className="text-sm text-zinc-400 mt-1">
Create a new workspace for{" "}
Create a new branch for{" "}
{repoUrl.split("/").pop()?.replace(".git", "")}
</p>
</DialogHeader>
@@ -99,8 +107,8 @@ export function AddBranchWorkspaceDialog({
</div>
<p className="text-xs text-zinc-500">
{useWorktree
? "Creates a git worktree - shares git history with base repo (recommended, faster)"
: "Creates a full clone - independent copy of the repository (slower, more disk space)"}
? "Creates a separate workspace directory - allows working on multiple branches simultaneously"
: "Creates a local branch in the current repository"}
</p>
</div>
@@ -112,12 +120,12 @@ export function AddBranchWorkspaceDialog({
{mutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
{useWorktree ? "Creating worktree..." : "Cloning..."}
{useWorktree ? "Creating worktree..." : "Creating branch..."}
</>
) : useWorktree ? (
"Create Worktree"
) : (
"Clone Branch"
"Create Branch"
)}
</Button>
{mutation.isError && (
+83 -47
View File
@@ -9,10 +9,11 @@ import {
} from "@/components/ui/dropdown-menu";
import { GitBranch, Check, Plus, GitCommit, Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { listBranches, switchBranch } from "@/api/repos";
import { listBranches, switchBranch, GitAuthError } from "@/api/repos";
import { useGitStatus } from "@/api/git";
import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog";
import { GitChangesSheet } from "@/components/file-browser/GitChangesSheet";
import { showToast } from "@/lib/toast";
interface BranchSwitcherProps {
repoId: number;
@@ -45,16 +46,22 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
const switchBranchMutation = useMutation({
mutationFn: (branch: string) => switchBranch(repoId, branch),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repo", repoId] });
onSuccess: (updatedRepo) => {
queryClient.setQueryData(["repo", repoId], updatedRepo);
queryClient.invalidateQueries({ queryKey: ["branches", repoId] });
queryClient.invalidateQueries({ queryKey: ["repos"] });
},
onError: (error) => {
if (error instanceof GitAuthError) {
showToast.error('Authentication failed. Please update your Git token in Settings or run "gh auth login".');
} else {
showToast.error(error.message || 'Failed to switch branch');
}
},
});
if (isWorktree) {
return null;
}
const isCurrentBranchInList = branches?.all?.includes(currentBranch) ?? false;
const showLoading = switchBranchMutation.isPending || (branchesLoading && !isCurrentBranchInList);
return (
<>
@@ -66,7 +73,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
disabled={switchBranchMutation.isPending}
className={`h-6 px-1 sm:px-2 text-[10px] sm:text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:bg-accent gap-1 border border-blue-500/20 ${iconOnly ? 'w-6' : ''} ${className || ""}`}
>
{switchBranchMutation.isPending ? (
{showLoading ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
<GitBranch className="w-3 h-3" />
@@ -75,58 +82,86 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent sideOffset={0} align="end" className="bg-card border-border min-w-[200px]">
{branchesLoading ? (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
</DropdownMenuItem>
) : branches?.local && branches.local.length > 0 ? (
branches.local.map((branch: string) => (
<DropdownMenuItem
key={branch}
onClick={() => switchBranchMutation.mutate(branch)}
disabled={switchBranchMutation.isPending}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
{isWorktree ? (
<>
<DropdownMenuItem disabled className="text-muted-foreground">
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">{branch}</span>
{branch === currentBranch && <Check className="w-3 h-3 text-green-500" />}
<span className="flex-1">Worktree: {currentBranch}</span>
</div>
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled className="text-muted-foreground">
No branches available
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setGitChangesOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitCommit className="w-3 h-3" />
<span className="flex-1">View Changes</span>
{gitStatus?.hasChanges && (
<span className="text-xs text-yellow-500">
{gitStatus.files.length}
</span>
)}
</div>
</DropdownMenuItem>
{!isWorktree && repoUrl && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setAddBranchOpen(true)}
onClick={() => setGitChangesOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<Plus className="w-3 h-3" />
<span className="flex-1">Add Branch</span>
<GitCommit className="w-3 h-3" />
<span className="flex-1">View Changes</span>
{gitStatus?.hasChanges && (
<span className="text-xs text-yellow-500">
{gitStatus.files.length}
</span>
)}
</div>
</DropdownMenuItem>
</>
) : (
<>
{branchesLoading ? (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
</DropdownMenuItem>
) : branches?.all && branches.all.length > 0 ? (
branches.all.map((branch: string) => (
<DropdownMenuItem
key={branch}
onClick={() => switchBranchMutation.mutate(branch)}
disabled={switchBranchMutation.isPending}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">{branch}</span>
{branch === currentBranch && <Check className="w-3 h-3 text-green-500" />}
</div>
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled className="text-muted-foreground">
No branches available
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setGitChangesOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitCommit className="w-3 h-3" />
<span className="flex-1">View Changes</span>
{gitStatus?.hasChanges && (
<span className="text-xs text-yellow-500">
{gitStatus.files.length}
</span>
)}
</div>
</DropdownMenuItem>
{repoUrl && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setAddBranchOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<Plus className="w-3 h-3" />
<span className="flex-1">Add Branch</span>
</div>
</DropdownMenuItem>
</>
)}
</>
)}
</DropdownMenuContent>
</DropdownMenu>
@@ -136,6 +171,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repoUrl}
repoId={repoId}
/>
)}
+10 -12
View File
@@ -83,7 +83,7 @@ export function RepoCard({
<Badge
className="text-xs px-2.5 py-0.5 bg-purple-600/20 text-purple-600 dark:text-purple-400 border-purple-600/40"
>
worktree
{branchToDisplay || "main"}
</Badge>
)}
{repo.cloneStatus === "cloning" && (
@@ -120,17 +120,15 @@ export function RepoCard({
Open
</Button>
{!repo.isWorktree && (
<BranchSwitcher
repoId={repo.id}
currentBranch={branchToDisplay || ""}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
repoLocalPath={repo.localPath}
iconOnly={true}
className="h-10 sm:h-9 w-10"
/>
)}
<BranchSwitcher
repoId={repo.id}
currentBranch={branchToDisplay || ""}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
repoLocalPath={repo.localPath}
iconOnly={true}
className="h-10 sm:h-9 w-10"
/>
<Button
size="sm"
@@ -140,7 +140,7 @@ export function PermissionRequestDialog({
return (
<Dialog open={true} onOpenChange={() => {}}>
<DialogContent hideCloseButton className="sm:max-w-md">
<DialogContent hideCloseButton className="max-w-[calc(100vw-2rem)] sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
Permission Request
@@ -163,16 +163,16 @@ export function PermissionRequestDialog({
</div>
{details.primary && (
<div className="bg-muted/50 border rounded-md p-3 max-h-32 overflow-y-auto">
<pre className="text-sm font-mono whitespace-pre-wrap break-all">
<div className="bg-muted/50 border rounded-md p-3 max-h-32 overflow-x-auto overflow-y-auto">
<pre className="text-sm font-mono whitespace-pre-wrap break-words max-w-full">
{details.primary}
</pre>
</div>
)}
{details.secondary && (
<div className="bg-muted/30 border rounded-md p-3 max-h-24 overflow-y-auto">
<pre className="text-xs font-mono whitespace-pre-wrap break-all text-muted-foreground">
<div className="bg-muted/30 border rounded-md p-3 max-h-24 overflow-x-auto overflow-y-auto">
<pre className="text-xs font-mono whitespace-pre-wrap break-words max-w-full text-muted-foreground">
{details.secondary}
</pre>
</div>
@@ -189,13 +189,13 @@ export function PermissionRequestDialog({
)}
</div>
<DialogFooter className="flex-row gap-2 sm:justify-between">
<DialogFooter className="flex-col-reverse gap-2 sm:flex-row sm:justify-between">
<Button
variant="outline"
onClick={() => handleResponse('reject')}
disabled={isLoading}
className={cn(
"flex-1",
"w-full sm:flex-1",
loadingAction === 'reject' && "opacity-70"
)}
>
@@ -206,7 +206,7 @@ export function PermissionRequestDialog({
onClick={() => handleResponse('once')}
disabled={isLoading}
className={cn(
"flex-1",
"w-full sm:flex-1",
loadingAction === 'once' && "opacity-70"
)}
>
@@ -217,7 +217,7 @@ export function PermissionRequestDialog({
onClick={() => handleResponse('always')}
disabled={isLoading}
className={cn(
"flex-1",
"w-full sm:flex-1",
loadingAction === 'always' && "opacity-70"
)}
>
@@ -5,7 +5,7 @@ import { z } from 'zod'
import { useSettings } from '@/hooks/useSettings'
import { useTTS } from '@/hooks/useTTS'
import { useTTSModels, useTTSVoices, useTTSDiscovery } from '@/api/tts'
import { Loader2, Volume2, Square, CheckCircle, XCircle, RefreshCw } from 'lucide-react'
import { Loader2, Volume2, Square, XCircle, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
@@ -49,7 +49,6 @@ export function TTSSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
const { speak, stop, isPlaying, isLoading: isTTSLoading, error: ttsError } = useTTS()
const { refreshAll } = useTTSDiscovery()
const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle')
const [isRefreshingDiscovery, setIsRefreshingDiscovery] = useState(false)
const form = useForm<TTSFormValues>({
@@ -124,20 +123,12 @@ export function TTSSettings() {
updateSettings({ tts: data })
}
const handleTest = async () => {
setTestStatus('idle')
try {
await speak(TEST_PHRASE)
setTestStatus('success')
setTimeout(() => setTestStatus('idle'), 3000)
} catch {
setTestStatus('error')
}
const handleTest = () => {
speak(TEST_PHRASE)
}
const handleStopTest = () => {
stop()
setTestStatus('idle')
}
if (isLoading) {
@@ -392,12 +383,6 @@ export function TTSSettings() {
Click "Refresh" to discover available voices, or check your API key and endpoint URL.
</p>
)}
{testStatus === 'success' && (
<p className="text-sm text-green-500 flex items-center gap-1">
<CheckCircle className="h-4 w-4" />
TTS is working
</p>
)}
</div>
<Button
type="button"
+259
View File
@@ -0,0 +1,259 @@
import { useState, useRef, useCallback, useEffect, type ReactNode } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { API_BASE_URL } from '@/config'
import { TTSContext, type TTSState } from './tts-context'
export { TTSContext, type TTSContextValue, type TTSState } from './tts-context'
const SENTENCE_REGEX = /(?<=[.!?])\s+/
const SENTENCES_PER_CHUNK = 2
function splitIntoChunks(text: string): string[] {
const sentences = text.split(SENTENCE_REGEX).filter(s => s.trim().length > 0)
if (sentences.length === 0) return [text]
const chunks: string[] = []
for (let i = 0; i < sentences.length; i += SENTENCES_PER_CHUNK) {
const chunk = sentences.slice(i, i + SENTENCES_PER_CHUNK).join(' ')
if (chunk.trim()) chunks.push(chunk.trim())
}
return chunks.length > 0 ? chunks : [text]
}
interface TTSProviderProps {
children: ReactNode
}
export function TTSProvider({ children }: TTSProviderProps) {
const { preferences } = useSettings()
const [state, setState] = useState<TTSState>('idle')
const [error, setError] = useState<string | null>(null)
const [currentText, setCurrentText] = useState<string | null>(null)
const abortControllerRef = useRef<AbortController | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const stoppedRef = useRef(false)
const chunksRef = useRef<string[]>([])
const chunkIndexRef = useRef(0)
const prefetchedBlobsRef = useRef<Map<number, Blob>>(new Map())
const fetchingIndexRef = useRef<number>(-1)
const ttsConfig = preferences?.tts
const isEnabled = !!(ttsConfig?.enabled && ttsConfig?.apiKey)
const cleanup = useCallback(() => {
if (audioRef.current) {
audioRef.current.pause()
audioRef.current.src = ''
audioRef.current = null
}
if (abortControllerRef.current) {
abortControllerRef.current.abort()
abortControllerRef.current = null
}
prefetchedBlobsRef.current.forEach((_, key) => {
prefetchedBlobsRef.current.delete(key)
})
prefetchedBlobsRef.current.clear()
chunksRef.current = []
chunkIndexRef.current = 0
fetchingIndexRef.current = -1
}, [])
const stop = useCallback(() => {
stoppedRef.current = true
cleanup()
setState('idle')
setCurrentText(null)
setError(null)
}, [cleanup])
useEffect(() => {
return () => {
stoppedRef.current = true
cleanup()
}
}, [cleanup])
const synthesize = useCallback(async (text: string, signal?: AbortSignal): Promise<Blob | null> => {
if (stoppedRef.current) return null
try {
const response = await fetch(`${API_BASE_URL}/api/tts/synthesize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
signal,
})
if (stoppedRef.current) return null
if (!response.ok) {
let errorMessage = 'TTS request failed'
try {
const errorData = await response.json()
errorMessage = errorData.error || errorData.details || errorMessage
} catch {
if (response.status === 401) errorMessage = 'Invalid API key'
else if (response.status === 429) errorMessage = 'Rate limit exceeded'
else if (response.status >= 500) errorMessage = 'Service unavailable'
}
throw new Error(errorMessage)
}
const contentType = response.headers.get('content-type')
if (!contentType?.includes('audio')) {
throw new Error('Invalid response from TTS service')
}
const blob = await response.blob()
if (blob.size === 0) {
throw new Error('Empty audio response')
}
return blob
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
return null
}
throw err
}
}, [])
const fetchNextChunk = useCallback(async (index: number) => {
if (stoppedRef.current) return
if (index >= chunksRef.current.length) return
if (prefetchedBlobsRef.current.has(index)) {
fetchNextChunk(index + 1)
return
}
fetchingIndexRef.current = index
try {
const blob = await synthesize(chunksRef.current[index], abortControllerRef.current?.signal)
if (blob && !stoppedRef.current) {
prefetchedBlobsRef.current.set(index, blob)
fetchNextChunk(index + 1)
}
} catch {
if (stoppedRef.current) return
}
fetchingIndexRef.current = -1
}, [synthesize])
const playChunk = useCallback(async (index: number) => {
if (stoppedRef.current || index >= chunksRef.current.length) {
if (!stoppedRef.current) {
setState('idle')
setCurrentText(null)
}
return
}
chunkIndexRef.current = index
try {
let blob: Blob | undefined = prefetchedBlobsRef.current.get(index)
if (!blob) {
setState('loading')
const fetched = await synthesize(chunksRef.current[index], abortControllerRef.current?.signal)
if (fetched && !stoppedRef.current) {
blob = fetched
}
fetchNextChunk(index + 1)
}
if (!blob || stoppedRef.current) return
prefetchedBlobsRef.current.delete(index)
const url = URL.createObjectURL(blob)
const audio = new Audio(url)
audioRef.current = audio
audio.onended = () => {
URL.revokeObjectURL(url)
audioRef.current = null
if (!stoppedRef.current) {
playChunk(index + 1)
}
}
audio.onerror = () => {
URL.revokeObjectURL(url)
audioRef.current = null
if (!stoppedRef.current) {
setError('Audio playback failed')
setState('error')
}
}
setState('playing')
await audio.play()
} catch (err) {
if (stoppedRef.current) return
setError(err instanceof Error ? err.message : 'TTS failed')
setState('error')
}
}, [synthesize, fetchNextChunk])
const speak = useCallback(async (text: string): Promise<boolean> => {
if (!ttsConfig?.enabled) {
setError('TTS is not enabled')
setState('error')
return false
}
if (!ttsConfig?.apiKey) {
setError('API key not configured')
setState('error')
return false
}
if (!text?.trim()) {
setError('No text provided')
setState('error')
return false
}
if (!ttsConfig.voice || !ttsConfig.model) {
setError('Voice or model not configured')
setState('error')
return false
}
stop()
stoppedRef.current = false
setError(null)
setCurrentText(text)
abortControllerRef.current = new AbortController()
chunksRef.current = splitIntoChunks(text)
playChunk(0)
return true
}, [ttsConfig, stop, playChunk])
const value = {
speak,
stop,
state,
error,
currentText,
isEnabled,
isPlaying: state === 'playing',
isLoading: state === 'loading',
isIdle: state === 'idle',
}
return (
<TTSContext.Provider value={value}>
{children}
</TTSContext.Provider>
)
}
+17
View File
@@ -0,0 +1,17 @@
import { createContext } from 'react'
export type TTSState = 'idle' | 'loading' | 'playing' | 'error'
export interface TTSContextValue {
speak: (text: string) => Promise<boolean>
stop: () => void
state: TTSState
error: string | null
currentText: string | null
isEnabled: boolean
isPlaying: boolean
isLoading: boolean
isIdle: boolean
}
export const TTSContext = createContext<TTSContextValue | null>(null)
+6 -4
View File
@@ -58,8 +58,9 @@ export function usePermissionRequests(currentSessionID?: string) {
const filtered = sessionPermissions.filter(p => p.id !== permissionID)
if (filtered.length === 0) {
const { [sessionID]: _, ...rest } = prev
return rest
return Object.fromEntries(
Object.entries(prev).filter(([key]) => key !== sessionID)
)
}
return { ...prev, [sessionID]: filtered }
})
@@ -93,8 +94,9 @@ export function usePermissionRequests(currentSessionID?: string) {
const filtered = sessionPermissions.filter(p => p.id !== permissionID)
if (filtered.length === 0) {
const { [sessionID]: _, ...rest } = prev
return rest
return Object.fromEntries(
Object.entries(prev).filter(([key]) => key !== sessionID)
)
}
return { ...prev, [sessionID]: filtered }
}
+8 -317
View File
@@ -1,321 +1,12 @@
import { useState, useRef, useCallback, useEffect } from 'react'
import { useSettings } from './useSettings'
import { API_BASE_URL } from '@/config'
import { useContext } from 'react'
import { TTSContext, type TTSContextValue, type TTSState } from '@/contexts/tts-context'
const TTS_CACHE_NAME = 'tts-audio-cache'
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
const PUNCTUATION_REGEX = /(?<=[.!?;])\s+/
const AUDIO_PLAYBACK_MAX_RETRIES = 3
const AUDIO_PLAYBACK_RETRY_DELAY_MS = 50
const AUDIO_LOAD_TIMEOUT_MS = 5000
export type { TTSState }
function generateCacheKey(text: string, voice: string, model: string, speed: number): string {
const data = `${text}|${voice}|${model}|${speed}`
let hash = 0
for (let i = 0; i < data.length; i++) {
const char = data.charCodeAt(i)
hash = ((hash << 5) - hash) + char
hash = hash & hash
}
return Math.abs(hash).toString(16).padStart(8, '0')
}
function isCacheApiAvailable(): boolean {
return typeof caches !== 'undefined'
}
async function getCachedAudio(cacheKey: string): Promise<Blob | null> {
if (!isCacheApiAvailable()) return null
try {
const cache = await caches.open(TTS_CACHE_NAME)
const response = await cache.match(cacheKey)
if (!response) return null
const cachedAt = response.headers.get('x-cached-at')
if (cachedAt && Date.now() - parseInt(cachedAt) > CACHE_TTL_MS) {
await cache.delete(cacheKey)
return null
}
return await response.blob()
} catch {
return null
}
}
async function cacheAudio(cacheKey: string, blob: Blob): Promise<void> {
if (!isCacheApiAvailable()) return
try {
const cache = await caches.open(TTS_CACHE_NAME)
const headers = new Headers({
'Content-Type': 'audio/mpeg',
'x-cached-at': Date.now().toString(),
})
const response = new Response(blob, { headers })
await cache.put(cacheKey, response)
} catch {
// Cache API not available or storage full, continue without caching
}
}
export type TTSState = 'idle' | 'loading' | 'playing' | 'paused' | 'error'
function splitTextByPunctuation(text: string): string[] {
const chunks = text.split(PUNCTUATION_REGEX).filter(chunk => chunk.trim().length > 0)
return chunks.length > 0 ? chunks : [text]
}
export function useTTS() {
const { preferences } = useSettings()
const [state, setState] = useState<TTSState>('idle')
const [error, setError] = useState<string | null>(null)
const [currentText, setCurrentText] = useState<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const abortControllerRef = useRef<AbortController | null>(null)
const chunkQueueRef = useRef<string[]>([])
const isPlayingChunksRef = useRef<boolean>(false)
const fullTextRef = useRef<string | null>(null)
const ttsConfig = preferences?.tts
const isEnabled = ttsConfig?.enabled && ttsConfig?.apiKey
const cleanup = useCallback(() => {
if (audioRef.current) {
audioRef.current.pause()
audioRef.current.src = ''
audioRef.current = null
}
if (abortControllerRef.current) {
abortControllerRef.current.abort()
abortControllerRef.current = null
}
chunkQueueRef.current = []
isPlayingChunksRef.current = false
}, [])
useEffect(() => {
return () => cleanup()
}, [cleanup])
const synthesizeChunk = useCallback(async (text: string): Promise<Blob | null> => {
if (!isPlayingChunksRef.current) return null
const { voice, model, speed } = ttsConfig!
const cacheKey = generateCacheKey(text, voice, model, speed ?? 1)
const cachedBlob = await getCachedAudio(cacheKey)
if (!isPlayingChunksRef.current) return null
if (cachedBlob) return cachedBlob
abortControllerRef.current = new AbortController()
const response = await fetch(`${API_BASE_URL}/api/tts/synthesize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text }),
signal: abortControllerRef.current.signal,
})
if (!isPlayingChunksRef.current) return null
if (!response.ok) {
let errorMessage = 'TTS request failed'
try {
const errorData = await response.json()
errorMessage = errorData.error || errorData.details || errorMessage
} catch {
if (response.status === 401) errorMessage = 'Invalid TTS API key'
else if (response.status === 429) errorMessage = 'TTS rate limit exceeded'
else if (response.status >= 500) errorMessage = 'TTS service unavailable'
}
throw new Error(errorMessage)
}
const contentType = response.headers.get('content-type')
if (!contentType?.includes('audio')) throw new Error('Invalid response from TTS service')
const audioBlob = await response.blob()
if (!isPlayingChunksRef.current) return null
if (audioBlob.size === 0) throw new Error('Empty audio response from TTS service')
await cacheAudio(cacheKey, audioBlob)
return audioBlob
}, [ttsConfig])
const playNextChunk = useCallback(async () => {
if (!isPlayingChunksRef.current || chunkQueueRef.current.length === 0) {
isPlayingChunksRef.current = false
fullTextRef.current = null
setState('idle')
setCurrentText(null)
return
}
const chunk = chunkQueueRef.current.shift()!
try {
const audioBlob = await synthesizeChunk(chunk)
if (!audioBlob || !isPlayingChunksRef.current) return
const playAudioBlob = async (blob: Blob, retries = AUDIO_PLAYBACK_MAX_RETRIES): Promise<void> => {
let lastError: Error | null = null
for (let attempt = 1; attempt <= retries; attempt++) {
if (!isPlayingChunksRef.current) return
const typedBlob = new Blob([blob], { type: 'audio/mpeg' })
const audioUrl = URL.createObjectURL(typedBlob)
const audio = new Audio()
try {
await new Promise<void>((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('Audio load timeout'))
}, AUDIO_LOAD_TIMEOUT_MS)
audio.oncanplaythrough = () => {
clearTimeout(timeoutId)
resolve()
}
audio.onerror = () => {
clearTimeout(timeoutId)
reject(new Error(audio.error?.message || 'Audio load failed'))
}
audio.src = audioUrl
audio.load()
})
if (!isPlayingChunksRef.current) {
URL.revokeObjectURL(audioUrl)
return
}
audioRef.current = audio
audio.onplay = () => setState('playing')
audio.onpause = () => {
if (audio.currentTime < audio.duration) setState('paused')
}
audio.onended = () => {
URL.revokeObjectURL(audioUrl)
playNextChunk()
}
audio.onerror = () => {
URL.revokeObjectURL(audioUrl)
}
await audio.play()
return
} catch (err) {
URL.revokeObjectURL(audioUrl)
lastError = err instanceof Error ? err : new Error('Unknown error')
if (attempt < retries) {
await new Promise(r => setTimeout(r, AUDIO_PLAYBACK_RETRY_DELAY_MS * attempt))
}
}
}
throw lastError || new Error('Audio playback failed after retries')
}
await playAudioBlob(audioBlob)
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
setState('idle')
return
}
setError(err instanceof Error ? err.message : 'TTS failed')
setState('error')
isPlayingChunksRef.current = false
}
}, [synthesizeChunk])
const speak = useCallback(async (text: string) => {
if (!ttsConfig?.enabled) {
setError('TTS is not enabled in settings')
setState('error')
return
}
if (!ttsConfig?.apiKey) {
setError('TTS API key is not configured')
setState('error')
return
}
if (!text?.trim()) {
setError('No text provided for speech')
setState('error')
return
}
if (!ttsConfig.voice || !ttsConfig.model) {
setError('TTS voice or model not configured')
setState('error')
return
}
cleanup()
setError(null)
setState('loading')
setCurrentText(text)
fullTextRef.current = text
const chunks = splitTextByPunctuation(text)
chunkQueueRef.current = chunks
isPlayingChunksRef.current = true
await playNextChunk()
}, [ttsConfig, cleanup, playNextChunk])
const stop = useCallback(() => {
cleanup()
fullTextRef.current = null
setState('idle')
setCurrentText(null)
setError(null)
}, [cleanup])
const pause = useCallback(() => {
if (audioRef.current && state === 'playing') {
audioRef.current.pause()
}
}, [state])
const resume = useCallback(() => {
if (audioRef.current && state === 'paused') {
audioRef.current.play()
}
}, [state])
const toggle = useCallback(() => {
if (state === 'playing') {
pause()
} else if (state === 'paused') {
resume()
}
}, [state, pause, resume])
return {
speak,
stop,
pause,
resume,
toggle,
state,
error,
currentText,
isEnabled,
isPlaying: state === 'playing',
isLoading: state === 'loading',
isPaused: state === 'paused',
isIdle: state === 'idle',
export function useTTS(): TTSContextValue {
const context = useContext(TTSContext)
if (!context) {
throw new Error('useTTS must be used within a TTSProvider')
}
return context
}
+3 -3
View File
@@ -128,7 +128,7 @@ export function RepoDetail() {
/>
) : branchToDisplay ? (
<Badge
className={`text-xs px-2.5 py-0.5 ${
className={`text-xs px-1.5 sm:px-2.5 py-0.5 ${
repo.isWorktree
? "bg-purple-600/20 text-purple-400 border-purple-600/40"
: isNotMainBranch
@@ -137,8 +137,8 @@ export function RepoDetail() {
}`}
title={repo.isWorktree ? "Worktree" : branchToDisplay}
>
{repo.isWorktree && <GitBranch className="h-3 w-3 mr-1" />}
{branchToDisplay}
{repo.isWorktree && <GitBranch className="h-3 w-3 sm:mr-1" />}
<span className="hidden sm:inline">{branchToDisplay}</span>
</Badge>
) : null}
</div>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opencode-manager",
"version": "0.4.2",
"version": "0.4.3",
"private": true,
"type": "module",
"packageManager": "pnpm@9.15.0",