mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add multiple git credentials support with migration
This commit is contained in:
1 parent
15643ae06b
commit
a736e98880
19 files changed
+1203
-1096
No files matched your search
@@ -21,6 +21,11 @@ RUN apt-get update && apt-get install -y \
|
||||
python3-venv \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
|
||||
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
|
||||
&& apt-get update && apt-get install -y gh \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate
|
||||
|
||||
RUN curl -fsSL https://bun.sh/install | bash && \
|
||||
|
||||
@@ -121,9 +121,55 @@ export function runMigrations(db: Database): void {
|
||||
logger.error('Failed to migrate local_path format:', error)
|
||||
}
|
||||
|
||||
migrateGitTokenToCredentials(db)
|
||||
|
||||
logger.info('Database migrations completed successfully')
|
||||
} catch (error) {
|
||||
logger.error('Failed to run database migrations:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function migrateGitTokenToCredentials(db: Database): void {
|
||||
try {
|
||||
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
|
||||
user_id: string
|
||||
preferences: string
|
||||
}>
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const parsed = JSON.parse(row.preferences) as Record<string, unknown>
|
||||
const gitToken = parsed.gitToken as string | undefined
|
||||
const existingCredentials = parsed.gitCredentials as Array<unknown> | undefined
|
||||
|
||||
if (!gitToken) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (existingCredentials && existingCredentials.length > 0) {
|
||||
continue
|
||||
}
|
||||
|
||||
const { gitToken: _, ...rest } = parsed
|
||||
const migrated = {
|
||||
...rest,
|
||||
gitCredentials: [{
|
||||
name: 'GitHub',
|
||||
host: 'https://github.com/',
|
||||
token: gitToken,
|
||||
}],
|
||||
}
|
||||
|
||||
db.prepare('UPDATE user_preferences SET preferences = ? WHERE user_id = ?')
|
||||
.run(JSON.stringify(migrated), row.user_id)
|
||||
|
||||
logger.info(`Migrated gitToken to gitCredentials for user: ${row.user_id}`)
|
||||
} catch (parseError) {
|
||||
logger.error(`Failed to parse preferences for user ${row.user_id}:`, parseError)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to migrate gitToken to gitCredentials:', error)
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,17 @@ import path from 'path'
|
||||
|
||||
export function createRepoRoutes(database: Database) {
|
||||
const app = new Hono()
|
||||
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { repoUrl, localPath, branch, openCodeConfigName, useWorktree } = body
|
||||
|
||||
const { repoUrl, localPath, branch, openCodeConfigName, useWorktree, provider } = body
|
||||
|
||||
if (!repoUrl && !localPath) {
|
||||
return c.json({ error: 'Either repoUrl or localPath is required' }, 400)
|
||||
}
|
||||
|
||||
logger.info(`Creating repo - URL: ${repoUrl}, Provider: ${provider || 'auto-detect'}`)
|
||||
|
||||
let repo
|
||||
if (localPath) {
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
import { logger } from '../utils/logger'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { DEFAULT_AGENTS_MD } from '../index'
|
||||
import { createGitHubGitEnv } from '../utils/git-auth'
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
|
||||
@@ -46,9 +45,7 @@ const UpdateCustomCommandSchema = z.object({
|
||||
promptTemplate: z.string().min(1).max(10000),
|
||||
})
|
||||
|
||||
const ValidateGitTokenSchema = z.object({
|
||||
gitToken: z.string(),
|
||||
})
|
||||
|
||||
|
||||
const ConnectMcpDirectorySchema = z.object({
|
||||
directory: z.string().min(1),
|
||||
@@ -86,13 +83,16 @@ export function createSettingsRoutes(db: Database) {
|
||||
const settings = settingsService.updateSettings(validated.preferences, userId)
|
||||
|
||||
let serverRestarted = false
|
||||
if (validated.preferences.gitToken !== undefined &&
|
||||
validated.preferences.gitToken !== currentSettings.preferences.gitToken) {
|
||||
logger.info('GitHub token changed, restarting OpenCode server')
|
||||
await opencodeServerManager.restart()
|
||||
serverRestarted = true
|
||||
if (validated.preferences.gitCredentials !== undefined) {
|
||||
const currentCreds = JSON.stringify(currentSettings.preferences.gitCredentials || [])
|
||||
const newCreds = JSON.stringify(validated.preferences.gitCredentials)
|
||||
if (currentCreds !== newCreds) {
|
||||
logger.info('Git credentials changed, restarting OpenCode server')
|
||||
await opencodeServerManager.restart()
|
||||
serverRestarted = true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return c.json({ ...settings, serverRestarted })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update settings:', error)
|
||||
@@ -459,72 +459,6 @@ export function createSettingsRoutes(db: Database) {
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/validate-git-token', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { gitToken } = ValidateGitTokenSchema.parse(body)
|
||||
|
||||
if (!gitToken) {
|
||||
return c.json({ valid: true, message: 'No token provided' })
|
||||
}
|
||||
|
||||
// Test the token by trying to access a public GitHub repo via git ls-remote
|
||||
const testRepoUrl = 'https://github.com/octocat/Hello-World.git'
|
||||
const env = createGitHubGitEnv(gitToken)
|
||||
|
||||
try {
|
||||
await execAsync(`git ls-remote ${testRepoUrl}`, {
|
||||
env: { ...process.env, ...env },
|
||||
timeout: 10000
|
||||
})
|
||||
|
||||
// If command succeeded (exit code 0), token is valid
|
||||
// stderr may contain warnings but that's ok
|
||||
return c.json({
|
||||
valid: true,
|
||||
message: 'Token is valid'
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Git token validation failed:', error)
|
||||
|
||||
if (error instanceof Error) {
|
||||
const errorMsg = error.message.toLowerCase()
|
||||
|
||||
if (errorMsg.includes('authentication failed') ||
|
||||
errorMsg.includes('not authorized') ||
|
||||
errorMsg.includes('invalid username or token') ||
|
||||
errorMsg.includes('password authentication is not supported') ||
|
||||
errorMsg.includes('401') ||
|
||||
errorMsg.includes('403') ||
|
||||
errorMsg.includes('code 128')) {
|
||||
return c.json({
|
||||
valid: false,
|
||||
message: 'Invalid GitHub token. Please check your token and permissions.'
|
||||
})
|
||||
}
|
||||
|
||||
if (errorMsg.includes('timeout') || errorMsg.includes('network')) {
|
||||
return c.json({
|
||||
valid: false,
|
||||
message: 'Network error - could not validate token. Please try again.'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({
|
||||
valid: false,
|
||||
message: 'Failed to validate token: ' + (error instanceof Error ? error.message : 'Unknown error')
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Token validation endpoint error:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to validate token' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
// MCP directory-aware endpoints
|
||||
app.post('/mcp/:name/connectdirectory', async (c) => {
|
||||
try {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { logger } from '../utils/logger'
|
||||
import { SettingsService } from './settings'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import path from 'path'
|
||||
import { createGitHubGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
|
||||
import { createGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
|
||||
|
||||
async function hasCommits(repoPath: string): Promise<boolean> {
|
||||
try {
|
||||
@@ -18,15 +18,11 @@ function getGitEnvironment(database: Database): Record<string, string> {
|
||||
try {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitToken = settings.preferences.gitToken
|
||||
const gitCredentials = settings.preferences.gitCredentials || []
|
||||
|
||||
if (gitToken) {
|
||||
return createGitHubGitEnv(gitToken)
|
||||
}
|
||||
|
||||
return createNoPromptGitEnv()
|
||||
return createGitEnv(gitCredentials)
|
||||
} catch (error) {
|
||||
logger.warn('Failed to get git token from settings:', error)
|
||||
logger.warn('Failed to get git credentials from settings:', error)
|
||||
return createNoPromptGitEnv()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { createGitHubGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
|
||||
import { createGitEnv, createNoPromptGitEnv } from '../utils/git-auth'
|
||||
import { SettingsService } from './settings'
|
||||
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitCredential } from '../utils/git-auth'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
|
||||
@@ -54,18 +55,18 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
const isDevelopment = ENV.SERVER.NODE_ENV !== 'production'
|
||||
|
||||
let gitToken = ''
|
||||
|
||||
let gitCredentials: GitCredential[] = []
|
||||
if (this.db) {
|
||||
try {
|
||||
const settingsService = new SettingsService(this.db)
|
||||
const settings = settingsService.getSettings('default')
|
||||
gitToken = settings.preferences.gitToken || ''
|
||||
gitCredentials = settings.preferences.gitCredentials || []
|
||||
} catch (error) {
|
||||
logger.warn('Failed to get git token from settings:', error)
|
||||
logger.warn('Failed to get git credentials from settings:', error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const existingProcesses = await this.findProcessesByPort(OPENCODE_SERVER_PORT)
|
||||
if (existingProcesses.length > 0) {
|
||||
logger.info(`OpenCode server already running on port ${OPENCODE_SERVER_PORT}`)
|
||||
@@ -105,7 +106,7 @@ class OpenCodeServerManager {
|
||||
logger.info(`OpenCode XDG_CONFIG_HOME: ${path.join(OPENCODE_SERVER_DIRECTORY, '.config')}`)
|
||||
logger.info(`OpenCode will use ?directory= parameter for session isolation`)
|
||||
|
||||
const gitEnv = gitToken ? createGitHubGitEnv(gitToken) : createNoPromptGitEnv()
|
||||
const gitEnv = createGitEnv(gitCredentials)
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SettingsService } from './settings'
|
||||
import { createGitEnvForRepoUrl, createNoPromptGitEnv, createGitHubGitEnv } from '../utils/git-auth'
|
||||
import { createGitEnv, createNoPromptGitEnv, createGitHubGitEnv, isGitHubHttpsUrl } from '../utils/git-auth'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import path from 'path'
|
||||
|
||||
@@ -34,27 +34,36 @@ async function executeGitWithFallback(
|
||||
options: GitCommandOptions = {}
|
||||
): Promise<string> {
|
||||
const { cwd, env = createNoPromptGitEnv(), silent } = options
|
||||
|
||||
|
||||
try {
|
||||
return await executeCommand(cmd, { cwd, env, silent })
|
||||
} catch (error: any) {
|
||||
if (!isAuthenticationError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
logger.warn(`Git command failed with auth, trying gh auth fallback`)
|
||||
try {
|
||||
const ghToken = (await executeCommand(['gh', 'auth', 'token'])).trim()
|
||||
const ghEnv = createGitHubGitEnv(ghToken)
|
||||
return await executeCommand(cmd, { cwd, env: ghEnv, silent })
|
||||
} catch (ghError: any) {
|
||||
if (!isAuthenticationError(ghError)) {
|
||||
throw ghError
|
||||
}
|
||||
|
||||
logger.warn(`Git command failed with gh auth, trying without auth (public repo)`)
|
||||
|
||||
logger.warn(`Git command failed with auth, trying CLI fallbacks`)
|
||||
|
||||
const url = cmd.find(arg => arg.includes('http://') || arg.includes('https://'))
|
||||
if (!url) {
|
||||
return await executeCommand(cmd, { cwd, env: createNoPromptGitEnv(), silent })
|
||||
}
|
||||
|
||||
try {
|
||||
if (isGitHubHttpsUrl(url)) {
|
||||
logger.warn(`Detected GitHub URL, trying gh auth token`)
|
||||
const ghToken = (await executeCommand(['gh', 'auth', 'token'])).trim()
|
||||
const ghEnv = createGitHubGitEnv(ghToken)
|
||||
return await executeCommand(cmd, { cwd, env: ghEnv, silent })
|
||||
}
|
||||
|
||||
|
||||
} catch (cliError: any) {
|
||||
logger.warn(`CLI auth fallback failed:`, cliError.message)
|
||||
}
|
||||
|
||||
logger.warn(`All auth fallbacks failed, trying without auth (public repo)`)
|
||||
return await executeCommand(cmd, { cwd, env: createNoPromptGitEnv(), silent })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,17 +96,13 @@ async function safeGetCurrentBranch(repoPath: string): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
function getGitEnv(database: Database, repoUrl?: string | null): Record<string, string> {
|
||||
function getGitEnv(database: Database): Record<string, string> {
|
||||
try {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitToken = settings.preferences.gitToken
|
||||
const gitCredentials = settings.preferences.gitCredentials || []
|
||||
|
||||
if (!repoUrl) {
|
||||
return createNoPromptGitEnv()
|
||||
}
|
||||
|
||||
return createGitEnvForRepoUrl(repoUrl, gitToken)
|
||||
return createGitEnv(gitCredentials)
|
||||
} catch {
|
||||
return createNoPromptGitEnv()
|
||||
}
|
||||
@@ -225,7 +230,7 @@ export async function cloneRepo(
|
||||
const repo = db.createRepo(database, createRepoInput)
|
||||
|
||||
try {
|
||||
const env = getGitEnv(database, normalizedRepoUrl)
|
||||
const env = getGitEnv(database)
|
||||
|
||||
if (shouldUseWorktree) {
|
||||
logger.info(`Creating worktree for branch: ${branch}`)
|
||||
@@ -408,7 +413,7 @@ export async function getCurrentBranch(repo: Repo): Promise<string | null> {
|
||||
export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], all: string[], current: string | null }> {
|
||||
try {
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const env = getGitEnv(database, repo.repoUrl)
|
||||
const env = getGitEnv(database)
|
||||
|
||||
if (!repo.isLocal) {
|
||||
try {
|
||||
@@ -457,7 +462,7 @@ export async function switchBranch(database: Database, repoId: number, branch: s
|
||||
|
||||
try {
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const env = getGitEnv(database, repo.repoUrl)
|
||||
const env = getGitEnv(database)
|
||||
|
||||
const sanitizedBranch = branch
|
||||
.replace(/^refs\/heads\//, '')
|
||||
@@ -537,7 +542,7 @@ export async function pullRepo(database: Database, repoId: number): Promise<void
|
||||
}
|
||||
|
||||
try {
|
||||
const env = getGitEnv(database, repo.repoUrl)
|
||||
const env = getGitEnv(database)
|
||||
|
||||
logger.info(`Pulling repo: ${repo.repoUrl}`)
|
||||
await executeCommand(['git', '-C', path.resolve(getReposPath(), repo.localPath), 'pull'], { env })
|
||||
|
||||
@@ -63,6 +63,7 @@ export class SettingsService {
|
||||
|
||||
try {
|
||||
const parsed = parseJsonc(row.preferences) as Record<string, unknown>
|
||||
|
||||
const validated = UserPreferencesSchema.parse({
|
||||
...DEFAULT_USER_PREFERENCES,
|
||||
...parsed,
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
export interface GitCredential {
|
||||
name: string
|
||||
host: string
|
||||
token: string
|
||||
username?: string
|
||||
}
|
||||
|
||||
export function isGitHubHttpsUrl(repoUrl: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(repoUrl)
|
||||
@@ -13,26 +20,60 @@ export function createNoPromptGitEnv(): Record<string, string> {
|
||||
}
|
||||
}
|
||||
|
||||
function getDefaultUsername(host: string): string {
|
||||
try {
|
||||
const parsed = new URL(host)
|
||||
const hostname = parsed.hostname.toLowerCase()
|
||||
|
||||
if (hostname === 'github.com') {
|
||||
return 'x-access-token'
|
||||
}
|
||||
if (hostname === 'gitlab.com' || hostname.includes('gitlab')) {
|
||||
return 'oauth2'
|
||||
}
|
||||
return 'oauth2'
|
||||
} catch {
|
||||
return 'oauth2'
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHost(host: string): string {
|
||||
if (!host.endsWith('/')) {
|
||||
return `${host}/`
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
export function createGitEnv(credentials: GitCredential[]): Record<string, string> {
|
||||
const env: Record<string, string> = { GIT_TERMINAL_PROMPT: '0' }
|
||||
|
||||
if (!credentials || credentials.length === 0) {
|
||||
return env
|
||||
}
|
||||
|
||||
let configIndex = 0
|
||||
|
||||
for (const cred of credentials) {
|
||||
if (!cred.host || !cred.token) {
|
||||
continue
|
||||
}
|
||||
|
||||
const host = normalizeHost(cred.host)
|
||||
const username = cred.username || getDefaultUsername(host)
|
||||
const basicAuth = Buffer.from(`${username}:${cred.token}`, 'utf8').toString('base64')
|
||||
|
||||
env[`GIT_CONFIG_KEY_${configIndex}`] = `http.${host}.extraheader`
|
||||
env[`GIT_CONFIG_VALUE_${configIndex}`] = `AUTHORIZATION: basic ${basicAuth}`
|
||||
configIndex++
|
||||
}
|
||||
|
||||
if (configIndex > 0) {
|
||||
env.GIT_CONFIG_COUNT = String(configIndex)
|
||||
}
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
export function createGitHubGitEnv(gitToken: string): Record<string, string> {
|
||||
const basicAuth = Buffer.from(`x-access-token:${gitToken}`, 'utf8').toString('base64')
|
||||
|
||||
return {
|
||||
...createNoPromptGitEnv(),
|
||||
GITHUB_TOKEN: gitToken,
|
||||
GIT_CONFIG_COUNT: '1',
|
||||
GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
|
||||
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basicAuth}`
|
||||
}
|
||||
}
|
||||
|
||||
export function createGitEnvForRepoUrl(repoUrl: string, gitToken?: string): Record<string, string> {
|
||||
if (!gitToken) {
|
||||
return createNoPromptGitEnv()
|
||||
}
|
||||
|
||||
if (isGitHubHttpsUrl(repoUrl)) {
|
||||
return createGitHubGitEnv(gitToken)
|
||||
}
|
||||
|
||||
return createNoPromptGitEnv()
|
||||
return createGitEnv([{ name: 'GitHub', host: 'https://github.com/', token: gitToken }])
|
||||
}
|
||||
@@ -29,7 +29,9 @@ vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({
|
||||
getSettings: () => ({
|
||||
preferences: {
|
||||
gitToken: 'ghp_test_token',
|
||||
gitCredentials: [
|
||||
{ name: 'GitHub', host: 'https://github.com/', token: 'ghp_test_token' }
|
||||
],
|
||||
},
|
||||
updatedAt: Date.now(),
|
||||
}),
|
||||
|
||||
@@ -160,7 +160,7 @@ async function getProvidersFromOpenCodeServer(): Promise<{ providers: Provider[]
|
||||
|
||||
Object.entries(openCodeProvider.models).forEach(([modelId, openCodeModel]) => {
|
||||
models[modelId] = {
|
||||
id: openCodeModel.id,
|
||||
id: modelId,
|
||||
name: openCodeModel.name,
|
||||
attachment: openCodeModel.capabilities.attachment,
|
||||
reasoning: openCodeModel.capabilities.reasoning,
|
||||
@@ -232,7 +232,7 @@ async function getConfiguredProviders(connectedIds: Set<string>): Promise<Provid
|
||||
if (!modelConfig || typeof modelConfig !== "object") continue;
|
||||
|
||||
models.push({
|
||||
id: modelConfig.id || modelId,
|
||||
id: modelId,
|
||||
name: modelConfig.name || modelId,
|
||||
limit: modelConfig.limit ? {
|
||||
context: modelConfig.limit.context || 0,
|
||||
@@ -273,7 +273,7 @@ export async function getProvidersWithModels(): Promise<ProviderWithModels[]> {
|
||||
.map((provider) => {
|
||||
const models = Object.entries(provider.models || {}).map(([id, model]) => ({
|
||||
...model,
|
||||
id: model.id || id,
|
||||
id: id,
|
||||
name: model.name || id,
|
||||
}));
|
||||
return {
|
||||
|
||||
@@ -122,9 +122,4 @@ export const settingsApi = {
|
||||
const { data } = await axios.put(`${API_BASE_URL}/api/settings/agents-md`, { content })
|
||||
return data
|
||||
},
|
||||
|
||||
validateGitToken: async (gitToken: string): Promise<{ valid: boolean; message: string }> => {
|
||||
const { data } = await axios.post(`${API_BASE_URL}/api/settings/validate-git-token`, { gitToken })
|
||||
return data
|
||||
},
|
||||
}
|
||||
@@ -21,6 +21,13 @@ export interface CustomAgent {
|
||||
config: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface GitCredential {
|
||||
name: string
|
||||
host: string
|
||||
token: string
|
||||
username?: string
|
||||
}
|
||||
|
||||
export interface UserPreferences {
|
||||
theme: 'dark' | 'light' | 'system'
|
||||
mode: 'plan' | 'build'
|
||||
@@ -33,7 +40,7 @@ export interface UserPreferences {
|
||||
keyboardShortcuts: Record<string, string>
|
||||
customCommands: CustomCommand[]
|
||||
customAgents: CustomAgent[]
|
||||
gitToken?: string
|
||||
gitCredentials?: GitCredential[]
|
||||
tts?: TTSConfig
|
||||
}
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
|
||||
/>
|
||||
<p className="text-xs text-zinc-500">
|
||||
Full URL or GitHub shorthand format (owner/repo)
|
||||
Full URL or shorthand format (owner/repo for GitHub)
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -66,22 +66,21 @@ export function RepoCard({
|
||||
}`}
|
||||
>
|
||||
<div className="p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
{onSelect && (
|
||||
<div
|
||||
className="pt-0.5"
|
||||
onClick={(e) => handleActionClick(e, () => onSelect(repo.id, !isSelected))}
|
||||
>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={(checked) => onSelect(repo.id, checked === true)}
|
||||
className="w-5 h-5"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-1">
|
||||
{onSelect && (
|
||||
<div
|
||||
onClick={(e) => handleActionClick(e, () => onSelect(repo.id, !isSelected))}
|
||||
>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={(checked) => onSelect(repo.id, checked === true)}
|
||||
className="w-5 h-5"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="font-semibold text-base text-foreground truncate">
|
||||
{repoName}
|
||||
</h3>
|
||||
@@ -91,8 +90,10 @@ export function RepoCard({
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="flex flex-1 items-center gap-3">
|
||||
{isCloning ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin text-blue-500" />
|
||||
@@ -113,56 +114,56 @@ export function RepoCard({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
|
||||
<BranchSwitcher
|
||||
repoId={repo.id}
|
||||
currentBranch={branchToDisplay || ""}
|
||||
isWorktree={repo.isWorktree}
|
||||
repoUrl={repo.repoUrl}
|
||||
repoLocalPath={repo.localPath}
|
||||
iconOnly={true}
|
||||
className="h-8 w-8"
|
||||
/>
|
||||
<div className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
|
||||
<BranchSwitcher
|
||||
repoId={repo.id}
|
||||
currentBranch={branchToDisplay || ""}
|
||||
isWorktree={repo.isWorktree}
|
||||
repoUrl={repo.repoUrl}
|
||||
repoLocalPath={repo.localPath}
|
||||
iconOnly={true}
|
||||
className="h-8 w-8"
|
||||
/>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => handleActionClick(e, async () => {
|
||||
setIsDownloading(true);
|
||||
try {
|
||||
await downloadRepo(repo.id, repoName);
|
||||
showToast.success("Download complete");
|
||||
} catch (error: unknown) {
|
||||
showToast.error(error instanceof Error ? error.message : "Download failed");
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
})}
|
||||
disabled={!isReady || isDownloading}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
{isDownloading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => handleActionClick(e, async () => {
|
||||
setIsDownloading(true);
|
||||
try {
|
||||
await downloadRepo(repo.id, repoName);
|
||||
showToast.success("Download complete");
|
||||
} catch (error: unknown) {
|
||||
showToast.error(error instanceof Error ? error.message : "Download failed");
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
})}
|
||||
disabled={!isReady || isDownloading}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
{isDownloading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => handleActionClick(e, () => onDelete(repo.id))}
|
||||
disabled={isDeleting}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => handleActionClick(e, () => onDelete(repo.id))}
|
||||
disabled={isDeleting}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,44 +1,66 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { Loader2, Plus, Trash2, Save } from 'lucide-react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { X } from 'lucide-react'
|
||||
import { TTSSettings } from './TTSSettings'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { GitCredential } from '@/api/types/settings'
|
||||
|
||||
export function GeneralSettings() {
|
||||
const { preferences, isLoading, updateSettings, updateSettingsAsync, isUpdating } = useSettings()
|
||||
const [gitToken, setGitToken] = useState('')
|
||||
const [isValidatingToken, setIsValidatingToken] = useState(false)
|
||||
const [gitCredentials, setGitCredentials] = useState<GitCredential[]>([])
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [hasChanges, setHasChanges] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (preferences) {
|
||||
setGitToken(preferences.gitToken || '')
|
||||
setGitCredentials(preferences.gitCredentials || [])
|
||||
setHasChanges(false)
|
||||
}
|
||||
}, [preferences])
|
||||
|
||||
const validateGitToken = async (token: string): Promise<boolean> => {
|
||||
if (!token) return true
|
||||
const checkForChanges = (newCredentials: GitCredential[]) => {
|
||||
const currentCreds = JSON.stringify(preferences?.gitCredentials || [])
|
||||
const newCreds = JSON.stringify(newCredentials)
|
||||
setHasChanges(currentCreds !== newCreds)
|
||||
}
|
||||
|
||||
const addCredential = () => {
|
||||
const newCredentials = [...gitCredentials, { name: '', host: '', token: '', username: '' }]
|
||||
setGitCredentials(newCredentials)
|
||||
checkForChanges(newCredentials)
|
||||
}
|
||||
|
||||
const updateCredential = (index: number, field: keyof GitCredential, value: string) => {
|
||||
const newCredentials = [...gitCredentials]
|
||||
newCredentials[index] = { ...newCredentials[index], [field]: value }
|
||||
setGitCredentials(newCredentials)
|
||||
checkForChanges(newCredentials)
|
||||
}
|
||||
|
||||
const removeCredential = (index: number) => {
|
||||
const newCredentials = gitCredentials.filter((_, i) => i !== index)
|
||||
setGitCredentials(newCredentials)
|
||||
checkForChanges(newCredentials)
|
||||
}
|
||||
|
||||
const saveCredentials = async () => {
|
||||
const validCredentials = gitCredentials.filter(cred => cred.name && cred.host && cred.token)
|
||||
|
||||
setIsValidatingToken(true)
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const result = await settingsApi.validateGitToken(token)
|
||||
if (!result.valid) {
|
||||
showToast.error(result.message, { id: 'validate-token' })
|
||||
return false
|
||||
}
|
||||
showToast.success('GitHub token validated successfully', { id: 'validate-token' })
|
||||
return true
|
||||
showToast.loading('Saving credentials and restarting server...', { id: 'git-credentials' })
|
||||
await updateSettingsAsync({ gitCredentials: validCredentials })
|
||||
setHasChanges(false)
|
||||
showToast.success('Git credentials updated', { id: 'git-credentials' })
|
||||
} catch {
|
||||
showToast.error('Failed to validate GitHub token - please try again', { id: 'validate-token' })
|
||||
return false
|
||||
showToast.error('Failed to update git credentials', { id: 'git-credentials' })
|
||||
} finally {
|
||||
setIsValidatingToken(false)
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,12 +75,12 @@ export function GeneralSettings() {
|
||||
return (
|
||||
<div className="bg-card border border-border rounded-lg p-6">
|
||||
<h2 className="text-lg font-semibold text-foreground mb-6">General Preferences</h2>
|
||||
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="theme">Theme</Label>
|
||||
<Select
|
||||
value={preferences?.theme || 'dark'}
|
||||
<Select
|
||||
value={preferences?.theme || 'dark'}
|
||||
onValueChange={(value) => updateSettings({ theme: value as 'dark' | 'light' | 'system' })}
|
||||
>
|
||||
<SelectTrigger id="theme">
|
||||
@@ -77,8 +99,8 @@ export function GeneralSettings() {
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="mode">Mode</Label>
|
||||
<Select
|
||||
value={preferences?.mode || 'build'}
|
||||
<Select
|
||||
value={preferences?.mode || 'build'}
|
||||
onValueChange={(value) => updateSettings({ mode: value as 'plan' | 'build' })}
|
||||
>
|
||||
<SelectTrigger id="mode">
|
||||
@@ -150,65 +172,111 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="gitToken">GitHub Personal Access Token</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="gitToken"
|
||||
type="password"
|
||||
placeholder="ghp_..."
|
||||
value={gitToken}
|
||||
onChange={(e) => setGitToken(e.target.value)}
|
||||
disabled={isValidatingToken}
|
||||
onBlur={async () => {
|
||||
if (gitToken !== preferences?.gitToken) {
|
||||
showToast.loading('Validating GitHub token...', { id: 'validate-token' })
|
||||
|
||||
const isValid = await validateGitToken(gitToken)
|
||||
if (!isValid) {
|
||||
// Reset to previous value if validation failed
|
||||
setGitToken(preferences?.gitToken || '')
|
||||
return
|
||||
}
|
||||
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'restart-server' })
|
||||
try {
|
||||
await updateSettingsAsync({ gitToken })
|
||||
showToast.success('GitHub token updated', { id: 'restart-server' })
|
||||
} catch {
|
||||
showToast.error('Failed to update GitHub token', { id: 'restart-server' })
|
||||
setGitToken(preferences?.gitToken || '')
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
{isValidatingToken && (
|
||||
<div className="flex items-center justify-center w-10">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={async () => {
|
||||
setGitToken('')
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'restart-server' })
|
||||
try {
|
||||
await updateSettingsAsync({ gitToken: '' })
|
||||
showToast.success('GitHub token cleared', { id: 'restart-server' })
|
||||
} catch {
|
||||
showToast.error('Failed to clear GitHub token', { id: 'restart-server' })
|
||||
}
|
||||
}}
|
||||
disabled={!gitToken || isValidatingToken}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-foreground">Git Credentials</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Add credentials for cloning private repositories from any Git host
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{hasChanges && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={saveCredentials}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
|
||||
Save
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addCredential}
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Required for cloning private repos. Get one at github.com/settings/tokens
|
||||
|
||||
{gitCredentials.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-border p-6 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No git credentials configured. Click "Add" to add credentials for GitHub, GitLab, Gitea, or other Git hosts.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{gitCredentials.map((cred, index) => (
|
||||
<div key={index} className="rounded-lg border border-border p-4 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<Input
|
||||
placeholder="Credential name (e.g., GitHub Personal, Work GitLab)"
|
||||
value={cred.name}
|
||||
onChange={(e) => updateCredential(index, 'name', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground font-medium"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeCredential(index)}
|
||||
disabled={isSaving}
|
||||
className="ml-2 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs text-muted-foreground">Host URL</Label>
|
||||
<Input
|
||||
placeholder="https://github.com/"
|
||||
value={cred.host}
|
||||
onChange={(e) => updateCredential(index, 'host', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs text-muted-foreground">Username (optional)</Label>
|
||||
<Input
|
||||
placeholder="Auto-detected if empty"
|
||||
value={cred.username || ''}
|
||||
onChange={(e) => updateCredential(index, 'username', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label className="text-xs text-muted-foreground">Access Token</Label>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Personal access token"
|
||||
value={cred.token}
|
||||
onChange={(e) => updateCredential(index, 'token', e.target.value)}
|
||||
disabled={isSaving}
|
||||
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Username defaults: github.com uses "x-access-token", gitlab.com uses "oauth2". For other hosts, specify your username if required.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
Generated
+789
-795
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -2,4 +2,4 @@ packages:
|
||||
- 'shared'
|
||||
- 'backend'
|
||||
- 'frontend'
|
||||
- '!workspace/**'
|
||||
- '!workspace/**'
|
||||
@@ -60,6 +60,15 @@ export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
|
||||
selectModel: `${CMD_KEY}+M`,
|
||||
};
|
||||
|
||||
export const GitCredentialSchema = z.object({
|
||||
name: z.string(),
|
||||
host: z.string(),
|
||||
token: z.string(),
|
||||
username: z.string().optional(),
|
||||
});
|
||||
|
||||
export type GitCredential = z.infer<typeof GitCredentialSchema>;
|
||||
|
||||
export const UserPreferencesSchema = z.object({
|
||||
theme: z.enum(["dark", "light", "system"]),
|
||||
mode: z.enum(["plan", "build"]),
|
||||
@@ -72,7 +81,7 @@ export const UserPreferencesSchema = z.object({
|
||||
keyboardShortcuts: z.record(z.string(), z.string()),
|
||||
customCommands: z.array(CustomCommandSchema),
|
||||
customAgents: z.array(CustomAgentSchema),
|
||||
gitToken: z.string().optional(),
|
||||
gitCredentials: z.array(GitCredentialSchema).optional(),
|
||||
tts: TTSConfigSchema.optional(),
|
||||
lastKnownGoodConfig: z.string().optional(),
|
||||
});
|
||||
@@ -101,7 +110,7 @@ export const DEFAULT_USER_PREFERENCES = {
|
||||
keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
customCommands: [],
|
||||
customAgents: [],
|
||||
gitToken: undefined,
|
||||
gitCredentials: [] as GitCredential[],
|
||||
tts: DEFAULT_TTS_CONFIG,
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user