diff --git a/backend/src/auth/middleware.ts b/backend/src/auth/middleware.ts index 1b25711e..bb9c900a 100644 --- a/backend/src/auth/middleware.ts +++ b/backend/src/auth/middleware.ts @@ -18,9 +18,15 @@ export function createAuthMiddleware(auth: AuthInstance) { logger.debug(`Cookie names: ${cookieNames}`) } - const session = await auth.api.getSession({ - headers: c.req.raw.headers, - }) + let session + try { + session = await auth.api.getSession({ + headers: c.req.raw.headers, + }) + } catch (error) { + logger.error('Session lookup failed', { error }) + return c.json({ error: 'Internal Server Error' }, 500) + } logger.debug(`Session result: ${session ? 'found' : 'not found'}`) @@ -69,9 +75,15 @@ export function createAdminMiddleware(auth: AuthInstance) { user: Session['user'] } }>(async (c, next) => { - const session = await auth.api.getSession({ - headers: c.req.raw.headers, - }) + let session + try { + session = await auth.api.getSession({ + headers: c.req.raw.headers, + }) + } catch (error) { + logger.error('Session lookup failed', { error }) + return c.json({ error: 'Internal Server Error' }, 500) + } if (!session) { return c.json({ error: 'Unauthorized' }, 401) diff --git a/backend/src/db/migrations.ts b/backend/src/db/migrations.ts index b0204fe8..0a587839 100644 --- a/backend/src/db/migrations.ts +++ b/backend/src/db/migrations.ts @@ -66,7 +66,7 @@ export function runMigrations(db: Database): void { WHERE branch IS NOT NULL `) } catch (error) { - logger.debug('Index already exists or could not be created', error) + logger.warn('Index already exists or could not be created', error) } try { @@ -75,7 +75,7 @@ export function runMigrations(db: Database): void { ON repos(local_path) `) } catch (error) { - logger.debug('Local path index already exists or could not be created', error) + logger.warn('Local path index already exists or could not be created', error) } const requiredColumns = [ @@ -111,7 +111,7 @@ export function runMigrations(db: Database): void { try { db.run(indexSql) } catch (error) { - logger.debug('Index already exists:', error) + logger.warn('Index already exists:', error) } } diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index 1a324a41..0153e10f 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -40,7 +40,7 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo { const existing = repo.isLocal ? getRepoByLocalPath(db, normalizedPath) - : getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch) + : getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch) if (existing) { return existing @@ -73,7 +73,7 @@ export function createRepo(db: Database, repo: CreateRepoInput): Repo { if (errorMessage.includes('UNIQUE constraint failed') || (error && typeof error === 'object' && 'code' in error && error.code === 'SQLITE_CONSTRAINT_UNIQUE')) { const conflictRepo = repo.isLocal ? getRepoByLocalPath(db, normalizedPath) - : getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch) + : getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch) if (conflictRepo) { return conflictRepo @@ -158,22 +158,34 @@ function getRepoName(repo: Repo): string { export function updateRepoStatus(db: Database, id: number, cloneStatus: Repo['cloneStatus']): void { const stmt = db.prepare('UPDATE repos SET clone_status = ? WHERE id = ?') - stmt.run(cloneStatus, id) + const result = stmt.run(cloneStatus, id) + if (result.changes === 0) { + throw new Error(`Repository with id ${id} not found`) + } } export function updateRepoConfigName(db: Database, id: number, configName: string): void { const stmt = db.prepare('UPDATE repos SET opencode_config_name = ? WHERE id = ?') - stmt.run(configName, id) + const result = stmt.run(configName, id) + if (result.changes === 0) { + throw new Error(`Repository with id ${id} not found`) + } } export function updateLastPulled(db: Database, id: number): void { const stmt = db.prepare('UPDATE repos SET last_pulled = ? WHERE id = ?') - stmt.run(Date.now(), id) + const result = stmt.run(Date.now(), id) + if (result.changes === 0) { + throw new Error(`Repository with id ${id} not found`) + } } export function updateRepoBranch(db: Database, id: number, branch: string): void { const stmt = db.prepare('UPDATE repos SET branch = ? WHERE id = ?') - stmt.run(branch, id) + const result = stmt.run(branch, id) + if (result.changes === 0) { + throw new Error(`Repository with id ${id} not found`) + } } export function deleteRepo(db: Database, id: number): void { diff --git a/backend/src/db/transactions.ts b/backend/src/db/transactions.ts deleted file mode 100644 index 48e3ba36..00000000 --- a/backend/src/db/transactions.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Database } from 'bun:sqlite' -import { logger } from '../utils/logger' - - - -export async function withTransactionAsync( - db: Database, - fn: (db: Database) => Promise -): Promise { - try { - db.exec('BEGIN TRANSACTION') - const result = await fn(db) - db.exec('COMMIT') - return result - } catch (error) { - db.exec('ROLLBACK') - logger.error('Transaction rolled back:', error) - throw error - } -} diff --git a/backend/src/index.ts b/backend/src/index.ts index bc0b50df..b524d9e8 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -189,7 +189,7 @@ try { settingsService.initializeLastKnownGoodConfig() ipcServer = await createIPCServer(process.env.STORAGE_PATH || undefined) - gitAuthService.initialize(ipcServer, db) + await gitAuthService.initialize(ipcServer, db) logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`) opencodeServerManager.setDatabase(db) @@ -340,7 +340,7 @@ const shutdown = async (signal: string) => { sseAggregator.shutdown() logger.info('SSE Aggregator stopped') if (ipcServer) { - ipcServer.dispose() + await ipcServer.dispose() logger.info('Git IPC server stopped') } await opencodeServerManager.stop() diff --git a/backend/src/ipc/ipcServer.ts b/backend/src/ipc/ipcServer.ts index d85f642c..5067967e 100644 --- a/backend/src/ipc/ipcServer.ts +++ b/backend/src/ipc/ipcServer.ts @@ -77,8 +77,10 @@ export class IPCServer { }) } - dispose(): void { - this.server.close() + dispose(): Promise { + return new Promise((resolve) => { + this.server.close(() => resolve()) + }) } } diff --git a/backend/src/ipc/passphraseHandler.ts b/backend/src/ipc/passphraseHandler.ts deleted file mode 100644 index a6129c5d..00000000 --- a/backend/src/ipc/passphraseHandler.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { IPCServer, IPCHandler } from './ipcServer' -import { logger } from '../utils/logger' - -interface PassphraseResponse { - type: 'passphrase-response' - passphrase: string -} - -export class PassphraseHandler implements IPCHandler { - private resolveMap = new Map void; reject: (error: Error) => void }>() - - constructor(ipcServer: IPCServer | undefined) { - if (ipcServer) { - ipcServer.registerHandler('passphrase', this) - logger.info('PassphraseHandler registered with IPC server') - } else { - logger.warn('PassphraseHandler: No IPC server provided, passphrase prompts will fail') - } - } - - async handle(request: PassphraseResponse): Promise { - if (request.type === 'passphrase-response') { - const pending = this.resolveMap.get('default') - if (pending) { - pending.resolve(request.passphrase) - this.resolveMap.delete('default') - } - return 'ack' - } - return '' - } - - requestPassphrase(credentialName: string, host: string): Promise { - return new Promise((resolve, reject) => { - const requestId = `default` - - this.resolveMap.set(requestId, { resolve, reject }) - - logger.info(`Requesting passphrase for ${credentialName} (${host})`) - - setTimeout(() => { - if (this.resolveMap.has(requestId)) { - this.resolveMap.delete(requestId) - reject(new Error('Passphrase request timed out')) - } - }, 120000) - }) - } - - cleanup(): void { - this.resolveMap.forEach(({ reject }) => reject(new Error('Passphrase handler closed'))) - this.resolveMap.clear() - } -} diff --git a/backend/src/ipc/sshHostKeyHandler.ts b/backend/src/ipc/sshHostKeyHandler.ts index 424b4c10..b2461cf2 100644 --- a/backend/src/ipc/sshHostKeyHandler.ts +++ b/backend/src/ipc/sshHostKeyHandler.ts @@ -119,8 +119,8 @@ export class SSHHostKeyHandler implements IPCHandler { const result = await executeCommand( ['ssh-keyscan', '-t', 'ed25519,rsa,ecdsa', ...portArgs, host], { silent: true, ignoreExitCode: true } - ) - const output = (result as unknown as { stdout: string }).stdout + ) as string | { exitCode: number; stdout: string; stderr: string } + const output = typeof result === 'string' ? result : result.stdout const bracketedHost = port && port !== '22' ? `[${host}]:${port}` : host const lines = output.trim().split('\n') for (const line of lines) { diff --git a/backend/src/routes/repo-git.ts b/backend/src/routes/repo-git.ts index 6c288738..94fba2aa 100644 --- a/backend/src/routes/repo-git.ts +++ b/backend/src/routes/repo-git.ts @@ -1,8 +1,9 @@ import { Hono } from 'hono' import type { Database } from 'bun:sqlite' +import type { ContentfulStatusCode } from 'hono/utils/http-status' import * as db from '../db/queries' import { logger } from '../utils/logger' -import { getErrorMessage } from '../utils/error-utils' +import { parseGitError } from '../utils/git-errors' import { GitService } from '../services/git/GitService' import type { GitAuthService } from '../services/git-auth' import { SettingsService } from '../services/settings' @@ -27,7 +28,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to get git status:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -63,7 +68,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(resultMap) } catch (error: unknown) { logger.error('Failed to get batch git status:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -87,7 +96,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(diff) } catch (error: unknown) { logger.error('Failed to get file diff:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -111,7 +124,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(diffResponse) } catch (error: unknown) { logger.error('Failed to get full file diff:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -130,7 +147,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to fetch git:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -149,7 +170,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to pull git:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -175,7 +200,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to commit git:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -197,7 +226,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to push git:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -223,7 +256,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to stage files:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -249,7 +286,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to unstage files:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -268,7 +309,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json({ commits }) } catch (error: unknown) { logger.error('Failed to get git log:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -294,7 +339,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json(status) } catch (error: unknown) { logger.error('Failed to reset to commit:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) @@ -313,7 +362,11 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS return c.json({ branches, status }) } catch (error: unknown) { logger.error('Failed to get branches:', error) - return c.json({ error: getErrorMessage(error) }, 500) + const gitError = parseGitError(error) + return c.json( + { error: gitError.summary, detail: gitError.detail, code: gitError.code }, + gitError.statusCode as ContentfulStatusCode + ) } }) diff --git a/backend/src/services/git-auth.ts b/backend/src/services/git-auth.ts index 99c76ee3..2510a550 100644 --- a/backend/src/services/git-auth.ts +++ b/backend/src/services/git-auth.ts @@ -16,10 +16,10 @@ export class GitAuthService { private sshPassphrase: string | null = null private sshPort: string | null = null - initialize(ipcServer: IPCServer | undefined, database: Database): void { + async initialize(ipcServer: IPCServer | undefined, database: Database): Promise { this.askpassHandler = new AskpassHandler(ipcServer, database) this.sshHostKeyHandler = new SSHHostKeyHandler(database, 120_000) - this.sshHostKeyHandler.initialize() + await this.sshHostKeyHandler.initialize() if (ipcServer) { const handlerPath = 'ssh-host-key' diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 6aa5a7f6..de8b1b12 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -144,7 +144,7 @@ class OpenCodeServerManager { if (cred.passphrase) { const passphrase = decryptSecret(cred.passphrase) - stripKeyPassphrase(keyPath, passphrase) + await stripKeyPassphrase(keyPath, passphrase) logger.info(`Stripped passphrase from SSH key for ${cred.name} (${host}:${port})`) } else { logger.info(`Setup SSH key for ${cred.name} (${host}:${port}): ${keyPath}`) diff --git a/backend/src/types/repo.ts b/backend/src/types/repo.ts index af8fe2fe..1486f274 100644 --- a/backend/src/types/repo.ts +++ b/backend/src/types/repo.ts @@ -6,13 +6,23 @@ export interface Repo extends BaseRepo { isWorktree?: boolean } -export interface CreateRepoInput { - repoUrl?: string +interface CreateRepoInputBase { localPath: string branch?: string defaultBranch: string cloneStatus: 'cloning' | 'ready' | 'error' clonedAt: number isWorktree?: boolean - isLocal?: boolean } + +interface CreateLocalRepoInput extends CreateRepoInputBase { + isLocal: true + repoUrl?: string +} + +interface CreateRemoteRepoInput extends CreateRepoInputBase { + isLocal?: false + repoUrl: string +} + +export type CreateRepoInput = CreateLocalRepoInput | CreateRemoteRepoInput diff --git a/backend/src/utils/crypto.ts b/backend/src/utils/crypto.ts index a491719d..686792df 100644 --- a/backend/src/utils/crypto.ts +++ b/backend/src/utils/crypto.ts @@ -6,7 +6,10 @@ const IV_LENGTH = 16 const KEY_LENGTH = 32 function deriveKey(): Buffer { - const secret = ENV.AUTH.SECRET || 'default-secret-do-not-use-in-production' + const secret = ENV.AUTH.SECRET + if (!secret) { + throw new Error('AUTH_SECRET must be configured for encryption') + } return scryptSync(secret, ENCRYPTION_KEY_SALT, KEY_LENGTH) } diff --git a/backend/src/utils/git-auth.ts b/backend/src/utils/git-auth.ts index 9c87e1ab..56e8b34b 100644 --- a/backend/src/utils/git-auth.ts +++ b/backend/src/utils/git-auth.ts @@ -145,13 +145,13 @@ export function getSSHCredentialsForHost(credentials: GitCredential[], host: str try { const parsedCredHost = new URL(credHost) const credHostname = parsedCredHost.hostname.toLowerCase() - const credPort = parsedCredHost.port || (parsedCredHost.protocol.includes('ssh') ? 22 : null) + const credPort = parsedCredHost.port || (parsedCredHost.protocol.includes('ssh') ? '22' : '') const normalizedCredHost = credPort ? `${credHostname}:${credPort}` : credHostname - + const parsedTargetHost = new URL(`ssh://dummy@${targetHost}`) const targetHostname = parsedTargetHost.hostname.toLowerCase() - const targetPort = parsedTargetHost.port || 22 - const normalizedTargetHost = targetPort !== '' ? `${targetHostname}:${targetPort}` : targetHostname + const targetPort = parsedTargetHost.port || '22' + const normalizedTargetHost = targetPort ? `${targetHostname}:${targetPort}` : targetHostname return normalizedCredHost === normalizedTargetHost } catch { diff --git a/backend/src/utils/git-errors.ts b/backend/src/utils/git-errors.ts index 44f00eda..e9cc15cc 100644 --- a/backend/src/utils/git-errors.ts +++ b/backend/src/utils/git-errors.ts @@ -1,3 +1,8 @@ +import type { GitErrorCode } from '@opencode-manager/shared' +import { getErrorMessage } from './error-utils' + +export type { GitErrorCode } + export function isNoUpstreamError(error: Error): boolean { const patterns = [ /The current branch .+ has no upstream branch/i, @@ -10,4 +15,202 @@ export function isNoUpstreamError(error: Error): boolean { export function parseBranchNameFromError(error: Error): string | null { const match = error.message.match(/The current branch (.+) has no upstream branch/i) return match?.[1]?.trim() ?? null -} \ No newline at end of file +} + +export interface GitErrorInfo { + code: GitErrorCode + summary: string + detail: string + statusCode: number +} + +interface ErrorPattern { + code: GitErrorCode + summary: string + statusCode: number + patterns: RegExp[] +} + +const ERROR_PATTERNS: ErrorPattern[] = [ + { + code: 'AUTH_FAILED', + summary: 'Authentication failed. Check your credentials in Settings > Git Credentials.', + statusCode: 401, + patterns: [ + /authentication failed/i, + /could not read Username/i, + /could not read password/i, + /git credentials/i, + ], + }, + { + code: 'REPO_NOT_FOUND', + summary: 'Repository not found. Check the URL and ensure you have access.', + statusCode: 404, + patterns: [ + /repository not found/i, + /fatal: .* does not exist/i, + /could not resolve host/i, + ], + }, + { + code: 'PERMISSION_DENIED', + summary: 'Permission denied. Check your repository access and credentials.', + statusCode: 403, + patterns: [ + /permission denied/i, + /access denied/i, + /not a readable path/i, + ], + }, + { + code: 'PUSH_REJECTED', + summary: 'Push rejected. Pull the latest changes first, then try again.', + statusCode: 409, + patterns: [ + /non-fast-forward/i, + /rejected push/i, + /fetch first/i, + /Updates were rejected/i, + /push failed/i, + ], + }, + { + code: 'MERGE_CONFLICT', + summary: 'Merge conflict detected. Resolve the conflicts before continuing.', + statusCode: 409, + patterns: [ + /CONFLICT \(/, + /merge conflict/i, + /fix conflicts/i, + ], + }, + { + code: 'NO_UPSTREAM', + summary: 'No upstream branch configured. Push will set upstream automatically.', + statusCode: 400, + patterns: [ + /no upstream branch/i, + /has no upstream branch/i, + /no upstream configured/i, + ], + }, + { + code: 'TIMEOUT', + summary: 'Operation timed out. Check your network connection and try again.', + statusCode: 504, + patterns: [ + /timed out/i, + /etimedout/i, + /connection timed out/i, + ], + }, + { + code: 'NOT_A_REPO', + summary: 'Not a valid Git repository.', + statusCode: 400, + patterns: [ + /not a git repository/i, + /fatal: not a git repository/i, + ], + }, + { + code: 'LOCK_FAILED', + summary: 'Git is locked by another process. Wait a moment and try again.', + statusCode: 409, + patterns: [ + /unable to create lock/i, + /index\.lock/i, + /another git process seems to be running/i, + ], + }, + { + code: 'DETACHED_HEAD', + summary: 'Repository is in detached HEAD state. Switch to a branch first.', + statusCode: 400, + patterns: [ + /HEAD detached/i, + /detached at/i, + /detached HEAD/i, + ], + }, + { + code: 'BRANCH_EXISTS', + summary: 'A branch with that name already exists.', + statusCode: 409, + patterns: [ + /branch .* already exists/i, + /fatal: A branch named .* already exists/i, + ], + }, + { + code: 'BRANCH_NOT_FOUND', + summary: 'Branch not found. Check the branch name and try again.', + statusCode: 404, + patterns: [ + /pathspec .* did not match/i, + /unknown revision/i, + /invalid ref/i, + /reference.*not found/i, + ], + }, + { + code: 'UNCOMMITTED_CHANGES', + summary: 'You have uncommitted changes. Commit or stash them first.', + statusCode: 409, + patterns: [ + /uncommitted changes/i, + /local changes.*overwritten/i, + /would lose uncommitted changes/i, + ], + }, +] + +function stripCommandFailedPrefix(message: string): string { + return message.replace(/^Command failed with code \d+:\s*/, '') +} + +const PROGRESS_LINE_PATTERNS = [ + /^remote: Counting objects:.*$/gm, + /^remote: Compressing objects:.*$/gm, + /^remote: Receiving objects:.*$/gm, + /^remote: Total .*$/gm, + /^Resolving deltas:.*$/gm, + /^From .+$/gm, + /^ \* \[new branch] {2,}.*$/gm, + /^ {3}.+-> .+$/gm, +] + +function cleanGitProgressLines(message: string): string { + let cleaned = message + for (const pattern of PROGRESS_LINE_PATTERNS) { + cleaned = cleaned.replace(pattern, '') + } + return cleaned.replace(/\n{3,}/g, '\n\n').trim() +} + +export function parseGitError(error: unknown): GitErrorInfo { + const rawMessage = getErrorMessage(error) + const message = stripCommandFailedPrefix(rawMessage) + const cleanedMessage = cleanGitProgressLines(message) + + for (const errorPattern of ERROR_PATTERNS) { + for (const pattern of errorPattern.patterns) { + if (pattern.test(message) || pattern.test(cleanedMessage)) { + return { + code: errorPattern.code, + summary: errorPattern.summary, + detail: cleanedMessage || message, + statusCode: errorPattern.statusCode, + } + } + } + } + + return { + code: 'UNKNOWN', + summary: 'A git operation failed.', + detail: cleanedMessage || message, + statusCode: 500, + } +} diff --git a/backend/src/utils/logger.ts b/backend/src/utils/logger.ts index cf534357..baad99c7 100644 --- a/backend/src/utils/logger.ts +++ b/backend/src/utils/logger.ts @@ -16,7 +16,7 @@ class Logger { } info(message: string, ...args: unknown[]): void { - console.warn(this.format('info', message), ...args) + console.log(this.format('info', message), ...args) } warn(message: string, ...args: unknown[]): void { @@ -29,7 +29,7 @@ class Logger { debug(message: string, ...args: unknown[]): void { if (ENV.LOGGING.DEBUG) { - console.warn(this.format('debug', message), ...args) + console.debug(this.format('debug', message), ...args) } } } diff --git a/backend/src/utils/ssh-key-manager.ts b/backend/src/utils/ssh-key-manager.ts index 07d3a3bd..e2da3bff 100644 --- a/backend/src/utils/ssh-key-manager.ts +++ b/backend/src/utils/ssh-key-manager.ts @@ -1,6 +1,6 @@ /* eslint-disable no-empty */ import { promises as fs } from 'fs' -import { execFileSync } from 'child_process' +import { execFile } from 'child_process' import { randomBytes } from 'crypto' import { join } from 'path' import { getWorkspacePath } from '@opencode-manager/shared/config/env' @@ -58,7 +58,11 @@ export async function writeTemporarySSHKey(keyContent: string, identifier: strin const randomSuffix = randomBytes(8).toString('hex') const fileName = `key-${identifier}-${randomSuffix}` const keyPath = join(SSH_KEYS_DIR, fileName) - + + if (!keyPath.startsWith(SSH_KEYS_DIR)) { + throw new Error('Invalid key path') + } + await fs.writeFile(keyPath, keyContent.trim() + '\n', { mode: 0o600 }) const isValid = await validateSSHKey(keyPath) @@ -108,6 +112,10 @@ export async function writePersistentSSHKey(keyContent: string, identifier: stri const fileName = `persistent-${identifier}` const keyPath = join(SSH_KEYS_DIR, fileName) + if (!keyPath.startsWith(SSH_KEYS_DIR)) { + throw new Error('Invalid key path') + } + await fs.writeFile(keyPath, keyContent.trim() + '\n', { mode: 0o600 }) const isValid = await validateSSHKey(keyPath) @@ -123,8 +131,13 @@ export function buildSSHCommandWithConfig(configPath: string, knownHostsPath: st return `ssh -T -F "${configPath}" -o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=accept-new -o PasswordAuthentication=no` } -export function stripKeyPassphrase(keyPath: string, passphrase: string): void { - execFileSync('ssh-keygen', ['-p', '-P', passphrase, '-N', '', '-f', keyPath], { stdio: 'ignore' }) +export async function stripKeyPassphrase(keyPath: string, passphrase: string): Promise { + await new Promise((resolve, reject) => { + execFile('ssh-keygen', ['-p', '-P', passphrase, '-N', '', '-f', keyPath], (error: Error | null) => { + if (error) reject(error) + else resolve() + }) + }) } export interface SSHConfigEntry { diff --git a/backend/src/utils/ssh-validation.ts b/backend/src/utils/ssh-validation.ts index 5ba97eed..d973fbdd 100644 --- a/backend/src/utils/ssh-validation.ts +++ b/backend/src/utils/ssh-validation.ts @@ -1,6 +1,7 @@ import { promises as fs } from 'fs' import { tmpdir } from 'os' import { join } from 'path' +import { randomBytes } from 'crypto' import { executeCommand } from './process' async function removeFile(filePath: string): Promise { @@ -21,7 +22,7 @@ export async function validateSSHPrivateKey(key: string): Promise<{ valid: boole let tempKeyPath: string | null = null try { - tempKeyPath = join(tmpdir(), `temp-ssh-key-${Date.now()}-${Math.random().toString(36).slice(2)}`) + tempKeyPath = join(tmpdir(), `temp-ssh-key-${Date.now()}-${randomBytes(8).toString('hex')}`) await fs.writeFile(tempKeyPath, trimmedKey + '\n', { mode: 0o600 }) try { diff --git a/backend/test/utils/git-errors.test.ts b/backend/test/utils/git-errors.test.ts new file mode 100644 index 00000000..5de0b49a --- /dev/null +++ b/backend/test/utils/git-errors.test.ts @@ -0,0 +1,286 @@ +import { describe, it, expect } from 'bun:test' +import { parseGitError } from '../../src/utils/git-errors' + +describe('parseGitError', () => { + describe('AUTH_FAILED', () => { + it('matches HTTPS authentication failure', () => { + const error = new Error( + 'Command failed with code 128: fatal: Authentication failed for \'https://github.com/user/repo.git\'' + ) + const result = parseGitError(error) + expect(result.code).toBe('AUTH_FAILED') + expect(result.statusCode).toBe(401) + }) + + it('matches SSH could not read Username', () => { + const error = new Error( + 'Command failed with code 128: fatal: could not read Username for \'https://github.com\': terminal prompts disabled' + ) + const result = parseGitError(error) + expect(result.code).toBe('AUTH_FAILED') + expect(result.statusCode).toBe(401) + }) + }) + + describe('REPO_NOT_FOUND', () => { + it('matches GitHub 404', () => { + const error = new Error( + 'Command failed with code 128: remote: Repository not found.\nfatal: repository \'https://github.com/user/nonexistent.git/\' not found' + ) + const result = parseGitError(error) + expect(result.code).toBe('REPO_NOT_FOUND') + expect(result.statusCode).toBe(404) + }) + + it('matches DNS failure', () => { + const error = new Error( + 'Command failed with code 128: fatal: unable to access \'https://notahost.example/repo.git/\': Could not resolve host: notahost.example' + ) + const result = parseGitError(error) + expect(result.code).toBe('REPO_NOT_FOUND') + expect(result.statusCode).toBe(404) + }) + }) + + describe('PERMISSION_DENIED', () => { + it('matches SSH permission denied', () => { + const error = new Error( + 'Command failed with code 128: git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.' + ) + const result = parseGitError(error) + expect(result.code).toBe('PERMISSION_DENIED') + expect(result.statusCode).toBe(403) + }) + }) + + describe('PUSH_REJECTED', () => { + it('matches non-fast-forward push rejection with progress lines', () => { + const error = new Error( + 'Command failed with code 1: To github.com:user/repo.git\n' + + ' ! [rejected] main -> main (non-fast-forward)\n' + + 'error: failed to push some refs to \'github.com:user/repo.git\'\n' + + 'hint: Updates were rejected because the tip of your current branch is behind\n' + + 'hint: its remote counterpart.' + ) + const result = parseGitError(error) + expect(result.code).toBe('PUSH_REJECTED') + expect(result.statusCode).toBe(409) + expect(result.detail).toContain('[rejected]') + expect(result.detail).toContain('non-fast-forward') + }) + + it('matches fetch-first rejection', () => { + const error = new Error( + 'Command failed with code 1: error: failed to push some refs\n' + + 'hint: Updates were rejected because the remote contains work that you do\n' + + 'hint: not have locally. Integrate the remote changes before pushing again.' + ) + const result = parseGitError(error) + expect(result.code).toBe('PUSH_REJECTED') + }) + }) + + describe('MERGE_CONFLICT', () => { + it('matches actual merge conflict output', () => { + const error = new Error( + 'Command failed with code 1: Auto-merging README.md\n' + + 'CONFLICT (content): Merge conflict in README.md\n' + + 'Automatic merge failed; fix conflicts and then commit the result.' + ) + const result = parseGitError(error) + expect(result.code).toBe('MERGE_CONFLICT') + expect(result.statusCode).toBe(409) + }) + + it('does NOT false-positive on Auto-merging without CONFLICT', () => { + const error = new Error( + 'Command failed with code 1: Auto-merging README.md\n' + + 'error: some other unrelated failure occurred' + ) + const result = parseGitError(error) + expect(result.code).not.toBe('MERGE_CONFLICT') + }) + }) + + describe('NO_UPSTREAM', () => { + it('matches no upstream branch error', () => { + const error = new Error( + 'Command failed with code 128: fatal: The current branch feature-xyz has no upstream branch.\n' + + 'To push the current branch and set the remote as upstream, use\n' + + '\n' + + ' git push --set-upstream origin feature-xyz' + ) + const result = parseGitError(error) + expect(result.code).toBe('NO_UPSTREAM') + expect(result.statusCode).toBe(400) + }) + }) + + describe('TIMEOUT', () => { + it('matches executeCommand timeout format', () => { + const error = new Error('Command timed out after 30000ms: git -C /path/to/repo push') + const result = parseGitError(error) + expect(result.code).toBe('TIMEOUT') + expect(result.statusCode).toBe(504) + }) + }) + + describe('NOT_A_REPO', () => { + it('matches not a git repository', () => { + const error = new Error( + 'Command failed with code 128: fatal: not a git repository (or any of the parent directories): .git' + ) + const result = parseGitError(error) + expect(result.code).toBe('NOT_A_REPO') + expect(result.statusCode).toBe(400) + }) + }) + + describe('LOCK_FAILED', () => { + it('matches index.lock error', () => { + const error = new Error( + 'Command failed with code 128: fatal: Unable to create \'/path/.git/index.lock\': File exists.\n\n' + + 'Another git process seems to be running in this repository.' + ) + const result = parseGitError(error) + expect(result.code).toBe('LOCK_FAILED') + expect(result.statusCode).toBe(409) + }) + }) + + describe('BRANCH_EXISTS', () => { + it('matches branch already exists', () => { + const error = new Error( + 'Command failed with code 128: fatal: A branch named \'feature\' already exists.' + ) + const result = parseGitError(error) + expect(result.code).toBe('BRANCH_EXISTS') + expect(result.statusCode).toBe(409) + }) + }) + + describe('BRANCH_NOT_FOUND', () => { + it('matches pathspec did not match', () => { + const error = new Error( + 'Command failed with code 1: error: pathspec \'nonexistent\' did not match any file(s) known to git' + ) + const result = parseGitError(error) + expect(result.code).toBe('BRANCH_NOT_FOUND') + expect(result.statusCode).toBe(404) + }) + }) + + describe('UNCOMMITTED_CHANGES', () => { + it('matches local changes would be overwritten', () => { + const error = new Error( + 'Command failed with code 1: error: Your local changes to the following files would be overwritten by merge:\n' + + '\tREADME.md\n' + + 'Please commit your changes or stash them before you merge.' + ) + const result = parseGitError(error) + expect(result.code).toBe('UNCOMMITTED_CHANGES') + expect(result.statusCode).toBe(409) + }) + }) + + describe('UNKNOWN', () => { + it('falls back for unrecognized errors', () => { + const error = new Error('Command failed with code 1: something completely unexpected happened') + const result = parseGitError(error) + expect(result.code).toBe('UNKNOWN') + expect(result.statusCode).toBe(500) + expect(result.summary).toBe('A git operation failed.') + expect(result.detail).toBe('something completely unexpected happened') + }) + + it('handles non-Error input', () => { + const result = parseGitError('a string error') + expect(result.code).toBe('UNKNOWN') + expect(result.detail).toBe('a string error') + }) + + it('handles object with message', () => { + const result = parseGitError({ message: 'object error' }) + expect(result.code).toBe('UNKNOWN') + expect(result.detail).toBe('object error') + }) + }) + + describe('prefix stripping', () => { + it('strips Command failed prefix', () => { + const error = new Error('Command failed with code 128: fatal: not a git repository') + const result = parseGitError(error) + expect(result.detail).not.toContain('Command failed with code') + }) + + it('handles errors without prefix', () => { + const error = new Error('Repository not found') + const result = parseGitError(error) + expect(result.code).toBe('REPO_NOT_FOUND') + }) + }) + + describe('progress line cleaning', () => { + it('strips remote progress lines from detail', () => { + const error = new Error( + 'Command failed with code 128: remote: Counting objects: 100% (10/10), done.\n' + + 'remote: Compressing objects: 100% (5/5), done.\n' + + 'remote: Total 10 (delta 3), reused 10 (delta 3)\n' + + 'fatal: Authentication failed for \'https://github.com/user/repo.git\'' + ) + const result = parseGitError(error) + expect(result.code).toBe('AUTH_FAILED') + expect(result.detail).not.toContain('Counting objects') + expect(result.detail).not.toContain('Compressing objects') + expect(result.detail).toContain('Authentication failed') + }) + + it('preserves rejection lines in detail', () => { + const error = new Error( + 'Command failed with code 1: To github.com:user/repo.git\n' + + ' ! [rejected] main -> main (non-fast-forward)\n' + + 'error: failed to push some refs' + ) + const result = parseGitError(error) + expect(result.detail).toContain('[rejected]') + expect(result.detail).toContain('main -> main') + }) + + it('strips tracking branch lines but not error lines with arrows', () => { + const error = new Error( + 'Command failed with code 128: From github.com:user/repo\n' + + ' * [new branch] dev -> origin/dev\n' + + ' abc1234..def5678 main -> origin/main\n' + + 'fatal: not a git repository' + ) + const result = parseGitError(error) + expect(result.detail).not.toContain('origin/dev') + expect(result.detail).not.toContain('abc1234..def5678') + expect(result.detail).toContain('not a git repository') + }) + + it('collapses excessive blank lines', () => { + const error = new Error( + 'Command failed with code 1: remote: Counting objects: done.\n\n\nfatal: error message here' + ) + const result = parseGitError(error) + const consecutiveNewlines = result.detail.match(/\n{3,}/g) + expect(consecutiveNewlines).toBeNull() + }) + }) + + describe('GitService plain Error passthrough', () => { + it('handles GitService "Repository not found" throw', () => { + const error = new Error('Repository not found') + const result = parseGitError(error) + expect(result.code).toBe('REPO_NOT_FOUND') + expect(result.statusCode).toBe(404) + }) + + it('handles GitService "Unable to detect current branch" as UNKNOWN', () => { + const error = new Error('Unable to detect current branch. Ensure you are on a branch before pushing with --set-upstream.') + const result = parseGitError(error) + expect(result.code).toBe('UNKNOWN') + }) + }) +}) diff --git a/frontend/src/api/fetchWrapper.ts b/frontend/src/api/fetchWrapper.ts index b4214fa0..607e487a 100644 --- a/frontend/src/api/fetchWrapper.ts +++ b/frontend/src/api/fetchWrapper.ts @@ -1,109 +1,101 @@ -export class FetchError extends Error { - statusCode?: number - code?: string +import { FetchError } from '@opencode-manager/shared' +import type { ApiErrorResponse } from '@opencode-manager/shared' - 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 -} +export { FetchError } interface FetchWrapperOptions extends RequestInit { timeout?: number - params?: Record + 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) + const data: ApiErrorResponse = await response.json().catch(() => ({ error: 'An error occurred' })) + throw new FetchError( + data.error || 'Request failed', + response.status, + data.code, + data.detail + ) +} + +function buildUrl(url: string, params?: Record): URL { + 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)) + } + }) + } + return urlObj +} + +async function fetchWithTimeout( + url: string, + options: FetchWrapperOptions = {} +): Promise { + const { timeout = 30000, params, ...fetchOptions } = options + const urlObj = buildUrl(url, params) + + const controller = new AbortController() + const timeoutId = timeout > 0 ? setTimeout(() => controller.abort(), timeout) : null + + try { + const response = await fetch(urlObj.toString(), { + ...fetchOptions, + signal: controller.signal, + }) + + if (timeoutId) clearTimeout(timeoutId) + + if (!response.ok) { + await handleResponse(response) + } + + return response + } catch (error) { + if (timeoutId) clearTimeout(timeoutId) + if (error instanceof Error && error.name === 'AbortError') { + throw new FetchError('Request timeout', 408, 'TIMEOUT') + } + throw error + } } 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) + const response = await fetchWithTimeout(url, options) 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 + return await response.json() + } catch { + throw new FetchError('Invalid JSON response', response.status, 'INVALID_JSON') } } +async function fetchWrapperText( + url: string, + options: FetchWrapperOptions = {} +): Promise { + const response = await fetchWithTimeout(url, options) + return response.text() +} + +async function fetchWrapperVoid( + url: string, + options: FetchWrapperOptions = {} +): Promise { + await fetchWithTimeout(url, options) +} + 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 - } + const response = await fetchWithTimeout(url, options) + return response.blob() } -export { fetchWrapper, fetchWrapperBlob } +export { fetchWrapper, fetchWrapperText, fetchWrapperVoid, fetchWrapperBlob } diff --git a/frontend/src/api/files.ts b/frontend/src/api/files.ts index 1cfa7783..8811927b 100644 --- a/frontend/src/api/files.ts +++ b/frontend/src/api/files.ts @@ -1,15 +1,10 @@ import { useQuery } from '@tanstack/react-query' +import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper' import { API_BASE_URL } from '@/config' import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files' async function fetchFile(path: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/files/${path}`) - - if (!response.ok) { - throw new Error(`Failed to load file: ${response.statusText}`) - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/files/${path}`) } export function useFile(path: string | undefined) { @@ -21,37 +16,21 @@ export function useFile(path: string | undefined) { } export async function fetchFileRange(path: string, startLine: number, endLine: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/files/${path}?startLine=${startLine}&endLine=${endLine}`) - - if (!response.ok) { - throw new Error(`Failed to load file range: ${response.statusText}`) - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/files/${path}`, { + params: { startLine, endLine }, + }) } export async function applyFilePatches(path: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> { - const response = await fetch(`${API_BASE_URL}/api/files/${path}`, { + return fetchWrapper(`${API_BASE_URL}/api/files/${path}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ patches }), }) - - if (!response.ok) { - throw new Error(`Failed to apply patches: ${response.statusText}`) - } - - return response.json() } export async function getIgnoredPaths(path: string): Promise<{ ignoredPaths: string[] }> { - const response = await fetch(`${API_BASE_URL}/api/files/${path}/ignored-paths`) - - if (!response.ok) { - throw new Error('Failed to get ignored paths') - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/files/${path}/ignored-paths`) } export interface DownloadOptions { @@ -65,14 +44,8 @@ export async function downloadDirectoryAsZip(path: string, options?: DownloadOpt if (options?.includePaths?.length) params.append('includePaths', options.includePaths.join(',')) const url = `${API_BASE_URL}/api/files/${path}/download-zip${params.toString() ? '?' + params.toString() : ''}` - const response = await fetch(url) - - if (!response.ok) { - const error = await response.json() - throw new Error(error.error || 'Failed to download directory') - } - - const blob = await response.blob() + + const blob = await fetchWrapperBlob(url) const urlObj = window.URL.createObjectURL(blob) const a = document.createElement('a') a.href = urlObj @@ -82,4 +55,4 @@ export async function downloadDirectoryAsZip(path: string, options?: DownloadOpt a.click() document.body.removeChild(a) window.URL.revokeObjectURL(urlObj) -} \ No newline at end of file +} diff --git a/frontend/src/api/git.ts b/frontend/src/api/git.ts index 7c553b5d..40aa0bed 100644 --- a/frontend/src/api/git.ts +++ b/frontend/src/api/git.ts @@ -1,182 +1,90 @@ import { useQuery } from '@tanstack/react-query' +import { fetchWrapper, FetchError } from './fetchWrapper' import { API_BASE_URL } from '@/config' import type { GitStatusResponse, FileDiffResponse, GitCommit } from '@/types/git' -export class GitError extends Error { - code?: string - statusCode?: number - - constructor(message: string, code?: string, statusCode?: number) { - super(message) - this.name = 'GitError' - this.code = code - this.statusCode = statusCode - } -} - -interface ApiError { - error: string - code?: string -} - -async function handleApiError(response: Response): Promise { - const data: ApiError = await response.json().catch(() => ({ error: 'An error occurred' })) - throw new GitError(data.error, data.code, response.status) -} - export async function fetchGitStatus(repoId: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/status`) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/status`) } export async function fetchReposGitStatus(repoIds: number[]): Promise> { - const response = await fetch(`${API_BASE_URL}/api/repos/git-status-batch`, { + const data = await fetchWrapper>(`${API_BASE_URL}/api/repos/git-status-batch`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repoIds }) }) - - if (!response.ok) { - await handleApiError(response) - } - - const data = await response.json() - return new Map(Object.entries(data).map(([id, status]) => [Number(id), status as GitStatusResponse])) + return new Map(Object.entries(data).map(([id, status]) => [Number(id), status])) } export async function fetchFileDiff(repoId: number, path: string, includeStaged?: boolean): Promise { - const params = new URLSearchParams({ path }) - if (includeStaged !== undefined) { - params.set('includeStaged', String(includeStaged)) - } - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/diff-full?${params}`) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/diff-full`, { + params: { path, includeStaged }, + }) } export async function fetchGitDiff(repoId: number, path: string): Promise<{ diff: string }> { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/diff?path=${encodeURIComponent(path)}`) - - if (!response.ok) { - await handleApiError(response) - } - - const data = await response.json() + const data = await fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/diff`, { + params: { path }, + }) return { diff: data } } export async function fetchGitLog(repoId: number, limit?: number): Promise<{ commits: GitCommit[] }> { - const params = limit ? `?limit=${limit}` : '' - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/log${params}`) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/log`, { + params: { limit }, + }) } export async function gitFetch(repoId: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/fetch`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/fetch`, { method: 'POST', }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export async function gitPull(repoId: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/pull`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/pull`, { method: 'POST', }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export async function gitPush(repoId: number, setUpstream: boolean = false): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/push`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/push`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ setUpstream }), }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export async function gitCommit(repoId: number, message: string, stagedPaths?: string[]): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/commit`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message, stagedPaths }), }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export async function gitStageFiles(repoId: number, paths: string[]): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/stage`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stage`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paths }), }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export async function gitUnstageFiles(repoId: number, paths: string[]): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/unstage`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/unstage`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paths }), }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export async function gitReset(repoId: number, commitHash: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${repoId}/git/reset`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/reset`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ commitHash }), }) - - if (!response.ok) { - await handleApiError(response) - } - - return response.json() } export function useGitStatus(repoId: number | undefined) { @@ -227,7 +135,7 @@ function parseGitErrorMessage(message: string): string { } export function getApiErrorMessage(error: unknown): string { - if (error instanceof GitError) { + if (error instanceof FetchError) { if (error.code === 'AUTH_FAILED') { return 'Git authentication failed. Check your credentials in Settings.' } @@ -237,6 +145,9 @@ export function getApiErrorMessage(error: unknown): string { if (error.code === 'NOT_FOUND') { return 'Repository or file not found.' } + if (error.statusCode === 401) return 'Git authentication failed. Check your credentials in Settings.' + if (error.statusCode === 409) return 'Merge conflict detected. Resolve conflicts before continuing.' + if (error.statusCode === 404) return 'Repository or file not found.' return parseGitErrorMessage(error.message) } if (error instanceof Error) { @@ -246,9 +157,6 @@ export function getApiErrorMessage(error: unknown): string { return parseGitErrorMessage(error) } const err = error as { status?: number; message?: string; error?: string } - if (err?.status === 401) return 'Git authentication failed. Check your credentials in Settings.' - if (err?.status === 409) return 'Merge conflict detected. Resolve conflicts before continuing.' - if (err?.status === 404) return 'Repository or file not found.' const message = err?.message || err?.error || String(error) || 'An error occurred' return parseGitErrorMessage(message) -} \ No newline at end of file +} diff --git a/frontend/src/api/mcp.ts b/frontend/src/api/mcp.ts index 510e4cf4..386ee92b 100644 --- a/frontend/src/api/mcp.ts +++ b/frontend/src/api/mcp.ts @@ -1,7 +1,6 @@ +import { fetchWrapper } from './fetchWrapper' import { API_BASE_URL } from '@/config' -const API_BASE = API_BASE_URL - export type McpStatus = | { status: 'connected' } | { status: 'disabled' } @@ -44,171 +43,108 @@ export type McpOAuthFlowStatus = export const mcpApi = { async getStatus(): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp`) - if (!response.ok) { - throw new Error(`Failed to get MCP status: ${response.statusText}`) - } - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp`) }, async addServer(name: string, config: McpServerConfig): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp`, { + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, config }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to add MCP server: ${response.statusText}`) - } - return response.json() }, async connect(name: string): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/connect`, { + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/connect`, { method: 'POST', }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to connect MCP server: ${response.statusText}`) - } - return response.json() }, async disconnect(name: string): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/disconnect`, { + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/disconnect`, { method: 'POST', }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to disconnect MCP server: ${response.statusText}`) - } - return response.json() }, async startAuth(name: string, serverUrl: string, scope?: string, clientId?: string, clientSecret?: string, directory?: string): Promise { - const response = await fetch(`${API_BASE}/api/mcp-oauth-proxy/start`, { + return fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/start`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ serverName: name, serverUrl, scope, clientId, clientSecret, directory }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to start MCP auth: ${response.statusText}`) - } - return response.json() }, async checkFlowStatus(flowId: string): Promise { - const response = await fetch(`${API_BASE}/api/mcp-oauth-proxy/status/${encodeURIComponent(flowId)}`) - if (!response.ok) { + try { + return await fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/status/${encodeURIComponent(flowId)}`) + } catch { return { status: 'unknown' } } - return response.json() }, async completeAuth(name: string, code: string): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth/callback`, { + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/auth/callback`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to complete MCP auth: ${response.statusText}`) - } - return response.json() }, async authenticate(name: string): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth/authenticate`, { + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/auth/authenticate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to authenticate MCP server: ${response.statusText}`) - } - return response.json() }, async removeAuth(name: string): Promise<{ success: true }> { - const response = await fetch(`${API_BASE}/api/opencode/mcp/${encodeURIComponent(name)}/auth`, { + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp/${encodeURIComponent(name)}/auth`, { method: 'DELETE', }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to remove MCP auth: ${response.statusText}`) - } - return response.json() }, async getStatusFor(directory: string): Promise { - const response = await fetch(`${API_BASE}/api/opencode/mcp?directory=${encodeURIComponent(directory)}`) - if (!response.ok) { - throw new Error(`Failed to get MCP status for directory: ${response.statusText}`) - } - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/opencode/mcp`, { + params: { directory }, + }) }, async getConfigForDirectory(directory: string): Promise> { - const response = await fetch(`${API_BASE}/api/opencode/config?directory=${encodeURIComponent(directory)}`) - if (!response.ok) { - throw new Error(`Failed to get config for directory: ${response.statusText}`) - } - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/opencode/config`, { + params: { directory }, + }) }, async connectDirectory(name: string, directory: string): Promise { - const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/connectdirectory`, { + return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/connectdirectory`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ directory }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to connect MCP server for directory: ${response.statusText}`) - } - return response.json() }, async disconnectDirectory(name: string, directory: string): Promise { - const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/disconnectdirectory`, { + return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/disconnectdirectory`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ directory }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to disconnect MCP server for directory: ${response.statusText}`) - } - return response.json() }, async authenticateDirectory(name: string, directory: string): Promise { - const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/authdirectedir`, { + return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/authdirectedir`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ directory }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to authenticate MCP server for directory: ${response.statusText}`) - } - return response.json() }, async removeAuthDirectory(name: string, directory: string): Promise<{ success: true }> { - const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/authdir`, { + return fetchWrapper(`${API_BASE_URL}/api/settings/mcp/${encodeURIComponent(name)}/authdir`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ directory }), }) - if (!response.ok) { - const error = await response.json().catch(() => ({ error: response.statusText })) - throw new Error(error.error || `Failed to remove MCP auth for directory: ${response.statusText}`) - } - return response.json() }, } diff --git a/frontend/src/api/oauth.ts b/frontend/src/api/oauth.ts index 66a25632..6c389c7d 100644 --- a/frontend/src/api/oauth.ts +++ b/frontend/src/api/oauth.ts @@ -31,7 +31,7 @@ function handleApiError(error: unknown, context: string): never { export const oauthApi = { authorize: async (providerId: string, method: number): Promise => { try { - return fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, { + return await fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ method }), @@ -43,7 +43,7 @@ export const oauthApi = { callback: async (providerId: string, request: OAuthCallbackRequest): Promise => { try { - return fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, { + return await fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request), diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index a4e82907..e3f59261 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -29,7 +29,7 @@ export class OpenCodeClient { this.directory = directory } - private getParams(params?: Record) { + private getParams(params?: Record) { if (!this.directory) return params return { ...params, directory: this.directory } } diff --git a/frontend/src/api/providers.ts b/frontend/src/api/providers.ts index 38cb8a4d..d43a0310 100644 --- a/frontend/src/api/providers.ts +++ b/frontend/src/api/providers.ts @@ -205,8 +205,8 @@ async function getProvidersFromOpenCodeServer(): Promise<{ providers: Provider[] return { providers, connected: response.connected || [] }; } - } catch (error) { - console.warn("Failed to load providers from OpenCode server", error); + } catch { + // Silently return empty providers on failure - graceful degradation } return { providers: [], connected: [] }; @@ -258,8 +258,8 @@ async function getConfiguredProviders(connectedIds: Set): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos`, { + return fetchWrapper(`${API_BASE_URL}/api/repos`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repoUrl, localPath, branch, openCodeConfigName, useWorktree, skipSSHVerification }), }) - - if (!response.ok) { - const error = await response.json() - throw new Error(error.error || 'Failed to create repo') - } - - return response.json() } export async function listRepos(): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos`) - - if (!response.ok) { - throw new Error('Failed to list repos') - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/repos`) } export async function getRepo(id: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}`) - - if (!response.ok) { - throw new Error('Failed to get repo') - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`) } export async function deleteRepo(id: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}`, { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}`, { method: 'DELETE', }) - - if (!response.ok) { - throw new Error('Failed to delete repo') - } } export async function startServer(id: number, openCodeConfigName?: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/server/start`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/server/start`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ openCodeConfigName }), }) - - if (!response.ok) { - throw new Error('Failed to start server') - } - - return response.json() } export async function stopServer(id: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/server/stop`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/server/stop`, { method: 'POST', }) - - if (!response.ok) { - throw new Error('Failed to stop server') - } - - return response.json() } export async function pullRepo(id: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/pull`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/pull`, { method: 'POST', }) - - if (!response.ok) { - throw new Error('Failed to pull repo') - } - - return response.json() } export async function getServerLogs(id: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/server/logs`) - - if (!response.ok) { - throw new Error('Failed to get server logs') - } - - return response.text() + return fetchWrapperText(`${API_BASE_URL}/api/repos/${id}/server/logs`) } export async function switchRepoConfig(id: number, configName: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/config/switch`, { + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/config/switch`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ configName }), }) - - if (!response.ok) { - const error = await response.json() - throw new Error(error.error || 'Failed to switch config') - } - - return response.json() } export class GitAuthError extends Error { @@ -126,21 +73,18 @@ export class GitAuthError extends Error { } export async function switchBranch(id: number, branch: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/switch`, { - 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) + try { + return await fetchWrapper(`${API_BASE_URL}/api/repos/${id}/branch/switch`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ branch }), + }) + } catch (error) { + if (error instanceof FetchError && error.code === 'AUTH_FAILED') { + throw new GitAuthError(error.message, error.code) } - throw new Error(error.error || 'Failed to switch branch') + throw error } - - return response.json() } interface GitBranch { @@ -154,31 +98,22 @@ interface GitBranch { } export async function listBranches(id: number): Promise<{ branches: GitBranch[], status: { ahead: number, behind: number } }> { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/git/branches`) - - if (!response.ok) { - throw new Error('Failed to list branches') - } - - return response.json() + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git/branches`) } export async function createBranch(id: number, branch: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/create`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ branch }), - }) - - if (!response.ok) { - const error = await response.json() - if (error.code === 'AUTH_FAILED') { - throw new GitAuthError(error.error || 'Git authentication failed', error.code) + try { + return await fetchWrapper(`${API_BASE_URL}/api/repos/${id}/branch/create`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ branch }), + }) + } catch (error) { + if (error instanceof FetchError && error.code === 'AUTH_FAILED') { + throw new GitAuthError(error.message, error.code) } - throw new Error(error.error || 'Failed to create branch') + throw error } - - return response.json() } export interface DownloadOptions { @@ -192,14 +127,8 @@ export async function downloadRepo(id: number, repoName: string, options?: Downl if (options?.includePaths?.length) params.append('includePaths', options.includePaths.join(',')) const url = `${API_BASE_URL}/api/repos/${id}/download${params.toString() ? '?' + params.toString() : ''}` - const response = await fetch(url) - - if (!response.ok) { - const error = await response.json() - throw new Error(error.error || 'Failed to download repo') - } - - const blob = await response.blob() + + const blob = await fetchWrapperBlob(url) const urlObj = window.URL.createObjectURL(blob) const a = document.createElement('a') a.href = urlObj @@ -211,25 +140,15 @@ export async function downloadRepo(id: number, repoName: string, options?: Downl } export async function updateRepoOrder(order: number[]): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/order`, { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/order`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order }), }) - - if (!response.ok) { - const error = await response.json() - throw new Error(error.error || 'Failed to update repo order') - } } export async function resetRepoPermissions(id: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/repos/${id}/reset-permissions`, { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}/reset-permissions`, { method: 'POST', }) - - if (!response.ok) { - const error = await response.json() - throw new Error(error.error || 'Failed to reset permissions') - } } diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index d6972d13..e7aac3b7 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -9,8 +9,10 @@ import type { import { API_BASE_URL } from '@/config' import { fetchWrapper, FetchError } from './fetchWrapper' +const DEFAULT_USER_ID = 'default' + export const settingsApi = { - getSettings: async (userId = 'default'): Promise => { + getSettings: async (userId = DEFAULT_USER_ID): Promise => { return fetchWrapper(`${API_BASE_URL}/api/settings`, { params: { userId }, }) @@ -18,7 +20,7 @@ export const settingsApi = { updateSettings: async ( updates: UpdateSettingsRequest, - userId = 'default' + userId = DEFAULT_USER_ID ): Promise => { return fetchWrapper(`${API_BASE_URL}/api/settings`, { method: 'PATCH', @@ -28,14 +30,14 @@ export const settingsApi = { }) }, - resetSettings: async (userId = 'default'): Promise => { + resetSettings: async (userId = DEFAULT_USER_ID): Promise => { return fetchWrapper(`${API_BASE_URL}/api/settings`, { method: 'DELETE', params: { userId }, }) }, - getOpenCodeConfigs: async (userId = 'default'): Promise => { + getOpenCodeConfigs: async (userId = DEFAULT_USER_ID): Promise => { return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs`, { params: { userId }, }) @@ -43,7 +45,7 @@ export const settingsApi = { createOpenCodeConfig: async ( request: CreateOpenCodeConfigRequest, - userId = 'default' + userId = DEFAULT_USER_ID ): Promise => { return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs`, { method: 'POST', @@ -56,7 +58,7 @@ export const settingsApi = { updateOpenCodeConfig: async ( configName: string, request: UpdateOpenCodeConfigRequest, - userId = 'default' + userId = DEFAULT_USER_ID ): Promise => { return fetchWrapper( `${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`, @@ -71,7 +73,7 @@ export const settingsApi = { deleteOpenCodeConfig: async ( configName: string, - userId = 'default' + userId = DEFAULT_USER_ID ): Promise => { await fetchWrapper( `${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}`, @@ -85,7 +87,7 @@ export const settingsApi = { setDefaultOpenCodeConfig: async ( configName: string, - userId = 'default' + userId = DEFAULT_USER_ID ): Promise => { return fetchWrapper( `${API_BASE_URL}/api/settings/opencode-configs/${encodeURIComponent(configName)}/set-default`, @@ -98,7 +100,7 @@ export const settingsApi = { ) }, - getDefaultOpenCodeConfig: async (userId = 'default'): Promise => { + getDefaultOpenCodeConfig: async (userId = DEFAULT_USER_ID): Promise => { try { return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs/default`, { params: { userId }, diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index ef19bd4a..2a0f2cab 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -210,7 +210,7 @@ export type ContentPart = | { type: 'file', path: string, name: string } | { type: 'image', id: string, filename: string, mime: string, dataUrl: string } -export interface FileInfo { +export interface FileAttachmentInfo { path: string name: string mime?: string diff --git a/frontend/src/components/message/MessageThread.tsx b/frontend/src/components/message/MessageThread.tsx index 69b59eb9..027870b5 100644 --- a/frontend/src/components/message/MessageThread.tsx +++ b/frontend/src/components/message/MessageThread.tsx @@ -4,15 +4,16 @@ import { MessagePart } from './MessagePart' import { UserMessageActionButtons } from './UserMessageActionButtons' import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage' import { MessageError } from './MessageError' -import type { MessageWithParts } from '@/api/types' +import type { Message, Part } from '@/api/types' import { useSessionStatusForSession } from '@/stores/sessionStatusStore' import { useSessionTodos } from '@/stores/sessionTodosStore' +import { useMessageParts, usePartsForMessage, usePartsVersion } from '@/stores/messagePartsStore' import type { components } from '@/api/opencode-types' import type { Todo } from '@/components/message/SessionTodoDisplay' import type { OpenCodeError } from '@/lib/opencode-errors' -function getMessageTextContent(msg: MessageWithParts): string { - return msg.parts +function getMessageTextContent(parts: Part[]): string { + return parts .filter(p => p.type === 'text') .map(p => p.text || '') .join('\n\n') @@ -23,16 +24,16 @@ interface MessageThreadProps { opcodeUrl: string sessionID: string directory?: string - messages?: MessageWithParts[] + messages?: Message[] onFileClick?: (filePath: string, lineNumber?: number) => void onChildSessionClick?: (sessionId: string) => void onUndoMessage?: (restoredPrompt: string) => void model?: string } -const isMessageStreaming = (msg: MessageWithParts): boolean => { - if (msg.info.role !== 'assistant') return false - return !('completed' in msg.info.time && msg.info.time.completed) +const isMessageStreaming = (msg: Message): boolean => { + if (msg.role !== 'assistant') return false + return !('completed' in msg.time && msg.time.completed) } function isSessionInRetry(sessionStatus: { type?: string }): boolean { @@ -47,19 +48,166 @@ const compareMessageIds = (id1: string, id2: string): number => { } const findLastMessageByRole = ( - messages: MessageWithParts[], + messages: Message[], role: 'user' | 'assistant', - predicate?: (msg: MessageWithParts) => boolean + predicate?: (msg: Message) => boolean ): string | undefined => { for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i] - if (msg.info.role === role && (!predicate || predicate(msg))) { - return msg.info.id + if (msg.role === role && (!predicate || predicate(msg))) { + return msg.id } } return undefined } +interface MessageRowProps { + msg: Message + index: number + messages: Message[] + pendingAssistantId: string | undefined + lastUserMessageId: string | undefined + isSessionBusy: boolean + onUndoMessage?: (restoredPrompt: string) => void + editingUserMessageId: string | null + editingForAssistantId: string | null + opcodeUrl: string + sessionID: string + directory?: string + onFileClick?: (filePath: string, lineNumber?: number) => void + onChildSessionClick?: (sessionId: string) => void + handleStartEditUserMessage: (userMessageId: string, assistantMessageId: string) => void + handleCancelEdit: () => void + model?: string +} + +const MessageRow = memo(function MessageRow({ + msg, + index, + messages, + pendingAssistantId, + lastUserMessageId, + isSessionBusy, + onUndoMessage, + editingUserMessageId, + editingForAssistantId, + opcodeUrl, + sessionID, + directory, + onFileClick, + onChildSessionClick, + handleStartEditUserMessage, + handleCancelEdit, + model, +}: MessageRowProps) { + const parts = usePartsForMessage(msg.id) + const streaming = isMessageStreaming(msg) + const isQueued = msg.role === 'user' && pendingAssistantId && compareMessageIds(msg.id, pendingAssistantId) > 0 + const isLastUserMessage = msg.role === 'user' && msg.id === lastUserMessageId + const messageTextContent = getMessageTextContent(parts) + + const nextAssistantMessage = messages.slice(index + 1).find(m => m.role === 'assistant') + const isUserBeforeAssistant = msg.role === 'user' && nextAssistantMessage + const canEditUserMessage = isLastUserMessage && isUserBeforeAssistant && !isSessionBusy + const canUndoUserMessage = isLastUserMessage && nextAssistantMessage && !isSessionBusy && onUndoMessage + + const isEditingThisMessage = editingUserMessageId === msg.id + + return ( +
+
+
+
+ + {msg.role === 'user' ? 'You' : (msg.role === 'assistant' && 'modelID' in msg ? msg.modelID : 'Assistant')} + + {msg.time && ( + + {new Date(msg.time.created).toLocaleTimeString()} + + )} + {canEditUserMessage && nextAssistantMessage && ( + + )} + {isQueued && ( + + QUEUED + + )} +
+ + {msg.role === 'user' && canUndoUserMessage && ( + + )} +
+ +
+ {msg.role === 'user' && isEditingThisMessage && editingForAssistantId ? ( + + ) : msg.role === 'user' && canEditUserMessage && nextAssistantMessage ? ( + handleStartEditUserMessage(msg.id, nextAssistantMessage.id)} + isEditable={false} + /> + ) : parts.length > 0 ? ( + parts.map((part: Part, partIndex: number) => ( +
+ +
+ )) + ) : null} + {msg.role === 'assistant' && 'error' in msg && msg.error && ( + + )} +
+
+
+ ) +}) + export const MessageThread = memo(function MessageThread({ opcodeUrl, sessionID, @@ -86,12 +234,21 @@ export const MessageThread = memo(function MessageThread({ const isSessionBusy = !!pendingAssistantId || isSessionInRetry(sessionStatus) const setSessionTodos = useSessionTodos((state) => state.setTodos) + const partsVersion = usePartsVersion() useEffect(() => { if (!messages || messages.length === 0) return - const latestTodoPart = messages - .flatMap(msg => msg.parts) + const partsMap = useMessageParts.getState().parts + const allParts: Part[] = [] + for (const msg of messages) { + const msgParts = partsMap.get(msg.id) + if (msgParts) { + allParts.push(...msgParts) + } + } + + const latestTodoPart = allParts .filter((part): part is components['schemas']['ToolPart'] => part.type === 'tool' && (part.tool === 'todowrite' || part.tool === 'todoread')) .filter(part => part.state.status === 'completed' && 'time' in part.state) .sort((a, b) => { @@ -102,8 +259,8 @@ export const MessageThread = memo(function MessageThread({ return bEndTime - aEndTime })[0] -if (latestTodoPart) { -const state = latestTodoPart.state + if (latestTodoPart) { + const state = latestTodoPart.state let todos: Todo[] = [] if ('metadata' in state && state.metadata?.todos && Array.isArray(state.metadata.todos)) { @@ -124,7 +281,7 @@ const state = latestTodoPart.state setSessionTodos(sessionID, todos) } } - }, [messages, sessionID, setSessionTodos]) + }, [messages, sessionID, setSessionTodos, partsVersion]) const handleStartEditUserMessage = useCallback((userMessageId: string, assistantMessageId: string) => { setEditingUserMessageId(userMessageId) @@ -146,113 +303,28 @@ const state = latestTodoPart.state return (
- {messages.map((msg, index) => { - const streaming = isMessageStreaming(msg) - const isQueued = msg.info.role === 'user' && pendingAssistantId && compareMessageIds(msg.info.id, pendingAssistantId) > 0 - const isLastUserMessage = msg.info.role === 'user' && msg.info.id === lastUserMessageId - const messageTextContent = getMessageTextContent(msg) - - const nextAssistantMessage = messages.slice(index + 1).find(m => m.info.role === 'assistant') - const isUserBeforeAssistant = msg.info.role === 'user' && nextAssistantMessage - const canEditUserMessage = isLastUserMessage && isUserBeforeAssistant && !isSessionBusy - const canUndoUserMessage = isLastUserMessage && nextAssistantMessage && !isSessionBusy && onUndoMessage - - const isEditingThisMessage = editingUserMessageId === msg.info.id - - return ( -
-
-
-
- - {msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')} - - {msg.info.time && ( - - {new Date(msg.info.time.created).toLocaleTimeString()} - - )} - {canEditUserMessage && nextAssistantMessage && ( - - )} - {isQueued && ( - - QUEUED - - )} -
- - {msg.info.role === 'user' && canUndoUserMessage && ( - - )} -
- -
- {msg.info.role === 'user' && isEditingThisMessage && editingForAssistantId ? ( - - ) : msg.info.role === 'user' && canEditUserMessage && nextAssistantMessage ? ( - handleStartEditUserMessage(msg.info.id, nextAssistantMessage.info.id)} - isEditable={false} - /> - ) : ( - msg.parts.map((part, partIndex) => ( -
- -
- )) - )} - {msg.info.role === 'assistant' && 'error' in msg.info && msg.info.error && ( - - )} -
-
-
- ) - })} + {messages.map((msg, index) => ( + + ))}
) -}) \ No newline at end of file +}) diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index 0b7245c0..be925cc9 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -25,7 +25,7 @@ import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQu import type { components } from '@/api/opencode-types' -import type { MessageWithParts, FileInfo, ImageAttachment } from '@/api/types' +import type { Message, FileAttachmentInfo, ImageAttachment } from '@/api/types' const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"] @@ -82,7 +82,7 @@ export const PromptInput = forwardRef(funct const [isBashMode, setIsBashMode] = useState(false) const [showSuggestions, setShowSuggestions] = useState(false) const [suggestionQuery, setSuggestionQuery] = useState('') - const [attachedFiles, setAttachedFiles] = useState(new Map()) + const [attachedFiles, setAttachedFiles] = useState(new Map()) const [imageAttachments, setImageAttachments] = useState([]) const [isDragging, setIsDragging] = useState(false) const [showMentionSuggestions, setShowMentionSuggestions] = useState(false) @@ -715,12 +715,12 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) } } - const isMessageIncomplete = (msg: MessageWithParts): boolean => { - if (msg.info.role !== 'assistant') return false - return !('completed' in msg.info.time && msg.info.time.completed) + const isMessageIncomplete = (msg: Message): boolean => { + if (msg.role !== 'assistant') return false + return !('completed' in msg.time && msg.time.completed) } - const lastAssistantMessage = messages?.filter(msg => msg.info.role === 'assistant').at(-1) + const lastAssistantMessage = messages?.filter(msg => msg.role === 'assistant').at(-1) const hasIncompleteMessages = lastAssistantMessage ? isMessageIncomplete(lastAssistantMessage) : false const sessionAgent = useSessionAgent(opcodeUrl, sessionID, directory) diff --git a/frontend/src/components/message/TextPart.tsx b/frontend/src/components/message/TextPart.tsx index ddefbd79..721c0dfa 100644 --- a/frontend/src/components/message/TextPart.tsx +++ b/frontend/src/components/message/TextPart.tsx @@ -190,11 +190,7 @@ export function TextPart({ part }: TextPartProps) { }, [part.text]) if (!part.text || part.text.trim() === '') { - return ( -
- [Empty message content] -
- ) + return null } return ( diff --git a/frontend/src/components/repo/RepoMcpDialog.tsx b/frontend/src/components/repo/RepoMcpDialog.tsx index dc3ea2b9..37f42212 100644 --- a/frontend/src/components/repo/RepoMcpDialog.tsx +++ b/frontend/src/components/repo/RepoMcpDialog.tsx @@ -1,12 +1,7 @@ import { useState, useEffect, useCallback } from 'react' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog' -import { Switch } from '@/components/ui/switch' -import { Button } from '@/components/ui/button' -import { Badge } from '@/components/ui/badge' -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' +import { RepoMcpServerList } from './RepoMcpServerList' import { DeleteDialog } from '@/components/ui/delete-dialog' -import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu' -import { Loader2, XCircle, AlertCircle, Plug, Shield, MoreVertical, Key, RefreshCw } from 'lucide-react' import { McpOAuthDialog } from '@/components/settings/McpOAuthDialog' import { mcpApi, type McpStatus, type McpServerConfig, type McpAuthStartResponse } from '@/api/mcp' import { useMutation, useQueryClient } from '@tanstack/react-query' @@ -133,58 +128,12 @@ export function RepoMcpDialog({ open, onOpenChange, directory }: RepoMcpDialogPr fetchStatus() } }, [open, directory, fetchStatus]) - + const getDisplayName = (serverId: string): string => { const name = serverId.replace(/[-_]/g, ' ') return name.charAt(0).toUpperCase() + name.slice(1) } - - const getDescription = (serverConfig: McpServerConfig): string => { - if (serverConfig.type === 'local' && serverConfig.command) { - const command = serverConfig.command.join(' ') - if (command.includes('filesystem')) return 'File system access' - if (command.includes('git')) return 'Git repository operations' - if (command.includes('sqlite')) return 'SQLite database access' - if (command.includes('postgres')) return 'PostgreSQL database access' - if (command.includes('brave-search')) return 'Web search via Brave' - if (command.includes('github')) return 'GitHub repository access' - if (command.includes('slack')) return 'Slack integration' - if (command.includes('puppeteer')) return 'Web automation' - if (command.includes('fetch')) return 'HTTP requests' - if (command.includes('memory')) return 'Persistent memory' - return `Local: ${command}` - } else if (serverConfig.type === 'remote' && serverConfig.url) { - return serverConfig.url - } - return 'MCP server' - } - - const getStatusBadge = (status?: McpStatus) => { - if (!status) return null - - switch (status.status) { - case 'connected': - return Connected - case 'disabled': - return Disabled - case 'failed': - return ( - - - Failed - - ) - case 'needs_auth': - return ( - - Needs Auth - - ) - default: - return Unknown - } - } - + if (!directory) return null return ( @@ -197,124 +146,17 @@ export function RepoMcpDialog({ open, onOpenChange, directory }: RepoMcpDialogPr -
- {hasFetchedStatus && serverIds.length === 0 ? ( -
- -

No MCP servers configured for this location

-

Add them in Settings or in the project's opencode.json

-
- ) : isLoadingStatus ? ( -
- - Loading... -
- ) : ( -
- {serverIds.map((serverId) => { - const serverConfig = mcpServers[serverId] - const status = localStatus[serverId] - const isConnected = status?.status === 'connected' - const needsAuth = status?.status === 'needs_auth' - const failed = status?.status === 'failed' - const isRemote = serverConfig?.type === 'remote' - const hasOAuthConfig = isRemote && !!serverConfig?.oauth - const hasOAuthError = failed && isRemote && !!status?.error && /oauth|auth.*state/i.test(status.error) - const isOAuthServer = hasOAuthConfig || hasOAuthError || (needsAuth && isRemote) - const connectedWithOAuth = isOAuthServer && isConnected - const showAuthButton = needsAuth || (isOAuthServer && failed) - - return ( -
-
-
-

- {getDisplayName(serverId)} -

- {connectedWithOAuth && ( - - - - )} - {getStatusBadge(status)} -
-

- {serverConfig ? getDescription(serverConfig) : 'MCP server'} -

- {failed && status.status === 'failed' && ( -
- - {status.error} -
- )} -
- -
- {showAuthButton ? ( - - ) : ( - { - toggleMutation.mutate({ serverId, enable: enabled }) - }} - onClick={(e) => e.stopPropagation()} - /> - )} - {(isOAuthServer || needsAuth) && ( - - - - - - {showAuthButton && ( - setAuthDialogServerId(serverId)}> - - Authenticate - - )} - {connectedWithOAuth && ( - setAuthDialogServerId(serverId)}> - - Re-authenticate - - )} - {connectedWithOAuth && ( - <> - - setRemoveAuthConfirmServer(serverId)} - disabled={removeAuthMutation.isPending} - > - - {removeAuthMutation.isPending ? 'Removing...' : 'Remove Auth'} - - - )} - - - )} -
-
- ) - })} -
- )} -
+ + mcpServers: Record + toggleMutation: { + mutate: (variables: { serverId: string; enable: boolean }) => void + isPending: boolean + } + removeAuthMutation: { + mutate: (variables: string) => void + isPending: boolean + } + onAuthClick: (serverId: string) => void + onRemoveAuthClick: (serverId: string) => void +} + +export function RepoMcpServerList({ + hasFetchedStatus, + serverIds, + isLoadingStatus, + localStatus, + mcpServers, + toggleMutation, + removeAuthMutation, + onAuthClick, + onRemoveAuthClick, +}: RepoMcpServerListProps) { + const getDisplayName = (serverId: string): string => { + const name = serverId.replace(/[-_]/g, ' ') + return name.charAt(0).toUpperCase() + name.slice(1) + } + + const getDescription = (serverConfig: McpServerConfig): string => { + if (serverConfig.type === 'local' && serverConfig.command) { + const command = serverConfig.command.join(' ') + if (command.includes('filesystem')) return 'File system access' + if (command.includes('git')) return 'Git repository operations' + if (command.includes('sqlite')) return 'SQLite database access' + if (command.includes('postgres')) return 'PostgreSQL database access' + if (command.includes('brave-search')) return 'Web search via Brave' + if (command.includes('github')) return 'GitHub repository access' + if (command.includes('slack')) return 'Slack integration' + if (command.includes('puppeteer')) return 'Web automation' + if (command.includes('fetch')) return 'HTTP requests' + if (command.includes('memory')) return 'Persistent memory' + return `Local: ${command}` + } else if (serverConfig.type === 'remote' && serverConfig.url) { + return serverConfig.url + } + return 'MCP server' + } + + const getStatusBadge = (status?: McpStatus) => { + if (!status) return null + + switch (status.status) { + case 'connected': + return Connected + case 'disabled': + return Disabled + case 'failed': + return ( + + + Failed + + ) + case 'needs_auth': + return ( + + Needs Auth + + ) + default: + return Unknown + } + } + + return ( +
+ {hasFetchedStatus && serverIds.length === 0 ? ( +
+ +

No MCP servers configured for this location

+

Add them in Settings or in the project's opencode.json

+
+ ) : isLoadingStatus ? ( +
+ + Loading... +
+ ) : ( +
+ {serverIds.map((serverId) => { + const serverConfig = mcpServers[serverId] + const status = localStatus[serverId] + const isConnected = status?.status === 'connected' + const needsAuth = status?.status === 'needs_auth' + const failed = status?.status === 'failed' + const isRemote = serverConfig?.type === 'remote' + const hasOAuthConfig = isRemote && !!serverConfig?.oauth + const hasOAuthError = failed && isRemote && !!status?.error && /oauth|auth.*state/i.test(status.error) + const isOAuthServer = hasOAuthConfig || hasOAuthError || (needsAuth && isRemote) + const connectedWithOAuth = isOAuthServer && isConnected + const showAuthButton = needsAuth || (isOAuthServer && failed) + + return ( +
+
+
+

+ {getDisplayName(serverId)} +

+ {(showAuthButton || connectedWithOAuth) ? ( + + + + + + {showAuthButton && ( + onAuthClick(serverId)}> + + Authenticate + + )} + {connectedWithOAuth && ( + onAuthClick(serverId)}> + + Re-authenticate + + )} + {connectedWithOAuth && ( + <> + + onRemoveAuthClick(serverId)} + disabled={removeAuthMutation.isPending} + > + + {removeAuthMutation.isPending ? 'Removing...' : 'Remove Auth'} + + + )} + + + ) : ( + getStatusBadge(status) + )} +
+

+ {serverConfig ? getDescription(serverConfig) : 'MCP server'} +

+ {failed && status.status === 'failed' && ( +
+ + {status.error} +
+ )} +
+ +
+ {showAuthButton ? ( + + ) : ( + { + toggleMutation.mutate({ serverId, enable: enabled }) + }} + onClick={(e) => e.stopPropagation()} + /> + )} +
+
+ ) + })} +
+ )} +
+ ) +} diff --git a/frontend/src/components/session/QuestionPrompt.tsx b/frontend/src/components/session/QuestionPrompt.tsx index b531fdd7..455f2a6d 100644 --- a/frontend/src/components/session/QuestionPrompt.tsx +++ b/frontend/src/components/session/QuestionPrompt.tsx @@ -179,20 +179,20 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr return (
-
+
{totalSteps > 1 && ( )} - + {isConfirmStep ? 'Review' : ( totalSteps > 1 ? `Question ${currentIndex + 1}/${questions.length}` @@ -203,7 +203,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr @@ -218,7 +218,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr
-
+
{isConfirmStep ? ( {totalSteps > 1 && ( -
+
{Array.from({ length: totalSteps }).map((_, i) => ( + + !open && setDeletePasskeyId(null)} + onConfirm={handleDeleteConfirm} + onCancel={handleDeleteCancel} + title="Delete Passkey" + description="Are you sure you want to delete this passkey? This action cannot be undone." + isDeleting={deletePasskeyMutation.isPending} + />
) } diff --git a/frontend/src/components/settings/ProviderSettings.tsx b/frontend/src/components/settings/ProviderSettings.tsx index 149833ae..f32dfb0e 100644 --- a/frontend/src/components/settings/ProviderSettings.tsx +++ b/frontend/src/components/settings/ProviderSettings.tsx @@ -3,6 +3,7 @@ import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Badge } from '@/components/ui/badge' import { Input } from '@/components/ui/input' +import { DeleteDialog } from '@/components/ui/delete-dialog' import { Loader2, Check, X, Shield, ChevronDown, ChevronRight, Key, Search, Pencil, Trash2 } from 'lucide-react' import { providerCredentialsApi, getProviders } from '@/api/providers' import type { Provider } from '@/api/providers' @@ -23,6 +24,7 @@ export function ProviderSettings() { const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false) const [apiKeyProvider, setApiKeyProvider] = useState(null) const [apiKeyMode, setApiKeyMode] = useState<'add' | 'edit'>('add') + const [deleteTarget, setDeleteTarget] = useState(null) const queryClient = useQueryClient() const { data: providersData, isLoading: providersLoading } = useQuery({ @@ -53,11 +55,20 @@ export function ProviderSettings() { }) const handleDeleteCredential = (providerId: string) => { - if (confirm(`Remove credentials for ${providerId}?`)) { - deleteCredentialMutation.mutate(providerId) + setDeleteTarget(providerId) + } + + const handleDeleteConfirm = () => { + if (deleteTarget) { + deleteCredentialMutation.mutate(deleteTarget) + setDeleteTarget(null) } } + const handleDeleteCancel = () => { + setDeleteTarget(null) + } + const handleOAuthAuthorize = (response: OAuthAuthorizeResponse) => { setOauthResponse(response) setOauthDialogOpen(false) @@ -418,6 +429,16 @@ export function ProviderSettings() { mode={apiKeyMode} /> )} + + !open && setDeleteTarget(null)} + onConfirm={handleDeleteConfirm} + onCancel={handleDeleteCancel} + title="Remove Credentials" + description={`Are you sure you want to remove credentials for ${deleteTarget || 'this provider'}?`} + isDeleting={deleteCredentialMutation.isPending} + />
) } diff --git a/frontend/src/components/source-control/ChangesTab.tsx b/frontend/src/components/source-control/ChangesTab.tsx index 79b30585..706f6dc4 100644 --- a/frontend/src/components/source-control/ChangesTab.tsx +++ b/frontend/src/components/source-control/ChangesTab.tsx @@ -1,53 +1,41 @@ import { useState } from 'react' -import { useGitStatus, getApiErrorMessage } from '@/api/git' +import { useGitStatus } from '@/api/git' import { useGit } from '@/hooks/useGit' import { GitFlatFileList } from './GitFlatFileList' import { Button } from '@/components/ui/button' import { Textarea } from '@/components/ui/textarea' import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' import { FileDiffView } from '@/components/file-browser/FileDiffView' -import { Loader2, GitCommit, FileText, AlertCircle, X } from 'lucide-react' +import { Loader2, GitCommit, FileText, AlertCircle } from 'lucide-react' interface ChangesTabProps { repoId: number onFileSelect: (path: string, staged: boolean) => void selectedFile?: {path: string, staged: boolean} isMobile: boolean + onError?: (error: unknown) => void } -export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: ChangesTabProps) { +export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile, onError }: ChangesTabProps) { const { data: status, isLoading, error } = useGitStatus(repoId) - const git = useGit(repoId) + const git = useGit(repoId, onError) const [commitMessage, setCommitMessage] = useState('') - const [apiError, setApiError] = useState(null) const stagedFiles = status?.files.filter(f => f.staged) || [] const unstagedFiles = status?.files.filter(f => !f.staged) || [] const canCommit = commitMessage.trim() && stagedFiles.length > 0 && !git.commit.isPending - const handleGitAction = async (action: () => Promise) => { - try { - setApiError(null) - await action() - } catch (error: unknown) { - const message = getApiErrorMessage(error) - setApiError(message) - } - } - const handleStage = (paths: string[]) => { - handleGitAction(() => git.stageFiles.mutateAsync(paths)) + git.stageFiles.mutate(paths) } const handleUnstage = (paths: string[]) => { - handleGitAction(() => git.unstageFiles.mutateAsync(paths)) + git.unstageFiles.mutate(paths) } const handleCommit = () => { - handleGitAction(async () => { - await git.commit.mutateAsync({ message: commitMessage.trim() }) - setCommitMessage('') - }) + git.commit.mutate({ message: commitMessage.trim() }) + setCommitMessage('') } if (isLoading) { @@ -73,16 +61,6 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: Cha if (isMobile && selectedFile) { return (
- {apiError && ( -
- - {apiError} - -
- )} - Files ({stagedFiles.length + unstagedFiles.length}) @@ -164,16 +142,6 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: Cha } else { return (
- {apiError && ( -
- - {apiError} - -
- )} -
{status.hasChanges ? ( <> diff --git a/frontend/src/components/source-control/GitErrorBanner.tsx b/frontend/src/components/source-control/GitErrorBanner.tsx new file mode 100644 index 00000000..0d09d868 --- /dev/null +++ b/frontend/src/components/source-control/GitErrorBanner.tsx @@ -0,0 +1,34 @@ +import { Alert, AlertDescription } from '@/components/ui/alert' +import { Button } from '@/components/ui/button' +import { AlertCircle, X } from 'lucide-react' + +interface GitErrorBannerProps { + error: { summary: string; detail?: string } + onDismiss: () => void +} + +export function GitErrorBanner({ error, onDismiss }: GitErrorBannerProps) { + return ( + +
+
+ + {error.summary} + +
+ {error.detail && ( +
+            {error.detail}
+          
+ )} +
+
+ ) +} diff --git a/frontend/src/components/source-control/SourceControlPanel.tsx b/frontend/src/components/source-control/SourceControlPanel.tsx index 4994610c..4ff4dfd6 100644 --- a/frontend/src/components/source-control/SourceControlPanel.tsx +++ b/frontend/src/components/source-control/SourceControlPanel.tsx @@ -1,10 +1,12 @@ import { useState } from 'react' +import { FetchError } from '@opencode-manager/shared' import { useGitStatus, getApiErrorMessage } from '@/api/git' import { useGit } from '@/hooks/useGit' import { ChangesTab } from './ChangesTab' import { CommitsTab } from './CommitsTab' import { BranchesTab } from './BranchesTab' +import { GitErrorBanner } from './GitErrorBanner' import { FileDiffView } from '@/components/file-browser/FileDiffView' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' @@ -23,7 +25,6 @@ import { } from 'lucide-react' import { cn } from '@/lib/utils' import { useMobile } from '@/hooks/useMobile' -import { showToast } from '@/lib/toast' interface SourceControlPanelProps { repoId: number @@ -48,15 +49,26 @@ export function SourceControlPanel({ }: SourceControlPanelProps) { const [activeTab, setActiveTab] = useState('changes') const [selectedFile, setSelectedFile] = useState<{path: string, staged: boolean} | undefined>() + const [gitError, setGitError] = useState<{ summary: string; detail?: string } | null>(null) const { data: status } = useGitStatus(repoId) - const git = useGit(repoId) const isMobile = useMobile() + + const handleGitError = (error: unknown) => { + if (error instanceof FetchError) { + setGitError({ summary: getApiErrorMessage(error), detail: error.detail }) + } else { + setGitError({ summary: getApiErrorMessage(error) }) + } + } + + const git = useGit(repoId, handleGitError) + const handleGitAction = async (action: () => Promise) => { try { + setGitError(null) await action() - } catch (error: unknown) { - const message = getApiErrorMessage(error) - showToast.error(message) + } catch { + // error already handled by useGit's onError -> handleGitError } } @@ -138,6 +150,10 @@ export function SourceControlPanel({
+ {gitError && ( + setGitError(null)} /> + )} +
{tabs.map((tab) => { const Icon = tab.icon @@ -175,6 +191,7 @@ export function SourceControlPanel({ onFileSelect={(path, staged) => setSelectedFile({ path, staged })} selectedFile={selectedFile} isMobile={isMobile} + onError={handleGitError} /> )} {activeTab === 'commits' && ( diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 82914f44..b43e9e9e 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -9,10 +9,31 @@ import { showToast } from '@/lib/toast' import { subscribeToSSE, addSSEDirectory, ensureSSEConnected } from '@/lib/sseManager' import { OPENCODE_API_ENDPOINT } from '@/config' import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState' +import { useMessageParts } from '@/stores/messagePartsStore' type PermissionsBySession = Record type QuestionsBySession = Record +function optimisticallyErrorToolPart(messageID: string, callID: string, errorMessage: string) { + const store = useMessageParts.getState() + const parts = store.parts.get(messageID) + const target = parts?.find(p => p.type === 'tool' && p.callID === callID) + if (target && target.type === 'tool' && target.state.status === 'running') { + store.setPart(messageID, { + ...target, + state: { + status: 'error' as const, + input: target.state.input, + error: errorMessage, + time: { + start: target.state.time.start, + end: Date.now(), + }, + }, + }) + } +} + interface SSHHostKeyState { request: SSHHostKeyRequest | null respond: (requestId: string, approved: boolean) => Promise @@ -181,9 +202,16 @@ export function EventProvider({ children }: { children: React.ReactNode }) { } const client = getClient(sessionID) if (!client) throw new Error('No client found for session') + + if (response === 'reject') { + const permission = (permissionsBySession[sessionID] ?? []).find(p => p.id === permissionID) + if (permission?.tool) { + optimisticallyErrorToolPart(permission.tool.messageID, permission.tool.callID, 'Permission denied') + } + } + await client.respondToPermission(sessionID, permissionID, response) - removePermission(permissionID, sessionID) - }, [getClient, removePermission]) + }, [getClient, permissionsBySession]) const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => { const connected = await ensureSSEConnected() @@ -196,8 +224,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const client = getClient(question.sessionID) if (!client) throw new Error('No client found for session') await client.replyToQuestion(requestID, answers) - removeQuestion(requestID, question.sessionID) - }, [getClient, removeQuestion, questionsBySession]) + }, [getClient, questionsBySession]) const rejectQuestion = useCallback(async (requestID: string) => { const connected = await ensureSSEConnected() @@ -209,9 +236,13 @@ export function EventProvider({ children }: { children: React.ReactNode }) { if (!question) throw new Error('Question not found') const client = getClient(question.sessionID) if (!client) throw new Error('No client found for session') + + if (question.tool) { + optimisticallyErrorToolPart(question.tool.messageID, question.tool.callID, 'Question rejected') + } + await client.rejectQuestion(requestID) - removeQuestion(requestID, question.sessionID) - }, [getClient, removeQuestion, questionsBySession]) + }, [getClient, questionsBySession]) const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => { const perms = permissionsBySession[sessionID] ?? [] diff --git a/frontend/src/hooks/useAutoScroll.ts b/frontend/src/hooks/useAutoScroll.ts index fab090f8..d56a0f02 100644 --- a/frontend/src/hooks/useAutoScroll.ts +++ b/frontend/src/hooks/useAutoScroll.ts @@ -1,18 +1,11 @@ import { useRef, useEffect, useCallback } from 'react' +import type { Message } from '@/api/types' const SCROLL_LOCK_MS = 300 -interface MessageInfo { - role: string -} - -interface Message { - info: MessageInfo -} - -interface UseAutoScrollOptions { +interface UseAutoScrollOptions { containerRef?: React.RefObject - messages?: T[] + messages?: Message[] sessionId?: string onScrollStateChange?: (isScrolledUp: boolean) => void } @@ -21,12 +14,12 @@ interface UseAutoScrollReturn { scrollToBottom: () => void } -export function useAutoScroll({ +export function useAutoScroll({ containerRef, messages, sessionId, onScrollStateChange -}: UseAutoScrollOptions): UseAutoScrollReturn { +}: UseAutoScrollOptions): UseAutoScrollReturn { const lastMessageCountRef = useRef(0) const hasInitialScrolledRef = useRef(false) const userScrolledAtRef = useRef(0) @@ -139,7 +132,7 @@ export function useAutoScroll({ if (currentCount > prevCount) { const newMessage = messages[currentCount - 1] - if (newMessage?.info.role === 'user') { + if (newMessage?.role === 'user') { scrollToBottom() return } diff --git a/frontend/src/hooks/useCommandHandler.ts b/frontend/src/hooks/useCommandHandler.ts index eaaf722e..ec8e2a59 100644 --- a/frontend/src/hooks/useCommandHandler.ts +++ b/frontend/src/hooks/useCommandHandler.ts @@ -88,7 +88,7 @@ export function useCommandHandler({ } } } catch (error) { - console.error('Failed to create new session:', error) + showToast.error(`Failed to create new session: ${error instanceof Error ? error.message : 'Unknown error'}`) } break @@ -147,7 +147,6 @@ export function useCommandHandler({ }) } } catch (error) { - console.error('Failed to execute command:', error) showToast.error(`Command failed: ${error instanceof Error ? error.message : 'Unknown error'}`) setSessionStatus(sessionID, { type: 'idle' }) } finally { diff --git a/frontend/src/hooks/useCommands.ts b/frontend/src/hooks/useCommands.ts index eec24fcd..91cd2fca 100644 --- a/frontend/src/hooks/useCommands.ts +++ b/frontend/src/hooks/useCommands.ts @@ -172,8 +172,7 @@ export function useCommands(opcodeUrl: string | null) { index === self.findIndex((c) => c.name === command.name) ) setCommands(uniqueCommands) - } catch (err) { - console.error('Failed to fetch commands:', err) + } catch { setError('Failed to load commands') setCommands(BUILTIN_COMMANDS) } finally { diff --git a/frontend/src/hooks/useContextUsage.ts b/frontend/src/hooks/useContextUsage.ts index 5798b87e..4715bd1f 100644 --- a/frontend/src/hooks/useContextUsage.ts +++ b/frontend/src/hooks/useContextUsage.ts @@ -2,6 +2,7 @@ import { useMemo } from 'react' import { useMessages } from './useOpenCode' import { useQuery } from '@tanstack/react-query' import { useModelSelection } from './useModelSelection' +import { fetchWrapper } from '@/api/fetchWrapper' interface ContextUsage { totalTokens: number @@ -33,11 +34,7 @@ interface ProvidersResponse { } async function fetchProviders(opcodeUrl: string): Promise { - const response = await fetch(`${opcodeUrl}/config/providers`) - if (!response.ok) { - throw new Error('Failed to fetch providers') - } - return response.json() + return fetchWrapper(`${opcodeUrl}/config/providers`) } export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string): ContextUsage => { @@ -47,7 +44,10 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID: const { data: providersData } = useQuery({ queryKey: ['providers', opcodeUrl], - queryFn: () => fetchProviders(opcodeUrl!), + queryFn: () => { + if (!opcodeUrl) throw new Error('opcodeUrl is required') + return fetchProviders(opcodeUrl) + }, enabled: !!opcodeUrl, staleTime: 5 * 60 * 1000, }) @@ -55,11 +55,11 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID: return useMemo(() => { const currentModel = modelString || null - const assistantMessages = messages?.filter(msg => msg.info.role === 'assistant') || [] + const assistantMessages = messages?.filter(msg => msg.role === 'assistant') || [] let latestAssistantMessage = assistantMessages[assistantMessages.length - 1] - if (latestAssistantMessage?.info.role === 'assistant') { - const tokens = latestAssistantMessage.info.tokens.input + latestAssistantMessage.info.tokens.output + latestAssistantMessage.info.tokens.reasoning + (latestAssistantMessage.info.tokens.cache?.read || 0) + if (latestAssistantMessage?.role === 'assistant') { + const tokens = latestAssistantMessage.tokens.input + latestAssistantMessage.tokens.output + latestAssistantMessage.tokens.reasoning + (latestAssistantMessage.tokens.cache?.read || 0) if (tokens === 0 && assistantMessages.length > 1) { latestAssistantMessage = assistantMessages[assistantMessages.length - 2] } @@ -88,8 +88,8 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID: } let totalTokens = 0 - if (latestAssistantMessage?.info.role === 'assistant') { - totalTokens = latestAssistantMessage.info.tokens.input + latestAssistantMessage.info.tokens.output + latestAssistantMessage.info.tokens.reasoning + (latestAssistantMessage.info.tokens.cache?.read || 0) + if (latestAssistantMessage?.role === 'assistant') { + totalTokens = latestAssistantMessage.tokens.input + latestAssistantMessage.tokens.output + latestAssistantMessage.tokens.reasoning + (latestAssistantMessage.tokens.cache?.read || 0) } const usagePercentage = contextLimit ? (totalTokens / contextLimit) * 100 : null diff --git a/frontend/src/hooks/useFileSearch.ts b/frontend/src/hooks/useFileSearch.ts index 58485623..cc8fbc8f 100644 --- a/frontend/src/hooks/useFileSearch.ts +++ b/frontend/src/hooks/useFileSearch.ts @@ -1,5 +1,6 @@ import { useState, useEffect } from 'react' import { useQuery } from '@tanstack/react-query' +import { fetchWrapper } from '@/api/fetchWrapper' export interface FileSearchResult { files: string[] @@ -30,14 +31,11 @@ export function useFileSearch( params.append('directory', directory) } - const response = await fetch( + const data = await fetchWrapper( `${opcodeUrl}/find/file?${params.toString()}` ) - if (!response.ok) throw new Error('File search failed') - - const data = await response.json() - return data as string[] + return data }, enabled: enabled && !!opcodeUrl && !!debouncedQuery, staleTime: 60000, diff --git a/frontend/src/hooks/useGit.ts b/frontend/src/hooks/useGit.ts index 4fdd1fbd..711904d1 100644 --- a/frontend/src/hooks/useGit.ts +++ b/frontend/src/hooks/useGit.ts @@ -3,9 +3,17 @@ import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, import { createBranch, switchBranch } from '@/api/repos' import { showToast } from '@/lib/toast' -export function useGit(repoId: number | undefined) { +export function useGit(repoId: number | undefined, onError?: (error: unknown) => void) { const queryClient = useQueryClient() + const handleError = (error: unknown) => { + if (onError) { + onError(error) + } else { + showToast.error(getApiErrorMessage(error)) + } + } + const invalidateCache = (additionalKeys: string[] = []) => { if (!repoId) return const keys = ['gitStatus', 'fileDiff', 'gitLog', ...additionalKeys] @@ -21,9 +29,7 @@ export function useGit(repoId: number | undefined) { invalidateCache() showToast.success('Fetch completed') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const pull = useMutation({ @@ -35,9 +41,7 @@ export function useGit(repoId: number | undefined) { invalidateCache() showToast.success('Pull completed') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const push = useMutation({ @@ -51,9 +55,7 @@ export function useGit(repoId: number | undefined) { keysToInvalidate.forEach(key => queryClient.invalidateQueries({ queryKey: [key, repoId] })) showToast.success('Push completed') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const commit = useMutation({ @@ -65,9 +67,7 @@ export function useGit(repoId: number | undefined) { invalidateCache() showToast.success('Commit created') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const stageFilesMutation = useMutation({ @@ -79,9 +79,7 @@ export function useGit(repoId: number | undefined) { invalidateCache() showToast.success('Files staged') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const unstageFilesMutation = useMutation({ @@ -93,9 +91,7 @@ export function useGit(repoId: number | undefined) { invalidateCache() showToast.success('Files unstaged') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const log = useMutation({ @@ -103,9 +99,7 @@ export function useGit(repoId: number | undefined) { if (!repoId) throw new Error('No repo ID') return fetchGitLog(repoId, limit) }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const diff = useMutation({ @@ -113,9 +107,7 @@ export function useGit(repoId: number | undefined) { if (!repoId) throw new Error('No repo ID') return fetchGitDiff(repoId, path) }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const createBranchMutation = useMutation({ @@ -127,9 +119,7 @@ export function useGit(repoId: number | undefined) { invalidateCache(['branches']) showToast.success('Branch created') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const switchBranchMutation = useMutation({ @@ -141,9 +131,7 @@ export function useGit(repoId: number | undefined) { invalidateCache(['branches']) showToast.success('Switched to branch') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) const resetMutation = useMutation({ @@ -155,9 +143,7 @@ export function useGit(repoId: number | undefined) { invalidateCache() showToast.success('Reset to commit') }, - onError: (error) => { - showToast.error(getApiErrorMessage(error)) - }, + onError: handleError, }) return { diff --git a/frontend/src/hooks/useMcpServers.ts b/frontend/src/hooks/useMcpServers.ts index 902c3dc5..59d54e85 100644 --- a/frontend/src/hooks/useMcpServers.ts +++ b/frontend/src/hooks/useMcpServers.ts @@ -3,6 +3,10 @@ import { mcpApi } from '@/api/mcp' import type { McpStatusMap, McpServerConfig } from '@/api/mcp' import { showToast as toast } from '@/lib/toast' +const SESSION_QUERY_PREDICATE = (query: { queryKey: readonly unknown[] }) => + query.queryKey[0] === 'opencode' && + (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') + export function useMcpServers() { const queryClient = useQueryClient() @@ -18,7 +22,7 @@ export function useMcpServers() { mcpApi.addServer(name, config), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['mcp-status'] }) - queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') }) + queryClient.invalidateQueries({ predicate: SESSION_QUERY_PREDICATE }) toast.success('MCP server added successfully') }, onError: (error: Error) => { @@ -30,7 +34,7 @@ export function useMcpServers() { mutationFn: (name: string) => mcpApi.connect(name), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['mcp-status'] }) - queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') }) + queryClient.invalidateQueries({ predicate: SESSION_QUERY_PREDICATE }) toast.success('MCP server connected') }, onError: (error: Error) => { @@ -42,7 +46,7 @@ export function useMcpServers() { mutationFn: (name: string) => mcpApi.disconnect(name), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['mcp-status'] }) - queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') }) + queryClient.invalidateQueries({ predicate: SESSION_QUERY_PREDICATE }) toast.success('MCP server disconnected') }, onError: (error: Error) => { @@ -74,7 +78,7 @@ export function useMcpServers() { mutationFn: (name: string) => mcpApi.removeAuth(name), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['mcp-status'] }) - queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') }) + queryClient.invalidateQueries({ predicate: SESSION_QUERY_PREDICATE }) toast.success('Authentication credentials removed') }, onError: (error: Error) => { diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 10bb5284..9e464cc4 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -2,15 +2,17 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useMemo, useRef, useEffect, useCallback, useState } from "react"; import { OpenCodeClient } from "../api/opencode"; import { API_BASE_URL } from "../config"; +import { fetchWrapper } from "../api/fetchWrapper"; import type { - MessageWithParts, - MessageListResponse, + Message, + Part, ContentPart, } from "../api/types"; import type { paths, components } from "../api/opencode-types"; import { parseNetworkError } from "../lib/opencode-errors"; import { showToast } from "../lib/toast"; import { useSessionStatus } from "../stores/sessionStatusStore"; +import { useMessageParts } from "@/stores/messagePartsStore"; import { ensureSSEConnected, reconnectSSE } from "../lib/sseManager"; const titleGeneratingSessionsState = new Set(); @@ -82,7 +84,11 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str return useQuery({ queryKey: ["opencode", "messages", opcodeUrl, sessionID, directory], - queryFn: () => client!.listMessages(sessionID!), + queryFn: async () => { + const response = await client!.listMessages(sessionID!) + useMessageParts.getState().initFromMessages(response) + return response.map(m => m.info) as Message[] + }, enabled: !!client && !!sessionID, refetchOnMount: 'always', refetchOnWindowFocus: true, @@ -160,12 +166,12 @@ export const useUpdateSession = (opcodeUrl: string | null | undefined, directory }); }; -const createOptimisticUserMessage = ( +const createOptimisticUserMessageParts = ( sessionID: string, parts: ContentPart[], optimisticID: string, -): MessageWithParts => { - const messageParts = parts.map((part, index) => { +) => { + return parts.map((part, index): Part => { if (part.type === "text") { return { id: `${optimisticID}_part_${index}`, @@ -173,38 +179,41 @@ const createOptimisticUserMessage = ( text: part.content, messageID: optimisticID, sessionID, - }; + } as Part; } else if (part.type === "image") { return { id: `${optimisticID}_part_${index}`, type: "file" as const, filename: part.filename, url: part.dataUrl, - mime: part.mime, + mime: part.mime || "image/*", messageID: optimisticID, sessionID, - }; + } as Part; } else { return { id: `${optimisticID}_part_${index}`, type: "file" as const, filename: part.name, - url: part.path, + url: part.path.startsWith("file:") ? part.path : `file://${part.path}`, + mime: "text/plain", messageID: optimisticID, sessionID, - }; + } as Part; } }); +}; +const createOptimisticUserMessageInfo = ( + sessionID: string, + optimisticID: string, +): Message => { return { - info: { - id: optimisticID, - role: "user", - sessionID, - time: { created: Date.now() }, - }, - parts: messageParts, - } as MessageWithParts; + id: optimisticID, + role: "user", + sessionID, + time: { created: Date.now() }, + } as Message; }; export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: string) => { @@ -225,28 +234,26 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: notifyTitleGeneratingListeners(); try { - const response = await fetch(`${API_BASE_URL}/api/generate-title`, { + await fetchWrapper(`${API_BASE_URL}/api/generate-title`, { method: "POST", headers: { "Content-Type": "application/json", directory: directory || "" }, body: JSON.stringify({ text: userPromptText, sessionID }), }); - if (response.ok) { - hasInitializedRef.current.add(sessionID); - queryClient.invalidateQueries({ - queryKey: ["opencode", "session", opcodeUrl, sessionID, directory], - }); - queryClient.invalidateQueries({ - queryKey: ["opencode", "sessions", opcodeUrl, directory], - }); - } + hasInitializedRef.current.add(sessionID); + queryClient.invalidateQueries({ + queryKey: ["opencode", "session", opcodeUrl, sessionID, directory], + }); + queryClient.invalidateQueries({ + queryKey: ["opencode", "sessions", opcodeUrl, directory], + }); } finally { titleGeneratingSessionsState.delete(sessionID); notifyTitleGeneratingListeners(); } } - } catch (error) { - console.error("Failed to generate session title:", error); + } catch { + // Silently fail - title generation is a background task } }; @@ -281,19 +288,21 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: const contentParts = parts || [{ type: "text" as const, content: prompt || "", name: "" }]; const userPromptText = prompt || (contentParts[0] as ContentPart & { type: "text" })?.content || ""; - const userMessage = createOptimisticUserMessage( + const userMessageParts = createOptimisticUserMessageParts( sessionID, contentParts, optimisticUserID, ); + const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID); const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory]; await queryClient.cancelQueries({ queryKey: messagesQueryKey }); - queryClient.setQueryData( + queryClient.setQueryData( messagesQueryKey, - (old) => [...(old || []), userMessage], + (old) => [...(old || []), userMessageInfo], ); + useMessageParts.getState().setParts(optimisticUserID, userMessageParts); const requestData: SendPromptRequest = { parts: parts?.map((part) => @@ -360,9 +369,9 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: } setSessionStatus(sessionID, { type: "idle" }); - queryClient.setQueryData( + queryClient.setQueryData( messagesQueryKey, - (old) => old?.filter((msg) => !msg.info.id.startsWith("optimistic_")), + (old) => old?.filter((msg) => !msg.id.startsWith("optimistic_")), ); const parsed = parseNetworkError(error); @@ -376,23 +385,25 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: const { optimisticUserID, userPromptText, response } = data; const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory]; - queryClient.setQueryData( + queryClient.setQueryData( messagesQueryKey, (old) => { if (!old) return old; - const withoutOptimistic = old.filter((msg) => msg.info.id !== optimisticUserID); + const withoutOptimistic = old.filter((msg) => msg.id !== optimisticUserID); - const existingIdx = withoutOptimistic.findIndex(m => m.info.id === response.info.id); + const existingIdx = withoutOptimistic.findIndex(m => m.id === response.info.id); if (existingIdx >= 0) { const updated = [...withoutOptimistic]; - updated[existingIdx] = { info: response.info, parts: response.parts }; + updated[existingIdx] = response.info; return updated; } - return [...withoutOptimistic, { info: response.info, parts: response.parts }]; + return [...withoutOptimistic, response.info]; }, ); + useMessageParts.getState().setParts(response.info.id, response.parts); + setSessionStatus(sessionID, { type: "idle" }); queryClient.invalidateQueries({ @@ -419,26 +430,24 @@ export const useAbortSession = ( const forceCompleteMessages = useCallback((targetSessionID: string) => { const queryKey = ["opencode", "messages", opcodeUrl, targetSessionID, directory]; + const now = Date.now(); - queryClient.setQueryData(queryKey, (old) => { + queryClient.setQueryData(queryKey, (old) => { if (!old) return old; return old.map(msg => { - if (msg.info.role === "assistant") { - const assistantInfo = msg.info as AssistantMessage; + if (msg.role === "assistant") { + const assistantInfo = msg as AssistantMessage; if (!assistantInfo.time.completed) { return { - ...msg, - info: { - ...assistantInfo, - time: { - ...assistantInfo.time, - completed: Date.now() - }, - error: { - name: "MessageAbortedError" as const, - data: { message: "Session aborted" } - } + ...assistantInfo, + time: { + ...assistantInfo.time, + completed: now + }, + error: { + name: "MessageAbortedError" as const, + data: { message: "Session aborted" } } }; } @@ -446,6 +455,32 @@ export const useAbortSession = ( return msg; }); }); + + const partsStore = useMessageParts.getState(); + for (const [messageID, parts] of partsStore.parts) { + if (!parts.some(p => p.sessionID === targetSessionID)) continue; + + const updatedParts = parts.map(part => { + if (part.type !== "tool") return part; + if (part.state.status !== "running" && part.state.status !== "pending") return part; + return { + ...part, + state: { + ...part.state, + status: "completed" as const, + output: part.state.status === "running" ? "[Session aborted]" : "[Tool was pending when session aborted]", + title: part.state.status === "running" ? (part.state as { title?: string }).title || "" : "", + metadata: (part.state as { metadata?: Record }).metadata || {}, + time: { + start: (part.state as { time?: { start: number } }).time?.start || now, + end: now + } + } + }; + }); + + useMessageParts.getState().setParts(messageID, updatedParts); + } }, [queryClient, opcodeUrl, directory]); const stopRetrying = useCallback(() => { @@ -458,11 +493,11 @@ export const useAbortSession = ( const isSessionComplete = useCallback((targetSessionID: string) => { const queryKey = ["opencode", "messages", opcodeUrl, targetSessionID, directory]; - const messages = queryClient.getQueryData(queryKey); + const messages = queryClient.getQueryData(queryKey); const hasActiveStream = messages?.some(msg => { - if (msg.info.role !== "assistant") return false; - const assistantInfo = msg.info as AssistantMessage; + if (msg.role !== "assistant") return false; + const assistantInfo = msg as AssistantMessage; return !assistantInfo.time.completed; }); @@ -550,19 +585,21 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`; - const userMessage = createOptimisticUserMessage( + const userMessageParts = createOptimisticUserMessageParts( sessionID, [{ type: "text" as const, content: command }], optimisticUserID, ); + const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID); const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory]; await queryClient.cancelQueries({ queryKey: messagesQueryKey }); - queryClient.setQueryData( + queryClient.setQueryData( messagesQueryKey, - (old) => [...(old || []), userMessage], + (old) => [...(old || []), userMessageInfo], ); + useMessageParts.getState().setParts(optimisticUserID, userMessageParts); const response = await client.sendShell(sessionID, { command, @@ -574,11 +611,11 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s onError: (_, variables) => { const { sessionID } = variables; setSessionStatus(sessionID, { type: "idle" }); - queryClient.setQueryData( + queryClient.setQueryData( ["opencode", "messages", opcodeUrl, sessionID, directory], (old) => { if (!old) return old; - return old.filter((msg) => !msg.info.id.startsWith("optimistic_")); + return old.filter((msg) => !msg.id.startsWith("optimistic_")); }, ); }, @@ -586,11 +623,11 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s const { sessionID } = variables; const { optimisticUserID } = data; - queryClient.setQueryData( + queryClient.setQueryData( ["opencode", "messages", opcodeUrl, sessionID, directory], (old) => { if (!old) return old; - return old.filter((msg) => msg.info.id !== optimisticUserID); + return old.filter((msg) => msg.id !== optimisticUserID); }, ); diff --git a/frontend/src/hooks/useRemoveMessage.ts b/frontend/src/hooks/useRemoveMessage.ts index 55d510d6..37b338d4 100644 --- a/frontend/src/hooks/useRemoveMessage.ts +++ b/frontend/src/hooks/useRemoveMessage.ts @@ -1,8 +1,9 @@ import { useMutation, useQueryClient } from '@tanstack/react-query' import { createOpenCodeClient } from '@/api/opencode' import { showToast } from '@/lib/toast' -import type { MessageWithParts, MessageListResponse } from '@/api/types' +import type { Message, Part } from '@/api/types' import { useSessionStatus } from '@/stores/sessionStatusStore' +import { useMessageParts } from '@/stores/messagePartsStore' interface UseRemoveMessageOptions { opcodeUrl: string | null @@ -10,10 +11,15 @@ interface UseRemoveMessageOptions { directory?: string } +interface RemoveMessageContext { + previousMessages?: Message[] +} + export function useRemoveMessage({ opcodeUrl, sessionId, directory }: UseRemoveMessageOptions) { const queryClient = useQueryClient() + const clearMessage = useMessageParts((state) => state.clearMessage) - return useMutation({ + return useMutation({ mutationFn: async ({ messageID, partID }: { messageID: string, partID?: string }) => { if (!opcodeUrl) throw new Error('OpenCode URL not available') @@ -25,25 +31,25 @@ export function useRemoveMessage({ opcodeUrl, sessionId, directory }: UseRemoveM await queryClient.cancelQueries({ queryKey }) - const previousMessages = queryClient.getQueryData(queryKey) + const previousMessages = queryClient.getQueryData(queryKey) if (previousMessages) { - const messageIndex = previousMessages.findIndex(m => m.info.id === messageID) + const messageIndex = previousMessages.findIndex(m => m.id === messageID) if (messageIndex !== -1) { const newMessages = previousMessages.slice(0, messageIndex) queryClient.setQueryData(queryKey, newMessages) } } + clearMessage(messageID) + return { previousMessages } }, - onError: (error, _, context) => { - console.error('Failed to remove message:', error) - - if (context?.previousMessages) { + onError: (_error, _variables, _context: RemoveMessageContext | undefined) => { + if (_context?.previousMessages) { queryClient.setQueryData( ['opencode', 'messages', opcodeUrl, sessionId, directory], - context.previousMessages + _context.previousMessages ) } @@ -70,6 +76,7 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres const queryClient = useQueryClient() const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory }) const setSessionStatus = useSessionStatus((state) => state.setStatus) + const setParts = useMessageParts((state) => state.setParts) return useMutation({ mutationFn: async ({ @@ -92,26 +99,26 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres const client = createOpenCodeClient(opcodeUrl, directory) const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}` - const userMessage = { - info: { - id: optimisticUserID, - role: 'user' as const, - sessionID: sessionId, - time: { created: Date.now() } - }, - parts: [{ - id: `${optimisticUserID}_part_0`, - type: 'text' as const, - text: userMessageContent, - messageID: optimisticUserID, - sessionID: sessionId - }] - } as MessageWithParts + const userMessageInfo = { + id: optimisticUserID, + role: 'user' as const, + sessionID: sessionId, + time: { created: Date.now() } + } as Message - queryClient.setQueryData( + const userMessageParts = [{ + id: `${optimisticUserID}_part_0`, + type: 'text' as const, + text: userMessageContent, + messageID: optimisticUserID, + sessionID: sessionId + }] as Part[] + + queryClient.setQueryData( ['opencode', 'messages', opcodeUrl, sessionId, directory], - (old) => [...(old || []), userMessage] + (old) => [...(old || []), userMessageInfo] ) + setParts(optimisticUserID, userMessageParts) interface SendPromptRequest { parts: Array<{ type: 'text'; text: string }> @@ -149,11 +156,11 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres onError: (_, variables) => { void variables setSessionStatus(sessionId, { type: 'idle' }) - queryClient.setQueryData( + queryClient.setQueryData( ['opencode', 'messages', opcodeUrl, sessionId, directory], (old) => { const messages = old || [] - const optimisticIndex = messages.findIndex((m) => m.info.id.startsWith('optimistic_user_')) + const optimisticIndex = messages.findIndex((m) => m.id.startsWith('optimistic_user_')) if (optimisticIndex !== -1) { return messages.slice(0, optimisticIndex) } diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 2a820873..f6dfaee8 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -1,11 +1,12 @@ import { useEffect, useRef, useState, useCallback } from 'react' import { useQueryClient } from '@tanstack/react-query' import { useOpenCodeClient } from './useOpenCode' -import type { SSEEvent, MessageListResponse } from '@/api/types' +import type { SSEEvent, Message } from '@/api/types' import { showToast } from '@/lib/toast' import { settingsApi } from '@/api/settings' import { useSessionStatus } from '@/stores/sessionStatusStore' import { useSessionTodos } from '@/stores/sessionTodosStore' +import { useMessageParts } from '@/stores/messagePartsStore' import { sseManager, subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager' import { parseOpenCodeError } from '@/lib/opencode-errors' @@ -50,6 +51,10 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const [isReconnecting, setIsReconnecting] = useState(false) const setSessionStatus = useSessionStatus((state) => state.setStatus) const setSessionTodos = useSessionTodos((state) => state.setTodos) + const setPart = useMessageParts((state) => state.setPart) + const removePart = useMessageParts((state) => state.removePart) + const clearMessage = useMessageParts((state) => state.clearMessage) + const setParts = useMessageParts((state) => state.setParts) const handleSSEEvent = useCallback((event: SSEEvent) => { switch (event.type) { @@ -81,38 +86,8 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, case 'message.part.updated': case 'messagev2.part.updated': { if (!('part' in event.properties)) break - const { part } = event.properties - const sessionID = part.sessionID - const messageID = part.messageID - - const currentData = queryClient.getQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory]) - if (!currentData) return - - const messageExists = currentData.some(msg => msg.info.id === messageID) - if (!messageExists) return - - const updated = currentData.map(msg => { - if (msg.info.id !== messageID) return msg - - const existingPartIndex = msg.parts.findIndex(p => p.id === part.id) - - if (existingPartIndex >= 0) { - const newParts = [...msg.parts] - newParts[existingPartIndex] = { ...part } - return { - info: { ...msg.info }, - parts: newParts - } - } else { - return { - info: { ...msg.info }, - parts: [...msg.parts, { ...part }] - } - } - }) - - queryClient.setQueryData(['opencode', 'messages', opcodeUrl, sessionID, directory], updated) + setPart(part.messageID, part) break } @@ -129,28 +104,25 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory] - const currentData = queryClient.getQueryData(messagesQueryKey) + const currentData = queryClient.getQueryData(messagesQueryKey) if (!currentData) { queryClient.invalidateQueries({ queryKey: messagesQueryKey }) return } - const messageExists = currentData.some(msg => msg.info.id === info.id) + const messageExists = currentData.some(msg => msg.id === info.id) if (!messageExists) { const filteredData = info.role === 'user' - ? currentData.filter(msg => !msg.info.id.startsWith('optimistic_')) + ? currentData.filter(msg => !msg.id.startsWith('optimistic_')) : currentData - queryClient.setQueryData(messagesQueryKey, [...filteredData, { info, parts: [] }]) + queryClient.setQueryData(messagesQueryKey, [...filteredData, info]) return } const updated = currentData.map(msg => { - if (msg.info.id !== info.id) return msg - return { - info: { ...info }, - parts: [...msg.parts] - } + if (msg.id !== info.id) return msg + return { ...info } }) queryClient.setQueryData(messagesQueryKey, updated) @@ -163,13 +135,14 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const { sessionID, messageID } = event.properties - queryClient.setQueryData( + queryClient.setQueryData( ['opencode', 'messages', opcodeUrl, sessionID, directory], (old) => { if (!old) return old - return old.filter(msg => msg.info.id !== messageID) + return old.filter(msg => msg.id !== messageID) } ) + clearMessage(messageID) break } @@ -177,22 +150,9 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, case 'messagev2.part.removed': { if (!('sessionID' in event.properties && 'messageID' in event.properties && 'partID' in event.properties)) break - const { sessionID, messageID, partID } = event.properties + const { messageID, partID } = event.properties - queryClient.setQueryData( - ['opencode', 'messages', opcodeUrl, sessionID, directory], - (old) => { - if (!old) return old - - return old.map(msg => { - if (msg.info.id !== messageID) return msg - return { - ...msg, - parts: msg.parts.filter(p => p.id !== partID) - } - }) - } - ) + removePart(messageID, partID) break } @@ -217,14 +177,28 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, setSessionStatus(sessionID, { type: 'idle' }) const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory] - const currentData = queryClient.getQueryData(messagesQueryKey) + const currentData = queryClient.getQueryData(messagesQueryKey) if (!currentData) break const now = Date.now() const updated = currentData.map(msg => { - if (msg.info.role !== 'assistant') return msg + if (msg.role !== 'assistant') return msg - const updatedParts = msg.parts.map(part => { + if ('completed' in msg.time && msg.time.completed) return msg + + return { + ...msg, + time: { ...msg.time, completed: now } + } + }) + + queryClient.setQueryData(messagesQueryKey, updated) + + const partsStore = useMessageParts.getState() + for (const [messageID, parts] of partsStore.parts) { + if (!parts.some(p => p.sessionID === sessionID)) continue + + const updatedParts = parts.map(part => { if (part.type !== 'tool') return part if (part.state.status !== 'running' && part.state.status !== 'pending') return part return { @@ -243,20 +217,8 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } }) - const msgUpdated = updatedParts !== msg.parts - if ('completed' in msg.info.time && msg.info.time.completed && !msgUpdated) return msg - - return { - ...msg, - info: { - ...msg.info, - time: { ...msg.info.time, completed: now } - }, - parts: updatedParts - } - }) - - queryClient.setQueryData(messagesQueryKey, updated) + setParts(messageID, updatedParts) + } queryClient.invalidateQueries({ queryKey: messagesQueryKey }) break @@ -324,7 +286,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, default: break } - }, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos, currentSessionId]) + }, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos, setPart, removePart, clearMessage, setParts, currentSessionId]) const fetchInitialData = useCallback(async () => { if (!client || !mountedRef.current) return diff --git a/frontend/src/hooks/useSSH.ts b/frontend/src/hooks/useSSH.ts deleted file mode 100644 index e2fc1461..00000000 --- a/frontend/src/hooks/useSSH.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { useEventContext } from '@/contexts/EventContext' - -export function useSSH() { - const { sshHostKey } = useEventContext() - return sshHostKey -} diff --git a/frontend/src/hooks/useServerHealth.ts b/frontend/src/hooks/useServerHealth.ts index a3c46d1c..893fc246 100644 --- a/frontend/src/hooks/useServerHealth.ts +++ b/frontend/src/hooks/useServerHealth.ts @@ -1,7 +1,9 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { useEffect, useRef } from 'react' import { toast } from 'sonner' import { settingsApi } from '@/api/settings' import { invalidateConfigCaches, invalidateSettingsCaches } from '@/lib/queryInvalidation' +import { fetchWrapper } from '@/api/fetchWrapper' interface HealthResponse { status: 'healthy' | 'degraded' | 'unhealthy' @@ -16,17 +18,13 @@ interface HealthResponse { } async function fetchHealth(): Promise { - const response = await fetch('/api/health') - if (!response.ok) { - throw new Error('Health check failed') - } - return response.json() + return fetchWrapper('/api/health') } -let lastHealthStatus: 'healthy' | 'unhealthy' = 'healthy' - export function useServerHealth(enabled = true) { const queryClient = useQueryClient() + const lastHealthStatusRef = useRef<'healthy' | 'unhealthy'>('healthy') + const prevHealthRef = useRef(null) const restartMutation = useMutation({ mutationFn: async () => { @@ -70,27 +68,35 @@ export function useServerHealth(enabled = true) { const { data: health } = query - if (health) { - const isUnhealthy = health.opencode !== 'healthy' + useEffect(() => { + if (!health) return - if (isUnhealthy && lastHealthStatus === 'healthy') { - toast.error(health.error || 'OpenCode server is currently unhealthy', { - duration: Infinity, - action: { - label: 'Reload', - onClick: () => restartMutation.mutate(), - }, - }) - } else if (!isUnhealthy && lastHealthStatus === 'unhealthy') { - toast.success('Server is back online') + const isUnhealthy = health.opencode !== 'healthy' + const currentStatus = isUnhealthy ? 'unhealthy' : 'healthy' + const previousStatus = lastHealthStatusRef.current + const prevHealth = prevHealthRef.current + + if (prevHealth && currentStatus !== prevHealth) { + if (isUnhealthy && previousStatus === 'healthy') { + toast.error(health.error || 'OpenCode server is currently unhealthy', { + duration: Infinity, + action: { + label: 'Reload', + onClick: () => restartMutation.mutate(), + }, + }) + } else if (!isUnhealthy && previousStatus === 'unhealthy') { + toast.success('Server is back online') + } } - lastHealthStatus = isUnhealthy ? 'unhealthy' : 'healthy' - } + lastHealthStatusRef.current = currentStatus + prevHealthRef.current = currentStatus + }, [health, restartMutation]) return { ...query, restartMutation, rollbackMutation, } -} \ No newline at end of file +} diff --git a/frontend/src/hooks/useSessionAgent.ts b/frontend/src/hooks/useSessionAgent.ts index b378428d..9ed5bb22 100644 --- a/frontend/src/hooks/useSessionAgent.ts +++ b/frontend/src/hooks/useSessionAgent.ts @@ -24,8 +24,8 @@ export function useSessionAgent( for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i] - if (msg.info.role === 'user') { - const userInfo = msg.info as UserMessage + if (msg.role === 'user') { + const userInfo = msg as UserMessage return { agent: userInfo.agent || DEFAULT_AGENT, model: userInfo.model, @@ -43,7 +43,7 @@ export function useSessionAgent( } export function getSessionAgentFromMessages( - messages: Array<{ info: { role: string; agent?: string } }> | undefined + messages: Array<{ role: string; agent?: string }> | undefined ): string { if (!messages || messages.length === 0) { return DEFAULT_AGENT @@ -51,8 +51,8 @@ export function getSessionAgentFromMessages( for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i] - if (msg.info.role === 'user' && 'agent' in msg.info) { - return (msg.info.agent as string) || DEFAULT_AGENT + if (msg.role === 'user' && 'agent' in msg) { + return (msg.agent as string) || DEFAULT_AGENT } } diff --git a/frontend/src/hooks/useSettingsDialog.ts b/frontend/src/hooks/useSettingsDialog.ts index 184289d6..e366c953 100644 --- a/frontend/src/hooks/useSettingsDialog.ts +++ b/frontend/src/hooks/useSettingsDialog.ts @@ -1,5 +1,60 @@ -import { useSettingsDialogUrl } from './useSettingsDialogUrl' +import { useCallback } from 'react' +import { useNavigate, useLocation } from 'react-router-dom' -export const useSettingsDialog = () => { - return useSettingsDialogUrl() +type Tab = 'account' | 'general' | 'notifications' | 'voice' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'menu' + +interface UseSettingsDialogReturn { + isOpen: boolean + open: () => void + close: () => void + toggle: () => void + activeTab: Tab + setActiveTab: (tab: Tab) => void +} + +export function useSettingsDialog(): UseSettingsDialogReturn { + const navigate = useNavigate() + const location = useLocation() + + const searchParams = new URLSearchParams(location.search) + const isOpen = searchParams.get('settings') === 'open' + const activeTab = (searchParams.get('tab') as Tab) || 'account' + + const open = useCallback(() => { + const newParams = new URLSearchParams(location.search) + newParams.set('settings', 'open') + newParams.set('tab', activeTab) + navigate({ search: newParams.toString() }, { replace: true }) + }, [activeTab, navigate, location.search]) + + const close = useCallback(() => { + const newParams = new URLSearchParams(location.search) + newParams.delete('settings') + newParams.delete('tab') + navigate({ search: newParams.toString() }, { replace: true }) + }, [navigate, location.search]) + + const toggle = useCallback(() => { + if (isOpen) { + close() + } else { + open() + } + }, [isOpen, open, close]) + + const setActiveTab = useCallback((tab: Tab) => { + const newParams = new URLSearchParams(location.search) + newParams.set('settings', 'open') + newParams.set('tab', tab) + navigate({ search: newParams.toString() }, { replace: true }) + }, [navigate, location.search]) + + return { + isOpen, + open, + close, + toggle, + activeTab, + setActiveTab, + } } diff --git a/frontend/src/hooks/useSettingsDialogUrl.ts b/frontend/src/hooks/useSettingsDialogUrl.ts deleted file mode 100644 index d6242c54..00000000 --- a/frontend/src/hooks/useSettingsDialogUrl.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { useCallback } from 'react' -import { useNavigate, useLocation } from 'react-router-dom' - -type Tab = 'account' | 'general' | 'notifications' | 'voice' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'menu' - -interface UseSettingsDialogUrlReturn { - isOpen: boolean - open: () => void - close: () => void - toggle: () => void - activeTab: Tab - setActiveTab: (tab: Tab) => void -} - -export function useSettingsDialogUrl(): UseSettingsDialogUrlReturn { - const navigate = useNavigate() - const location = useLocation() - - const searchParams = new URLSearchParams(location.search) - const isOpen = searchParams.get('settings') === 'open' - const activeTab = (searchParams.get('tab') as Tab) || 'account' - - const open = useCallback(() => { - const newParams = new URLSearchParams(location.search) - newParams.set('settings', 'open') - newParams.set('tab', activeTab) - navigate({ search: newParams.toString() }, { replace: true }) - }, [activeTab, navigate, location.search]) - - const close = useCallback(() => { - const newParams = new URLSearchParams(location.search) - newParams.delete('settings') - newParams.delete('tab') - navigate({ search: newParams.toString() }, { replace: true }) - }, [navigate, location.search]) - - const toggle = useCallback(() => { - if (isOpen) { - close() - } else { - open() - } - }, [isOpen, open, close]) - - const setActiveTab = useCallback((tab: Tab) => { - const newParams = new URLSearchParams(location.search) - newParams.set('settings', 'open') - newParams.set('tab', tab) - navigate({ search: newParams.toString() }, { replace: true }) - }, [navigate, location.search]) - - return { - isOpen, - open, - close, - toggle, - activeTab, - setActiveTab, - } -} diff --git a/frontend/src/hooks/useSwipe.ts b/frontend/src/hooks/useSwipe.ts index 5fe0199c..13dcfcd4 100644 --- a/frontend/src/hooks/useSwipe.ts +++ b/frontend/src/hooks/useSwipe.ts @@ -62,7 +62,7 @@ export function useSwipe(options: SwipeOptions = {}) { const absDeltaX = Math.abs(deltaX) const absDeltaY = Math.abs(deltaY) - if (!state.directionLocked && absDeltaX > 10 || absDeltaY > 10) { + if (!state.directionLocked && (absDeltaX > 10 || absDeltaY > 10)) { if (absDeltaX > absDeltaY * directionRatio) { state.directionLocked = 'horizontal' } else { diff --git a/frontend/src/hooks/useUndoMessage.ts b/frontend/src/hooks/useUndoMessage.ts index b79fc84c..027a1631 100644 --- a/frontend/src/hooks/useUndoMessage.ts +++ b/frontend/src/hooks/useUndoMessage.ts @@ -1,7 +1,8 @@ import { useMutation, useQueryClient } from '@tanstack/react-query' import { createOpenCodeClient } from '@/api/opencode' import { showToast } from '@/lib/toast' -import type { MessageListResponse } from '@/api/types' +import type { Message } from '@/api/types' +import { useMessageParts } from '@/stores/messagePartsStore' interface UseUndoMessageOptions { opcodeUrl: string | null @@ -10,6 +11,10 @@ interface UseUndoMessageOptions { onSuccess?: (restoredPrompt: string) => void } +interface UndoMessageContext { + previousMessages?: Message[] +} + export function useUndoMessage({ opcodeUrl, sessionId, @@ -17,8 +22,9 @@ export function useUndoMessage({ onSuccess }: UseUndoMessageOptions) { const queryClient = useQueryClient() + const clearMessage = useMessageParts((state) => state.clearMessage) - return useMutation({ + return useMutation({ mutationFn: async ({ messageID, messageContent }: { messageID: string, messageContent: string }) => { if (!opcodeUrl) throw new Error('OpenCode URL not available') @@ -31,25 +37,25 @@ export function useUndoMessage({ await queryClient.cancelQueries({ queryKey }) - const previousMessages = queryClient.getQueryData(queryKey) + const previousMessages = queryClient.getQueryData(queryKey) if (previousMessages) { - const messageIndex = previousMessages.findIndex(m => m.info.id === messageID) + const messageIndex = previousMessages.findIndex(m => m.id === messageID) if (messageIndex !== -1) { const newMessages = previousMessages.slice(0, messageIndex) queryClient.setQueryData(queryKey, newMessages) } } + clearMessage(messageID) + return { previousMessages } }, - onError: (error, _, context) => { - console.error('Failed to undo message:', error) - - if (context?.previousMessages) { + onError: (_error, _variables, _context: UndoMessageContext | undefined) => { + if (_context?.previousMessages) { queryClient.setQueryData( ['opencode', 'messages', opcodeUrl, sessionId, directory], - context.previousMessages + _context.previousMessages ) } diff --git a/frontend/src/hooks/useVirtualizedContent.ts b/frontend/src/hooks/useVirtualizedContent.ts index d68cb640..a900d10e 100644 --- a/frontend/src/hooks/useVirtualizedContent.ts +++ b/frontend/src/hooks/useVirtualizedContent.ts @@ -121,13 +121,13 @@ export function useVirtualizedContent({ const ranges: Array<{ startLine: number; endLine: number; content: string }> = [] let rangeStart = sortedLineNums[0] - let rangeLines: string[] = [editedLines.get(rangeStart)!] + let rangeLines: string[] = [editedLines.get(rangeStart) ?? ''] let lastLine = rangeStart for (let i = 1; i < sortedLineNums.length; i++) { const lineNum = sortedLineNums[i] if (lineNum === lastLine + 1) { - rangeLines.push(editedLines.get(lineNum)!) + rangeLines.push(editedLines.get(lineNum) ?? '') lastLine = lineNum } else { ranges.push({ @@ -136,7 +136,7 @@ export function useVirtualizedContent({ content: rangeLines.join('\n'), }) rangeStart = lineNum - rangeLines = [editedLines.get(lineNum)!] + rangeLines = [editedLines.get(lineNum) ?? ''] lastLine = lineNum } } diff --git a/frontend/src/lib/auth-client.ts b/frontend/src/lib/auth-client.ts index e2bf2f5d..e1a5050d 100644 --- a/frontend/src/lib/auth-client.ts +++ b/frontend/src/lib/auth-client.ts @@ -1,11 +1,12 @@ import { createAuthClient } from 'better-auth/react' import { passkeyClient } from '@better-auth/passkey/client' +import { API_BASE_URL } from '@/config' const getBaseUrl = () => { if (typeof window !== 'undefined') { return `${window.location.origin}/api/auth` } - return 'http://localhost:5003/api/auth' + return `${API_BASE_URL}/api/auth` } export const authClient = createAuthClient({ diff --git a/frontend/src/lib/auth-loaders.ts b/frontend/src/lib/auth-loaders.ts index 45d99547..cce1af14 100644 --- a/frontend/src/lib/auth-loaders.ts +++ b/frontend/src/lib/auth-loaders.ts @@ -9,16 +9,21 @@ export interface AuthConfig { } async function fetchAuthConfig(): Promise { + const defaultConfig: AuthConfig = { + enabledProviders: ['credentials'], + registrationEnabled: true, + isFirstUser: false, + adminConfigured: false, + } const response = await fetch('/api/auth-info/config') if (!response.ok) { - return { - enabledProviders: ['credentials'], - registrationEnabled: true, - isFirstUser: false, - adminConfigured: false, - } + return defaultConfig + } + try { + return await response.json() + } catch { + return defaultConfig } - return response.json() } export async function loginLoader() { diff --git a/frontend/src/lib/jsonc.ts b/frontend/src/lib/jsonc.ts index d678dbbe..f32dba67 100644 --- a/frontend/src/lib/jsonc.ts +++ b/frontend/src/lib/jsonc.ts @@ -1,7 +1,11 @@ import stripJsonComments from 'strip-json-comments' export function parseJsonc(content: string): T { - return JSON.parse(stripJsonComments(content)) as T + try { + return JSON.parse(stripJsonComments(content)) as T + } catch (e) { + throw new Error(`Failed to parse JSONC: ${e instanceof Error ? e.message : String(e)}`) + } } export function hasJsoncComments(content: string): boolean { diff --git a/frontend/src/lib/promptParser.ts b/frontend/src/lib/promptParser.ts index 2596b349..035f2d99 100644 --- a/frontend/src/lib/promptParser.ts +++ b/frontend/src/lib/promptParser.ts @@ -1,4 +1,4 @@ -import type { ContentPart, FileInfo, ImageAttachment } from '@/api/types' +import type { ContentPart, FileAttachmentInfo, ImageAttachment } from '@/api/types' export const MENTION_PATTERN = /@([A-Za-z0-9_\-./]+)/g export const MENTION_TRIGGER_PATTERN = /(^|\s)@([A-Za-z0-9_\-./]*)$/ @@ -40,7 +40,7 @@ export function filterAgentsByQuery(agents: AgentInfo[], query: string): AgentIn export function parsePromptToParts( rawInput: string, - fileMap: Map, + fileMap: Map, imageAttachments?: ImageAttachment[] ): ContentPart[] { const parts: ContentPart[] = [] diff --git a/frontend/src/lib/serviceWorker.ts b/frontend/src/lib/serviceWorker.ts index d534bb5d..be87cd26 100644 --- a/frontend/src/lib/serviceWorker.ts +++ b/frontend/src/lib/serviceWorker.ts @@ -13,7 +13,12 @@ export async function getServiceWorkerRegistration(): Promise cb()); - resolve(); }; utterance.onerror = (event: SpeechSynthesisErrorEvent) => { @@ -230,7 +229,6 @@ export class WebSpeechSynthesizer { this.pendingReject = null; } this.onErrorCallbacks.forEach((cb) => cb(errorMessage)); - reject(new Error(errorMessage)); }; utterance.onboundary = (event) => { diff --git a/frontend/src/pages/Login.tsx b/frontend/src/pages/Login.tsx index 3ee1aa57..90ad4b60 100644 --- a/frontend/src/pages/Login.tsx +++ b/frontend/src/pages/Login.tsx @@ -25,6 +25,7 @@ export function Login() { const theme = useTheme() const [error, setError] = useState(null) const [isSubmitting, setIsSubmitting] = useState(false) + const [isPasskeyLoading, setIsPasskeyLoading] = useState(false) const [oauthLoading, setOauthLoading] = useState(null) const { @@ -63,14 +64,14 @@ export function Login() { const handlePasskey = async () => { setError(null) - setIsSubmitting(true) + setIsPasskeyLoading(true) try { const result = await signInWithPasskey() if (result.error) { setError(result.error) } } finally { - setIsSubmitting(false) + setIsPasskeyLoading(false) } } @@ -102,9 +103,9 @@ export function Login() { variant="outline" className="w-full border-border hover:bg-accent transition-all duration-200" onClick={handlePasskey} - disabled={isSubmitting} + disabled={isSubmitting || isPasskeyLoading} > - {isSubmitting ? ( + {isPasskeyLoading ? ( ) : ( @@ -226,7 +227,7 @@ export function Login() {

{errors.password.message}

)}
-
@@ -514,7 +523,7 @@ export function SessionDetail() { isOpen={fileBrowserOpen} onClose={handleFileBrowserClose} basePath={repo.localPath} - repoName={repo.repoUrl?.split("/").pop()?.replace(".git", "") || repo.localPath || "Repository"} + repoName={getRepoDisplayName(repo.repoUrl, repo.localPath)} repoId={repoId} initialSelectedFile={selectedFilePath} /> @@ -530,7 +539,7 @@ export function SessionDetail() { isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo.currentBranch || repo.branch || "main"} - repoName={repo.repoUrl?.split("/").pop()?.replace(".git", "") || repo.localPath || "Repository"} + repoName={getRepoDisplayName(repo.repoUrl, repo.localPath)} />
); diff --git a/frontend/src/stores/messagePartsStore.ts b/frontend/src/stores/messagePartsStore.ts new file mode 100644 index 00000000..126611ef --- /dev/null +++ b/frontend/src/stores/messagePartsStore.ts @@ -0,0 +1,99 @@ +import { create } from 'zustand' +import type { Part } from '@/api/types' + +const EMPTY_PARTS: Part[] = [] + +interface MessagePartsStore { + parts: Map + version: number + setPart: (messageID: string, part: Part) => void + setParts: (messageID: string, parts: Part[]) => void + removePart: (messageID: string, partID: string) => void + clearMessage: (messageID: string) => void + clearSession: (sessionID: string) => void + initFromMessages: (messages: Array<{ info: { id: string }, parts: Part[] }>) => void +} + +export const useMessageParts = create((set) => ({ + parts: new Map(), + version: 0, + + setPart: (messageID, part) => { + set((state) => { + const newMap = new Map(state.parts) + const existing = newMap.get(messageID) + if (!existing) { + newMap.set(messageID, [part]) + return { parts: newMap, version: state.version + 1 } + } + const idx = existing.findIndex(p => p.id === part.id) + if (idx >= 0) { + const updated = [...existing] + updated[idx] = part + newMap.set(messageID, updated) + } else { + newMap.set(messageID, [...existing, part]) + } + return { parts: newMap, version: state.version + 1 } + }) + }, + + setParts: (messageID, parts) => { + set((state) => { + const newMap = new Map(state.parts) + newMap.set(messageID, parts) + return { parts: newMap, version: state.version + 1 } + }) + }, + + removePart: (messageID, partID) => { + set((state) => { + const existing = state.parts.get(messageID) + if (!existing) return state + const newMap = new Map(state.parts) + newMap.set(messageID, existing.filter(p => p.id !== partID)) + return { parts: newMap, version: state.version + 1 } + }) + }, + + clearMessage: (messageID) => { + set((state) => { + const newMap = new Map(state.parts) + newMap.delete(messageID) + return { parts: newMap, version: state.version + 1 } + }) + }, + + clearSession: (sessionID) => { + set((state) => { + const newMap = new Map(state.parts) + for (const [, parts] of newMap) { + if (parts.some(p => p.sessionID === sessionID)) { + newMap.delete(sessionID) + } + } + return { parts: newMap, version: state.version + 1 } + }) + }, + + initFromMessages: (messages) => { + set((state) => { + const newMap = new Map(state.parts) + for (const msg of messages) { + newMap.set(msg.info.id, msg.parts) + } + return { parts: newMap, version: state.version + 1 } + }) + }, +})) + +export const usePartsForMessage = (messageID: string | undefined): Part[] => { + return useMessageParts((state) => { + if (!messageID) return EMPTY_PARTS + return state.parts.get(messageID) ?? EMPTY_PARTS + }) +} + +export const usePartsVersion = (): number => { + return useMessageParts((state) => state.version) +} diff --git a/shared/package.json b/shared/package.json index c1fb13c2..9c25693e 100644 --- a/shared/package.json +++ b/shared/package.json @@ -9,6 +9,7 @@ ".": "./src/index.ts", "./schemas": "./src/schemas/index.ts", "./types": "./src/types/index.ts", + "./types/errors": "./src/types/errors.ts", "./config": "./src/config/index.ts", "./config/defaults": "./src/config/defaults.ts", "./config/env": "./src/config/env.ts", diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index de455958..82ea4ac1 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -1,5 +1,6 @@ import path from 'path' import os from 'os' +import { randomBytes } from 'crypto' import { DEFAULTS } from './defaults' try { @@ -38,12 +39,7 @@ const resolveWorkspacePath = (): string => { const workspaceBasePath = resolveWorkspacePath() const generateDefaultSecret = (): string => { - const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' - let result = '' - for (let i = 0; i < 32; i++) { - result += chars.charAt(Math.floor(Math.random() * chars.length)) - } - return result + return randomBytes(32).toString('base64').slice(0, 32) } export const ENV = { diff --git a/shared/src/types/errors.ts b/shared/src/types/errors.ts new file mode 100644 index 00000000..20a06774 --- /dev/null +++ b/shared/src/types/errors.ts @@ -0,0 +1,38 @@ +export type GitErrorCode = + | 'AUTH_FAILED' + | 'REPO_NOT_FOUND' + | 'PERMISSION_DENIED' + | 'PUSH_REJECTED' + | 'MERGE_CONFLICT' + | 'NO_UPSTREAM' + | 'TIMEOUT' + | 'NOT_A_REPO' + | 'LOCK_FAILED' + | 'DETACHED_HEAD' + | 'BRANCH_EXISTS' + | 'BRANCH_NOT_FOUND' + | 'UNCOMMITTED_CHANGES' + | 'UNKNOWN' + +export type ApiErrorCode = GitErrorCode | 'INVALID_JSON' | 'TIMEOUT' + +export interface ApiErrorResponse { + error: string + code?: string + detail?: string + details?: unknown +} + +export class FetchError extends Error { + statusCode?: number + code?: string + detail?: string + + constructor(message: string, statusCode?: number, code?: string, detail?: string) { + super(message) + this.name = 'FetchError' + this.statusCode = statusCode + this.code = code + this.detail = detail + } +} diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index b6ed6b4f..adbeaab5 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -69,10 +69,8 @@ export type PushSubscriptionRequest = z.infer export type PushNotificationPayload = z.infer -export interface ErrorResponse { - error: string - details?: unknown -} +export { FetchError } from './errors' +export type { ApiErrorResponse, ApiErrorCode, GitErrorCode } from './errors' export interface SuccessResponse { success: boolean