Merge pull request #2 from chriswritescode-dev/fix-env

fix: consolidate environment configuration and improve config management
This commit is contained in:
Chris Scott authored and GitHub committed 2025-11-25 10:36:49 -05:00
commit a1a8433f2c
38 files changed
+479 -545

No files matched your search

+17 -12
View File
@@ -1,27 +1,31 @@
# OpenCode WebUI Configuration
# Copy this file to .env and customize as needed
# Default values are defined in: shared/src/config/defaults.ts
# ============================================
# Backend Server (Hono API)
# Backend Server Configuration
# ============================================
PORT=8080
PORT=5001
HOST=0.0.0.0
CORS_ORIGIN=http://localhost:5173
NODE_ENV=development
LOG_LEVEL=info
# ============================================
# OpenCode Server
# ============================================
OPENCODE_SERVER_PORT=5551
OPENCODE_HOST=127.0.0.1
# ============================================
# Database
# ============================================
DATABASE_PATH=./backend/data/opencode.db
DATABASE_PATH=./data/opencode.db
# ============================================
# Workspace Configuration
# ============================================
# Local workspace path for repositories and configs
WORKSPACE_PATH=~./workspace
WORKSPACE_PATH=./workspace
# ============================================
# Timeouts (milliseconds)
@@ -32,9 +36,8 @@ HEALTH_CHECK_INTERVAL_MS=5000
HEALTH_CHECK_TIMEOUT_MS=30000
# ============================================
# File Upload Limits
# File Limits (MB)
# ============================================
# File size limits in MB
MAX_FILE_SIZE_MB=50
MAX_UPLOAD_SIZE_MB=50
@@ -44,9 +47,11 @@ MAX_UPLOAD_SIZE_MB=50
DEBUG=false
# ============================================
# Frontend Configuration (REQUIRED)
# Frontend Configuration (Vite)
# These are optional - frontend uses defaults if not set
# ============================================
# Backend API URL - frontend connects to this
# Must include full URL with port (e.g., http://localhost:8080)
VITE_API_URL=http://localhost:8080
# VITE_API_URL=http://localhost:5001
# VITE_SERVER_PORT=5001
# VITE_OPENCODE_PORT=5551
# VITE_MAX_FILE_SIZE_MB=50
# VITE_MAX_UPLOAD_SIZE_MB=50
+2 -2
View File
@@ -48,7 +48,7 @@ ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=5001
ENV OPENCODE_SERVER_PORT=5551
ENV DATABASE_PATH=/app/backend/data/opencode.db
ENV DATABASE_PATH=/app/data/opencode.db
ENV WORKSPACE_PATH=/workspace
COPY --from=builder /app/backend/dist ./backend/dist
@@ -61,7 +61,7 @@ COPY --from=builder /app/frontend/dist ./frontend/dist
COPY scripts/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
RUN mkdir -p /workspace /app/backend/data
RUN mkdir -p /workspace /app/data
EXPOSE 5001
-24
View File
@@ -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 || './backend/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 -1
View File
@@ -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 {
+4
View File
@@ -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
+126 -10
View File
@@ -6,20 +6,26 @@ 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'
import { ensureDirectoryExists, writeFileContent } from './services/file-operations'
import { SettingsService } from './services/settings'
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,
getOpenCodeConfigFilePath,
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()
@@ -31,6 +37,90 @@ app.use('/*', cors({
const db = initializeDatabase(DB_PATH)
const DEFAULT_OPENCODE_CONFIG = {
$schema: 'https://opencode.ai/config.json',
theme: 'opencode',
autoupdate: true,
share: 'disabled',
keybinds: {
leader: 'ctrl+x',
app_exit: 'ctrl+c,ctrl+d,<leader>q',
editor_open: '<leader>e',
theme_list: '<leader>t',
sidebar_toggle: '<leader>b',
status_view: '<leader>s',
session_export: '<leader>x',
session_new: '<leader>n',
session_list: '<leader>l',
session_timeline: '<leader>g',
session_share: 'none',
session_unshare: 'none',
session_interrupt: 'escape',
session_compact: '<leader>c',
messages_page_up: 'pageup',
messages_page_down: 'pagedown',
messages_half_page_up: 'ctrl+alt+u',
messages_half_page_down: 'ctrl+alt+d',
messages_first: 'ctrl+g,home',
messages_last: 'ctrl+alt+g,end',
messages_copy: '<leader>y',
messages_undo: '<leader>u',
messages_redo: '<leader>r',
messages_toggle_conceal: '<leader>h',
model_list: '<leader>m',
model_cycle_recent: 'f2',
model_cycle_recent_reverse: 'shift+f2',
command_list: 'ctrl+p',
agent_list: '<leader>a',
agent_cycle: 'tab',
agent_cycle_reverse: 'shift+tab',
input_clear: 'ctrl+c',
input_forward_delete: 'ctrl+d',
input_paste: 'ctrl+v',
input_submit: 'return',
input_newline: 'shift+return,ctrl+j',
history_previous: 'up',
history_next: 'down',
session_child_cycle: '<leader>right',
session_child_cycle_reverse: '<leader>left',
terminal_suspend: 'ctrl+z',
},
permission: {
bash: {
'*': 'allow',
},
},
}
async function ensureDefaultConfigExists(): Promise<void> {
const settingsService = new SettingsService(db)
const configs = settingsService.getOpenCodeConfigs()
if (configs.configs.length === 0) {
logger.info('No OpenCode configs found, creating default config')
settingsService.createOpenCodeConfig({
name: 'default',
content: DEFAULT_OPENCODE_CONFIG,
isDefault: true,
})
logger.info('Created default OpenCode config')
}
}
async function syncDefaultConfigToDisk(): Promise<void> {
const settingsService = new SettingsService(db)
const defaultConfig = settingsService.getDefaultOpenCodeConfig()
if (defaultConfig) {
const configPath = getOpenCodeConfigFilePath()
const configContent = JSON.stringify(defaultConfig.content, null, 2)
await writeFileContent(configPath, configContent)
logger.info(`Synced default config '${defaultConfig.name}' to: ${configPath}`)
} else {
logger.info('No default OpenCode config found in database')
}
}
try {
await ensureDirectoryExists(getWorkspacePath())
await ensureDirectoryExists(getReposPath())
@@ -40,6 +130,9 @@ try {
await cleanupOrphanedDirectories(db)
logger.info('Orphaned directory cleanup completed')
await ensureDefaultConfigExists()
await syncDefaultConfigToDisk()
await opencodeServerManager.start()
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
} catch (error) {
@@ -49,7 +142,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 +150,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 +179,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 +230,4 @@ serve({
hostname: HOST,
})
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
+14 -8
View File
@@ -4,10 +4,10 @@ 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 { getOpenCodeConfigFilePath } from '../config'
export function createRepoRoutes(database: Database) {
const app = new Hono()
@@ -33,10 +33,10 @@ export function createRepoRoutes(database: Database) {
const configContent = settingsService.getOpenCodeConfigContent(openCodeConfigName)
if (configContent) {
const workingDir = path.join(getReposPath(), repo.localPath)
const configPath = `${workingDir}/opencode.json`
await writeFileContent(configPath, configContent)
const openCodeConfigPath = getOpenCodeConfigFilePath()
await writeFileContent(openCodeConfigPath, configContent)
db.updateRepoConfigName(database, repo.id, openCodeConfigName)
logger.info(`Applied config '${openCodeConfigName}' to: ${openCodeConfigPath}`)
}
}
@@ -137,13 +137,19 @@ export function createRepoRoutes(database: Database) {
return c.json({ error: `Config '${configName}' not found` }, 404)
}
const workingDir = path.join(getReposPath(), repo.localPath)
const configPath = `${workingDir}/opencode.json`
const openCodeConfigPath = getOpenCodeConfigFilePath()
await writeFileContent(openCodeConfigPath, configContent)
await writeFileContent(configPath, configContent)
db.updateRepoConfigName(database, id, configName)
logger.info(`Switched config for repo ${id} to '${configName}'`)
logger.info(`Updated OpenCode config: ${openCodeConfigPath}`)
// 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)
-154
View File
@@ -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
}
+32 -5
View File
@@ -2,11 +2,12 @@ import { Hono } from 'hono'
import { z } from 'zod'
import type { Database } from 'bun:sqlite'
import { SettingsService } from '../services/settings'
import { writeFileContent } from '../services/file-operations'
import { patchOpenCodeConfig } from '../services/proxy'
import { getOpenCodeConfigFilePath } from '../config'
import {
UserPreferencesSchema,
OpenCodeConfigSchema,
OpenCodeConfigMetadataSchema,
CustomCommandSchema
} from '../types/settings'
import { logger } from '../utils/logger'
@@ -98,6 +99,16 @@ export function createSettingsRoutes(db: Database) {
const validated = CreateOpenCodeConfigSchema.parse(body)
const config = settingsService.createOpenCodeConfig(validated, userId)
if (config.isDefault) {
const configPath = getOpenCodeConfigFilePath()
const configContent = JSON.stringify(config.content, null, 2)
await writeFileContent(configPath, configContent)
logger.info(`Wrote default config to: ${configPath}`)
await patchOpenCodeConfig(config.content)
}
return c.json(config)
} catch (error) {
logger.error('Failed to create OpenCode config:', error)
@@ -120,6 +131,15 @@ export function createSettingsRoutes(db: Database) {
return c.json({ error: 'Config not found' }, 404)
}
if (config.isDefault) {
const configPath = getOpenCodeConfigFilePath()
const configContent = JSON.stringify(config.content, null, 2)
await writeFileContent(configPath, configContent)
logger.info(`Wrote default config to: ${configPath}`)
await patchOpenCodeConfig(config.content)
}
return c.json(config)
} catch (error) {
logger.error('Failed to update OpenCode config:', error)
@@ -157,6 +177,13 @@ export function createSettingsRoutes(db: Database) {
return c.json({ error: 'Config not found' }, 404)
}
const configPath = getOpenCodeConfigFilePath()
const configContent = JSON.stringify(config.content, null, 2)
await writeFileContent(configPath, configContent)
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
await patchOpenCodeConfig(config.content)
return c.json(config)
} catch (error) {
logger.error('Failed to set default OpenCode config:', error)
@@ -204,7 +231,7 @@ export function createSettingsRoutes(db: Database) {
return c.json({ error: 'Command with this name already exists' }, 409)
}
const updatedSettings = settingsService.updateSettings({
settingsService.updateSettings({
customCommands: [...settings.preferences.customCommands, validated]
}, userId)
@@ -238,7 +265,7 @@ export function createSettingsRoutes(db: Database) {
promptTemplate: validated.promptTemplate
}
const updatedSettings = settingsService.updateSettings({
settingsService.updateSettings({
customCommands: updatedCommands
}, userId)
@@ -264,7 +291,7 @@ export function createSettingsRoutes(db: Database) {
}
const updatedCommands = settings.preferences.customCommands.filter(cmd => cmd.name !== commandName)
const updatedSettings = settingsService.updateSettings({
settingsService.updateSettings({
customCommands: updatedCommands
}, userId)
+1 -1
View File
@@ -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 -1
View File
@@ -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 {
+1 -2
View File
@@ -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()
+10 -15
View File
@@ -1,12 +1,11 @@
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, getOpenCodeConfigFilePath, ENV } from '../config'
const OPENCODE_SERVER_PORT = ENV.OPENCODE_SERVER_PORT
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
const OPENCODE_CONFIG_PATH = getOpenCodeConfigFilePath()
class OpenCodeServerManager {
private static instance: OpenCodeServerManager
@@ -29,7 +28,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 +65,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: OPENCODE_CONFIG_PATH
}
}
)
if (!isDevelopment) {
this.serverProcess.unref()
}
this.serverPid = this.serverProcess.pid
logger.info(`OpenCode server started with PID ${this.serverPid}`)
@@ -131,7 +126,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
+23 -2
View File
@@ -1,7 +1,28 @@
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 patchOpenCodeConfig(config: Record<string, unknown>): Promise<boolean> {
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config),
})
if (response.ok) {
logger.info('Patched OpenCode config via API')
return true
}
logger.error(`Failed to patch OpenCode config: ${response.status} ${response.statusText}`)
return false
} catch (error) {
logger.error('Failed to patch OpenCode config:', error)
return false
}
}
export async function proxyRequest(request: Request) {
const url = new URL(request.url)
@@ -44,4 +65,4 @@ export async function proxyRequest(request: Request) {
headers: { 'Content-Type': 'application/json' },
})
}
}
}
+1 -1
View File
@@ -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(
+29 -3
View File
@@ -145,7 +145,13 @@ export class SettingsService {
const contentValidated = OpenCodeConfigSchema.parse(request.content)
const now = Date.now()
if (request.isDefault) {
const existingCount = this.db
.query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ?')
.get(userId) as { count: number }
const shouldBeDefault = request.isDefault || existingCount.count === 0
if (shouldBeDefault) {
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
@@ -160,7 +166,7 @@ export class SettingsService {
userId,
request.name,
JSON.stringify(contentValidated),
request.isDefault || false,
shouldBeDefault,
now,
now
)
@@ -169,7 +175,7 @@ export class SettingsService {
id: result.lastInsertRowid as number,
name: request.name,
content: contentValidated,
isDefault: request.isDefault || false,
isDefault: shouldBeDefault,
createdAt: now,
updatedAt: now,
}
@@ -240,6 +246,7 @@ export class SettingsService {
const deleted = result.changes > 0
if (deleted) {
logger.info(`Deleted OpenCode config '${configName}' for user: ${userId}`)
this.ensureSingleConfigIsDefault(userId)
}
return deleted
@@ -374,4 +381,23 @@ export class SettingsService {
return null
}
}
ensureSingleConfigIsDefault(userId: string = 'default'): void {
const hasDefault = this.db
.query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ? AND is_default = TRUE')
.get(userId) as { count: number }
if (hasDefault.count === 0) {
const firstConfig = this.db
.query('SELECT config_name FROM opencode_configs WHERE user_id = ? ORDER BY created_at ASC LIMIT 1')
.get(userId) as { config_name: string } | undefined
if (firstConfig) {
this.db
.query('UPDATE opencode_configs SET is_default = TRUE WHERE user_id = ? AND config_name = ?')
.run(userId, firstConfig.config_name)
logger.info(`Auto-set '${firstConfig.config_name}' as default (only config)`)
}
}
}
}
+4 -2
View File
@@ -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)
}
}
+2 -2
View File
@@ -13,14 +13,14 @@ services:
- HOST=0.0.0.0
- PORT=5001
- OPENCODE_SERVER_PORT=5551
- DATABASE_PATH=/app/backend/data/opencode.db
- DATABASE_PATH=/app/data/opencode.db
- WORKSPACE_PATH=/workspace
- DEBUG=true
volumes:
- ./backend:/app/backend
- ./shared:/app/shared
- opencode-workspace-dev:/workspace
- opencode-data-dev:/app/backend/data
- opencode-data-dev:/app/data
restart: unless-stopped
frontend:
+2 -2
View File
@@ -11,7 +11,7 @@ services:
- HOST=0.0.0.0
- PORT=5001
- OPENCODE_SERVER_PORT=5551
- DATABASE_PATH=/app/backend/data/opencode.db
- DATABASE_PATH=/app/data/opencode.db
- WORKSPACE_PATH=/workspace
- PROCESS_START_WAIT_MS=2000
- PROCESS_VERIFY_WAIT_MS=1000
@@ -24,7 +24,7 @@ services:
- DEBUG=false
volumes:
- opencode-workspace:/workspace
- opencode-data:/app/backend/data
- opencode-data:/app/data
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:5001/api/health"]
+23
View File
@@ -0,0 +1,23 @@
import { useQuery } from '@tanstack/react-query'
import { API_BASE_URL } from '@/constants/api'
import type { FileInfo } from '@/types/files'
const API_BASE = API_BASE_URL
async function fetchFile(path: string): Promise<FileInfo> {
const response = await fetch(`${API_BASE}/api/files/${path}`)
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
return response.json()
}
export function useFile(path: string | undefined) {
return useQuery({
queryKey: ['file', path],
queryFn: () => path ? fetchFile(path) : Promise.reject(new Error('No file path provided')),
enabled: !!path,
})
}
+1
View File
@@ -39,6 +39,7 @@ export interface Provider {
env: string[];
npm?: string;
models: Record<string, Model>;
options?: Record<string, unknown>;
}
export interface ProviderWithModels {
@@ -2,33 +2,18 @@ import { useState, useEffect, useRef, useCallback } from 'react'
import { FileTree } from './FileTree'
import { FileOperations } from './FileOperations'
import { FilePreview } from './FilePreview'
import { MobileFilePreviewModal } from './MobileFilePreviewModal'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
import { FolderOpen, Upload, RefreshCw } from 'lucide-react'
import type { FileInfo } from '@/types/files'
import { API_BASE_URL } from '@/constants/api'
import { useMobile } from '@/hooks/useMobile'
import { useFile } from '@/api/files'
const API_BASE = API_BASE_URL
// Hook to detect mobile screens
const useIsMobile = () => {
const [isMobile, setIsMobile] = useState(false)
useEffect(() => {
const checkIsMobile = () => {
setIsMobile(window.innerWidth < 768)
}
checkIsMobile()
window.addEventListener('resize', checkIsMobile)
return () => window.removeEventListener('resize', checkIsMobile)
}, [])
return isMobile
}
interface FileBrowserProps {
basePath?: string
@@ -48,42 +33,31 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false)
const dropZoneRef = useRef<HTMLDivElement>(null)
const isMobile = useIsMobile()
const isMobile = useMobile()
useEffect(() => {
if (initialSelectedFile) {
const loadInitialFile = async () => {
try {
const url = `${API_BASE}/api/files/${initialSelectedFile}`
const response = await fetch(url)
if (response.ok) {
const fileData = await response.json()
setSelectedFile(fileData)
if (isMobile) {
setIsPreviewModalOpen(true)
}
} else {
const errorText = await response.text()
console.error('[FileBrowser] Failed to load file:', errorText)
setError(`Failed to load file: ${errorText}`)
}
} catch (err) {
console.error('[FileBrowser] Failed to load initial file:', err)
setError(err instanceof Error ? err.message : 'Failed to load file')
}
}
loadInitialFile()
const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile)
useEffect(() => {
if (initialFileData) {
setSelectedFile(initialFileData)
if (isMobile) {
setIsPreviewModalOpen(true)
}
}, [initialSelectedFile, isMobile, basePath])
}
}, [initialFileData, isMobile])
useEffect(() => {
if (initialFileError) {
setError(initialFileError.message)
}
}, [initialFileError])
const loadFiles = async (path: string) => {
setLoading(true)
setError(null)
try {
const response = await fetch(`${API_BASE}/api/files/${path}`)
const response = await fetch(`${API_BASE_URL}/api/files/${path}`)
if (!response.ok) {
throw new Error(`Failed to load files: ${response.statusText}`)
}
@@ -107,7 +81,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
// Fetch the full file content when selecting a file
setLoading(true)
try {
const response = await fetch(`${API_BASE}/api/files/${file.path}`)
const response = await fetch(`${API_BASE_URL}/api/files/${file.path}`)
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
@@ -133,14 +107,6 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
setSelectedFile(null)
}
const handleTouchStart = (e: React.TouchEvent) => {
e.preventDefault()
}
const handleTouchEnd = (e: React.TouchEvent) => {
e.preventDefault()
}
const handleDirectoryClick = (path: string) => {
loadFiles(path)
}
@@ -154,7 +120,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
formData.append('file', files[0])
try {
const response = await fetch(`${API_BASE}/api/files/${currentPath}`, {
const response = await fetch(`${API_BASE_URL}/api/files/${currentPath}`, {
method: 'POST',
body: formData,
})
@@ -171,7 +137,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
const handleCreateFile = async (name: string, type: 'file' | 'folder') => {
try {
const response = await fetch(`${API_BASE}/api/files/${currentPath}/${name}`, {
const response = await fetch(`${API_BASE_URL}/api/files/${currentPath}/${name}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, content: type === 'file' ? '' : undefined }),
@@ -189,7 +155,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
const handleDelete = async (path: string) => {
try {
const response = await fetch(`${API_BASE}/api/files/${path}`, {
const response = await fetch(`${API_BASE_URL}/api/files/${path}`, {
method: 'DELETE',
})
@@ -206,7 +172,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
const handleRename = async (oldPath: string, newPath: string) => {
try {
const response = await fetch(`${API_BASE}/api/files/${oldPath}`, {
const response = await fetch(`${API_BASE_URL}/api/files/${oldPath}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ newPath }),
@@ -305,11 +271,11 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
)}
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className="flex-1 flex overflow-hidden">
<div className={`${isMobile ? 'w-full' : 'w-1/2'} border-r border-border px-4 flex flex-col`}>
<div className="flex-1 flex overflow-hidden min-h-0">
<div className={`${isMobile ? 'w-full' : 'w-1/2'} border-r border-border px-4 flex flex-col min-h-0`}>
<div className="flex items-center gap-2 mb-4 mt-4 flex-shrink-0">
<Input
placeholder="Search files..."
placeholder="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
@@ -330,7 +296,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
</div>
)}
<div className="flex-1 overflow-y-auto">
<div className="flex-1 overflow-y-auto min-h-0">
{loading ? (
<div className="flex items-center justify-center h-64">
<RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
@@ -352,7 +318,7 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 pl-4 overflow-y-auto">
<div className="flex-1 overflow-y-auto min-h-0 pb-8">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
@@ -365,17 +331,12 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
</div>
{/* Mobile: File Preview Modal */}
{isMobile && selectedFile && !selectedFile.isDirectory && (
<Dialog open={isPreviewModalOpen} onOpenChange={(open) => !open && handleCloseModal()}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col [&>button:last-child]:hidden"
>
<div className="flex-1 overflow-hidden min-h-0">
<FilePreview file={selectedFile} hideHeader={false} isMobileModal={true} onCloseModal={handleCloseModal} />
</div>
</DialogContent>
</Dialog>
)}
<MobileFilePreviewModal
isOpen={isMobile && isPreviewModalOpen}
onClose={handleCloseModal}
file={selectedFile}
showFilePreviewHeader={true}
/>
</div>
)
}
@@ -410,19 +371,6 @@ export function FileBrowser({ basePath = '', onFileSelect, embedded = false, ini
</Button>
</div>
<div className="flex items-center gap-2">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{error && (
<div className="text-sm text-destructive bg-destructive/10 p-2 rounded">
{error}
@@ -430,12 +378,12 @@ onUpload={handleUpload}
)}
</CardHeader>
<CardContent className="flex-1 flex overflow-hidden">
<CardContent className="flex-1 flex overflow-hidden min-h-0">
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className={`${isMobile ? 'w-full' : 'w-1/3'} border-r pr-4 flex flex-col`}>
<div className={`${isMobile ? 'w-full' : 'w-1/3'} border-r pr-4 flex flex-col min-h-0`}>
<div className="flex items-center gap-2 mb-4 flex-shrink-0">
<Input
placeholder="Search files..."
placeholder="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
@@ -452,7 +400,7 @@ onUpload={handleUpload}
<RefreshCw className="w-6 h-6 animate-spin" />
</div>
) : (
<div className="flex-1 overflow-y-auto">
<div className="flex-1 overflow-y-auto min-h-0">
<FileTree
files={filteredFiles || []}
onFileSelect={handleFileSelect}
@@ -469,7 +417,7 @@ onUpload={handleUpload}
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 pl-4 overflow-y-auto">
<div className="flex-1 overflow-y-auto min-h-0 ">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
@@ -483,34 +431,11 @@ onUpload={handleUpload}
</Card>
{/* Mobile: File Preview Modal */}
{isMobile && selectedFile && !selectedFile.isDirectory && (
<Dialog open={isPreviewModalOpen} onOpenChange={(open) => !open && handleCloseModal()}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col"
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
>
<DialogHeader className="p-4 border-b border-border flex-shrink-0 relative bg-background z-10">
<div className="flex justify-center mb-2">
<div className="w-8 h-1 bg-muted rounded-full"></div>
</div>
<DialogTitle className="text-foreground text-lg pr-12">
{selectedFile.name}
</DialogTitle>
<button
onClick={handleCloseModal}
className="absolute right-4 top-4 p-2 rounded-md hover:bg-muted text-foreground transition-colors touch-manipulation bg-muted border border-border"
aria-label="Close modal"
>
<X className="w-6 h-6" />
</button>
</DialogHeader>
<div className="flex-1 overflow-hidden min-h-0">
<FilePreview file={selectedFile} hideHeader={true} />
</div>
</DialogContent>
</Dialog>
)}
<MobileFilePreviewModal
isOpen={isMobile && isPreviewModalOpen}
onClose={handleCloseModal}
file={selectedFile}
/>
</div>
)
}
}
@@ -1,4 +1,4 @@
import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import { FileBrowser } from './FileBrowser'
import { Button } from '@/components/ui/button'
import { X } from 'lucide-react'
@@ -12,6 +12,7 @@ interface FileBrowserSheetProps {
}
export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, initialSelectedFile }: FileBrowserSheetProps) {
const [isEditing, setIsEditing] = useState(false)
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
@@ -20,13 +21,19 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini
}
}
const handleEditModeChange = (event: CustomEvent<{ isEditing: boolean }>) => {
setIsEditing(event.detail.isEditing)
}
if (isOpen) {
document.addEventListener('keydown', handleEscape)
document.addEventListener('editModeChange', handleEditModeChange as EventListener)
document.body.style.overflow = 'hidden'
}
return () => {
document.removeEventListener('keydown', handleEscape)
document.removeEventListener('editModeChange', handleEditModeChange as EventListener)
document.body.style.overflow = 'unset'
}
}, [isOpen, onClose])
@@ -49,14 +56,16 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini
</span>
)}
</div>
<Button
variant="ghost"
size="icon"
onClick={onClose}
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-all duration-200"
>
<X className="w-5 h-5" />
</Button>
{!isEditing && (
<Button
variant="ghost"
size="icon"
onClick={onClose}
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-all duration-200"
>
<X className="w-5 h-5" />
</Button>
)}
</div>
</div>
@@ -69,6 +69,8 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
const content = decodeBase64(file.content)
setEditContent(content)
setViewMode('edit')
const event = new CustomEvent('editModeChange', { detail: { isEditing: true } })
window.dispatchEvent(event)
} catch (err) {
console.error('Failed to load content for editing:', err)
}
@@ -89,6 +91,8 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
}
setViewMode('preview')
const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } })
window.dispatchEvent(editEvent)
const event = new CustomEvent('fileSaved', { detail: { path: file.path, content: editContent } })
window.dispatchEvent(event)
} catch (err) {
@@ -101,6 +105,8 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
const handleCancel = () => {
setEditContent('')
setViewMode('preview')
const event = new CustomEvent('editModeChange', { detail: { isEditing: false } })
window.dispatchEvent(event)
}
const isTextFile = file.mimeType?.startsWith('text/') ||
@@ -127,7 +133,7 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
className="text-sm bg-muted text-foreground p-4 rounded whitespace-pre-wrap font-mono break-words w-full resize-none focus:outline-none focus:ring-0 border-none block"
className="text-[16px] bg-muted text-foreground p-2 rounded whitespace-pre-wrap font-mono break-words w-full resize-none focus:outline-none focus:ring-0 border-none block"
style={{ minHeight: '95vh' }}
placeholder="Edit file content..."
autoFocus
@@ -139,7 +145,7 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
try {
const textContent = decodeBase64(file.content)
return (
<pre className="text-sm bg-muted text-foreground p-4 rounded whitespace-pre-wrap font-mono break-words overflow-x-hidden">
<pre className="pb-[200px] text-sm bg-muted text-foreground rounded whitespace-pre-wrap font-mono break-words overflow-x-hidden">
<code>{textContent}</code>
</pre>
)
@@ -222,4 +228,4 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
</div>
</div>
)
}
}
@@ -0,0 +1,57 @@
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { FilePreview } from "./FilePreview";
import { X } from "lucide-react";
import type { FileInfo } from "@/types/files";
interface MobileFilePreviewModalProps {
isOpen: boolean;
onClose: () => void;
file: FileInfo | null;
showFilePreviewHeader?: boolean;
}
export function MobileFilePreviewModal({
isOpen,
onClose,
file,
showFilePreviewHeader = false,
}: MobileFilePreviewModalProps) {
const handleTouchStart = (e: React.TouchEvent) => {
e.preventDefault();
};
const handleTouchEnd = (e: React.TouchEvent) => {
e.preventDefault();
};
if (!file || file.isDirectory) {
return null;
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()} hideCloseButton={true}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col"
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
>
<div
className={`flex-1 overflow-hidden min-h-0 ${showFilePreviewHeader ? "" : "pb-8"}`}
>
<FilePreview
file={file}
hideHeader={!showFilePreviewHeader}
isMobileModal={showFilePreviewHeader}
onCloseModal={onClose}
/>
</div>
</DialogContent>
</Dialog>
);
}
@@ -1,5 +1,5 @@
import { useState, useRef, useEffect, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell } from '@/hooks/useOpenCode'
import { useSendPrompt, useAbortSession, useMessages, useSendShell, useConfig } from '@/hooks/useOpenCode'
import { useSettings } from '@/hooks/useSettings'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
@@ -58,6 +58,7 @@ export function PromptInput({
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory)
const { data: messages } = useMessages(opcodeUrl, sessionID, directory)
const { data: config } = useConfig(opcodeUrl)
const { preferences, updateSettings } = useSettings()
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
@@ -370,10 +371,15 @@ export function PromptInput({
const hasActiveStream = messages?.some(msg => isMessageStreaming(msg)) || false
const currentMode = preferences?.mode || 'build'
const currentModel = preferences?.defaultModel || ''
const modeColor = currentMode === 'plan' ? 'text-yellow-600 dark:text-yellow-500' : 'text-green-600 dark:text-green-500'
const modeBg = currentMode === 'plan' ? 'bg-yellow-500/10 border-yellow-500/30' : 'bg-green-500/10 border-green-500/30'
const lastAssistantMessage = messages?.filter(msg => msg.info.role === 'assistant').pop()
const sessionModel = lastAssistantMessage?.info.role === 'assistant'
? `${lastAssistantMessage.info.providerID}/${lastAssistantMessage.info.modelID}`
: null
const currentModel = sessionModel || config?.model || ''
useEffect(() => {
const loadModelName = async () => {
if (currentModel) {
@@ -495,9 +501,9 @@ export function PromptInput({
<div className="flex gap-2 items-end">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
className={`w-16 px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
{currentMode.toUpperCase()}
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
@@ -24,7 +24,6 @@ interface SessionDetailHeaderProps {
repoDirectory: string | undefined;
onFileBrowserOpen: () => void;
onSettingsOpen: () => void;
onShowModelsDialog?: () => void;
}
export function SessionDetailHeader({
@@ -68,12 +67,12 @@ export function SessionDetailHeader({
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
{repoName}
</p>
<BranchSwitcher
repoId={repoId}
currentBranch={currentBranch}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
/>
<BranchSwitcher
repoId={repoId}
currentBranch={currentBranch}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
/>
</div>
</div>
</div>
@@ -56,7 +56,7 @@ export function AddProviderDialog({ open, onOpenChange }: AddProviderDialogProps
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
queryClient.invalidateQueries({ queryKey: ['opencode-providers'] })
queryClient.invalidateQueries({ queryKey: ['providers'] })
handleClose()
},
})
@@ -9,7 +9,7 @@ import { Loader2, Key, Check, X, Plus } from 'lucide-react'
import { providerCredentialsApi } from '@/api/providers'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { AddProviderDialog } from './AddProviderDialog'
import { useProviders } from '@/hooks/useProviders'
import { getProviders } from '@/api/providers'
export function ProviderSettings() {
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
@@ -18,7 +18,11 @@ export function ProviderSettings() {
const [addDialogOpen, setAddDialogOpen] = useState(false)
const queryClient = useQueryClient()
const { data: providers, isLoading: providersLoading } = useProviders()
const { data: providers, isLoading: providersLoading } = useQuery({
queryKey: ['providers'],
queryFn: () => getProviders(),
staleTime: 300000,
})
const { data: credentialsList, isLoading: credentialsLoading } = useQuery({
queryKey: ['provider-credentials'],
+1 -3
View File
@@ -1,3 +1 @@
export const API_BASE_URL = import.meta.env.VITE_API_URL || ''
export const OPENCODE_API_ENDPOINT = '/api/opencode'
export { API_BASE_URL, OPENCODE_API_ENDPOINT } from '../config'
-58
View File
@@ -1,58 +0,0 @@
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
const OPENCODE_URL = `${window.location.protocol}//${window.location.hostname}:5551`
interface ProviderModel {
id: string
name: string
attachment?: boolean
reasoning?: boolean
temperature?: boolean
tool_call?: boolean
cost?: {
input: number
output: number
cache_read?: number
cache_write?: number
}
limit?: {
context: number
output: number
}
modalities?: {
input: string[]
output: string[]
}
options?: Record<string, unknown>
}
interface Provider {
id: string
name: string
npm?: string
env?: string[]
models: Record<string, ProviderModel>
options?: {
baseURL?: string
[key: string]: unknown
}
}
interface ProvidersResponse {
providers: Provider[]
default: Record<string, string>
}
export function useProviders() {
return useQuery({
queryKey: ['opencode-providers'],
queryFn: async (): Promise<Provider[]> => {
const { data } = await axios.get<ProvidersResponse>(
`${OPENCODE_URL}/config/providers`
)
return data.providers
},
staleTime: 30000,
})
}
+1 -1
View File
@@ -31,7 +31,7 @@ export function RepoDetail() {
const opcodeUrl = repo ? OPENCODE_API_ENDPOINT : null;
const opcodeUrl = OPENCODE_API_ENDPOINT;
const repoDirectory = repo?.fullPath;
+1 -1
View File
@@ -40,7 +40,7 @@ export function SessionDetail() {
const opcodeUrl = repo ? OPENCODE_API_ENDPOINT : null;
const opcodeUrl = OPENCODE_API_ENDPOINT;
const repoDirectory = repo?.fullPath;
+16 -19
View File
@@ -1,40 +1,37 @@
import path from 'path'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
envDir: path.resolve(__dirname, '..'),
plugins: [
react(),
tailwindcss(),
],
envDir: path.resolve(__dirname, ".."),
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
"@": path.resolve(__dirname, "./src"),
},
},
server: {
host: '0.0.0.0',
host: "0.0.0.0",
port: 5173,
proxy: process.env.VITE_API_URL ? {
'/api': {
target: process.env.VITE_API_URL,
proxy: {
"/api": {
target: "http://localhost:5001",
changeOrigin: true,
},
} : undefined,
},
},
build: {
assetsInlineLimit: 4096,
rollupOptions: {
output: {
assetFileNames: (assetInfo) => {
if (assetInfo.name === 'manifest.json') {
return 'manifest.json';
if (assetInfo.name === "manifest.json") {
return "manifest.json";
}
return 'assets/[name]-[hash][extname]';
return "assets/[name]-[hash][extname]";
},
},
},
},
})
});
+6 -3
View File
@@ -3,15 +3,18 @@
import { writeFile } from 'fs/promises'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import {ENV} from '../backend/src/config'
const __dirname = dirname(fileURLToPath(import.meta.url))
const OPENCODE_SERVER_URL = process.env.OPENCODE_SERVER_URL || 'http://localhost:5561'
const OPENCODE_URL = ENV.VITE_API_URL + '/api/opencode'
async function generateOpenAPISpec() {
console.log(`📥 Fetching OpenAPI spec from ${OPENCODE_SERVER_URL}/doc...`)
console.log(`📥 Fetching OpenAPI spec from ${OPENCODE_URL}/doc`)
try {
const response = await fetch(`${OPENCODE_SERVER_URL}/doc`, {
const response = await fetch(`${OPENCODE_URL }/doc`, {
headers: {
'Accept': 'application/json'
}
+4 -1
View File
@@ -9,7 +9,10 @@
".": "./src/index.ts",
"./schemas": "./src/schemas/index.ts",
"./types": "./src/types/index.ts",
"./constants": "./src/constants.ts"
"./config": "./src/config/index.ts",
"./config/defaults": "./src/config/defaults.ts",
"./config/env": "./src/config/env.ts",
"./config/client": "./src/config/client.ts"
},
"dependencies": {
"dotenv": "^17.2.3",
-62
View File
@@ -1,62 +0,0 @@
import { config } from 'dotenv'
import path from 'path'
import os from 'os'
config({ path: '../.env' })
const getEnvNumber = (key: string, defaultValue: number): number => {
const value = process.env[key]
return value ? parseInt(value, 10) : defaultValue
}
const workspaceBasePath = process.env.WORKSPACE_PATH
? path.resolve(process.env.WORKSPACE_PATH)
: path.join(os.homedir(), '.opencode-workspace')
export const WORKSPACE = {
BASE_PATH: workspaceBasePath,
REPOS_DIR: 'repos',
CONFIG_DIR: 'config',
AUTH_FILE: '.opencode/state/opencode/auth.json',
} as const
export const getWorkspacePath = () => WORKSPACE.BASE_PATH
export const getReposPath = () => path.join(WORKSPACE.BASE_PATH, WORKSPACE.REPOS_DIR)
export const getConfigPath = () => path.join(WORKSPACE.BASE_PATH, WORKSPACE.CONFIG_DIR)
export const getAuthPath = () => path.join(WORKSPACE.BASE_PATH, WORKSPACE.AUTH_FILE)
export const TIMEOUTS = {
PROCESS_START_WAIT_MS: getEnvNumber('PROCESS_START_WAIT_MS', 2000),
PROCESS_VERIFY_WAIT_MS: getEnvNumber('PROCESS_VERIFY_WAIT_MS', 1000),
HEALTH_CHECK_INTERVAL_MS: getEnvNumber('HEALTH_CHECK_INTERVAL_MS', 5000),
HEALTH_CHECK_TIMEOUT_MS: getEnvNumber('HEALTH_CHECK_TIMEOUT_MS', 30000),
} as const
const maxFileSizeMB = getEnvNumber('MAX_FILE_SIZE_MB', 50)
const maxUploadSizeMB = getEnvNumber('MAX_UPLOAD_SIZE_MB', 50)
export const FILE_LIMITS = {
MAX_SIZE_BYTES: maxFileSizeMB * 1024 * 1024,
MAX_UPLOAD_SIZE_BYTES: maxUploadSizeMB * 1024 * 1024,
} as const
export const ALLOWED_MIME_TYPES = [
'text/plain',
'text/html',
'text/css',
'text/javascript',
'text/typescript',
'application/json',
'application/xml',
'image/png',
'image/jpeg',
'image/gif',
'image/svg+xml',
'application/pdf',
'application/zip',
] as const
export const GIT_PROVIDERS = {
GITHUB: 'github.com',
GITLAB: 'gitlab.com',
BITBUCKET: 'bitbucket.org',
} as const
+1 -1
View File
@@ -1,3 +1,3 @@
export * from './constants'
export * from './config'
export * from './schemas'
export * from './types'