mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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
+15
-10
@@ -1,16 +1,21 @@
|
||||
# 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=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
|
||||
@@ -20,8 +25,7 @@ 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
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 +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'
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -31,7 +31,7 @@ export function RepoDetail() {
|
||||
|
||||
|
||||
|
||||
const opcodeUrl = repo ? OPENCODE_API_ENDPOINT : null;
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
|
||||
|
||||
@@ -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
@@ -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]";
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
});
|
||||
@@ -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
@@ -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",
|
||||
|
||||
@@ -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
@@ -1,3 +1,3 @@
|
||||
export * from './constants'
|
||||
export * from './config'
|
||||
export * from './schemas'
|
||||
export * from './types'
|
||||
Reference in new issue
Block a user