mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix issues (#136)
* fix: prevent delete button click when card is not swiped open * refactor: improve CreateRepoInput type safety * security: require AUTH_SECRET and use secure random generation * fix: SSH key path validation, async passphrase stripping, and port handling * fix: use correct console methods for logger levels * Add error handling to DB update functions and improve migration logging * Add error handling for session lookup in auth middleware * Add structured git error handling with user-friendly messages - Parse git errors with specific error codes (AUTH_FAILED, REPO_NOT_FOUND, PUSH_REJECTED, MERGE_CONFLICT, etc.) and appropriate HTTP status codes - Return structured error responses with summary and detail from backend - Add GitErrorBanner component for better error display in UI - Add optional onError callback to useGit hook for external error handling * Make IPC server initialization/disposal async and fix SSH host key handler * add try-catch error handling in frontend lib utilities * remove unresolved promise handlers in speech synthesizer callbacks * Extract error types to shared package * Import GitErrorCode from shared package * Refactor API layer to use shared FetchError and fetchWrapper * Update prompt parser and source control components * Extract MCP server list to separate component with improved badge menu UX * merge useSettingsDialogUrl into useSettingsDialog and extract getRepoDisplayName utility * add separate loading state for passkey sign in * refactor hooks: use fetchWrapper, improve error handling, add proper types * replace browser confirm() with DeleteDialog component in settings * fix: add missing variables parameter in React Query onError callbacks * Refactor message parts to use separate Zustand store * Update QuestionPrompt styling for light/dark mode
This commit is contained in:
1 parent
7f7d106c28
commit
5de419ee28
75 files changed
+1990
-1367
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
|
||||
|
||||
export async function withTransactionAsync<T>(
|
||||
db: Database,
|
||||
fn: (db: Database) => Promise<T>
|
||||
): Promise<T> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -77,8 +77,10 @@ export class IPCServer {
|
||||
})
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.server.close()
|
||||
dispose(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this.server.close(() => resolve())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, { resolve: (passphrase: string) => 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<string> {
|
||||
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<string> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -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<void> {
|
||||
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'
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
execFile('ssh-keygen', ['-p', '-P', passphrase, '-N', '', '-f', keyPath], (error: Error | null) => {
|
||||
if (error) reject(error)
|
||||
else resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export interface SSHConfigEntry {
|
||||
|
||||
@@ -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<void> {
|
||||
@@ -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 {
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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<string, string | number | boolean | undefined | unknown>
|
||||
params?: Record<string, string | number | boolean | undefined>
|
||||
}
|
||||
|
||||
async function handleResponse(response: Response): Promise<never> {
|
||||
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<string, string | number | boolean | undefined>): 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<Response> {
|
||||
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<T = unknown>(
|
||||
url: string,
|
||||
options: FetchWrapperOptions = {}
|
||||
): Promise<T> {
|
||||
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<string> {
|
||||
const response = await fetchWithTimeout(url, options)
|
||||
return response.text()
|
||||
}
|
||||
|
||||
async function fetchWrapperVoid(
|
||||
url: string,
|
||||
options: FetchWrapperOptions = {}
|
||||
): Promise<void> {
|
||||
await fetchWithTimeout(url, options)
|
||||
}
|
||||
|
||||
async function fetchWrapperBlob(
|
||||
url: string,
|
||||
options: FetchWrapperOptions = {}
|
||||
): Promise<Blob> {
|
||||
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 }
|
||||
+10
-37
@@ -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<FileInfo> {
|
||||
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<ChunkedFileInfo> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
+25
-117
@@ -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<never> {
|
||||
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<GitStatusResponse> {
|
||||
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<Map<number, GitStatusResponse>> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/repos/git-status-batch`, {
|
||||
const data = await fetchWrapper<Record<string, GitStatusResponse>>(`${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<FileDiffResponse> {
|
||||
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<string>(`${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<GitStatusResponse> {
|
||||
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<GitStatusResponse> {
|
||||
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<GitStatusResponse> {
|
||||
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<GitStatusResponse> {
|
||||
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<GitStatusResponse> {
|
||||
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<GitStatusResponse> {
|
||||
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<GitStatusResponse> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
+22
-86
@@ -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<McpStatusMap> {
|
||||
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<McpStatusMap> {
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
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<McpAuthStartResponse> {
|
||||
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<McpOAuthFlowStatus> {
|
||||
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<McpStatus> {
|
||||
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<McpStatus> {
|
||||
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<McpStatusMap> {
|
||||
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<Record<string, unknown>> {
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
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<McpStatus> {
|
||||
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()
|
||||
},
|
||||
}
|
||||
@@ -31,7 +31,7 @@ function handleApiError(error: unknown, context: string): never {
|
||||
export const oauthApi = {
|
||||
authorize: async (providerId: string, method: number): Promise<OAuthAuthorizeResponse> => {
|
||||
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<boolean> => {
|
||||
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),
|
||||
|
||||
@@ -29,7 +29,7 @@ export class OpenCodeClient {
|
||||
this.directory = directory
|
||||
}
|
||||
|
||||
private getParams(params?: Record<string, unknown>) {
|
||||
private getParams(params?: Record<string, string>) {
|
||||
if (!this.directory) return params
|
||||
return { ...params, directory: this.directory }
|
||||
}
|
||||
|
||||
@@ -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<string>): Promise<Provid
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.warn("Failed to load configured providers", error);
|
||||
} catch {
|
||||
// Silently return empty providers on failure - graceful degradation
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
+35
-116
@@ -1,4 +1,5 @@
|
||||
import type { Repo } from './types'
|
||||
import { FetchError, fetchWrapper, fetchWrapperText, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
export async function createRepo(
|
||||
@@ -9,111 +10,57 @@ export async function createRepo(
|
||||
useWorktree?: boolean,
|
||||
skipSSHVerification?: boolean
|
||||
): Promise<Repo> {
|
||||
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<Repo[]> {
|
||||
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<Repo> {
|
||||
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<void> {
|
||||
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<Repo> {
|
||||
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<Repo> {
|
||||
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<Repo> {
|
||||
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<string> {
|
||||
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<Repo> {
|
||||
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<Repo> {
|
||||
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<Repo> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/create`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ branch }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json()
|
||||
if (error.code === 'AUTH_FAILED') {
|
||||
throw new GitAuthError(error.error || 'Git authentication failed', error.code)
|
||||
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<void> {
|
||||
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<void> {
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -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<SettingsResponse> => {
|
||||
getSettings: async (userId = DEFAULT_USER_ID): Promise<SettingsResponse> => {
|
||||
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<SettingsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, {
|
||||
method: 'PATCH',
|
||||
@@ -28,14 +30,14 @@ export const settingsApi = {
|
||||
})
|
||||
},
|
||||
|
||||
resetSettings: async (userId = 'default'): Promise<SettingsResponse> => {
|
||||
resetSettings: async (userId = DEFAULT_USER_ID): Promise<SettingsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, {
|
||||
method: 'DELETE',
|
||||
params: { userId },
|
||||
})
|
||||
},
|
||||
|
||||
getOpenCodeConfigs: async (userId = 'default'): Promise<OpenCodeConfigResponse> => {
|
||||
getOpenCodeConfigs: async (userId = DEFAULT_USER_ID): Promise<OpenCodeConfigResponse> => {
|
||||
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<OpenCodeConfig> => {
|
||||
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<OpenCodeConfig> => {
|
||||
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<boolean> => {
|
||||
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<OpenCodeConfig> => {
|
||||
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<OpenCodeConfig | null> => {
|
||||
getDefaultOpenCodeConfig: async (userId = DEFAULT_USER_ID): Promise<OpenCodeConfig | null> => {
|
||||
try {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-configs/default`, {
|
||||
params: { userId },
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="flex flex-col group"
|
||||
>
|
||||
<div
|
||||
className={`w-full rounded-lg p-1.5 ${
|
||||
msg.role === 'user'
|
||||
? isQueued
|
||||
? 'bg-amber-500/10 border border-amber-500/30'
|
||||
: isEditingThisMessage
|
||||
? 'bg-blue-600/30 border border-blue-600/50'
|
||||
: 'bg-blue-600/20 border border-blue-600/30'
|
||||
: 'bg-card/50 border border-border'
|
||||
} ${streaming ? 'animate-pulse-subtle' : ''}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{msg.role === 'user' ? 'You' : (msg.role === 'assistant' && 'modelID' in msg ? msg.modelID : 'Assistant')}
|
||||
</span>
|
||||
{msg.time && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(msg.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
)}
|
||||
{canEditUserMessage && nextAssistantMessage && (
|
||||
<button
|
||||
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMessage.id)}
|
||||
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="Edit message"
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
{isQueued && (
|
||||
<span className="text-xs font-semibold bg-amber-500 text-amber-950 px-1.5 py-0.5 rounded">
|
||||
QUEUED
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{msg.role === 'user' && canUndoUserMessage && (
|
||||
<UserMessageActionButtons
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
userMessageId={msg.id}
|
||||
userMessageContent={messageTextContent}
|
||||
onUndo={onUndoMessage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{msg.role === 'user' && isEditingThisMessage && editingForAssistantId ? (
|
||||
<EditableUserMessage
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
content={messageTextContent}
|
||||
assistantMessageId={editingForAssistantId}
|
||||
onCancel={handleCancelEdit}
|
||||
model={model}
|
||||
/>
|
||||
) : msg.role === 'user' && canEditUserMessage && nextAssistantMessage ? (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMessage.id)}
|
||||
isEditable={false}
|
||||
/>
|
||||
) : parts.length > 0 ? (
|
||||
parts.map((part: Part, partIndex: number) => (
|
||||
<div key={`${msg.id}-${part.id}-${partIndex}`}>
|
||||
<MessagePart
|
||||
part={part}
|
||||
role={msg.role}
|
||||
allParts={parts}
|
||||
partIndex={partIndex}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
messageTextContent={msg.role === 'assistant' ? messageTextContent : undefined}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
) : null}
|
||||
{msg.role === 'assistant' && 'error' in msg && msg.error && (
|
||||
<MessageError error={msg.error as OpenCodeError} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
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 (
|
||||
<div className="flex flex-col space-y-2 p-2 overflow-x-hidden">
|
||||
{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 (
|
||||
<div
|
||||
key={msg.info.id}
|
||||
className="flex flex-col group"
|
||||
>
|
||||
<div
|
||||
className={`w-full rounded-lg p-1.5 ${
|
||||
msg.info.role === 'user'
|
||||
? isQueued
|
||||
? 'bg-amber-500/10 border border-amber-500/30'
|
||||
: isEditingThisMessage
|
||||
? 'bg-blue-600/30 border border-blue-600/50'
|
||||
: 'bg-blue-600/20 border border-blue-600/30'
|
||||
: 'bg-card/50 border border-border'
|
||||
} ${streaming ? 'animate-pulse-subtle' : ''}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')}
|
||||
</span>
|
||||
{msg.info.time && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(msg.info.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
)}
|
||||
{canEditUserMessage && nextAssistantMessage && (
|
||||
<button
|
||||
onClick={() => handleStartEditUserMessage(msg.info.id, nextAssistantMessage.info.id)}
|
||||
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="Edit message"
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
{isQueued && (
|
||||
<span className="text-xs font-semibold bg-amber-500 text-amber-950 px-1.5 py-0.5 rounded">
|
||||
QUEUED
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{msg.info.role === 'user' && canUndoUserMessage && (
|
||||
<UserMessageActionButtons
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
userMessageId={msg.info.id}
|
||||
userMessageContent={messageTextContent}
|
||||
onUndo={onUndoMessage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{msg.info.role === 'user' && isEditingThisMessage && editingForAssistantId ? (
|
||||
<EditableUserMessage
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
content={messageTextContent}
|
||||
assistantMessageId={editingForAssistantId}
|
||||
onCancel={handleCancelEdit}
|
||||
model={model}
|
||||
/>
|
||||
) : msg.info.role === 'user' && canEditUserMessage && nextAssistantMessage ? (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => handleStartEditUserMessage(msg.info.id, nextAssistantMessage.info.id)}
|
||||
isEditable={false}
|
||||
/>
|
||||
) : (
|
||||
msg.parts.map((part, partIndex) => (
|
||||
<div key={`${msg.info.id}-${part.id}-${partIndex}`}>
|
||||
<MessagePart
|
||||
part={part}
|
||||
role={msg.info.role}
|
||||
allParts={msg.parts}
|
||||
partIndex={partIndex}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
messageTextContent={msg.info.role === 'assistant' ? messageTextContent : undefined}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{msg.info.role === 'assistant' && 'error' in msg.info && msg.info.error && (
|
||||
<MessageError error={msg.info.error as OpenCodeError} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{messages.map((msg, index) => (
|
||||
<MessageRow
|
||||
key={msg.id}
|
||||
msg={msg}
|
||||
index={index}
|
||||
messages={messages}
|
||||
pendingAssistantId={pendingAssistantId}
|
||||
lastUserMessageId={lastUserMessageId}
|
||||
isSessionBusy={isSessionBusy}
|
||||
onUndoMessage={onUndoMessage}
|
||||
editingUserMessageId={editingUserMessageId}
|
||||
editingForAssistantId={editingForAssistantId}
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionID={sessionID}
|
||||
directory={directory}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
handleStartEditUserMessage={handleStartEditUserMessage}
|
||||
handleCancelEdit={handleCancelEdit}
|
||||
model={model}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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<PromptInputHandle, PromptInputProps>(funct
|
||||
const [isBashMode, setIsBashMode] = useState(false)
|
||||
const [showSuggestions, setShowSuggestions] = useState(false)
|
||||
const [suggestionQuery, setSuggestionQuery] = useState('')
|
||||
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileInfo>())
|
||||
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileAttachmentInfo>())
|
||||
const [imageAttachments, setImageAttachments] = useState<ImageAttachment[]>([])
|
||||
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)
|
||||
|
||||
@@ -190,11 +190,7 @@ export function TextPart({ part }: TextPartProps) {
|
||||
}, [part.text])
|
||||
|
||||
if (!part.text || part.text.trim() === '') {
|
||||
return (
|
||||
<div className="text-muted-foreground italic text-sm">
|
||||
[Empty message content]
|
||||
</div>
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -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 <Badge variant="default" className="text-xs bg-green-600">Connected</Badge>
|
||||
case 'disabled':
|
||||
return <Badge className="text-xs bg-gray-700 text-gray-300 border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600">Disabled</Badge>
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs flex items-center gap-1">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_auth':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs border-yellow-500 text-yellow-600">
|
||||
Needs Auth
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return <Badge variant="outline" className="text-xs">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!directory) return null
|
||||
|
||||
return (
|
||||
@@ -197,124 +146,17 @@ export function RepoMcpDialog({ open, onOpenChange, directory }: RepoMcpDialogPr
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4 flex-1 overflow-y-auto min-h-0">
|
||||
{hasFetchedStatus && serverIds.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<Plug className="w-10 h-10 mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No MCP servers configured for this location</p>
|
||||
<p className="text-xs mt-1">Add them in Settings or in the project's opencode.json</p>
|
||||
</div>
|
||||
) : isLoadingStatus ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{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 (
|
||||
<div
|
||||
key={serverId}
|
||||
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-border bg-card"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{getDisplayName(serverId)}
|
||||
</p>
|
||||
{connectedWithOAuth && (
|
||||
<span title="OAuth authenticated">
|
||||
<Shield className="h-3 w-3 text-muted-foreground" />
|
||||
</span>
|
||||
)}
|
||||
{getStatusBadge(status)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{serverConfig ? getDescription(serverConfig) : 'MCP server'}
|
||||
</p>
|
||||
{failed && status.status === 'failed' && (
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-red-500">
|
||||
<XCircle className="w-3 h-3 flex-shrink-0" />
|
||||
<span className="truncate">{status.error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{showAuthButton ? (
|
||||
<Button
|
||||
onClick={() => setAuthDialogServerId(serverId)}
|
||||
disabled={toggleMutation.isPending}
|
||||
variant="default"
|
||||
size="sm"
|
||||
>
|
||||
<Key className="h-3 w-3 mr-1" />
|
||||
Auth
|
||||
</Button>
|
||||
) : (
|
||||
<Switch
|
||||
checked={isConnected}
|
||||
disabled={toggleMutation.isPending || removeAuthMutation.isPending}
|
||||
onCheckedChange={(enabled) => {
|
||||
toggleMutation.mutate({ serverId, enable: enabled })
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
)}
|
||||
{(isOAuthServer || needsAuth) && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{showAuthButton && (
|
||||
<DropdownMenuItem onClick={() => setAuthDialogServerId(serverId)}>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && (
|
||||
<DropdownMenuItem onClick={() => setAuthDialogServerId(serverId)}>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Re-authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => setRemoveAuthConfirmServer(serverId)}
|
||||
disabled={removeAuthMutation.isPending}
|
||||
>
|
||||
<Shield className="h-4 w-4 mr-2" />
|
||||
{removeAuthMutation.isPending ? 'Removing...' : 'Remove Auth'}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<RepoMcpServerList
|
||||
hasFetchedStatus={hasFetchedStatus}
|
||||
serverIds={serverIds}
|
||||
isLoadingStatus={isLoadingStatus}
|
||||
localStatus={localStatus}
|
||||
mcpServers={mcpServers}
|
||||
toggleMutation={toggleMutation}
|
||||
removeAuthMutation={removeAuthMutation}
|
||||
onAuthClick={setAuthDialogServerId}
|
||||
onRemoveAuthClick={setRemoveAuthConfirmServer}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!removeAuthConfirmServer}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
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 { DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
|
||||
import { Loader2, XCircle, AlertCircle, Plug, Shield, Key, RefreshCw, ChevronDown } from 'lucide-react'
|
||||
import type { McpStatus, McpServerConfig } from '@/api/mcp'
|
||||
|
||||
|
||||
interface RepoMcpServerListProps {
|
||||
hasFetchedStatus: boolean
|
||||
serverIds: string[]
|
||||
isLoadingStatus: boolean
|
||||
localStatus: Record<string, McpStatus>
|
||||
mcpServers: Record<string, McpServerConfig>
|
||||
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 <Badge variant="default" className="text-xs bg-green-600">Connected</Badge>
|
||||
case 'disabled':
|
||||
return <Badge className="text-xs bg-gray-700 text-gray-300 border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600">Disabled</Badge>
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge variant="destructive" className="text-xs flex items-center gap-1">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</Badge>
|
||||
)
|
||||
case 'needs_auth':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs border-yellow-500 text-yellow-600">
|
||||
Needs Auth
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return <Badge variant="outline" className="text-xs">Unknown</Badge>
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4 flex-1 overflow-y-auto min-h-0">
|
||||
{hasFetchedStatus && serverIds.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<Plug className="w-10 h-10 mx-auto mb-3 opacity-50" />
|
||||
<p className="text-sm">No MCP servers configured for this location</p>
|
||||
<p className="text-xs mt-1">Add them in Settings or in the project's opencode.json</p>
|
||||
</div>
|
||||
) : isLoadingStatus ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{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 (
|
||||
<div
|
||||
key={serverId}
|
||||
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-border bg-card"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{getDisplayName(serverId)}
|
||||
</p>
|
||||
{(showAuthButton || connectedWithOAuth) ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
className="cursor-pointer hover:bg-accent rounded inline-flex items-center gap-1"
|
||||
title="Click for options"
|
||||
>
|
||||
{status?.status === 'connected' && (
|
||||
<span className="text-xs bg-green-600 text-white px-2 py-0.5 rounded-full inline-flex items-center gap-1">
|
||||
Connected<ChevronDown className="h-3 w-3" />
|
||||
</span>
|
||||
)}
|
||||
{status?.status === 'needs_auth' && (
|
||||
<span className="text-xs border border-yellow-500 text-yellow-600 px-2 py-0.5 rounded-full inline-flex items-center gap-1">
|
||||
Needs Auth<ChevronDown className="h-3 w-3" />
|
||||
</span>
|
||||
)}
|
||||
{status?.status === 'failed' && (
|
||||
<span className="text-xs bg-red-500 text-white px-2 py-0.5 rounded-full inline-flex items-center gap-1">
|
||||
<AlertCircle className="h-3 w-3" />Failed<ChevronDown className="h-3 w-3" />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{showAuthButton && (
|
||||
<DropdownMenuItem onClick={() => onAuthClick(serverId)}>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && (
|
||||
<DropdownMenuItem onClick={() => onAuthClick(serverId)}>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Re-authenticate
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{connectedWithOAuth && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => onRemoveAuthClick(serverId)}
|
||||
disabled={removeAuthMutation.isPending}
|
||||
>
|
||||
<Shield className="h-4 w-4 mr-2" />
|
||||
{removeAuthMutation.isPending ? 'Removing...' : 'Remove Auth'}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
getStatusBadge(status)
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{serverConfig ? getDescription(serverConfig) : 'MCP server'}
|
||||
</p>
|
||||
{failed && status.status === 'failed' && (
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-red-500">
|
||||
<XCircle className="w-3 h-3 flex-shrink-0" />
|
||||
<span className="truncate">{status.error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{showAuthButton ? (
|
||||
<Button
|
||||
onClick={() => onAuthClick(serverId)}
|
||||
disabled={toggleMutation.isPending}
|
||||
variant="default"
|
||||
size="sm"
|
||||
>
|
||||
<Key className="h-3 w-3 mr-1" />
|
||||
Auth
|
||||
</Button>
|
||||
) : (
|
||||
<Switch
|
||||
checked={isConnected}
|
||||
disabled={toggleMutation.isPending || removeAuthMutation.isPending}
|
||||
onCheckedChange={(enabled) => {
|
||||
toggleMutation.mutate({ serverId, enable: enabled })
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -179,20 +179,20 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-full bg-gradient-to-br from-blue-500/10 to-blue-600/5 border-2 border-blue-500/30 rounded-xl shadow-lg shadow-blue-500/10 backdrop-blur-sm mb-3 overflow-hidden"
|
||||
className="w-full bg-gradient-to-br from-blue-100 to-blue-200 dark:from-blue-950 dark:to-blue-900 border-2 border-blue-300 dark:border-blue-700 rounded-xl shadow-lg shadow-blue-500/20 mb-3 overflow-hidden"
|
||||
>
|
||||
<div className="flex items-center justify-between px-2 py-1.5 sm:px-3 sm:py-2 border-b border-blue-500/20 bg-blue-500/5">
|
||||
<div className="flex items-center justify-between px-2 py-1.5 sm:px-3 sm:py-2 border-b border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/50">
|
||||
<div className="flex items-center gap-2">
|
||||
{totalSteps > 1 && (
|
||||
<button
|
||||
onClick={goToPrev}
|
||||
disabled={currentIndex === 0}
|
||||
className="p-0.5 sm:p-1 rounded hover:bg-blue-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
|
||||
className="p-0.5 sm:p-1 rounded hover:bg-blue-200 dark:hover:bg-blue-800 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronLeft className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 dark:text-blue-400" />
|
||||
</button>
|
||||
)}
|
||||
<span className="text-xs sm:text-sm font-semibold text-blue-400">
|
||||
<span className="text-xs sm:text-sm font-semibold text-blue-600 dark:text-white">
|
||||
{isConfirmStep ? 'Review' : (
|
||||
totalSteps > 1
|
||||
? `Question ${currentIndex + 1}/${questions.length}`
|
||||
@@ -203,7 +203,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr
|
||||
<button
|
||||
onClick={goToNext}
|
||||
disabled={currentIndex === totalSteps - 1}
|
||||
className="p-0.5 sm:p-1 rounded hover:bg-blue-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
|
||||
className="p-0.5 sm:p-1 rounded hover:bg-blue-200 dark:hover:bg-blue-800 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronRight className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-blue-600 dark:text-blue-400" />
|
||||
</button>
|
||||
@@ -218,7 +218,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-2 sm:p-3 max-h-[50vh] sm:max-h-[70vh] overflow-y-auto overflow-x-hidden">
|
||||
<div className="p-2 sm:p-3 max-h-[50vh] sm:max-h-[70vh] overflow-y-auto overflow-x-hidden bg-background/60 dark:bg-black/30">
|
||||
{isConfirmStep ? (
|
||||
<ConfirmStep
|
||||
questions={questions}
|
||||
@@ -243,7 +243,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr
|
||||
</div>
|
||||
|
||||
{totalSteps > 1 && (
|
||||
<div className="flex justify-center gap-1 sm:gap-1.5 py-1.5 sm:py-2 border-t border-blue-500/10">
|
||||
<div className="flex justify-center gap-1 sm:gap-1.5 py-1.5 sm:py-2 border-t border-blue-200 dark:border-blue-800">
|
||||
{Array.from({ length: totalSteps }).map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
@@ -264,7 +264,7 @@ export function QuestionPrompt({ question, onReply, onReject }: QuestionPromptPr
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-1.5 sm:gap-2 px-2 pb-2 sm:px-3 sm:pb-3">
|
||||
<div className="flex gap-1.5 sm:gap-2 px-2 py-2 sm:px-3 sm:py-3">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleReject}
|
||||
@@ -362,10 +362,10 @@ function QuestionStep({
|
||||
key={i}
|
||||
onClick={() => onSelectOption(option.label)}
|
||||
className={cn(
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg border-2 transition-all duration-200 active:scale-[0.98]",
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg transition-all duration-200 active:scale-[0.98]",
|
||||
isSelected
|
||||
? "border-blue-500 bg-blue-500/10"
|
||||
: "border-border hover:border-blue-500/50 hover:bg-blue-500/5"
|
||||
? "bg-blue-200 dark:bg-blue-700/50"
|
||||
: "bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-1.5 sm:gap-2">
|
||||
@@ -380,7 +380,7 @@ function QuestionStep({
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-xs sm:text-sm font-semibold",
|
||||
isSelected ? "text-blue-400" : "text-foreground"
|
||||
isSelected ? "text-blue-600 dark:text-blue-300" : "text-foreground"
|
||||
)}>
|
||||
{option.label}
|
||||
</span>
|
||||
@@ -404,10 +404,10 @@ function QuestionStep({
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg border-2 transition-all duration-200",
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg transition-all duration-200",
|
||||
expandedOther || isCustomSelected
|
||||
? "border-blue-500 bg-blue-500/10"
|
||||
: "border-border hover:border-blue-500/50 hover:bg-blue-500/5"
|
||||
? "bg-blue-200 dark:bg-blue-700/50"
|
||||
: "bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
@@ -421,7 +421,7 @@ function QuestionStep({
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-xs sm:text-sm font-semibold",
|
||||
expandedOther || isCustomSelected ? "text-blue-400" : "text-foreground"
|
||||
expandedOther || isCustomSelected ? "text-blue-600 dark:text-blue-300" : "text-foreground"
|
||||
)}>
|
||||
Other...
|
||||
</span>
|
||||
@@ -479,18 +479,18 @@ function ConfirmStep({ questions, answers, onEditQuestion }: ConfirmStepProps) {
|
||||
key={i}
|
||||
onClick={() => onEditQuestion(i)}
|
||||
className={cn(
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg border transition-colors",
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg transition-colors",
|
||||
hasAnswer
|
||||
? "border-green-500/40 bg-green-500/10 hover:bg-green-500/15"
|
||||
: "border-red-500/40 bg-red-500/10 hover:bg-red-500/15"
|
||||
? "bg-green-50 dark:bg-green-900/30 hover:bg-green-100 dark:hover:bg-green-900/50"
|
||||
: "bg-red-50 dark:bg-red-900/30 hover:bg-red-100 dark:hover:bg-red-900/50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-1.5 sm:gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[10px] sm:text-xs text-foreground/60 truncate">{q.header}</p>
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">{q.header}</p>
|
||||
<p className={cn(
|
||||
"text-xs sm:text-sm font-semibold mt-0.5",
|
||||
hasAnswer ? "text-green-400" : "text-red-400"
|
||||
hasAnswer ? "text-green-700 dark:text-green-400" : "text-red-700 dark:text-red-400"
|
||||
)}>
|
||||
{hasAnswer ? answer.join(', ') : '(not answered)'}
|
||||
</p>
|
||||
|
||||
@@ -45,7 +45,7 @@ export const SessionCard = ({
|
||||
<div className="relative" onClick={close}>
|
||||
<div
|
||||
className={`absolute top-0.5 right-0 bottom-0.5 w-20 bg-red-600 flex items-center justify-center rounded-r-lg transition-opacity ${
|
||||
!isSwipingBack && (isOpen || swipeOffset > 40) ? "opacity-100" : "opacity-0"
|
||||
!isSwipingBack && (isOpen || swipeOffset > 40) ? "opacity-100" : "opacity-0 pointer-events-none"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { Loader2, User, KeyRound, LogOut, Plus, Trash2, AlertCircle, CheckCircle, Lock } from 'lucide-react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { passkey, changePassword } from '@/lib/auth-client'
|
||||
@@ -28,6 +29,7 @@ export function AccountSettings() {
|
||||
const [success, setSuccess] = useState<string | null>(null)
|
||||
const [showChangePassword, setShowChangePassword] = useState(false)
|
||||
const [editingProfile, setEditingProfile] = useState(false)
|
||||
const [deletePasskeyId, setDeletePasskeyId] = useState<string | null>(null)
|
||||
|
||||
const { data: passkeys, isLoading: passkeysLoading } = useQuery({
|
||||
queryKey: ['passkeys'],
|
||||
@@ -104,11 +106,20 @@ export function AccountSettings() {
|
||||
const handleDeletePasskey = (id: string) => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
if (confirm('Are you sure you want to delete this passkey?')) {
|
||||
deletePasskeyMutation.mutate(id)
|
||||
setDeletePasskeyId(id)
|
||||
}
|
||||
|
||||
const handleDeleteConfirm = () => {
|
||||
if (deletePasskeyId) {
|
||||
deletePasskeyMutation.mutate(deletePasskeyId)
|
||||
setDeletePasskeyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteCancel = () => {
|
||||
setDeletePasskeyId(null)
|
||||
}
|
||||
|
||||
const handleChangePassword = () => {
|
||||
setError(null)
|
||||
setSuccess(null)
|
||||
@@ -343,6 +354,16 @@ export function AccountSettings() {
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<DeleteDialog
|
||||
open={deletePasskeyId !== null}
|
||||
onOpenChange={(open) => !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}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<Provider | null>(null)
|
||||
const [apiKeyMode, setApiKeyMode] = useState<'add' | 'edit'>('add')
|
||||
const [deleteTarget, setDeleteTarget] = useState<string | null>(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}
|
||||
/>
|
||||
)}
|
||||
|
||||
<DeleteDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => !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}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<string | null>(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<unknown>) => {
|
||||
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 (
|
||||
<div className="flex flex-col h-full">
|
||||
{apiError && (
|
||||
<div className="mx-3 mt-3 p-2 rounded border bg-destructive/10 border-destructive/20 flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-destructive flex-shrink-0" />
|
||||
<span className="text-sm text-destructive flex-1">{apiError}</span>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={() => setApiError(null)}>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Tabs defaultValue="files" className="flex flex-col h-full">
|
||||
<TabsList className="flex-shrink-0">
|
||||
<TabsTrigger value="files">Files ({stagedFiles.length + unstagedFiles.length})</TabsTrigger>
|
||||
@@ -164,16 +142,6 @@ export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: Cha
|
||||
} else {
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
{apiError && (
|
||||
<div className="mx-3 mt-3 p-2 rounded border bg-destructive/10 border-destructive/20 flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-destructive flex-shrink-0" />
|
||||
<span className="text-sm text-destructive flex-1">{apiError}</span>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={() => setApiError(null)}>
|
||||
<X className="w-3 h-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-4">
|
||||
{status.hasChanges ? (
|
||||
<>
|
||||
|
||||
@@ -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 (
|
||||
<Alert variant="destructive" className="mb-0 p-3 sm:p-4 [&>svg]:hidden [&>svg~*]:pl-0">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<AlertDescription className="flex-1 min-w-0 text-sm">{error.summary}</AlertDescription>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 flex-shrink-0"
|
||||
onClick={onDismiss}
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
{error.detail && (
|
||||
<pre className="p-2 rounded border bg-destructive/5 border-destructive/20 text-xs font-mono overflow-auto max-h-32">
|
||||
{error.detail}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
@@ -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<Tab>('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<unknown>) => {
|
||||
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({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{gitError && (
|
||||
<GitErrorBanner error={gitError} onDismiss={() => setGitError(null)} />
|
||||
)}
|
||||
|
||||
<div className="flex border-b border-border flex-shrink-0">
|
||||
{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' && (
|
||||
|
||||
@@ -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<string, PermissionRequest[]>
|
||||
type QuestionsBySession = Record<string, QuestionRequest[]>
|
||||
|
||||
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<void>
|
||||
@@ -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] ?? []
|
||||
|
||||
@@ -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<T extends Message> {
|
||||
interface UseAutoScrollOptions {
|
||||
containerRef?: React.RefObject<HTMLDivElement | null>
|
||||
messages?: T[]
|
||||
messages?: Message[]
|
||||
sessionId?: string
|
||||
onScrollStateChange?: (isScrolledUp: boolean) => void
|
||||
}
|
||||
@@ -21,12 +14,12 @@ interface UseAutoScrollReturn {
|
||||
scrollToBottom: () => void
|
||||
}
|
||||
|
||||
export function useAutoScroll<T extends Message>({
|
||||
export function useAutoScroll({
|
||||
containerRef,
|
||||
messages,
|
||||
sessionId,
|
||||
onScrollStateChange
|
||||
}: UseAutoScrollOptions<T>): UseAutoScrollReturn {
|
||||
}: UseAutoScrollOptions): UseAutoScrollReturn {
|
||||
const lastMessageCountRef = useRef(0)
|
||||
const hasInitialScrolledRef = useRef(false)
|
||||
const userScrolledAtRef = useRef(0)
|
||||
@@ -139,7 +132,7 @@ export function useAutoScroll<T extends Message>({
|
||||
|
||||
if (currentCount > prevCount) {
|
||||
const newMessage = messages[currentCount - 1]
|
||||
if (newMessage?.info.role === 'user') {
|
||||
if (newMessage?.role === 'user') {
|
||||
scrollToBottom()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<ProvidersResponse> {
|
||||
const response = await fetch(`${opcodeUrl}/config/providers`)
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch providers')
|
||||
}
|
||||
return response.json()
|
||||
return fetchWrapper<ProvidersResponse>(`${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
|
||||
|
||||
@@ -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<string[]>(
|
||||
`${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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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<string>();
|
||||
@@ -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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
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<MessageListResponse>(queryKey, (old) => {
|
||||
queryClient.setQueryData<Message[]>(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<string, unknown> }).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<MessageListResponse>(queryKey);
|
||||
const messages = queryClient.getQueryData<Message[]>(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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
["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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
["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);
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -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<unknown, Error, { messageID: string; partID?: string }, RemoveMessageContext>({
|
||||
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<MessageListResponse>(queryKey)
|
||||
const previousMessages = queryClient.getQueryData<Message[]>(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<MessageListResponse>(
|
||||
const userMessageParts = [{
|
||||
id: `${optimisticUserID}_part_0`,
|
||||
type: 'text' as const,
|
||||
text: userMessageContent,
|
||||
messageID: optimisticUserID,
|
||||
sessionID: sessionId
|
||||
}] as Part[]
|
||||
|
||||
queryClient.setQueryData<Message[]>(
|
||||
['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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
['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)
|
||||
}
|
||||
|
||||
@@ -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<MessageListResponse>(['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<MessageListResponse>(messagesQueryKey)
|
||||
const currentData = queryClient.getQueryData<Message[]>(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<MessageListResponse>(
|
||||
queryClient.setQueryData<Message[]>(
|
||||
['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<MessageListResponse>(
|
||||
['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<MessageListResponse>(messagesQueryKey)
|
||||
const currentData = queryClient.getQueryData<Message[]>(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
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { useEventContext } from '@/contexts/EventContext'
|
||||
|
||||
export function useSSH() {
|
||||
const { sshHostKey } = useEventContext()
|
||||
return sshHostKey
|
||||
}
|
||||
@@ -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<HealthResponse> {
|
||||
const response = await fetch('/api/health')
|
||||
if (!response.ok) {
|
||||
throw new Error('Health check failed')
|
||||
}
|
||||
return response.json()
|
||||
return fetchWrapper<HealthResponse>('/api/health')
|
||||
}
|
||||
|
||||
let lastHealthStatus: 'healthy' | 'unhealthy' = 'healthy'
|
||||
|
||||
export function useServerHealth(enabled = true) {
|
||||
const queryClient = useQueryClient()
|
||||
const lastHealthStatusRef = useRef<'healthy' | 'unhealthy'>('healthy')
|
||||
const prevHealthRef = useRef<string | null>(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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string, Error, { messageID: string; messageContent: string }, UndoMessageContext>({
|
||||
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<MessageListResponse>(queryKey)
|
||||
const previousMessages = queryClient.getQueryData<Message[]>(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
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -9,16 +9,21 @@ export interface AuthConfig {
|
||||
}
|
||||
|
||||
async function fetchAuthConfig(): Promise<AuthConfig> {
|
||||
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() {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import stripJsonComments from 'strip-json-comments'
|
||||
|
||||
export function parseJsonc<T = unknown>(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 {
|
||||
|
||||
@@ -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<string, FileInfo>,
|
||||
fileMap: Map<string, FileAttachmentInfo>,
|
||||
imageAttachments?: ImageAttachment[]
|
||||
): ContentPart[] {
|
||||
const parts: ContentPart[] = []
|
||||
|
||||
@@ -13,7 +13,12 @@ export async function getServiceWorkerRegistration(): Promise<ServiceWorkerRegis
|
||||
export function urlBase64ToUint8Array(base64String: string): Uint8Array {
|
||||
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
|
||||
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
|
||||
const rawData = window.atob(base64);
|
||||
let rawData: string;
|
||||
try {
|
||||
rawData = window.atob(base64);
|
||||
} catch {
|
||||
throw new Error(`Invalid base64 string: ${base64String.slice(0, 20)}...`);
|
||||
}
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
for (let i = 0; i < rawData.length; ++i) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
|
||||
@@ -18,6 +18,13 @@ export const MODAL_TRANSITION_MS = 300
|
||||
* Sanitizes markdown text for TTS playback by removing non-read-aloud symbols
|
||||
* Converts markdown into clean, readable text suitable for speech synthesis
|
||||
*/
|
||||
export function getRepoDisplayName(repoUrl?: string | null, localPath?: string | null): string {
|
||||
if (repoUrl) {
|
||||
return repoUrl.split("/").pop()?.replace(".git", "") || "Repository"
|
||||
}
|
||||
return localPath || "Repository"
|
||||
}
|
||||
|
||||
export function sanitizeForTTS(text: string): string {
|
||||
if (!text) return ''
|
||||
|
||||
|
||||
@@ -218,7 +218,6 @@ export class WebSpeechSynthesizer {
|
||||
this.pendingReject = null;
|
||||
}
|
||||
this.onEndCallbacks.forEach((cb) => 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) => {
|
||||
|
||||
@@ -25,6 +25,7 @@ export function Login() {
|
||||
const theme = useTheme()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isPasskeyLoading, setIsPasskeyLoading] = useState(false)
|
||||
const [oauthLoading, setOauthLoading] = useState<string | null>(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 ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
@@ -226,7 +227,7 @@ export function Login() {
|
||||
<p className="text-sm text-destructive">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting}>
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting || isPasskeyLoading}>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
|
||||
@@ -27,12 +27,13 @@ import { Plug, FolderOpen, Plus, GitBranch, Loader2, GitCommitHorizontal, Shield
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { showToast } from "@/lib/toast";
|
||||
import { invalidateConfigCaches } from "@/lib/queryInvalidation";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
|
||||
export function RepoDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const repoId = parseInt(id || "0");
|
||||
const repoId = Number(id) || 0;
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
|
||||
const [switchConfigOpen, setSwitchConfigOpen] = useState(false);
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
|
||||
@@ -123,9 +124,7 @@ export function RepoDetail() {
|
||||
);
|
||||
}
|
||||
|
||||
const repoName = repo.repoUrl
|
||||
? repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository"
|
||||
: repo.localPath || "Local Repository";
|
||||
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath);
|
||||
const branchToDisplay = repo.currentBranch || repo.branch;
|
||||
const displayName = branchToDisplay ? `${repoName} (${branchToDisplay})` : repoName;
|
||||
const currentBranch = repo.currentBranch || repo.branch || "main";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useParams, useNavigate, Navigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getRepo } from "@/api/repos";
|
||||
import { MessageThread } from "@/components/message/MessageThread";
|
||||
@@ -28,7 +28,10 @@ import { useTTS } from "@/hooks/useTTS";
|
||||
import { useEffect, useRef, useCallback, useMemo } from "react";
|
||||
import { MessageSkeleton } from "@/components/message/MessageSkeleton";
|
||||
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
|
||||
import { useMessageParts } from "@/stores/messagePartsStore";
|
||||
import type { MessageWithParts } from "@/api/types";
|
||||
import { showToast } from "@/lib/toast";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { createOpenCodeClient } from "@/api/opencode";
|
||||
import { useSessionStatus } from "@/stores/sessionStatusStore";
|
||||
@@ -48,7 +51,7 @@ const compareMessageIds = (id1: string, id2: string): number => {
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const repoId = parseInt(id || "0");
|
||||
const repoId = Number(id) || 0;
|
||||
const { preferences, updateSettings } = useSettings();
|
||||
const messageContainerRef = useRef<HTMLDivElement>(null);
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
@@ -95,9 +98,18 @@ export function SessionDetail() {
|
||||
if (!rawMessages) return undefined
|
||||
const revertMessageID = session?.revert?.messageID
|
||||
if (!revertMessageID) return rawMessages
|
||||
return rawMessages.filter(msg => compareMessageIds(msg.info.id, revertMessageID) < 0)
|
||||
return rawMessages.filter(msg => compareMessageIds(msg.id, revertMessageID) < 0)
|
||||
}, [rawMessages, session?.revert?.messageID]);
|
||||
|
||||
const getMessagesWithParts = useCallback((): MessageWithParts[] | undefined => {
|
||||
if (!messages) return undefined
|
||||
const partsMap = useMessageParts.getState().parts
|
||||
return messages.map(msg => ({
|
||||
info: msg,
|
||||
parts: partsMap.get(msg.id) || []
|
||||
}))
|
||||
}, [messages])
|
||||
|
||||
const { scrollToBottom } = useAutoScroll({
|
||||
containerRef: messageContainerRef,
|
||||
messages,
|
||||
@@ -260,15 +272,16 @@ export function SessionDetail() {
|
||||
}, [preferences?.expandToolCalls, updateSettings]);
|
||||
|
||||
const handleExportSession = useCallback(() => {
|
||||
if (!messages || !session) {
|
||||
const data = getMessagesWithParts()
|
||||
if (!data || !session) {
|
||||
showToast.error('No session data to export')
|
||||
return
|
||||
}
|
||||
|
||||
const { filename, content } = exportSession(messages, session)
|
||||
const { filename, content } = exportSession(data, session)
|
||||
downloadMarkdown(content, filename)
|
||||
showToast.success(`Exported to ${filename}`)
|
||||
}, [messages, session]);
|
||||
}, [getMessagesWithParts, session]);
|
||||
|
||||
const handleUndoMessage = useCallback((restoredPrompt: string) => {
|
||||
promptInputRef.current?.setPromptValue(restoredPrompt)
|
||||
@@ -283,11 +296,7 @@ export function SessionDetail() {
|
||||
|
||||
|
||||
if (!sessionId) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-background text-muted-foreground">
|
||||
Session not found
|
||||
</div>
|
||||
);
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
if (!repo) {
|
||||
@@ -331,7 +340,7 @@ export function SessionDetail() {
|
||||
<Header.EditableTitle
|
||||
value={session?.title || "Untitled Session"}
|
||||
onChange={handleSessionTitleUpdate}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{repo.repoUrl?.split("/").pop()?.replace(".git", "") || repo.localPath || "Repository"}</span>}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{getRepoDisplayName(repo.repoUrl, repo.localPath)}</span>}
|
||||
generating={isTitleGenerating}
|
||||
/>
|
||||
</div>
|
||||
@@ -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)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { create } from 'zustand'
|
||||
import type { Part } from '@/api/types'
|
||||
|
||||
const EMPTY_PARTS: Part[] = []
|
||||
|
||||
interface MessagePartsStore {
|
||||
parts: Map<string, Part[]>
|
||||
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<MessagePartsStore>((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)
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -69,10 +69,8 @@ export type PushSubscriptionRequest = z.infer<typeof PushSubscriptionRequestSche
|
||||
export type PushSubscriptionRecord = z.infer<typeof PushSubscriptionRecordSchema>
|
||||
export type PushNotificationPayload = z.infer<typeof PushNotificationPayloadSchema>
|
||||
|
||||
export interface ErrorResponse {
|
||||
error: string
|
||||
details?: unknown
|
||||
}
|
||||
export { FetchError } from './errors'
|
||||
export type { ApiErrorResponse, ApiErrorCode, GitErrorCode } from './errors'
|
||||
|
||||
export interface SuccessResponse {
|
||||
success: boolean
|
||||
|
||||
Reference in new issue
Block a user