From 65434c166ace0726b2d4813fa13f4f678b1e3373 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 1 Feb 2026 21:08:37 -0500 Subject: [PATCH 01/10] Remove unused variables from routes and migrations --- backend/src/db/migrations.ts | 3 ++- backend/src/index.ts | 2 +- backend/src/routes/auth.ts | 2 +- backend/test/services/git/GitBranchService.test.ts | 2 -- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/backend/src/db/migrations.ts b/backend/src/db/migrations.ts index 8a765671..3f2af61c 100644 --- a/backend/src/db/migrations.ts +++ b/backend/src/db/migrations.ts @@ -163,7 +163,8 @@ function migrateGitTokenToCredentials(db: Database): void { continue } - const { gitToken: _, ...rest } = parsed + const { gitToken: _gitToken, ...rest } = parsed + void _gitToken const migrated = { ...rest, gitCredentials: [{ diff --git a/backend/src/index.ts b/backend/src/index.ts index a4b644e7..7ce32e83 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -201,7 +201,7 @@ try { logger.error('Failed to initialize workspace:', error) } -app.route('/api/auth', createAuthRoutes(auth, db)) +app.route('/api/auth', createAuthRoutes(auth)) app.route('/api/auth-info', createAuthInfoRoutes(auth, db)) app.route('/api/health', createHealthRoutes(db)) diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts index f30b728b..19c24251 100644 --- a/backend/src/routes/auth.ts +++ b/backend/src/routes/auth.ts @@ -5,7 +5,7 @@ import { ENV } from '@opencode-manager/shared/config/env' import { logger } from '../utils/logger' import { hashPassword } from 'better-auth/crypto' -export function createAuthRoutes(auth: AuthInstance, _db: Database) { +export function createAuthRoutes(auth: AuthInstance): Hono { const app = new Hono() app.all('/*', async (c) => { diff --git a/backend/test/services/git/GitBranchService.test.ts b/backend/test/services/git/GitBranchService.test.ts index 8ff5a820..087a0473 100644 --- a/backend/test/services/git/GitBranchService.test.ts +++ b/backend/test/services/git/GitBranchService.test.ts @@ -218,12 +218,10 @@ describe('GitBranchService', () => { it('handles getBranchStatus failure for current branch gracefully', async () => { const mockRepo = { id: 1, fullPath: '/path/to/repo' } getRepoByIdMock.mockReturnValue(mockRepo as any) - let revListCalls = 0 executeCommandMock.mockImplementation((args) => { if (args.includes('rev-parse')) return Promise.resolve('main') if (args.includes('branch')) return Promise.resolve('* main abc123 Initial commit') if (args.includes('rev-list')) { - revListCalls++ return Promise.reject(new Error('No upstream')) } return Promise.resolve('') From 89a53d76452aafdf9114c6c6311bd6e13afbdd9c Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 1 Feb 2026 21:08:38 -0500 Subject: [PATCH 02/10] Use structured logging instead of console in archive service --- backend/src/services/archive.ts | 40 ++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/backend/src/services/archive.ts b/backend/src/services/archive.ts index 301ff94c..86573c39 100644 --- a/backend/src/services/archive.ts +++ b/backend/src/services/archive.ts @@ -4,6 +4,11 @@ import { readdir, stat, unlink } from 'fs/promises' import path from 'path' import os from 'os' import { logger } from '../utils/logger' +import { getReposPath } from '@opencode-manager/shared/config/env' + +function resolvePath(userPath: string): string { + return path.isAbsolute(userPath) ? userPath : path.join(getReposPath(), userPath) +} export interface ArchiveOptions { includeGit?: boolean @@ -57,14 +62,14 @@ async function getIgnoredPaths(gitRoot: string, targetPath: string, paths: strin const { spawn } = await import('child_process') const targetRelativeToRoot = path.relative(gitRoot, targetPath) - console.log('[getIgnoredPaths] gitRoot:', gitRoot, 'targetPath:', targetPath, 'targetRelativeToRoot:', targetRelativeToRoot) + logger.debug('[getIgnoredPaths] gitRoot:', gitRoot, 'targetPath:', targetPath, 'targetRelativeToRoot:', targetRelativeToRoot) const relativePaths = paths.map(p => { const relativeToTarget = p return targetRelativeToRoot ? path.join(targetRelativeToRoot, relativeToTarget) : relativeToTarget }) - console.log('[getIgnoredPaths] First 5 relativePaths:', relativePaths.slice(0, 5)) + logger.debug('[getIgnoredPaths] First 5 relativePaths:', relativePaths.slice(0, 5)) return new Promise((resolve) => { const ignored = new Set() @@ -83,9 +88,9 @@ async function getIgnoredPaths(gitRoot: string, targetPath: string, paths: strin proc.stdin?.end() proc.on('close', (code) => { - console.log('[getIgnoredPaths] git check-ignore exited with code:', code) + logger.debug('[getIgnoredPaths] git check-ignore exited with code:', code) const ignoredFullPaths = stdout.split('\n').filter(p => p.trim()) - console.log('[getIgnoredPaths] Raw ignored count:', ignoredFullPaths.length, 'first 5:', ignoredFullPaths.slice(0, 5)) + logger.debug('[getIgnoredPaths] Raw ignored count:', ignoredFullPaths.length, 'first 5:', ignoredFullPaths.slice(0, 5)) const targetRelativeToRoot = path.relative(gitRoot, targetPath) for (const fullPath of ignoredFullPaths) { @@ -99,7 +104,7 @@ async function getIgnoredPaths(gitRoot: string, targetPath: string, paths: strin ignored.add(relativePath) } } - console.log('[getIgnoredPaths] Final ignored set size:', ignored.size) + logger.debug('[getIgnoredPaths] Final ignored set size:', ignored.size) resolve(ignored) }) @@ -200,6 +205,7 @@ async function filterIgnoredPaths(targetPath: string, allPaths: string[], option } export async function createRepoArchive(repoPath: string, options?: ArchiveOptions): Promise { + repoPath = resolvePath(repoPath) const repoName = path.basename(repoPath) const tempFile = path.join(os.tmpdir(), `${repoName}-${Date.now()}.zip`) @@ -237,6 +243,7 @@ export async function createRepoArchive(repoPath: string, options?: ArchiveOptio } export async function createDirectoryArchive(directoryPath: string, archiveName?: string, options?: ArchiveOptions): Promise { + directoryPath = resolvePath(directoryPath) const dirName = archiveName || path.basename(directoryPath) const tempFile = path.join(os.tmpdir(), `${dirName}-${Date.now()}.zip`) @@ -293,34 +300,35 @@ export async function getArchiveSize(filePath: string): Promise { } export async function getIgnoredPathsList(directoryPath: string): Promise { - console.log('[getIgnoredPathsList] Starting for:', directoryPath) + directoryPath = resolvePath(directoryPath) + logger.debug('[getIgnoredPathsList] Starting for:', directoryPath) const gitRoot = await findGitRoot(directoryPath) - console.log('[getIgnoredPathsList] Git root:', gitRoot) + logger.debug('[getIgnoredPathsList] Git root:', gitRoot) if (!gitRoot) { - console.log('[getIgnoredPathsList] No git root found') + logger.debug('[getIgnoredPathsList] No git root found') const hasGitDir = await collectFiles(directoryPath).then( paths => paths.some(p => p.startsWith('.git/') || p === '.git') ).catch(() => false) if (hasGitDir) { - console.log('[getIgnoredPathsList] Has .git dir, returning [.git/]') + logger.debug('[getIgnoredPathsList] Has .git dir, returning [.git/]') return ['.git/'] } - console.log('[getIgnoredPathsList] No .git dir, returning []') + logger.debug('[getIgnoredPathsList] No .git dir, returning []') return [] } const allPaths = await collectFiles(directoryPath) - console.log('[getIgnoredPathsList] Collected', allPaths.length, 'paths') + logger.debug('[getIgnoredPathsList] Collected', allPaths.length, 'paths') const ignoredSet = new Set() const batchSize = 1000 for (let i = 0; i < allPaths.length; i += batchSize) { const batch = allPaths.slice(i, i + batchSize) - console.log('[getIgnoredPathsList] Checking batch', i, 'to', i + batch.length) + logger.debug('[getIgnoredPathsList] Checking batch', i, 'to', i + batch.length) const ignored = await getIgnoredPaths(gitRoot, directoryPath, batch) - console.log('[getIgnoredPathsList] Batch ignored count:', ignored.size) + logger.debug('[getIgnoredPathsList] Batch ignored count:', ignored.size) for (const p of ignored) { ignoredSet.add(p) if (p.endsWith('/')) { @@ -331,7 +339,7 @@ export async function getIgnoredPathsList(directoryPath: string): Promise() @@ -358,14 +366,14 @@ export async function getIgnoredPathsList(directoryPath: string): Promise true).catch(() => false) - console.log('[getIgnoredPathsList] .git exists:', gitDirExists) + logger.debug('[getIgnoredPathsList] .git exists:', gitDirExists) if (gitDirExists && !ignoredDirs.some(p => p.startsWith('.git'))) { ignoredDirs.push('.git/') } ignoredDirs.sort() - console.log('[getIgnoredPathsList] Final result:', ignoredDirs) + logger.debug('[getIgnoredPathsList] Final result:', ignoredDirs) return ignoredDirs } From 504ad64b583610cf3733cc2169bf4e720f056ba0 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 1 Feb 2026 21:08:38 -0500 Subject: [PATCH 03/10] Remove unused test variables and configure ESLint for test files --- backend/eslint.config.js | 6 ++++++ backend/test/routes/files.test.ts | 15 ++----------- backend/test/routes/tts.test.ts | 21 +------------------ .../test/services/git/GitLogService.test.ts | 1 - backend/test/utils/helpers.test.ts | 13 ------------ 5 files changed, 9 insertions(+), 47 deletions(-) diff --git a/backend/eslint.config.js b/backend/eslint.config.js index 19671e83..76cb27e9 100644 --- a/backend/eslint.config.js +++ b/backend/eslint.config.js @@ -28,4 +28,10 @@ export default defineConfig([ 'no-useless-escape': 'warn', }, }, + { + files: ['test/**/*.ts'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + }, + }, ]) \ No newline at end of file diff --git a/backend/test/routes/files.test.ts b/backend/test/routes/files.test.ts index 301dc3b5..23aaa5ad 100644 --- a/backend/test/routes/files.test.ts +++ b/backend/test/routes/files.test.ts @@ -4,7 +4,7 @@ import { Hono } from 'hono' import type { ReadStream } from 'fs' import * as fileService from '../../src/services/files' import * as archiveService from '../../src/services/archive' -import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@opencode-manager/shared' +import type { FileInfo, ChunkedFileInfo } from '@opencode-manager/shared' interface FileUploadResult { name: string @@ -47,7 +47,6 @@ vi.mock('../../src/services/archive', () => ({ })) const getFile = fileService.getFile as MockedFunction -const getRawFileContent = fileService.getRawFileContent as MockedFunction const getFileRange = fileService.getFileRange as MockedFunction const uploadFile = fileService.uploadFile as MockedFunction const createFileOrFolder = fileService.createFileOrFolder as MockedFunction @@ -58,7 +57,6 @@ const applyFilePatches = fileService.applyFilePatches as MockedFunction const getArchiveSize = archiveService.getArchiveSize as MockedFunction const getArchiveStream = archiveService.getArchiveStream as MockedFunction -const deleteArchive = archiveService.deleteArchive as MockedFunction describe('File Routes', () => { let app: Hono @@ -81,7 +79,7 @@ describe('File Routes', () => { getArchiveSize.mockResolvedValue(1024) getArchiveStream.mockReturnValue(mockStream) - const response = await app.request('/api/files/test-repo/src/download-zip') + await app.request('/api/files/test-repo/src/download-zip') expect(createDirectoryArchive).toHaveBeenCalledWith('test-repo/src', undefined, { includeGit: false, @@ -497,15 +495,6 @@ describe('File Routes', () => { }) describe('Path Traversal Protection', () => { - const mockFileInfo: FileInfo = { - name: 'test.txt', - path: 'safe-path/test.txt', - isDirectory: false, - size: 100, - mimeType: 'text/plain', - content: '', - lastModified: new Date(), - } it('should reject path with ../ segments via service error', async () => { const error = { message: 'Path traversal detected', statusCode: 403 } diff --git a/backend/test/routes/tts.test.ts b/backend/test/routes/tts.test.ts index 7504e7a0..2b3e561d 100644 --- a/backend/test/routes/tts.test.ts +++ b/backend/test/routes/tts.test.ts @@ -1,6 +1,5 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import * as fs from 'fs/promises' -import { logger } from '../../src/utils/logger' vi.mock('fs/promises', () => ({ mkdir: vi.fn(), @@ -27,7 +26,6 @@ vi.mock('../../src/utils/logger', () => ({ const mockMkdir = fs.mkdir as any const mockReadFile = fs.readFile as any -const mockWriteFile = fs.writeFile as any const mockReaddir = fs.readdir as any const mockStat = fs.stat as any const mockUnlink = fs.unlink as any @@ -36,29 +34,12 @@ import { createTTSRoutes, cleanupExpiredCache, getCacheStats, generateCacheKey, 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) + createTTSRoutes(mockDb) }) describe('generateCacheKey', () => { diff --git a/backend/test/services/git/GitLogService.test.ts b/backend/test/services/git/GitLogService.test.ts index 8fb96751..defc3730 100644 --- a/backend/test/services/git/GitLogService.test.ts +++ b/backend/test/services/git/GitLogService.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ import { describe, it, expect, vi, beforeEach, type MockedFunction } from 'vitest' vi.mock('bun:sqlite', () => ({ diff --git a/backend/test/utils/helpers.test.ts b/backend/test/utils/helpers.test.ts index 55d30295..8a9ead66 100644 --- a/backend/test/utils/helpers.test.ts +++ b/backend/test/utils/helpers.test.ts @@ -3,28 +3,24 @@ import { describe, it, expect } from 'vitest' describe('Process Helper Functions', () => { describe('mapProcessState', () => { it('should map "running" state correctly', () => { - const state = 'running' const mapped = 'running' as const expect(mapped).toBe('running') }) it('should map "stopped" state to "stopped"', () => { - const state = 'stopped' const mapped = 'stopped' as const expect(mapped).toBe('stopped') }) it('should map "starting" state to "starting"', () => { - const state = 'starting' const mapped = 'starting' as const expect(mapped).toBe('starting') }) it('should map unknown states to "error"', () => { - const state = 'unknown' const mapped = 'error' as const expect(mapped).toBe('error') @@ -62,28 +58,24 @@ describe('Process Helper Functions', () => { describe('validateRepoUrl', () => { it('should accept valid GitHub HTTPS URLs', () => { - const url = 'https://github.com/user/repo' const isValid = true expect(isValid).toBe(true) }) it('should accept valid GitHub SSH URLs', () => { - const url = 'git@github.com:user/repo.git' const isValid = true expect(isValid).toBe(true) }) it('should reject invalid URLs', () => { - const url = 'not-a-url' const isValid = false expect(isValid).toBe(false) }) it('should accept GitLab URLs', () => { - const url = 'https://gitlab.com/user/repo' const isValid = true expect(isValid).toBe(true) @@ -92,11 +84,6 @@ describe('Process Helper Functions', () => { describe('sanitizeEnvVars', () => { it('should filter out undefined values', () => { - const env = { - DEFINED: 'value', - UNDEFINED: undefined - } - const sanitized = ['DEFINED=value'] expect(sanitized).not.toContain('UNDEFINED') From 910f18f2aac25aad6b88e62ee7365f53909238c3 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 1 Feb 2026 21:15:42 -0500 Subject: [PATCH 04/10] refactor sse directory management with reference counting and improve message invalidation --- frontend/src/contexts/EventContext.tsx | 37 +++++++++++++-- frontend/src/hooks/useSSE.ts | 20 +++++--- frontend/src/lib/sseManager.ts | 64 ++++++++++++-------------- 3 files changed, 76 insertions(+), 45 deletions(-) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 2977817c..6707aa1c 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -6,7 +6,7 @@ import { OpenCodeClient } from '@/api/opencode' import { listRepos } from '@/api/repos' import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent } from '@/api/types' import { showToast } from '@/lib/toast' -import { subscribeToSSE } from '@/lib/sseManager' +import { subscribeToSSE, addSSEDirectory } from '@/lib/sseManager' import { OPENCODE_API_ENDPOINT } from '@/config' import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState' @@ -51,6 +51,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const clientsRef = useRef>(new Map()) const prevPermissionCountRef = useRef(0) + const initialFetchDoneRef = useRef(false) const MAX_CACHED_CLIENTS = 50 useEffect(() => { @@ -259,10 +260,15 @@ export function EventProvider({ children }: { children: React.ReactNode }) { case 'question.replied': case 'question.rejected': if ('requestID' in event.properties && 'sessionID' in event.properties) { + const sessionID = event.properties.sessionID as string removeQuestion( event.properties.requestID as string, - event.properties.sessionID as string + sessionID ) + queryClient.invalidateQueries({ + queryKey: ['opencode', 'messages'], + predicate: (query) => query.queryKey.includes(sessionID) + }) } break } @@ -270,13 +276,38 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const handleStatusChange = (connected: boolean) => { if (connected) { + initialFetchDoneRef.current = false fetchInitialPendingData() } } const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange) return unsubscribe - }, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData]) + }, [addPermission, removePermission, addQuestion, removeQuestion, fetchInitialPendingData, queryClient]) + + useEffect(() => { + if (!repos || repos.length === 0) return + + const cleanupFns: (() => void)[] = [] + const uniqueDirectories = [...new Set(repos.map(r => r.fullPath))] + + uniqueDirectories.forEach(directory => { + const cleanup = addSSEDirectory(directory) + cleanupFns.push(cleanup) + }) + + return () => { + cleanupFns.forEach(fn => fn()) + } + }, [repos]) + + useEffect(() => { + if (!repos || repos.length === 0) return + if (initialFetchDoneRef.current) return + + initialFetchDoneRef.current = true + fetchInitialPendingData() + }, [repos, fetchInitialPendingData]) const value: EventContextValue = useMemo(() => ({ permissions: { diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index c13c986d..e65d8aec 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -6,7 +6,7 @@ import { showToast } from '@/lib/toast' import { settingsApi } from '@/api/settings' import { useSessionStatus } from '@/stores/sessionStatusStore' import { useSessionTodos } from '@/stores/sessionTodosStore' -import { subscribeToSSE, reconnectSSE, addSSEDirectory, removeSSEDirectory } from '@/lib/sseManager' +import { subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager' import { parseOpenCodeError } from '@/lib/opencode-errors' const handleRestartServer = async () => { @@ -309,6 +309,16 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, break } + case 'question.replied': + case 'question.rejected': { + if (!('sessionID' in event.properties)) break + const { sessionID } = event.properties + queryClient.invalidateQueries({ + queryKey: ['opencode', 'messages', opcodeUrl, sessionID, directory] + }) + break + } + default: break } @@ -358,9 +368,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } } - if (directory) { - addSSEDirectory(directory) - } + const directoryCleanup = directory ? addSSEDirectory(directory) : undefined const unsubscribe = subscribeToSSE(handleMessage, handleStatusChange) @@ -376,9 +384,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, window.removeEventListener('focus', handleReconnect) window.removeEventListener('online', handleReconnect) unsubscribe() - if (directory) { - removeSSEDirectory(directory) - } + directoryCleanup?.() } }, [opcodeUrl, directory, handleSSEEvent, fetchInitialData]) diff --git a/frontend/src/lib/sseManager.ts b/frontend/src/lib/sseManager.ts index 20dc48b7..59007af0 100644 --- a/frontend/src/lib/sseManager.ts +++ b/frontend/src/lib/sseManager.ts @@ -15,7 +15,7 @@ class SSEManager { private static instance: SSEManager private eventSource: EventSource | null = null private subscribers: Map = new Map() - private directories: Set = new Set() + private directoryRefCounts: Map = new Map() private pendingDirectories: Set = new Set() private reconnectTimeout: ReturnType | null = null private reconnectDelay: number = RECONNECT_DELAY_MS @@ -65,18 +65,17 @@ class SSEManager { } addDirectory(directory: string): () => void { - if (this.directories.has(directory)) { - return () => this.cleanupDirectory(directory) - } + const currentCount = this.directoryRefCounts.get(directory) ?? 0 + this.directoryRefCounts.set(directory, currentCount + 1) - this.directories.add(directory) - - if (this.clientId && this.isConnected) { - this.subscribeToDirectory(directory) - } else { - this.pendingDirectories.add(directory) - if (!this.eventSource) { - this.reconnect() + if (currentCount === 0) { + if (this.clientId && this.isConnected) { + this.subscribeToDirectory(directory) + } else { + this.pendingDirectories.add(directory) + if (!this.eventSource) { + this.reconnect() + } } } @@ -84,15 +83,20 @@ class SSEManager { } private cleanupDirectory(directory: string): void { - this.directories.delete(directory) - this.pendingDirectories.delete(directory) - - if (this.clientId && this.isConnected) { - fetch('/api/sse/unsubscribe', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ clientId: this.clientId, directories: [directory] }) - }).catch(() => {}) + const currentCount = this.directoryRefCounts.get(directory) ?? 0 + if (currentCount <= 1) { + this.directoryRefCounts.delete(directory) + this.pendingDirectories.delete(directory) + + if (this.clientId && this.isConnected) { + fetch('/api/sse/unsubscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ clientId: this.clientId, directories: [directory] }) + }).catch(() => {}) + } + } else { + this.directoryRefCounts.set(directory, currentCount - 1) } } @@ -133,27 +137,17 @@ class SSEManager { } removeDirectory(directory: string): void { - if (!this.directories.has(directory)) return - - this.directories.delete(directory) - - if (this.clientId && this.isConnected) { - fetch('/api/sse/unsubscribe', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ clientId: this.clientId, directories: [directory] }) - }).catch(() => {}) - } + this.cleanupDirectory(directory) } getDirectories(): string[] { - return Array.from(this.directories) + return Array.from(this.directoryRefCounts.keys()) } private buildUrl(): string { const url = new URL('/api/sse/stream', window.location.origin) - if (this.directories.size > 0) { - url.searchParams.set('directories', Array.from(this.directories).join(',')) + if (this.directoryRefCounts.size > 0) { + url.searchParams.set('directories', Array.from(this.directoryRefCounts.keys()).join(',')) } return url.toString() } From 13ea42c5321b919768067204182250e216076461 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sun, 1 Feb 2026 21:44:53 -0500 Subject: [PATCH 05/10] simplify question prompt Other option handling and increase max height Remove redundant Cancel/Confirm buttons, use main Next/Confirm button for custom input, prevent double selection in single-select mode, auto-scroll textarea on focus, increase max-height from 40vh to 70vh --- .../src/components/session/QuestionPrompt.tsx | 55 +++++++++++-------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/frontend/src/components/session/QuestionPrompt.tsx b/frontend/src/components/session/QuestionPrompt.tsx index 73f2e3d1..8046cc5b 100644 --- a/frontend/src/components/session/QuestionPrompt.tsx +++ b/frontend/src/components/session/QuestionPrompt.tsx @@ -88,6 +88,22 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr }) }, []) + const handleExpandOther = useCallback((questionIndex: number) => { + if (!isMultiSelect) { + setAnswers(prev => { + const updated = [...prev] + updated[questionIndex] = [] + return updated + }) + } + setConfirmedCustoms(prev => { + const updated = [...prev] + updated[questionIndex] = '' + return updated + }) + setExpandedOther(questionIndex) + }, [isMultiSelect]) + const confirmCustomInput = useCallback((questionIndex: number) => { const value = customInputs[questionIndex]?.trim() if (!value) { @@ -125,6 +141,14 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr } }, [customInputs, confirmedCustoms, questions, isSingleSelect, goToNext, handleSubmitSingle]) + const handleNext = useCallback(() => { + if (expandedOther === currentIndex) { + confirmCustomInput(currentIndex) + } else { + goToNext() + } + }, [expandedOther, currentIndex, confirmCustomInput, goToNext]) + const handleSubmit = async () => { setIsSubmitting(true) try { @@ -194,7 +218,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr -
+
{isConfirmStep ? ( selectOption(currentIndex, label)} - onExpandOther={() => setExpandedOther(currentIndex)} + onExpandOther={() => handleExpandOther(currentIndex)} onCustomInputChange={(value) => handleCustomInput(currentIndex, value)} onConfirmCustomInput={() => confirmCustomInput(currentIndex)} onCollapseOther={() => setExpandedOther(null)} @@ -267,11 +291,11 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr ) : ( ) @@ -315,6 +339,7 @@ function QuestionStep({ useEffect(() => { if (expandedOther && textareaRef.current) { textareaRef.current.focus() + textareaRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' }) } }, [expandedOther]) @@ -388,7 +413,7 @@ function QuestionStep({
@@ -421,24 +446,6 @@ function QuestionStep({ } }} /> -
- - -
)} From 8233fec1a954c7c38d5cdb092365b2e68e3f7ac5 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Mon, 2 Feb 2026 23:58:16 -0500 Subject: [PATCH 06/10] Standardize on fetch and remove axios dependency --- frontend/package.json | 1 - frontend/src/api/fetchWrapper.ts | 109 ++++++++++++++++++ frontend/src/api/oauth.ts | 27 +++-- frontend/src/api/opencode.ts | 190 ++++++++++++++++++++----------- frontend/src/api/providers.ts | 38 ++++--- frontend/src/api/settings.ts | 111 +++++++++++------- frontend/src/api/stt.ts | 52 ++++++--- frontend/src/api/tts.ts | 28 ++--- pnpm-lock.yaml | 190 ------------------------------- 9 files changed, 379 insertions(+), 367 deletions(-) create mode 100644 frontend/src/api/fetchWrapper.ts diff --git a/frontend/package.json b/frontend/package.json index d6d757fe..b8ba2f8e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -29,7 +29,6 @@ "@radix-ui/react-tabs": "^1.1.13", "@tailwindcss/vite": "^4.1.14", "@tanstack/react-query": "^5.90.5", - "axios": "^1.12.2", "better-auth": "^1.4.17", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/frontend/src/api/fetchWrapper.ts b/frontend/src/api/fetchWrapper.ts new file mode 100644 index 00000000..b4214fa0 --- /dev/null +++ b/frontend/src/api/fetchWrapper.ts @@ -0,0 +1,109 @@ +export class FetchError extends Error { + statusCode?: number + code?: string + + constructor(message: string, statusCode?: number, code?: string) { + super(message) + this.name = 'FetchError' + this.statusCode = statusCode + this.code = code + } +} + +interface ApiError { + error?: string + code?: string + message?: string +} + +interface FetchWrapperOptions extends RequestInit { + timeout?: number + params?: Record +} + +async function handleResponse(response: Response): Promise { + const data: ApiError = await response.json().catch(() => ({ error: 'An error occurred' })) + throw new FetchError(data.error || data.message || 'Request failed', response.status, data.code) +} + +async function fetchWrapper( + url: string, + options: FetchWrapperOptions = {} +): Promise { + const { timeout = 30000, params, ...fetchOptions } = options + + const urlObj = new URL(url, window.location.origin) + if (params) { + Object.entries(params).forEach(([key, value]) => { + if (value !== undefined) { + urlObj.searchParams.append(key, String(value)) + } + }) + } + + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), timeout) + + try { + const response = await fetch(urlObj.toString(), { + ...fetchOptions, + signal: controller.signal, + }) + + clearTimeout(timeoutId) + + if (!response.ok) { + await handleResponse(response) + } + + return response.json() + } catch (error) { + clearTimeout(timeoutId) + if (error instanceof Error && error.name === 'AbortError') { + throw new FetchError('Request timeout', 408, 'TIMEOUT') + } + throw error + } +} + +async function fetchWrapperBlob( + url: string, + options: FetchWrapperOptions = {} +): Promise { + const { timeout = 30000, params, ...fetchOptions } = options + + const urlObj = new URL(url, window.location.origin) + if (params) { + Object.entries(params).forEach(([key, value]) => { + if (value !== undefined) { + urlObj.searchParams.append(key, String(value)) + } + }) + } + + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), timeout) + + try { + const response = await fetch(urlObj.toString(), { + ...fetchOptions, + signal: controller.signal, + }) + + clearTimeout(timeoutId) + + if (!response.ok) { + await handleResponse(response) + } + + return response.blob() + } catch (error) { + clearTimeout(timeoutId) + if (error instanceof Error && error.name === 'AbortError') { + throw new FetchError('Request timeout', 408, 'TIMEOUT') + } + throw error + } +} + +export { fetchWrapper, fetchWrapperBlob } diff --git a/frontend/src/api/oauth.ts b/frontend/src/api/oauth.ts index b4e187c3..d45e7168 100644 --- a/frontend/src/api/oauth.ts +++ b/frontend/src/api/oauth.ts @@ -1,5 +1,5 @@ -import axios from "axios" import { API_BASE_URL } from "@/config" +import { fetchWrapper, FetchError } from "./fetchWrapper" export interface OAuthAuthorizeResponse { url: string @@ -22,9 +22,8 @@ export interface ProviderAuthMethods { } function handleApiError(error: unknown, context: string): never { - if (axios.isAxiosError(error)) { - const message = error.response?.data?.error || error.message - throw new Error(`${context}: ${message}`) + if (error instanceof FetchError) { + throw new Error(`${context}: ${error.message}`) } throw error } @@ -32,10 +31,11 @@ function handleApiError(error: unknown, context: string): never { export const oauthApi = { authorize: async (providerId: string, method: number): Promise => { try { - const { data } = await axios.post(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, { - method, + return fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ method }), }) - return data } catch (error) { handleApiError(error, "OAuth authorization failed") } @@ -43,8 +43,11 @@ export const oauthApi = { callback: async (providerId: string, request: OAuthCallbackRequest): Promise => { try { - const { data } = await axios.post(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, request) - return data + return fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), + }) } catch (error) { handleApiError(error, "OAuth callback failed") } @@ -52,8 +55,10 @@ export const oauthApi = { getAuthMethods: async (): Promise => { try { - const { data } = await axios.get(`${API_BASE_URL}/api/oauth/auth-methods`) - return data.providers || data + const { providers, ...rest } = await fetchWrapper<{ providers?: ProviderAuthMethods } & ProviderAuthMethods>( + `${API_BASE_URL}/api/oauth/auth-methods` + ) + return providers || rest } catch (error) { handleApiError(error, "Failed to get provider auth methods") } diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index b2f04dc8..a4e82907 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -1,5 +1,5 @@ -import axios, { type AxiosInstance } from 'axios' import type { paths } from './opencode-types' +import { fetchWrapper } from './fetchWrapper' type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json'] type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json'] @@ -17,165 +17,217 @@ type SendPromptResponse = paths['/session/{sessionID}/message']['post']['respons export type { SendPromptResponse } export class OpenCodeClient { - private client: AxiosInstance private baseURL: string private directory?: string constructor(baseURL: string, directory?: string) { this.baseURL = baseURL this.directory = directory - this.client = axios.create({ - baseURL, - timeout: 30000 - }) - - this.client.interceptors.request.use((config) => { - if (this.directory) { - config.params = { ...config.params, directory: this.directory } - } - return config - }) } setDirectory(directory: string) { this.directory = directory } + private getParams(params?: Record) { + if (!this.directory) return params + return { ...params, directory: this.directory } + } + async listSessions() { - const response = await this.client.get('/session') - return response.data + return fetchWrapper(`${this.baseURL}/session`, { + params: this.getParams(), + }) } async getSession(sessionID: string) { - const response = await this.client.get(`/session/${sessionID}`) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}`, { + params: this.getParams(), + }) } async createSession(data: CreateSessionRequest) { - const response = await this.client.post('/session', data) - return response.data + return fetchWrapper(`${this.baseURL}/session`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) } async deleteSession(sessionID: string) { - await this.client.delete(`/session/${sessionID}`) + return fetchWrapper(`${this.baseURL}/session/${sessionID}`, { + method: 'DELETE', + params: this.getParams(), + }) } async updateSession(sessionID: string, data: { title?: string }) { - const response = await this.client.patch(`/session/${sessionID}`, data) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}`, { + method: 'PATCH', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) } async forkSession(sessionID: string, messageID?: string) { - const response = await this.client.post(`/session/${sessionID}/fork`, { - messageID + return fetchWrapper(`${this.baseURL}/session/${sessionID}/fork`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ messageID }), }) - return response.data } async abortSession(sessionID: string) { - await this.client.post(`/session/${sessionID}/abort`) + return fetchWrapper(`${this.baseURL}/session/${sessionID}/abort`, { + method: 'POST', + params: this.getParams(), + }) } async listMessages(sessionID: string) { - const response = await this.client.get(`/session/${sessionID}/message`) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}/message`, { + params: this.getParams(), + }) } async sendPrompt(sessionID: string, data: SendPromptRequest): Promise { - const response = await this.client.post( - `/session/${sessionID}/message`, - data, - { timeout: 0 } + return fetchWrapper( + `${this.baseURL}/session/${sessionID}/message`, + { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + timeout: 0, + } ) - return response.data } async summarizeSession(sessionID: string, providerID: string, modelID: string) { - const response = await this.client.post(`/session/${sessionID}/summarize`, { - providerID, - modelID + return fetchWrapper(`${this.baseURL}/session/${sessionID}/summarize`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ providerID, modelID }), }) - return response.data } async getConfig() { - const response = await this.client.get('/config') - return response.data + return fetchWrapper(`${this.baseURL}/config`, { + params: this.getParams(), + }) } async updateConfig(config: Partial) { - const response = await this.client.patch('/config', config) - return response.data + return fetchWrapper(`${this.baseURL}/config`, { + method: 'PATCH', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(config), + }) } async getProviders() { - const response = await this.client.get('/provider') - return response.data + return fetchWrapper(`${this.baseURL}/provider`, { + params: this.getParams(), + }) } async getConfigProviders() { - const response = await this.client.get('/config/providers') - return response.data + return fetchWrapper(`${this.baseURL}/config/providers`, { + params: this.getParams(), + }) } async listCommands() { - const response = await this.client.get('/command') - return response.data + return fetchWrapper(`${this.baseURL}/command`, { + params: this.getParams(), + }) } async sendCommand(sessionID: string, data: CommandRequest) { - const response = await this.client.post(`/session/${sessionID}/command`, data) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}/command`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) } async sendShell(sessionID: string, data: ShellRequest) { - const response = await this.client.post(`/session/${sessionID}/shell`, data) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}/shell`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) } async respondToPermission(sessionID: string, permissionID: string, response: 'once' | 'always' | 'reject') { - const result = await this.client.post(`/session/${sessionID}/permissions/${permissionID}`, { response }) - return result.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}/permissions/${permissionID}`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ response }), + }) } async replyToQuestion(requestID: string, answers: string[][]) { - const result = await this.client.post(`/question/${requestID}/reply`, { answers }) - return result.data + return fetchWrapper(`${this.baseURL}/question/${requestID}/reply`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ answers }), + }) } async rejectQuestion(requestID: string) { - const result = await this.client.post(`/question/${requestID}/reject`) - return result.data + return fetchWrapper(`${this.baseURL}/question/${requestID}/reject`, { + method: 'POST', + params: this.getParams(), + }) } async listPendingQuestions() { - const response = await this.client.get('/question') - return response.data + return fetchWrapper(`${this.baseURL}/question`, { + params: this.getParams(), + }) } async listAgents() { - const response = await this.client.get('/agent') - return response.data + return fetchWrapper(`${this.baseURL}/agent`, { + params: this.getParams(), + }) } async revertMessage(sessionID: string, data: { messageID: string, partID?: string }) { - const response = await this.client.post(`/session/${sessionID}/revert`, data) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}/revert`, { + method: 'POST', + params: this.getParams(), + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + }) } async unrevertSession(sessionID: string) { - const response = await this.client.post(`/session/${sessionID}/unrevert`) - return response.data + return fetchWrapper(`${this.baseURL}/session/${sessionID}/unrevert`, { + method: 'POST', + params: this.getParams(), + }) } async getSessionStatuses() { - const response = await this.client.get>('/session/status') - return response.data + return fetchWrapper>(`${this.baseURL}/session/status`, { + params: this.getParams(), + }) } getEventSourceURL() { - const base = this.baseURL.startsWith('http') - ? this.baseURL + const base = this.baseURL.startsWith('http') + ? this.baseURL : `${window.location.origin}${this.baseURL}` const url = new URL(`${base}/event`) if (this.directory) { diff --git a/frontend/src/api/providers.ts b/frontend/src/api/providers.ts index f9bd0183..7f631439 100644 --- a/frontend/src/api/providers.ts +++ b/frontend/src/api/providers.ts @@ -1,6 +1,6 @@ -import axios from "axios"; import { API_BASE_URL } from "@/config"; import { settingsApi } from "./settings"; +import { fetchWrapper } from "./fetchWrapper"; export type ProviderSource = "configured" | "local" | "builtin"; @@ -152,14 +152,14 @@ interface OpenCodeProviderResponse { async function getProvidersFromOpenCodeServer(): Promise<{ providers: Provider[]; connected: string[] }> { try { - const response = await axios.get(`${API_BASE_URL}/api/opencode/provider`); - - if (response?.data?.all && Array.isArray(response.data.all)) { - const connectedSet = new Set(response.data.connected || []); - - const providers = response.data.all.map((openCodeProvider: OpenCodeProvider) => { + const response = await fetchWrapper(`${API_BASE_URL}/api/opencode/provider`); + + if (response?.all && Array.isArray(response.all)) { + const connectedSet = new Set(response.connected || []); + + const providers = response.all.map((openCodeProvider: OpenCodeProvider) => { const models: Record = {}; - + Object.entries(openCodeProvider.models).forEach(([modelId, openCodeModel]) => { models[modelId] = { id: modelId, @@ -203,7 +203,7 @@ async function getProvidersFromOpenCodeServer(): Promise<{ providers: Provider[] }; }); - return { providers, connected: response.data.connected || [] }; + return { providers, connected: response.connected || [] }; } } catch (error) { console.warn("Failed to load providers from OpenCode server", error); @@ -267,7 +267,7 @@ async function getConfiguredProviders(connectedIds: Set): Promise { const { providers: builtinProviders, connected } = await getProviders(); const connectedIds = new Set(connected); - + const configuredProviders = await getConfiguredProviders(connectedIds); const configuredIds = new Set(configuredProviders.map((p) => p.id)); @@ -326,24 +326,28 @@ export function formatProviderName( export const providerCredentialsApi = { list: async (): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/providers/credentials`); - return data.providers; + const { providers } = await fetchWrapper<{ providers: string[] }>(`${API_BASE_URL}/api/providers/credentials`); + return providers; }, getStatus: async (providerId: string): Promise => { - const { data } = await axios.get( + const { hasCredentials } = await fetchWrapper<{ hasCredentials: boolean }>( `${API_BASE_URL}/api/providers/${providerId}/credentials/status` ); - return data.hasCredentials; + return hasCredentials; }, set: async (providerId: string, apiKey: string): Promise => { - await axios.post(`${API_BASE_URL}/api/providers/${providerId}/credentials`, { - apiKey, + await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ apiKey }), }); }, delete: async (providerId: string): Promise => { - await axios.delete(`${API_BASE_URL}/api/providers/${providerId}/credentials`); + await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, { + method: 'DELETE', + }); }, }; diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index a19f35be..f7e6a7fb 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -1,4 +1,3 @@ -import axios from 'axios' import type { SettingsResponse, UpdateSettingsRequest, @@ -8,47 +7,50 @@ import type { UpdateOpenCodeConfigRequest } from './types/settings' import { API_BASE_URL } from '@/config' +import { fetchWrapper, FetchError } from './fetchWrapper' export const settingsApi = { getSettings: async (userId = 'default'): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/settings`, { + return fetchWrapper(`${API_BASE_URL}/api/settings`, { params: { userId }, }) - return data }, updateSettings: async ( updates: UpdateSettingsRequest, userId = 'default' ): Promise => { - const { data } = await axios.patch(`${API_BASE_URL}/api/settings`, updates, { + return fetchWrapper(`${API_BASE_URL}/api/settings`, { + method: 'PATCH', params: { userId }, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(updates), }) - return data }, resetSettings: async (userId = 'default'): Promise => { - const { data } = await axios.delete(`${API_BASE_URL}/api/settings`, { + return fetchWrapper(`${API_BASE_URL}/api/settings`, { + method: 'DELETE', params: { userId }, }) - return data }, getOpenCodeConfigs: async (userId = 'default'): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/settings/opencode-configs`, { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs`, { params: { userId }, }) - return data }, createOpenCodeConfig: async ( request: CreateOpenCodeConfigRequest, userId = 'default' ): Promise => { - const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-configs`, request, { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs`, { + method: 'POST', params: { userId }, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), }) - return data }, updateOpenCodeConfig: async ( @@ -56,21 +58,27 @@ export const settingsApi = { request: UpdateOpenCodeConfigRequest, userId = 'default' ): Promise => { - const { data } = await axios.put( + return fetchWrapper( `${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`, - request, - { params: { userId } } + { + method: 'PUT', + params: { userId }, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), + } ) - return data }, deleteOpenCodeConfig: async ( configName: string, userId = 'default' ): Promise => { - await axios.delete( + await fetchWrapper( `${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`, - { params: { userId } } + { + method: 'DELETE', + params: { userId }, + } ) return true }, @@ -79,46 +87,56 @@ export const settingsApi = { configName: string, userId = 'default' ): Promise => { - const { data } = await axios.post( + return fetchWrapper( `${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}/set-default`, - {}, - { params: { userId } } + { + method: 'POST', + params: { userId }, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + } ) - return data }, getDefaultOpenCodeConfig: async (userId = 'default'): Promise => { try { - const { data } = await axios.get(`${API_BASE_URL}/api/settings/opencode-configs/default`, { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs/default`, { params: { userId }, }) - return data } catch { return null } }, restartOpenCodeServer: async (): Promise<{ success: boolean; message: string; details?: string }> => { - const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-restart`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-restart`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) }, reloadOpenCodeConfig: async (): Promise<{ success: boolean; message: string; details?: string }> => { try { - const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-reload`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-reload`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) } catch (error) { - if (axios.isAxiosError(error) && error.response?.status === 404) { - const result = await axios.post(`${API_BASE_URL}/api/settings/opencode-restart`) - return result.data + if (error instanceof FetchError && error.statusCode === 404) { + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-restart`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) } throw error } }, rollbackOpenCodeConfig: async (): Promise<{ success: boolean; message: string; configName?: string }> => { - const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-rollback`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-rollback`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) }, getOpenCodeVersions: async (): Promise<{ @@ -130,8 +148,7 @@ export const settingsApi = { }> currentVersion: string | null }> => { - const { data } = await axios.get(`${API_BASE_URL}/api/settings/opencode-versions`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-versions`) }, installOpenCodeVersion: async (version: string): Promise<{ @@ -142,8 +159,11 @@ export const settingsApi = { recovered?: boolean recoveryMessage?: string }> => { - const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-install-version`, { version }) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-install-version`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ version }), + }) }, upgradeOpenCode: async (): Promise<{ @@ -155,22 +175,25 @@ export const settingsApi = { recovered?: boolean recoveryMessage?: string }> => { - const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-upgrade`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-upgrade`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }) }, getAgentsMd: async (): Promise<{ content: string }> => { - const { data } = await axios.get(`${API_BASE_URL}/api/settings/agents-md`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`) }, getDefaultAgentsMd: async (): Promise<{ content: string }> => { - const { data } = await axios.get(`${API_BASE_URL}/api/settings/agents-md/default`) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md/default`) }, updateAgentsMd: async (content: string): Promise<{ success: boolean }> => { - const { data } = await axios.put(`${API_BASE_URL}/api/settings/agents-md`, { content }) - return data + return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ content }), + }) }, } diff --git a/frontend/src/api/stt.ts b/frontend/src/api/stt.ts index f042872f..6725daaf 100644 --- a/frontend/src/api/stt.ts +++ b/frontend/src/api/stt.ts @@ -1,5 +1,5 @@ -import axios from 'axios' import { API_BASE_URL } from '@/config' +import { fetchWrapper, FetchError } from './fetchWrapper' export interface STTModelsResponse { models: string[] @@ -24,17 +24,15 @@ export interface STTErrorResponse { export const sttApi = { getModels: async (userId = 'default', forceRefresh = false): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/stt/models`, { + return fetchWrapper(`${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`, { + return fetchWrapper(`${API_BASE_URL}/api/stt/status`, { params: { userId }, }) - return data }, transcribe: async ( @@ -43,23 +41,41 @@ export const sttApi = { signal?: AbortSignal ): Promise => { const formData = new FormData() - - const extension = audioBlob.type.includes('webm') ? 'webm' : + + 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, + const urlObj = new URL(`${API_BASE_URL}/api/stt/transcribe`, window.location.origin) + urlObj.searchParams.set('userId', userId) + + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), 60000) + + const abortSignal = signal || controller.signal + + try { + const response = await fetch(urlObj.toString(), { + method: 'POST', + body: formData, + signal: abortSignal, + }) + + clearTimeout(timeoutId) + + if (!response.ok) { + const data = await response.json().catch(() => ({ error: 'Transcription failed' })) + throw new FetchError(data.error || 'Transcription failed', response.status) } - ) - return data + + return response.json() + } catch (error) { + clearTimeout(timeoutId) + if (error instanceof Error && error.name === 'AbortError') { + throw new FetchError('Transcription timeout', 408, 'TIMEOUT') + } + throw error + } }, } diff --git a/frontend/src/api/tts.ts b/frontend/src/api/tts.ts index 57de7231..4535a228 100644 --- a/frontend/src/api/tts.ts +++ b/frontend/src/api/tts.ts @@ -1,5 +1,5 @@ -import axios from 'axios' import { API_BASE_URL } from '@/config' +import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper' export interface TTSModelsResponse { models: string[] @@ -25,36 +25,30 @@ export interface TTSStatusResponse { export const ttsApi = { getModels: async (userId = 'default', forceRefresh = false): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/tts/models`, { + return fetchWrapper(`${API_BASE_URL}/api/tts/models`, { params: { userId, ...(forceRefresh && { refresh: 'true' }) }, }) - return data }, getVoices: async (userId = 'default', forceRefresh = false): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/tts/voices`, { + return fetchWrapper(`${API_BASE_URL}/api/tts/voices`, { params: { userId, ...(forceRefresh && { refresh: 'true' }) }, }) - return data }, getStatus: async (userId = 'default'): Promise => { - const { data } = await axios.get(`${API_BASE_URL}/api/tts/status`, { + return fetchWrapper(`${API_BASE_URL}/api/tts/status`, { params: { userId }, }) - return data }, synthesize: async (text: string, userId = 'default', signal?: AbortSignal): Promise => { - const { data } = await axios.post( - `${API_BASE_URL}/api/tts/synthesize`, - { text }, - { - params: { userId }, - responseType: 'blob', - signal, - } - ) - return data + return fetchWrapperBlob(`${API_BASE_URL}/api/tts/synthesize`, { + method: 'POST', + params: { userId }, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ text }), + signal, + }) }, } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d01b4cc7..59efff32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -139,9 +139,6 @@ importers: '@tanstack/react-query': specifier: ^5.90.5 version: 5.90.16(react@19.2.3) - axios: - specifier: ^1.12.2 - version: 1.13.2 better-auth: specifier: ^1.4.17 version: 1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4) @@ -1860,9 +1857,6 @@ packages: async@3.2.6: resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==} - asynckit@0.4.0: - resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - autoprefixer@10.4.23: resolution: {integrity: sha512-YYTXSFulfwytnjAPlw8QHncHJmlvFKtczb8InXaAx9Q0LbfDnfEYDE55omerIJKihhmU61Ft+cAOSzQVaBUmeA==} engines: {node: ^10 || ^12 || >=14} @@ -1870,9 +1864,6 @@ packages: peerDependencies: postcss: ^8.1.0 - axios@1.13.2: - resolution: {integrity: sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==} - b4a@1.7.3: resolution: {integrity: sha512-5Q2mfq2WfGuFp3uS//0s6baOJLMoVduPYVeNmDYxu5OUA1/cBfvr2RIS7vi62LdNj/urk1hfmj867I3qt6uZ7Q==} peerDependencies: @@ -2000,10 +1991,6 @@ packages: resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} engines: {node: '>=8'} - call-bind-apply-helpers@1.0.2: - resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} - engines: {node: '>= 0.4'} - callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} @@ -2076,10 +2063,6 @@ packages: colorette@1.4.0: resolution: {integrity: sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==} - combined-stream@1.0.8: - resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} - engines: {node: '>= 0.8'} - comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} @@ -2343,10 +2326,6 @@ packages: delaunator@5.0.1: resolution: {integrity: sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==} - delayed-stream@1.0.0: - resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} - engines: {node: '>=0.4.0'} - dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -2381,10 +2360,6 @@ packages: resolution: {integrity: sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==} engines: {node: '>=12'} - dunder-proto@1.0.1: - resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} - engines: {node: '>= 0.4'} - eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} @@ -2405,25 +2380,9 @@ packages: resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} engines: {node: '>=0.12'} - es-define-property@1.0.1: - resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} - engines: {node: '>= 0.4'} - - es-errors@1.3.0: - resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} - engines: {node: '>= 0.4'} - es-module-lexer@1.7.0: resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} - es-object-atoms@1.1.1: - resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} - engines: {node: '>= 0.4'} - - es-set-tostringtag@2.1.0: - resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} - engines: {node: '>= 0.4'} - esbuild@0.27.2: resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==} engines: {node: '>=18'} @@ -2568,23 +2527,10 @@ packages: flatted@3.3.3: resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} - follow-redirects@1.15.11: - resolution: {integrity: sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==} - engines: {node: '>=4.0'} - peerDependencies: - debug: '*' - peerDependenciesMeta: - debug: - optional: true - foreground-child@3.3.1: resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} engines: {node: '>=14'} - form-data@4.0.5: - resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==} - engines: {node: '>= 6'} - fraction.js@5.3.4: resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} @@ -2593,9 +2539,6 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] - function-bind@1.1.2: - resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - gensync@1.0.0-beta.2: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} @@ -2604,18 +2547,10 @@ packages: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} - get-intrinsic@1.3.0: - resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} - engines: {node: '>= 0.4'} - get-nonce@1.0.1: resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} engines: {node: '>=6'} - get-proto@1.0.1: - resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} - engines: {node: '>= 0.4'} - glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -2632,10 +2567,6 @@ packages: resolution: {integrity: sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==} engines: {node: '>=18'} - gopd@1.2.0: - resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} - engines: {node: '>= 0.4'} - graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} @@ -2646,18 +2577,6 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} - has-symbols@1.1.0: - resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} - engines: {node: '>= 0.4'} - - has-tostringtag@1.0.2: - resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} - engines: {node: '>= 0.4'} - - hasown@2.0.2: - resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} - engines: {node: '>= 0.4'} - hast-util-from-parse5@8.0.3: resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==} @@ -3013,10 +2932,6 @@ packages: engines: {node: '>= 20'} hasBin: true - math-intrinsics@1.1.0: - resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} - engines: {node: '>= 0.4'} - mdast-util-find-and-replace@3.0.2: resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==} @@ -3152,14 +3067,6 @@ packages: micromark@4.0.2: resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==} - mime-db@1.52.0: - resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} - engines: {node: '>= 0.6'} - - mime-types@2.1.35: - resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} - engines: {node: '>= 0.6'} - min-indent@1.0.1: resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} engines: {node: '>=4'} @@ -3319,9 +3226,6 @@ packages: property-information@7.1.0: resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} - proxy-from-env@1.1.0: - resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} - punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -5631,8 +5535,6 @@ snapshots: async@3.2.6: {} - asynckit@0.4.0: {} - autoprefixer@10.4.23(postcss@8.5.6): dependencies: browserslist: 4.28.1 @@ -5642,14 +5544,6 @@ snapshots: postcss: 8.5.6 postcss-value-parser: 4.2.0 - axios@1.13.2: - dependencies: - follow-redirects: 1.15.11 - form-data: 4.0.5 - proxy-from-env: 1.1.0 - transitivePeerDependencies: - - debug - b4a@1.7.3: {} bail@2.0.2: {} @@ -5733,11 +5627,6 @@ snapshots: cac@6.7.14: {} - call-bind-apply-helpers@1.0.2: - dependencies: - es-errors: 1.3.0 - function-bind: 1.1.2 - callsites@3.1.0: {} caniuse-lite@1.0.30001762: {} @@ -5815,10 +5704,6 @@ snapshots: colorette@1.4.0: {} - combined-stream@1.0.8: - dependencies: - delayed-stream: 1.0.0 - comma-separated-tokens@2.0.3: {} commander@7.2.0: {} @@ -6104,8 +5989,6 @@ snapshots: dependencies: robust-predicates: 3.0.2 - delayed-stream@1.0.0: {} - dequal@2.0.3: {} detect-libc@2.1.2: {} @@ -6132,12 +6015,6 @@ snapshots: dotenv@17.2.3: {} - dunder-proto@1.0.1: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-errors: 1.3.0 - gopd: 1.2.0 - eastasianwidth@0.2.0: {} electron-to-chromium@1.5.267: {} @@ -6153,23 +6030,8 @@ snapshots: entities@6.0.1: {} - es-define-property@1.0.1: {} - - es-errors@1.3.0: {} - es-module-lexer@1.7.0: {} - es-object-atoms@1.1.1: - dependencies: - es-errors: 1.3.0 - - es-set-tostringtag@2.1.0: - dependencies: - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - has-tostringtag: 1.0.2 - hasown: 2.0.2 - esbuild@0.27.2: optionalDependencies: '@esbuild/aix-ppc64': 0.27.2 @@ -6339,52 +6201,22 @@ snapshots: flatted@3.3.3: {} - follow-redirects@1.15.11: {} - foreground-child@3.3.1: dependencies: cross-spawn: 7.0.6 signal-exit: 4.1.0 - form-data@4.0.5: - dependencies: - asynckit: 0.4.0 - combined-stream: 1.0.8 - es-set-tostringtag: 2.1.0 - hasown: 2.0.2 - mime-types: 2.1.35 - fraction.js@5.3.4: {} fsevents@2.3.3: optional: true - function-bind@1.1.2: {} - gensync@1.0.0-beta.2: {} get-caller-file@2.0.5: {} - get-intrinsic@1.3.0: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - function-bind: 1.1.2 - get-proto: 1.0.1 - gopd: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.2 - math-intrinsics: 1.1.0 - get-nonce@1.0.1: {} - get-proto@1.0.1: - dependencies: - dunder-proto: 1.0.1 - es-object-atoms: 1.1.1 - glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -6402,24 +6234,12 @@ snapshots: globals@16.5.0: {} - gopd@1.2.0: {} - graceful-fs@4.2.11: {} hachure-fill@0.5.2: {} has-flag@4.0.0: {} - has-symbols@1.1.0: {} - - has-tostringtag@1.0.2: - dependencies: - has-symbols: 1.1.0 - - hasown@2.0.2: - dependencies: - function-bind: 1.1.2 - hast-util-from-parse5@8.0.3: dependencies: '@types/hast': 3.0.4 @@ -6778,8 +6598,6 @@ snapshots: marked@16.4.2: {} - math-intrinsics@1.1.0: {} - mdast-util-find-and-replace@3.0.2: dependencies: '@types/mdast': 4.0.4 @@ -7149,12 +6967,6 @@ snapshots: transitivePeerDependencies: - supports-color - mime-db@1.52.0: {} - - mime-types@2.1.35: - dependencies: - mime-db: 1.52.0 - min-indent@1.0.1: {} minimatch@3.1.2: @@ -7312,8 +7124,6 @@ snapshots: property-information@7.1.0: {} - proxy-from-env@1.1.0: {} - punycode@2.3.1: {} pvtsutils@1.3.6: From bdd04083468513ae2fef0136ed27b650e6755b15 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 3 Feb 2026 15:35:11 -0500 Subject: [PATCH 07/10] Fix missing timer cleanup in TTS route tests Add afterEach to useRealTimers to prevent timer leak between tests in getCachedAudio describe block --- backend/test/routes/tts.test.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/backend/test/routes/tts.test.ts b/backend/test/routes/tts.test.ts index 2b3e561d..d882bcb1 100644 --- a/backend/test/routes/tts.test.ts +++ b/backend/test/routes/tts.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import * as fs from 'fs/promises' vi.mock('fs/promises', () => ({ @@ -78,9 +78,13 @@ describe('TTS Routes', () => { }) describe('getCachedAudio', () => { - beforeEach(() => { - vi.useFakeTimers() - }) + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) it('should return cached audio when file exists and is not expired', async () => { const cacheKey = 'test-key' From e3cf6482efc35bcfdc77c295e12d65413c8fe2ce Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 3 Feb 2026 16:04:32 -0500 Subject: [PATCH 08/10] Add OpenCode install method detection and improve process termination handling --- backend/src/routes/settings.ts | 33 ++++++++++++++++--- .../src/services/opencode-single-server.ts | 14 ++++++-- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 6be991ce..22bf3b16 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -1,6 +1,8 @@ import { Hono } from 'hono' import { z } from 'zod' import { execSync } from 'child_process' +import { existsSync } from 'fs' +import { resolve, dirname } from 'path' import type { Database } from 'bun:sqlite' import { SettingsService } from '../services/settings' import { writeFileContent, readFileContent, fileExists } from '../services/file-operations' @@ -27,6 +29,27 @@ function compareVersions(v1: string, v2: string): number { return 0 } +function getOpenCodeInstallMethod(): string { + const homePath = process.env.HOME || '' + const opencodePath = process.env.OPENCOD_PATH || resolve(homePath, '.opencode', 'bin', 'opencode') + + if (!existsSync(opencodePath)) return 'curl' + + try { + const opencodeDir = dirname(opencodePath) + if (opencodeDir.includes('.opencode')) return 'curl' + + if (opencodePath.includes('/homebrew/') || opencodePath.includes('/HOMEBREW/')) return 'brew' + if (opencodePath.includes('/.npm/') || opencodePath.includes('/node_modules/')) return 'npm' + if (opencodePath.includes('/.pnpm/')) return 'pnpm' + if (opencodePath.includes('/.bun/')) return 'bun' + } catch { + return 'curl' + } + + return 'curl' +} + function execWithTimeout(command: string, timeoutMs: number): { output: string; timedOut: boolean } { try { const output = execSync(command, { @@ -396,8 +419,9 @@ export function createSettingsRoutes(db: Database) { logger.info(`Current OpenCode version: ${oldVersion}`) try { - logger.info('Running opencode upgrade with 90s timeout...') - const { output: upgradeOutput, timedOut } = execWithTimeout('opencode upgrade 2>&1', 90000) + const installMethod = getOpenCodeInstallMethod() + logger.info(`Running opencode upgrade --method ${installMethod} with 90s timeout...`) + const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade --method ${installMethod} 2>&1`, 90000) logger.info(`Upgrade output: ${upgradeOutput}`) if (timedOut) { @@ -546,9 +570,10 @@ export function createSettingsRoutes(db: Database) { logger.info(`Installing OpenCode version: ${version}`) const versionArg = version.startsWith('v') ? version : `v${version}` - logger.info(`Running opencode upgrade ${versionArg} with 90s timeout...`) + const installMethod = getOpenCodeInstallMethod() + logger.info(`Running opencode upgrade ${versionArg} --method ${installMethod} with 90s timeout...`) - const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade ${versionArg} 2>&1`, 90000) + const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade ${versionArg} --method ${installMethod} 2>&1`, 90000) logger.info(`Upgrade output: ${upgradeOutput}`) if (timedOut) { diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index d366baf2..534b9487 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -185,7 +185,12 @@ class OpenCodeServerManager { try { process.kill(this.serverPid, 'SIGTERM') } catch (error) { - logger.warn(`Failed to send SIGTERM to ${this.serverPid}:`, error) + const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : '' + if (errorCode === 'ESRCH') { + logger.debug(`Process ${this.serverPid} already stopped`) + } else { + logger.warn(`Failed to send SIGTERM to ${this.serverPid}:`, error) + } } await new Promise(r => setTimeout(r, 2000)) @@ -193,7 +198,12 @@ class OpenCodeServerManager { try { process.kill(this.serverPid, 'SIGKILL') } catch (error) { - logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error) + const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : '' + if (errorCode === 'ESRCH') { + logger.debug(`Process ${this.serverPid} already stopped`) + } else { + logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error) + } } this.serverPid = null From 99a8f8881a07960883b9970091b389bd2d2bf112 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 3 Feb 2026 16:36:59 -0500 Subject: [PATCH 09/10] Fix getProviders return type handling in frontend --- .../src/components/model/ModelQuickSelect.tsx | 38 +++++++++---------- frontend/src/hooks/useVariants.ts | 19 +++++----- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/frontend/src/components/model/ModelQuickSelect.tsx b/frontend/src/components/model/ModelQuickSelect.tsx index 81c29b49..005d0ff1 100644 --- a/frontend/src/components/model/ModelQuickSelect.tsx +++ b/frontend/src/components/model/ModelQuickSelect.tsx @@ -10,7 +10,7 @@ import { } from '@/components/ui/dropdown-menu' import { useModelSelection } from '@/hooks/useModelSelection' import { useVariants } from '@/hooks/useVariants' -import { formatModelName } from '@/api/providers' +import { formatModelName, getProviders } from '@/api/providers' import { useQuery } from '@tanstack/react-query' import { useOpenCodeClient } from '@/hooks/useOpenCode' @@ -33,25 +33,25 @@ export function ModelQuickSelect({ const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(opcodeUrl, directory) const client = useOpenCodeClient(opcodeUrl, directory) - const { data: providersData } = useQuery({ - queryKey: ['opencode', 'providers', opcodeUrl, directory], - queryFn: () => client!.getProviders(), - enabled: !!client, - staleTime: 30000, - }) + const { data: providersData } = useQuery({ + queryKey: ['opencode', 'providers', opcodeUrl, directory], + queryFn: () => getProviders(), + enabled: !!client, + staleTime: 30000, + }) - const recentModelsWithNames = useMemo(() => { - if (!providersData?.all || recentModels.length === 0) return [] - - return recentModels - .filter(recent => { - const key = `${recent.providerID}/${recent.modelID}` - return key !== modelString - }) - .slice(0, 5) - .map(recent => { - let displayName = recent.modelID - for (const provider of providersData.all) { + const recentModelsWithNames = useMemo(() => { + if (!providersData?.providers || providersData.providers.length === 0 || recentModels.length === 0) return [] + + return recentModels + .filter(recent => { + const key = `${recent.providerID}/${recent.modelID}` + return key !== modelString + }) + .slice(0, 5) + .map(recent => { + let displayName = recent.modelID + for (const provider of providersData.providers) { if (provider.id === recent.providerID && provider.models) { const modelData = provider.models[recent.modelID] if (modelData) { diff --git a/frontend/src/hooks/useVariants.ts b/frontend/src/hooks/useVariants.ts index 6a15e0df..ee6c04ef 100644 --- a/frontend/src/hooks/useVariants.ts +++ b/frontend/src/hooks/useVariants.ts @@ -2,6 +2,7 @@ import { useMemo } from 'react' import { useModelSelection } from './useModelSelection' import { useModelStore } from '@/stores/modelStore' import { useOpenCodeClient } from './useOpenCode' +import { getProviders } from '@/api/providers' import { useQuery } from '@tanstack/react-query' export interface UseVariantsResult { @@ -21,16 +22,16 @@ export function useVariants( const { setVariant: setStoreVariant, clearVariant: clearStoreVariant } = useModelStore() const client = useOpenCodeClient(opcodeUrl, directory) - const { data: providersData, isLoading } = useQuery({ - queryKey: ['opencode', 'providers', opcodeUrl, directory], - queryFn: () => client!.getProviders(), - enabled: !!client && !!model, - staleTime: 30000, - }) + const { data: providersData, isLoading } = useQuery({ + queryKey: ['opencode', 'providers', opcodeUrl, directory], + queryFn: () => getProviders(), + enabled: !!client && !!model, + staleTime: 30000, + }) - const currentModel = useMemo(() => { - if (!model || isLoading || !providersData?.all) return null - for (const provider of providersData.all) { + const currentModel = useMemo(() => { + if (!model || isLoading || !providersData?.providers || providersData.providers.length === 0) return null + for (const provider of providersData.providers) { if (provider.id === model.providerID && provider.models) { const modelData = provider.models[model.modelID] if (modelData) { From 8955573037dc2d14b58954f5df10c259609daf97 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 3 Feb 2026 16:46:04 -0500 Subject: [PATCH 10/10] Update settings tests to expect opencode install method argument --- backend/test/routes/settings.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index c229f514..ca46a0e7 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -180,7 +180,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { const res = await settingsApp.fetch(req) const json = await res.json() as Record - expect(mockExecSync).toHaveBeenCalledWith('opencode upgrade 2>&1', expect.objectContaining({ + expect(mockExecSync).toHaveBeenCalledWith('opencode upgrade --method curl 2>&1', expect.objectContaining({ timeout: 90000, killSignal: 'SIGKILL' })) @@ -304,7 +304,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { await settingsApp.fetch(req) expect(mockExecSync).toHaveBeenCalledWith( - 'opencode upgrade v1.0.5 2>&1', + 'opencode upgrade v1.0.5 --method curl 2>&1', expect.any(Object) ) }) @@ -322,7 +322,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { await settingsApp.fetch(req) expect(mockExecSync).toHaveBeenCalledWith( - 'opencode upgrade v1.0.5 2>&1', + 'opencode upgrade v1.0.5 --method curl 2>&1', expect.any(Object) ) }) @@ -346,8 +346,8 @@ describe('Settings Routes - OpenCode Upgrade', () => { const json = await res.json() as Record expect(mockExecSync).toHaveBeenCalledWith( - 'opencode upgrade v1.0.5 2>&1', - expect.objectContaining({ timeout: 90000 }) + 'opencode upgrade v1.0.5 --method curl 2>&1', + expect.any(Object) ) expect(mockRestart).toHaveBeenCalled() expect(res.status).toBe(400)