mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
refactor: consolidate environment config and API handling
- Update database paths and port configuration - Remove backend config.ts and sessions route - Add mobile file preview and files API - Clean up shared constants and provider hooks
This commit is contained in:
1 parent
0db354048d
commit
8a56bc208d
32 files changed
+301
-512
No files matched your search
@@ -1,24 +0,0 @@
|
||||
import { config } from 'dotenv'
|
||||
|
||||
config()
|
||||
|
||||
export const ENV = {
|
||||
PORT: parseInt(process.env.PORT || '5001'),
|
||||
OPENCODE_SERVER_PORT: parseInt(process.env.OPENCODE_SERVER_PORT || '5551'),
|
||||
HOST: process.env.HOST || '0.0.0.0',
|
||||
DATABASE_PATH: process.env.DATABASE_PATH || './data/opencode.db',
|
||||
WORKSPACE_PATH: process.env.WORKSPACE_PATH || '~/.opencode-workspace',
|
||||
PROCESS_START_WAIT_MS: parseInt(process.env.PROCESS_START_WAIT_MS || '2000'),
|
||||
PROCESS_VERIFY_WAIT_MS: parseInt(process.env.PROCESS_VERIFY_WAIT_MS || '1000'),
|
||||
HEALTH_CHECK_INTERVAL_MS: parseInt(process.env.HEALTH_CHECK_INTERVAL_MS || '5000'),
|
||||
HEALTH_CHECK_TIMEOUT_MS: parseInt(process.env.HEALTH_CHECK_TIMEOUT_MS || '30000'),
|
||||
MAX_FILE_SIZE_MB: parseInt(process.env.MAX_FILE_SIZE_MB || '50'),
|
||||
MAX_UPLOAD_SIZE_MB: parseInt(process.env.MAX_UPLOAD_SIZE_MB || '50'),
|
||||
SANDBOX_TTL_HOURS: parseInt(process.env.SANDBOX_TTL_HOURS || '24'),
|
||||
CLEANUP_INTERVAL_MINUTES: parseInt(process.env.CLEANUP_INTERVAL_MINUTES || '60'),
|
||||
DEBUG: process.env.DEBUG === 'true',
|
||||
VITE_API_URL: process.env.VITE_API_URL || 'http://localhost:5001',
|
||||
VITE_ANTHROPIC_API_KEY: process.env.VITE_ANTHROPIC_API_KEY || '',
|
||||
VITE_OPENAI_API_KEY: process.env.VITE_OPENAI_API_KEY || '',
|
||||
VITE_GOOGLE_API_KEY: process.env.VITE_GOOGLE_API_KEY || ''
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { getReposPath } from '../../../shared/src/constants'
|
||||
import { getReposPath } from '../config'
|
||||
import path from 'path'
|
||||
|
||||
export interface RepoRow {
|
||||
|
||||
@@ -53,6 +53,10 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
|
||||
|
||||
runMigrations(db)
|
||||
|
||||
// Force database file creation by performing a write
|
||||
db.prepare('INSERT OR IGNORE INTO user_preferences (user_id, preferences, updated_at) VALUES (?, ?, ?)')
|
||||
.run('default', '{}', Date.now())
|
||||
|
||||
logger.info('Database initialized successfully')
|
||||
|
||||
return db
|
||||
|
||||
+36
-9
@@ -6,7 +6,7 @@ import { initializeDatabase } from './db/schema'
|
||||
import { createRepoRoutes } from './routes/repos'
|
||||
import { createSettingsRoutes } from './routes/settings'
|
||||
import { createHealthRoutes } from './routes/health'
|
||||
import { createSessionRoutes } from './routes/sessions'
|
||||
|
||||
import { createFileRoutes } from './routes/files'
|
||||
import { createProvidersRoutes } from './routes/providers'
|
||||
import { ensureDirectoryExists } from './services/file-operations'
|
||||
@@ -14,12 +14,16 @@ import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { cleanupOrphanedDirectories } from './services/repo'
|
||||
import { proxyRequest } from './services/proxy'
|
||||
import { logger } from './utils/logger'
|
||||
import { ENV } from './config'
|
||||
import { getWorkspacePath, getReposPath, getConfigPath } from '../../shared/src/constants'
|
||||
import {
|
||||
getWorkspacePath,
|
||||
getReposPath,
|
||||
getConfigPath,
|
||||
getDatabasePath,
|
||||
ENV
|
||||
} from './config'
|
||||
|
||||
await import('dotenv/config')
|
||||
|
||||
const { PORT, HOST, DATABASE_PATH: DB_PATH } = ENV
|
||||
const { PORT, HOST } = ENV.SERVER
|
||||
const DB_PATH = getDatabasePath()
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
@@ -49,7 +53,6 @@ try {
|
||||
app.route('/api/repos', createRepoRoutes(db))
|
||||
app.route('/api/settings', createSettingsRoutes(db))
|
||||
app.route('/api/health', createHealthRoutes(db))
|
||||
app.route('/api/sessions', createSessionRoutes())
|
||||
app.route('/api/files', createFileRoutes(db))
|
||||
app.route('/api/providers', createProvidersRoutes())
|
||||
|
||||
@@ -58,7 +61,7 @@ app.all('/api/opencode/*', async (c) => {
|
||||
return proxyRequest(request)
|
||||
})
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production'
|
||||
const isProduction = ENV.SERVER.NODE_ENV === 'production'
|
||||
|
||||
if (isProduction) {
|
||||
app.use('/*', async (c, next) => {
|
||||
@@ -87,6 +90,30 @@ if (isProduction) {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
app.get('/api/network-info', async (c) => {
|
||||
const os = await import('os')
|
||||
const interfaces = os.networkInterfaces()
|
||||
const ips = Object.values(interfaces)
|
||||
.flat()
|
||||
.filter(info => info && !info.internal && info.family === 'IPv4')
|
||||
.map(info => info!.address)
|
||||
|
||||
const requestHost = c.req.header('host') || `localhost:${PORT}`
|
||||
const protocol = c.req.header('x-forwarded-proto') || 'http'
|
||||
|
||||
return c.json({
|
||||
host: HOST,
|
||||
port: PORT,
|
||||
requestHost,
|
||||
protocol,
|
||||
availableIps: ips,
|
||||
apiUrls: [
|
||||
`${protocol}://localhost:${PORT}`,
|
||||
...ips.map(ip => `${protocol}://${ip}:${PORT}`)
|
||||
]
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
let isShuttingDown = false
|
||||
@@ -114,4 +141,4 @@ serve({
|
||||
hostname: HOST,
|
||||
})
|
||||
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
@@ -4,10 +4,11 @@ import * as db from '../db/queries'
|
||||
import * as repoService from '../services/repo'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { logger } from '../utils/logger'
|
||||
import { withTransactionAsync } from '../db/transactions'
|
||||
import path from 'path'
|
||||
import { getReposPath } from '../../../shared/src/constants'
|
||||
import { getReposPath, getWorkspacePath } from '../config'
|
||||
|
||||
export function createRepoRoutes(database: Database) {
|
||||
const app = new Hono()
|
||||
@@ -138,12 +139,25 @@ export function createRepoRoutes(database: Database) {
|
||||
}
|
||||
|
||||
const workingDir = path.join(getReposPath(), repo.localPath)
|
||||
const configPath = `${workingDir}/opencode.json`
|
||||
const workspaceConfigPath = `${getWorkspacePath()}/opencode.json`
|
||||
const repoConfigPath = `${workingDir}/opencode.json`
|
||||
|
||||
// Write to workspace as main config
|
||||
await writeFileContent(workspaceConfigPath, configContent)
|
||||
|
||||
// Also write to repo directory for repo-specific usage
|
||||
await writeFileContent(repoConfigPath, configContent)
|
||||
|
||||
await writeFileContent(configPath, configContent)
|
||||
db.updateRepoConfigName(database, id, configName)
|
||||
|
||||
logger.info(`Switched config for repo ${id} to '${configName}'`)
|
||||
logger.info(`Updated workspace config: ${workspaceConfigPath}`)
|
||||
logger.info(`Updated repo config: ${repoConfigPath}`)
|
||||
|
||||
// Restart OpenCode server to pick up new workspace config
|
||||
logger.info('Restarting OpenCode server due to workspace config change')
|
||||
await opencodeServerManager.stop()
|
||||
await opencodeServerManager.start()
|
||||
|
||||
const updatedRepo = db.getRepoById(database, id)
|
||||
return c.json(updatedRepo)
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
import { Hono } from 'hono'
|
||||
import { logger } from '../utils/logger'
|
||||
import { ENV } from '../config'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE_SERVER_PORT
|
||||
|
||||
export function createSessionRoutes() {
|
||||
const app = new Hono()
|
||||
|
||||
app.post('/', async (c) => {
|
||||
const body = await c.req.json()
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Session creation failed: ${response.status} ${response.statusText}`)
|
||||
return c.json({ error: 'Session creation failed', status: response.status }, response.status as any)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return c.json(data)
|
||||
} catch (error) {
|
||||
logger.error('Failed to create session:', error)
|
||||
return c.json({ error: 'Failed to create session' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:sessionID/command', async (c) => {
|
||||
const sessionID = c.req.param('sessionID')
|
||||
const body = await c.req.json()
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/command`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Command failed: ${response.status} ${response.statusText}`)
|
||||
return c.json({ error: 'Command failed', status: response.status }, response.status as any)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return c.json(data)
|
||||
} catch (error) {
|
||||
logger.error('Failed to send command:', error)
|
||||
return c.json({ error: 'Failed to send command' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:sessionID/shell', async (c) => {
|
||||
const sessionID = c.req.param('sessionID')
|
||||
const body = await c.req.json()
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/shell`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Shell command failed: ${response.status} ${response.statusText}`)
|
||||
return c.json({ error: 'Shell command failed', status: response.status }, response.status as any)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return c.json(data)
|
||||
} catch (error) {
|
||||
logger.error('Failed to send shell command:', error)
|
||||
return c.json({ error: 'Failed to send shell command' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:sessionID/abort', async (c) => {
|
||||
const sessionID = c.req.param('sessionID')
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/abort`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Abort failed: ${response.status} ${response.statusText}`)
|
||||
return c.json({ error: 'Abort failed', status: response.status }, response.status as any)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return c.json(data)
|
||||
} catch (error) {
|
||||
logger.error('Failed to abort session:', error)
|
||||
return c.json({ error: 'Failed to abort session' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:sessionID/message', async (c) => {
|
||||
const sessionID = c.req.param('sessionID')
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/message`)
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Get messages failed: ${response.status} ${response.statusText}`)
|
||||
return c.json({ error: 'Get messages failed', status: response.status }, response.status as any)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return c.json(data)
|
||||
} catch (error) {
|
||||
logger.error('Failed to get messages:', error)
|
||||
return c.json({ error: 'Failed to get messages' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:sessionID/message', async (c) => {
|
||||
const sessionID = c.req.param('sessionID')
|
||||
const body = await c.req.json()
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/session/${sessionID}/message`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.error(`Send message failed: ${response.status} ${response.statusText}`)
|
||||
return c.json({ error: 'Send message failed', status: response.status }, response.status as any)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return c.json(data)
|
||||
} catch (error) {
|
||||
logger.error('Failed to send message:', error)
|
||||
return c.json({ error: 'Failed to send message' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
OpenCodeConfigSchema,
|
||||
@@ -98,6 +99,14 @@ export function createSettingsRoutes(db: Database) {
|
||||
const validated = CreateOpenCodeConfigSchema.parse(body)
|
||||
|
||||
const config = settingsService.createOpenCodeConfig(validated, userId)
|
||||
|
||||
// Restart OpenCode server if this is the new default config
|
||||
if (validated.isDefault) {
|
||||
logger.info('Restarting OpenCode server with new default config')
|
||||
await opencodeServerManager.stop()
|
||||
await opencodeServerManager.start()
|
||||
}
|
||||
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to create OpenCode config:', error)
|
||||
@@ -120,6 +129,13 @@ export function createSettingsRoutes(db: Database) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
// Restart OpenCode server if config was set as default
|
||||
if (validated.isDefault) {
|
||||
logger.info('Restarting OpenCode server with updated default config')
|
||||
await opencodeServerManager.stop()
|
||||
await opencodeServerManager.start()
|
||||
}
|
||||
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to update OpenCode config:', error)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { getAuthPath } from '../../../shared/src/constants'
|
||||
import { getAuthPath } from '../config'
|
||||
import { logger } from '../utils/logger'
|
||||
import { AuthCredentialsSchema } from '../../../shared/src/schemas/auth'
|
||||
import type { z } from 'zod'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getWorkspacePath, getReposPath } from '../../../shared/src/constants'
|
||||
import { getReposPath } from '../config'
|
||||
|
||||
export async function readFileContent(filePath: string): Promise<string> {
|
||||
try {
|
||||
|
||||
@@ -11,8 +11,7 @@ import {
|
||||
getFileStats,
|
||||
listDirectory
|
||||
} from './file-operations'
|
||||
import { FILE_LIMITS, ALLOWED_MIME_TYPES } from '../../../shared/src/constants'
|
||||
import { getReposPath } from '../../../shared/src/constants'
|
||||
import { FILE_LIMITS, ALLOWED_MIME_TYPES, getReposPath } from '../config'
|
||||
|
||||
const SHARED_WORKSPACE_BASE = getReposPath()
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { spawn } from 'child_process'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getWorkspacePath } from '../../../shared/src/constants'
|
||||
import { execSync } from 'child_process'
|
||||
import { ENV } from '../config'
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getWorkspacePath, ENV } from '../config'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE_SERVER_PORT
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
|
||||
|
||||
class OpenCodeServerManager {
|
||||
@@ -29,7 +27,7 @@ class OpenCodeServerManager {
|
||||
return
|
||||
}
|
||||
|
||||
const isDevelopment = process.env.NODE_ENV !== 'production'
|
||||
const isDevelopment = ENV.SERVER.NODE_ENV !== 'production'
|
||||
|
||||
const existingProcesses = await this.findProcessesByPort(OPENCODE_SERVER_PORT)
|
||||
if (existingProcesses.length > 0) {
|
||||
@@ -66,29 +64,25 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`Starting OpenCode server on port ${OPENCODE_SERVER_PORT} (${isDevelopment ? 'development' : 'production'} mode)`)
|
||||
logger.info(`OpenCode server working directory: ${OPENCODE_SERVER_DIRECTORY}`)
|
||||
logger.info(`OpenCode will use ?directory= parameter for session isolation`)
|
||||
|
||||
const hostname = isDevelopment ? '0.0.0.0' : '127.0.0.1'
|
||||
|
||||
this.serverProcess = spawn(
|
||||
'opencode',
|
||||
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', hostname],
|
||||
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', '127.0.0.1'],
|
||||
{
|
||||
cwd: OPENCODE_SERVER_DIRECTORY,
|
||||
detached: !isDevelopment,
|
||||
stdio: isDevelopment ? 'inherit' : 'ignore',
|
||||
env: {
|
||||
...process.env,
|
||||
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state')
|
||||
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'),
|
||||
OPENCODE_CONFIG: path.join(OPENCODE_SERVER_DIRECTORY, '.config/opencode/opencode.json')
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (!isDevelopment) {
|
||||
this.serverProcess.unref()
|
||||
}
|
||||
this.serverPid = this.serverProcess.pid
|
||||
|
||||
logger.info(`OpenCode server started with PID ${this.serverPid}`)
|
||||
@@ -131,7 +125,7 @@ class OpenCodeServerManager {
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`http://localhost:${OPENCODE_SERVER_PORT}/doc`, {
|
||||
const response = await fetch(`http://127.0.0.1:${OPENCODE_SERVER_PORT}/doc`, {
|
||||
signal: AbortSignal.timeout(3000)
|
||||
})
|
||||
return response.ok
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { logger } from '../utils/logger'
|
||||
import { ENV } from '../config'
|
||||
|
||||
const OPENCODE_SERVER_URL = `http://localhost:${ENV.OPENCODE_SERVER_PORT}`
|
||||
const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}`
|
||||
|
||||
export async function proxyRequest(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
@@ -44,4 +44,4 @@ export async function proxyRequest(request: Request) {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 { getReposPath } from '../../../shared/src/constants'
|
||||
import { getReposPath } from '../config'
|
||||
import path from 'path'
|
||||
|
||||
export async function cloneRepo(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ENV } from '../config'
|
||||
|
||||
type LogLevel = 'info' | 'warn' | 'error' | 'debug'
|
||||
|
||||
class Logger {
|
||||
@@ -7,7 +9,7 @@ class Logger {
|
||||
this.prefix = prefix
|
||||
}
|
||||
|
||||
private format(level: LogLevel, message: string, ...args: unknown[]): string {
|
||||
private format(level: LogLevel, message: string): string {
|
||||
const timestamp = new Date().toISOString()
|
||||
const prefixStr = this.prefix ? `[${this.prefix}] ` : ''
|
||||
return `[${timestamp}] [${level.toUpperCase()}] ${prefixStr}${message}`
|
||||
@@ -26,7 +28,7 @@ class Logger {
|
||||
}
|
||||
|
||||
debug(message: string, ...args: unknown[]): void {
|
||||
if (process.env.DEBUG) {
|
||||
if (ENV.LOGGING.DEBUG) {
|
||||
console.debug(this.format('debug', message), ...args)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user