diff --git a/backend/src/index.ts b/backend/src/index.ts index 7729e468..21b37830 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -135,6 +135,7 @@ try { await ensureDefaultConfigExists() await syncDefaultConfigToDisk() + opencodeServerManager.setDatabase(db) await opencodeServerManager.start() logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`) } catch (error) { diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index bd2ee7b5..2acf5c42 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -79,8 +79,18 @@ export function createSettingsRoutes(db: Database) { const body = await c.req.json() const validated = UpdateSettingsSchema.parse(body) + const currentSettings = settingsService.getSettings(userId) const settings = settingsService.updateSettings(validated.preferences, userId) - return c.json(settings) + + 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 + } + + return c.json({ ...settings, serverRestarted }) } catch (error) { logger.error('Failed to update settings:', error) if (error instanceof z.ZodError) { diff --git a/backend/src/services/git-operations.ts b/backend/src/services/git-operations.ts index 18e29b20..94aef729 100644 --- a/backend/src/services/git-operations.ts +++ b/backend/src/services/git-operations.ts @@ -1,5 +1,7 @@ import { executeCommand } from '../utils/process' import { logger } from '../utils/logger' +import { SettingsService } from './settings' +import type { Database } from 'bun:sqlite' import path from 'path' async function hasCommits(repoPath: string): Promise { @@ -11,6 +13,33 @@ async function hasCommits(repoPath: string): Promise { } } +function getGitEnvironment(database: Database): Record { + try { + const settingsService = new SettingsService(database) + const settings = settingsService.getSettings('default') + const gitToken = settings.preferences.gitToken + + if (gitToken) { + return { + GITHUB_TOKEN: gitToken, + GIT_ASKPASS: 'echo', + GIT_TERMINAL_PROMPT: '0' + } + } + + return { + GIT_ASKPASS: 'echo', + GIT_TERMINAL_PROMPT: '0' + } + } catch (error) { + logger.warn('Failed to get git token from settings:', error) + return { + GIT_ASKPASS: 'echo', + GIT_TERMINAL_PROMPT: '0' + } + } +} + export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied' export interface GitFileStatus { @@ -123,10 +152,11 @@ function parsePorcelainV2(output: string): { branch: string; ahead: number; behi return { branch, ahead, behind, files } } -export async function getGitStatus(repoPath: string): Promise { +export async function getGitStatus(repoPath: string, database?: Database): Promise { try { const fullPath = path.resolve(repoPath) - const output = await executeCommand(['git', '-C', fullPath, 'status', '--porcelain=v2', '--branch']) + const env = database ? getGitEnvironment(database) : undefined + const output = await executeCommand(['git', '-C', fullPath, 'status', '--porcelain=v2', '--branch'], { env }) const { branch, ahead, behind, files } = parsePorcelainV2(output) return { @@ -142,10 +172,10 @@ export async function getGitStatus(repoPath: string): Promise } } -export async function getFileDiff(repoPath: string, filePath: string): Promise { +export async function getFileDiff(repoPath: string, filePath: string, database?: Database): Promise { try { const fullRepoPath = path.resolve(repoPath) - const status = await getGitStatus(repoPath) + const status = await getGitStatus(repoPath, database) const fileStatus = status.files.find(f => f.path === filePath) if (!fileStatus) { @@ -164,9 +194,11 @@ export async function getFileDiff(repoPath: string, filePath: string): Promise 0) { logger.info(`OpenCode server already running on port ${OPENCODE_SERVER_PORT}`) @@ -79,7 +97,10 @@ class OpenCodeServerManager { env: { ...process.env, XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'), - OPENCODE_CONFIG: OPENCODE_CONFIG_PATH + OPENCODE_CONFIG: OPENCODE_CONFIG_PATH, + GITHUB_TOKEN: gitToken, + GIT_ASKPASS: 'echo', + GIT_TERMINAL_PROMPT: '0' } } ) diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index af1601e1..772c1221 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -17,6 +17,13 @@ async function hasCommits(repoPath: string): Promise { } } +function getAuthenticatedUrl(repoUrl: string, gitToken: string): string { + if (gitToken && repoUrl.startsWith('https://github.com')) { + return repoUrl.replace('https://', `https://${gitToken}@`) + } + return repoUrl +} + async function safeGetCurrentBranch(repoPath: string): Promise { try { const repoHasCommits = await hasCommits(repoPath) @@ -75,7 +82,18 @@ export async function initLocalRepo( logger.info(`Created directory for local repo: ${fullPath}`) logger.info(`Initializing git repository: ${fullPath}`) - await executeCommand(['git', 'init'], fullPath) + const settingsService = new SettingsService(database) + const settings = settingsService.getSettings('default') + const gitToken = settings.preferences.gitToken + const env: Record = gitToken ? + { + GITHUB_TOKEN: gitToken, + GIT_ASKPASS: 'echo', + GIT_TERMINAL_PROMPT: '0' + } : + { GIT_ASKPASS: 'echo', GIT_TERMINAL_PROMPT: '0' } + + await executeCommand(['git', 'init'], { cwd: fullPath }) if (branch && branch !== 'main') { await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branch]) @@ -158,9 +176,7 @@ export async function cloneRepo( const settings = settingsService.getSettings('default') const gitToken = settings.preferences.gitToken - let cloneUrl = gitToken && repoUrl.startsWith('https://github.com') - ? repoUrl.replace('https://', `https://${gitToken}@`) - : repoUrl + const cloneUrl = getAuthenticatedUrl(repoUrl, gitToken || '') if (shouldUseWorktree) { logger.info(`Creating worktree for branch: ${branch}`) @@ -201,7 +217,7 @@ export async function cloneRepo( } try { - const cloneCmd = ['git', 'clone', '-b', branch, cloneUrl, worktreeDirName] + const cloneCmd = ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] await executeCommand(cloneCmd, getReposPath()) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { @@ -210,7 +226,7 @@ export async function cloneRepo( } logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`) - const cloneCmd = ['git', 'clone', cloneUrl, worktreeDirName] + const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] await executeCommand(cloneCmd, getReposPath()) let localBranchExists = 'missing' try { @@ -292,8 +308,8 @@ export async function cloneRepo( try { const cloneCmd = branch - ? ['git', 'clone', '-b', branch, cloneUrl, worktreeDirName] - : ['git', 'clone', cloneUrl, worktreeDirName] + ? ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] + : ['git', 'clone', repoUrl, worktreeDirName] await executeCommand(cloneCmd, getReposPath()) } catch (error: any) { @@ -304,7 +320,7 @@ export async function cloneRepo( if (branch && (error.message.includes('Remote branch') || error.message.includes('not found'))) { logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`) - const cloneCmd = ['git', 'clone', cloneUrl, worktreeDirName] +const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] await executeCommand(cloneCmd, getReposPath()) let localBranchExists = 'missing' try { diff --git a/backend/src/utils/process.ts b/backend/src/utils/process.ts index 2c6cc1c0..e10b56b3 100644 --- a/backend/src/utils/process.ts +++ b/backend/src/utils/process.ts @@ -4,6 +4,7 @@ import { logger } from './logger' interface ExecuteCommandOptions { cwd?: string silent?: boolean + env?: Record } export async function executeCommand( @@ -19,7 +20,8 @@ export async function executeCommand( const proc: ChildProcess = spawn(command || '', cmdArgs, { cwd: options.cwd, - shell: false + shell: false, + env: { ...process.env, ...options.env } }) let stdout = '' diff --git a/bun.lockb b/bun.lockb index fb513b36..c1159041 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/frontend/package.json b/frontend/package.json index 3ea1f05d..79b67e6f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -50,7 +50,7 @@ "@types/react-dom": "^19.2.2", "@vitejs/plugin-react": "^5.0.4", "autoprefixer": "^10.4.21", - "eslint": "^9.36.0", + "eslint": "^9.39.1", "eslint-plugin-react-hooks": "^5.2.0", "eslint-plugin-react-refresh": "^0.4.22", "globals": "^16.4.0", diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 6e3dcfaf..afb3ba8b 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -46,6 +46,7 @@ export interface UserPreferences { export interface SettingsResponse { preferences: UserPreferences updatedAt: number + serverRestarted?: boolean } export interface UpdateSettingsRequest { diff --git a/frontend/src/components/settings/GeneralSettings.tsx b/frontend/src/components/settings/GeneralSettings.tsx index 984db30d..8186237a 100644 --- a/frontend/src/components/settings/GeneralSettings.tsx +++ b/frontend/src/components/settings/GeneralSettings.tsx @@ -6,9 +6,10 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ import { Switch } from '@/components/ui/switch' import { Input } from '@/components/ui/input' import { TTSSettings } from './TTSSettings' +import { showToast } from '@/lib/toast' export function GeneralSettings() { - const { preferences, isLoading, updateSettings, isUpdating } = useSettings() + const { preferences, isLoading, updateSettings, updateSettingsAsync, isUpdating } = useSettings() const [gitToken, setGitToken] = useState('') @@ -120,7 +121,17 @@ export function GeneralSettings() { placeholder="ghp_..." value={gitToken} onChange={(e) => setGitToken(e.target.value)} - onBlur={() => updateSettings({ gitToken })} + onBlur={async () => { + if (gitToken !== preferences?.gitToken) { + 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' }) + } + } + }} className="bg-background border-border text-foreground placeholder:text-muted-foreground" />

diff --git a/frontend/src/lib/toast.ts b/frontend/src/lib/toast.ts index 4ffb5ca3..e1a597a3 100644 --- a/frontend/src/lib/toast.ts +++ b/frontend/src/lib/toast.ts @@ -10,6 +10,12 @@ interface ToastOptions { id?: string | number } +interface PromiseToastMessages { + loading: string + success: string + error: string +} + export const showToast = { success: (message: string, options?: ToastOptions) => { return toast.success(message, options) @@ -31,6 +37,10 @@ export const showToast = { return toast.loading(message, options) }, + promise: (promise: Promise, messages: PromiseToastMessages) => { + return toast.promise(promise, messages) + }, + dismiss: (id?: string | number) => { toast.dismiss(id) }