mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(settings): harden config directory replace and consolidate upload plumbing
Validate the config before any filesystem work and persist the default row only after the directory swap succeeds; reject oversize uploads before buffering and stream parts to staging; re-ensure AGENTS.md after a replace. Consolidate the upload contract in shared, unify the default-config upsert, single-own the browser directory-upload and restart state, and drop dead code.
This commit is contained in:
1 parent
b1bccb3dd5
commit
39d2b98370
36 files changed
+1098
-510
No files matched your search
@@ -25,7 +25,6 @@
|
||||
"croner": "^10.0.1",
|
||||
"eventsource": "^4.1.0",
|
||||
"hono": "^4.11.7",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"web-push": "^3.6.7",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
|
||||
+6
-21
@@ -41,7 +41,9 @@ import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
import { SettingsService, DEFAULT_SEED_OPENCODE_CONFIG } from './services/settings'
|
||||
import { sweepStaleOpenCodeConfigDirectoryDirs } from './services/opencode-config-directory'
|
||||
import { ensureDefaultAgentsMdExists } from './services/agents-md'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { NotificationService } from './services/notification'
|
||||
@@ -66,7 +68,6 @@ import {
|
||||
getReposPath,
|
||||
getConfigPath,
|
||||
getOpenCodeConfigFilePath,
|
||||
getAgentsMdPath,
|
||||
getDatabasePath,
|
||||
ENV
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
@@ -104,8 +105,6 @@ const auth = createAuth(db)
|
||||
const requireAuth = createAuthMiddleware(auth)
|
||||
const openCodeClient = createOpenCodeClient(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
|
||||
import { DEFAULT_AGENTS_MD } from './constants'
|
||||
|
||||
let ipcServer: IPCServer | undefined
|
||||
const gitAuthService = new GitAuthService()
|
||||
let openCodeSupervisor: OpenCodeSupervisor | undefined
|
||||
@@ -150,13 +149,8 @@ async function ensureDefaultConfigExists(): Promise<void> {
|
||||
}
|
||||
|
||||
logger.info('No existing config found, creating minimal seed config')
|
||||
const seedConfig = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: seedConfig,
|
||||
isDefault: true,
|
||||
})
|
||||
await writeFileContent(workspaceConfigPath, seedConfig)
|
||||
settingsService.upsertDefaultOpenCodeConfig(DEFAULT_SEED_OPENCODE_CONFIG)
|
||||
await writeFileContent(workspaceConfigPath, DEFAULT_SEED_OPENCODE_CONFIG)
|
||||
logger.info('Created minimal seed config')
|
||||
}
|
||||
|
||||
@@ -216,16 +210,6 @@ async function ensureHomeStateImported(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureDefaultAgentsMdExists(): Promise<void> {
|
||||
const agentsMdPath = getAgentsMdPath()
|
||||
const exists = await fileExists(agentsMdPath)
|
||||
|
||||
if (!exists) {
|
||||
await writeFileContent(agentsMdPath, DEFAULT_AGENTS_MD)
|
||||
logger.info(`Created default AGENTS.md at: ${agentsMdPath}`)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (ENV.SERVER.NODE_ENV === 'production' && !ENV.AUTH.SECRET) {
|
||||
logger.error('AUTH_SECRET is required in production mode')
|
||||
@@ -241,6 +225,7 @@ try {
|
||||
|
||||
await cleanupExpiredCache()
|
||||
await sweepStaleUploadSessions()
|
||||
await sweepStaleOpenCodeConfigDirectoryDirs()
|
||||
|
||||
await ensureDefaultConfigExists()
|
||||
await backfillOpenCodeModelStateFromFile()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Hono, type Context } from 'hono'
|
||||
import { bodyLimit } from 'hono/body-limit'
|
||||
import { z } from 'zod'
|
||||
import { execSync, spawnSync } from 'child_process'
|
||||
import { randomUUID } from 'crypto'
|
||||
@@ -39,7 +40,8 @@ import { encryptSecret } from '../utils/crypto'
|
||||
import { compareVersions, isValidVersion } from '../utils/version-utils'
|
||||
import { getImportedSessionDirectories, getOpenCodeImportStatus, OpenCodeImportProtectionError, syncOpenCodeImport } from '../services/opencode-import'
|
||||
import { relinkReposFromSessionDirectories } from '../services/repo'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { ENV, FILE_LIMITS } from '@opencode-manager/shared/config/env'
|
||||
import { MAX_OPENCODE_CONFIG_DIRECTORY_FILES, OPENCODE_CONFIG_UPLOAD_ERRORS } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
listManagedSkills,
|
||||
getSkill,
|
||||
@@ -50,6 +52,7 @@ import {
|
||||
installSkillFromUploadedFiles,
|
||||
} from '../services/skills'
|
||||
import { replaceOpenCodeConfigDirectory } from '../services/opencode-config-directory'
|
||||
import { ensureDefaultAgentsMdExists } from '../services/agents-md'
|
||||
import {
|
||||
installOpenCodeDirectoryFiles,
|
||||
listOpenCodeDirectoryFiles,
|
||||
@@ -57,7 +60,7 @@ import {
|
||||
updateOpenCodeDirectoryFile,
|
||||
deleteOpenCodeDirectoryFile,
|
||||
} from '../services/opencode-directory-files'
|
||||
import { parseUploadManifest, readUploadedManifestFiles, UploadValidationError } from './upload-utils'
|
||||
import { parseUploadManifest, parseUploadPreamble, readUploadedManifestFiles, resolveUploadedManifestFiles, UploadValidationError, UPLOAD_PATH_ERROR_STATUS } from './upload-utils'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { githubFetch } from '../utils/github'
|
||||
|
||||
@@ -147,25 +150,16 @@ async function reloadAfterSkillInstall(
|
||||
|
||||
const OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS: ReadonlyArray<readonly [string, 400]> = [
|
||||
['No markdown', 400],
|
||||
['Path must be relative', 400],
|
||||
['Path must not contain', 400],
|
||||
['Path must reference', 400],
|
||||
['escapes', 400],
|
||||
['Missing upload file', 400],
|
||||
['not a valid file', 400],
|
||||
...UPLOAD_PATH_ERROR_STATUS,
|
||||
]
|
||||
|
||||
const OPENCODE_CONFIG_DIRECTORY_REPLACE_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 413]> = [
|
||||
['No files were provided', 400],
|
||||
['must contain opencode.json', 400],
|
||||
['too many files', 400],
|
||||
['contains too many files', 400],
|
||||
['exceed maximum upload size', 413],
|
||||
['Path must be relative', 400],
|
||||
['Path must not contain', 400],
|
||||
['escapes', 400],
|
||||
['Missing upload file', 400],
|
||||
['not a valid file', 400],
|
||||
...UPLOAD_PATH_ERROR_STATUS,
|
||||
]
|
||||
|
||||
function matchErrorStatus<T extends number>(
|
||||
@@ -204,14 +198,10 @@ const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 404 | 40
|
||||
['Invalid skill name', 400],
|
||||
['Only one skill', 400],
|
||||
['Skill source must contain', 400],
|
||||
['Path must be relative', 400],
|
||||
['Path must not contain', 400],
|
||||
['escapes', 400],
|
||||
['no downloadable files', 400],
|
||||
['repoId is required', 400],
|
||||
['Missing upload file', 400],
|
||||
['Invalid repoId', 400],
|
||||
['not a valid file', 400],
|
||||
...UPLOAD_PATH_ERROR_STATUS,
|
||||
]
|
||||
|
||||
function didConfigFieldChange(
|
||||
@@ -1280,15 +1270,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
app.post('/opencode-directory-files/install', async (c) => {
|
||||
try {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
if (!contentType.includes('multipart/form-data')) {
|
||||
return c.json({ error: 'Unsupported content type. Use multipart/form-data' }, 400)
|
||||
}
|
||||
|
||||
const formData = await c.req.parseBody({ all: true })
|
||||
const { formData, manifest } = await parseUploadPreamble(c)
|
||||
const kind = z.enum(['agents', 'commands']).parse(formData['kind'])
|
||||
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
const markdownManifest = getMarkdownUploadManifest(manifest)
|
||||
if (markdownManifest.length === 0) {
|
||||
return c.json({ error: `No markdown ${kind} files found` }, 400)
|
||||
@@ -1322,40 +1306,50 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
app.use('/opencode-config-directory/replace', bodyLimit({
|
||||
maxSize: FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES,
|
||||
onError: (c) => c.json({ error: OPENCODE_CONFIG_UPLOAD_ERRORS.EXCEEDS_MAX_UPLOAD_SIZE }, 413),
|
||||
}))
|
||||
|
||||
app.post('/opencode-config-directory/replace', async (c) => {
|
||||
try {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
if (!contentType.includes('multipart/form-data')) {
|
||||
return c.json({ error: 'Unsupported content type. Use multipart/form-data' }, 400)
|
||||
}
|
||||
|
||||
const formData = await c.req.parseBody({ all: true })
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
|
||||
let manifest: ReturnType<typeof parseUploadManifest>
|
||||
let preamble: Awaited<ReturnType<typeof parseUploadPreamble>>
|
||||
try {
|
||||
manifest = parseUploadManifest(formData['fileManifest'])
|
||||
preamble = await parseUploadPreamble(c)
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid upload manifest', details: error.issues }, 400)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
const { formData, manifest } = preamble
|
||||
|
||||
if (manifest.length === 0) {
|
||||
return c.json({ error: 'fileManifest must contain at least one entry' }, 400)
|
||||
}
|
||||
if (manifest.length > MAX_OPENCODE_CONFIG_DIRECTORY_FILES) {
|
||||
return c.json({ error: OPENCODE_CONFIG_UPLOAD_ERRORS.TOO_MANY_FILES }, 400)
|
||||
}
|
||||
|
||||
const files = await readUploadedManifestFiles(formData, manifest)
|
||||
const files = resolveUploadedManifestFiles(formData, manifest)
|
||||
|
||||
settingsService.saveLastKnownGoodConfig(userId)
|
||||
|
||||
const result = await replaceOpenCodeConfigDirectory(db, files, userId)
|
||||
|
||||
try {
|
||||
await ensureDefaultAgentsMdExists()
|
||||
} catch (error) {
|
||||
logger.warn('Failed to ensure AGENTS.md after OpenCode config directory replace', error)
|
||||
}
|
||||
|
||||
opencodeServerManager.markRestartPending()
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'OpenCode config directory replace')
|
||||
|
||||
return c.json({ ...result, restartRequired: true })
|
||||
return c.json(result)
|
||||
} catch (error) {
|
||||
logger.error('Failed to replace OpenCode config directory:', error)
|
||||
|
||||
@@ -1457,14 +1451,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
const formData = await c.req.parseBody({ all: true })
|
||||
const { formData, manifest } = await parseUploadPreamble(c)
|
||||
|
||||
const scope = formData['scope']
|
||||
const repoIdValue = formData['repoId']
|
||||
const overwriteValue = formData['overwrite']
|
||||
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
|
||||
const repoId = parseOptionalRepoId(repoIdValue as string | undefined)
|
||||
const overwrite = parseBooleanFormValue(overwriteValue)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { InstallSkillUploadManifestEntrySchema, type InstallSkillUploadManifestEntry } from '@opencode-manager/shared'
|
||||
import type { Context } from 'hono'
|
||||
|
||||
export class UploadValidationError extends Error {}
|
||||
|
||||
@@ -19,23 +20,53 @@ export function parseUploadManifest(fileManifestRaw: unknown): InstallSkillUploa
|
||||
return InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries)
|
||||
}
|
||||
|
||||
export async function readUploadedManifestFiles(
|
||||
export async function parseUploadPreamble(c: Context): Promise<{ formData: ParsedFormData; manifest: InstallSkillUploadManifestEntry[] }> {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
if (!contentType.includes('multipart/form-data')) {
|
||||
throw new UploadValidationError('Unsupported content type. Use multipart/form-data')
|
||||
}
|
||||
|
||||
const formData = await c.req.parseBody({ all: true })
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
|
||||
return { formData, manifest }
|
||||
}
|
||||
|
||||
export const UPLOAD_PATH_ERROR_STATUS: ReadonlyArray<readonly [string, 400]> = [
|
||||
['Path must be relative', 400],
|
||||
['Path must not be empty', 400],
|
||||
['Path must not contain', 400],
|
||||
['escapes', 400],
|
||||
['not a valid file', 400],
|
||||
]
|
||||
|
||||
export function resolveUploadedManifestFiles(
|
||||
formData: ParsedFormData,
|
||||
manifest: InstallSkillUploadManifestEntry[],
|
||||
): Promise<{ relativePath: string; content: Buffer }[]> {
|
||||
): { relativePath: string; file: File }[] {
|
||||
const missingFields = manifest.filter((entry) => !formData[entry.fieldName])
|
||||
if (missingFields.length > 0) {
|
||||
throw new UploadValidationError(`Missing upload file(s): ${missingFields.map((e) => e.fieldName).join(', ')}`)
|
||||
}
|
||||
|
||||
return manifest.map((entry) => {
|
||||
const file = formData[entry.fieldName]
|
||||
if (!file || !(file instanceof File)) {
|
||||
throw new Error(`Field "${entry.fieldName}" is not a valid file`)
|
||||
}
|
||||
return { relativePath: entry.relativePath, file }
|
||||
})
|
||||
}
|
||||
|
||||
export async function readUploadedManifestFiles(
|
||||
formData: ParsedFormData,
|
||||
manifest: InstallSkillUploadManifestEntry[],
|
||||
): Promise<{ relativePath: string; content: Buffer }[]> {
|
||||
const files = resolveUploadedManifestFiles(formData, manifest)
|
||||
return Promise.all(
|
||||
manifest.map(async (entry) => {
|
||||
const file = formData[entry.fieldName]
|
||||
if (!file || !(file instanceof File)) {
|
||||
throw new Error(`Field "${entry.fieldName}" is not a valid file`)
|
||||
}
|
||||
const content = Buffer.from(await file.arrayBuffer())
|
||||
return { relativePath: entry.relativePath, content }
|
||||
}),
|
||||
files.map(async ({ relativePath, file }) => ({
|
||||
relativePath,
|
||||
content: Buffer.from(await file.arrayBuffer()),
|
||||
})),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { getAgentsMdPath } from '@opencode-manager/shared/config/env'
|
||||
import { writeFileContent, fileExists } from './file-operations'
|
||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export async function ensureDefaultAgentsMdExists(): Promise<void> {
|
||||
const agentsMdPath = getAgentsMdPath()
|
||||
const exists = await fileExists(agentsMdPath)
|
||||
|
||||
if (!exists) {
|
||||
await writeFileContent(agentsMdPath, DEFAULT_AGENTS_MD)
|
||||
logger.info(`Created default AGENTS.md at: ${agentsMdPath}`)
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,18 @@ import { randomUUID } from 'crypto'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { FILE_LIMITS, getConfigPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
MAX_OPENCODE_CONFIG_DIRECTORY_FILES,
|
||||
OPENCODE_CANONICAL_CONFIG_FILENAME,
|
||||
OPENCODE_CONFIG_BACKUP_PREFIX,
|
||||
OPENCODE_CONFIG_STAGING_PREFIX,
|
||||
OPENCODE_CONFIG_UPLOAD_ERRORS,
|
||||
PRESERVED_OPENCODE_CONFIG_ENTRIES,
|
||||
getCommonUploadRootDirectory,
|
||||
isExcludedOpenCodeConfigUploadPath,
|
||||
isOpenCodeConfigUploadPath,
|
||||
stripUploadRootDirectory,
|
||||
} from '@opencode-manager/shared/utils'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
import { fileExists, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
import { SettingsService } from './settings'
|
||||
@@ -16,23 +23,36 @@ import { logger } from '../utils/logger'
|
||||
|
||||
export interface UploadedConfigDirectoryFile {
|
||||
relativePath: string
|
||||
content: Buffer
|
||||
file: File
|
||||
}
|
||||
|
||||
export interface ReplaceOpenCodeConfigDirectoryResult {
|
||||
configDirectory: string
|
||||
configSourceFilename: string
|
||||
filesInstalled: string[]
|
||||
skippedPaths: string[]
|
||||
preservedEntries: string[]
|
||||
executablesRestored: string[]
|
||||
}
|
||||
|
||||
const MAX_CONFIG_DIRECTORY_FILES = 5000
|
||||
const PRESERVED_ENTRIES = ['node_modules']
|
||||
const STAGING_PREFIX = '.opencode-config-staging-'
|
||||
const BACKUP_PREFIX = '.opencode-config-backup-'
|
||||
const SHEBANG_PREFIX = '#!'
|
||||
const WRITE_BATCH_CONCURRENCY = 8
|
||||
|
||||
function readFileHead(file: File): Promise<string> {
|
||||
const slicable = file as unknown as { slice(start: number, end: number): { text(): Promise<string> } }
|
||||
return slicable.slice(0, SHEBANG_PREFIX.length).text()
|
||||
}
|
||||
|
||||
export async function sweepStaleOpenCodeConfigDirectoryDirs(): Promise<void> {
|
||||
const parent = path.dirname(getConfigPath())
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await fs.readdir(parent)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const name of entries) {
|
||||
if (name.startsWith(OPENCODE_CONFIG_STAGING_PREFIX) || name.startsWith(OPENCODE_CONFIG_BACKUP_PREFIX)) {
|
||||
try {
|
||||
await fs.rm(path.join(parent, name), { recursive: true, force: true })
|
||||
logger.info(`Removed stale OpenCode config directory temp dir '${name}'`)
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to remove stale OpenCode config directory temp dir '${name}'`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function replaceOpenCodeConfigDirectory(
|
||||
db: Database,
|
||||
@@ -41,20 +61,12 @@ export async function replaceOpenCodeConfigDirectory(
|
||||
): Promise<ReplaceOpenCodeConfigDirectoryResult> {
|
||||
const normalizedFiles = files.map((file) => ({
|
||||
relativePath: normalizeUploadRelativePath(file.relativePath, { collapseEmptySegments: true }),
|
||||
content: file.content,
|
||||
file: file.file,
|
||||
}))
|
||||
|
||||
const commonRoot = getCommonUploadRootDirectory(normalizedFiles.map((file) => file.relativePath))
|
||||
const strippedFiles = normalizedFiles
|
||||
.map((file) => ({
|
||||
relativePath: commonRoot ? file.relativePath.slice(commonRoot.length + 1) : file.relativePath,
|
||||
content: file.content,
|
||||
}))
|
||||
.filter((file) => file.relativePath !== '')
|
||||
|
||||
const kept: UploadedConfigDirectoryFile[] = []
|
||||
const skippedPaths: string[] = []
|
||||
for (const file of strippedFiles) {
|
||||
for (const file of normalizedFiles) {
|
||||
if (isExcludedOpenCodeConfigUploadPath(file.relativePath)) {
|
||||
skippedPaths.push(file.relativePath)
|
||||
} else {
|
||||
@@ -63,38 +75,47 @@ export async function replaceOpenCodeConfigDirectory(
|
||||
}
|
||||
|
||||
if (kept.length === 0) {
|
||||
throw new Error('No files were provided for the OpenCode config directory replace')
|
||||
throw new Error(OPENCODE_CONFIG_UPLOAD_ERRORS.NO_FILES_PROVIDED)
|
||||
}
|
||||
if (kept.length > MAX_CONFIG_DIRECTORY_FILES) {
|
||||
throw new Error('Uploaded config directory contains too many files (max 5000)')
|
||||
if (kept.length > MAX_OPENCODE_CONFIG_DIRECTORY_FILES) {
|
||||
throw new Error(OPENCODE_CONFIG_UPLOAD_ERRORS.TOO_MANY_FILES)
|
||||
}
|
||||
const totalBytes = kept.reduce((sum, file) => sum + file.content.length, 0)
|
||||
const totalBytes = kept.reduce((sum, file) => sum + file.file.size, 0)
|
||||
if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
|
||||
throw new Error('Uploaded config directory files exceed maximum upload size')
|
||||
throw new Error(OPENCODE_CONFIG_UPLOAD_ERRORS.EXCEEDS_MAX_UPLOAD_SIZE)
|
||||
}
|
||||
|
||||
const configCandidates = kept
|
||||
.map((file, index) => ({ file, index }))
|
||||
.filter(({ file }) => isOpenCodeConfigUploadPath(file.relativePath))
|
||||
const jsonCandidate = configCandidates.find(({ file }) => file.relativePath === 'opencode.json')
|
||||
const jsoncCandidate = configCandidates.find(({ file }) => file.relativePath === 'opencode.jsonc')
|
||||
const commonRoot = getCommonUploadRootDirectory(kept.map((file) => file.relativePath))
|
||||
const strippedFiles = kept
|
||||
.map((file) => ({
|
||||
relativePath: stripUploadRootDirectory(file.relativePath, commonRoot),
|
||||
file: file.file,
|
||||
}))
|
||||
.filter((file) => file.relativePath !== '')
|
||||
|
||||
const configCandidates = strippedFiles.filter((file) => isOpenCodeConfigUploadPath(file.relativePath))
|
||||
const jsonCandidate = configCandidates.find((file) => file.relativePath === 'opencode.json')
|
||||
const jsoncCandidate = configCandidates.find((file) => file.relativePath === 'opencode.jsonc')
|
||||
const chosenConfig = jsonCandidate ?? jsoncCandidate
|
||||
if (!chosenConfig) {
|
||||
throw new Error('Uploaded directory must contain opencode.json or opencode.jsonc at its root')
|
||||
throw new Error(OPENCODE_CONFIG_UPLOAD_ERRORS.MISSING_ROOT_CONFIG)
|
||||
}
|
||||
|
||||
const configSourceFilename = chosenConfig.file.relativePath
|
||||
const droppedJsoncFile = jsonCandidate && jsoncCandidate ? jsoncCandidate.file : undefined
|
||||
const configSourceFile = chosenConfig.file
|
||||
const configSourceFilename = chosenConfig.relativePath
|
||||
const droppedJsoncFile = jsonCandidate && jsoncCandidate ? jsoncCandidate : undefined
|
||||
if (droppedJsoncFile) {
|
||||
skippedPaths.push(droppedJsoncFile.relativePath)
|
||||
}
|
||||
|
||||
new SettingsService(db).upsertDefaultOpenCodeConfig(chosenConfig.file.content.toString('utf8'), userId)
|
||||
const configSourceText = await configSourceFile.text()
|
||||
const settingsService = new SettingsService(db)
|
||||
settingsService.validateOpenCodeConfigContent(configSourceText)
|
||||
|
||||
const filesToWrite = kept
|
||||
const filesToWrite = strippedFiles
|
||||
.filter((file) => file !== droppedJsoncFile)
|
||||
.map((file) => file.relativePath === configSourceFilename
|
||||
? { relativePath: OPENCODE_CANONICAL_CONFIG_FILENAME, content: file.content }
|
||||
? { relativePath: OPENCODE_CANONICAL_CONFIG_FILENAME, file: file.file }
|
||||
: file)
|
||||
|
||||
const configDirectory = getConfigPath()
|
||||
@@ -104,63 +125,99 @@ export async function replaceOpenCodeConfigDirectory(
|
||||
const preservedEntries: string[] = []
|
||||
let staged: string | null = null
|
||||
let backupPath: string | null = null
|
||||
let swapCompleted = false
|
||||
|
||||
const buildResult = (): ReplaceOpenCodeConfigDirectoryResult => ({
|
||||
configSourceFilename,
|
||||
filesInstalled: filesToWrite.map((file) => file.relativePath),
|
||||
skippedPaths,
|
||||
preservedEntries,
|
||||
executablesRestored,
|
||||
})
|
||||
|
||||
try {
|
||||
await mkdirSafe(parent)
|
||||
staged = await fs.mkdtemp(path.join(parent, STAGING_PREFIX))
|
||||
staged = await fs.mkdtemp(path.join(parent, OPENCODE_CONFIG_STAGING_PREFIX))
|
||||
const stagingDir = staged
|
||||
|
||||
for (const file of filesToWrite) {
|
||||
const target = resolveWithinDirectory(staged, file.relativePath, 'config directory')
|
||||
await mkdirSafe(path.dirname(target))
|
||||
await fs.writeFile(target, file.content)
|
||||
if (file.content.subarray(0, SHEBANG_PREFIX.length).toString() === SHEBANG_PREFIX) {
|
||||
await fs.chmod(target, 0o755)
|
||||
executablesRestored.push(file.relativePath)
|
||||
}
|
||||
const createdDirectories = new Set<string>()
|
||||
for (let i = 0; i < filesToWrite.length; i += WRITE_BATCH_CONCURRENCY) {
|
||||
const batch = filesToWrite.slice(i, i + WRITE_BATCH_CONCURRENCY)
|
||||
await Promise.all(batch.map(async (file) => {
|
||||
const target = resolveWithinDirectory(stagingDir, file.relativePath, 'config directory')
|
||||
const targetDirectory = path.dirname(target)
|
||||
if (!createdDirectories.has(targetDirectory)) {
|
||||
createdDirectories.add(targetDirectory)
|
||||
await mkdirSafe(targetDirectory)
|
||||
}
|
||||
await Bun.write(target, file.file)
|
||||
if (await readFileHead(file.file) === SHEBANG_PREFIX) {
|
||||
await fs.chmod(target, 0o755)
|
||||
executablesRestored.push(file.relativePath)
|
||||
}
|
||||
}))
|
||||
}
|
||||
executablesRestored.sort()
|
||||
|
||||
if (await fileExists(configDirectory)) {
|
||||
backupPath = path.join(parent, BACKUP_PREFIX + randomUUID())
|
||||
backupPath = path.join(parent, OPENCODE_CONFIG_BACKUP_PREFIX + randomUUID())
|
||||
await fs.rename(configDirectory, backupPath)
|
||||
await fs.rename(staged, configDirectory)
|
||||
staged = null
|
||||
swapCompleted = true
|
||||
|
||||
for (const name of PRESERVED_ENTRIES) {
|
||||
const backupEntryPath = path.join(backupPath, name)
|
||||
const targetEntryPath = path.join(configDirectory, name)
|
||||
if (await fileExists(backupEntryPath) && !(await fileExists(targetEntryPath))) {
|
||||
await fs.rename(backupEntryPath, targetEntryPath)
|
||||
preservedEntries.push(name)
|
||||
for (const name of PRESERVED_OPENCODE_CONFIG_ENTRIES) {
|
||||
try {
|
||||
const backupEntryPath = path.join(backupPath, name)
|
||||
const targetEntryPath = path.join(configDirectory, name)
|
||||
if (await fileExists(backupEntryPath) && !(await fileExists(targetEntryPath))) {
|
||||
await fs.rename(backupEntryPath, targetEntryPath)
|
||||
preservedEntries.push(name)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to preserve '${name}' after OpenCode config directory replace`, error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await fs.rename(staged, configDirectory)
|
||||
staged = null
|
||||
swapCompleted = true
|
||||
}
|
||||
|
||||
if (backupPath) {
|
||||
await fs.rm(backupPath, { recursive: true, force: true })
|
||||
try {
|
||||
await fs.rm(backupPath, { recursive: true, force: true })
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to remove OpenCode config directory backup at ${backupPath}`, error)
|
||||
}
|
||||
}
|
||||
|
||||
settingsService.upsertDefaultOpenCodeConfig(configSourceText, userId)
|
||||
|
||||
logger.info(`Replaced OpenCode config directory at ${configDirectory}`)
|
||||
|
||||
return {
|
||||
configDirectory,
|
||||
configSourceFilename,
|
||||
filesInstalled: filesToWrite.map((file) => file.relativePath),
|
||||
skippedPaths,
|
||||
preservedEntries,
|
||||
executablesRestored,
|
||||
}
|
||||
return buildResult()
|
||||
} catch (error) {
|
||||
if (swapCompleted) {
|
||||
logger.warn('OpenCode config directory swap completed despite a post-swap error', error)
|
||||
return buildResult()
|
||||
}
|
||||
if (staged) {
|
||||
await fs.rm(staged, { recursive: true, force: true })
|
||||
try {
|
||||
await fs.rm(staged, { recursive: true, force: true })
|
||||
} catch (cleanupError) {
|
||||
logger.warn('Failed to remove staging directory after failed replace', cleanupError)
|
||||
}
|
||||
}
|
||||
if (backupPath) {
|
||||
if (await fileExists(configDirectory)) {
|
||||
await fs.rm(backupPath, { recursive: true, force: true })
|
||||
} else {
|
||||
await fs.rename(backupPath, configDirectory)
|
||||
try {
|
||||
if (await fileExists(configDirectory)) {
|
||||
await fs.rm(backupPath, { recursive: true, force: true })
|
||||
} else {
|
||||
await fs.rename(backupPath, configDirectory)
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
logger.warn('Failed to restore the previous config directory after failed replace', cleanupError)
|
||||
}
|
||||
}
|
||||
throw error
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import path from 'path'
|
||||
import type { SettingsService } from './settings'
|
||||
import { DEFAULT_SEED_OPENCODE_CONFIG, type SettingsService } from './settings'
|
||||
import { logger } from '../utils/logger'
|
||||
import { ensureDirectoryExists, writeFileContent } from './file-operations'
|
||||
import { getOpenCodeConfigFilePath, getWorkspacePath, ENV } from '@opencode-manager/shared/config/env'
|
||||
@@ -304,23 +304,9 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
private async seedDefaultConfig(): Promise<void> {
|
||||
const seedConfig = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
const defaultConfig = this.settingsService.getDefaultOpenCodeConfig(this.userId)
|
||||
this.settingsService.upsertDefaultOpenCodeConfig(DEFAULT_SEED_OPENCODE_CONFIG, this.userId)
|
||||
|
||||
if (defaultConfig) {
|
||||
this.settingsService.updateOpenCodeConfig(defaultConfig.name, { content: seedConfig }, this.userId)
|
||||
} else {
|
||||
this.settingsService.createOpenCodeConfig(
|
||||
{
|
||||
name: 'default',
|
||||
content: seedConfig,
|
||||
isDefault: true,
|
||||
},
|
||||
this.userId,
|
||||
)
|
||||
}
|
||||
|
||||
await this.writeConfig(seedConfig)
|
||||
await this.writeConfig(DEFAULT_SEED_OPENCODE_CONFIG)
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
await this.openCodeServerManager.restart()
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ import type {
|
||||
UserPreferences,
|
||||
SettingsResponse,
|
||||
CreateOpenCodeConfigRequest,
|
||||
UpdateOpenCodeConfigRequest
|
||||
UpdateOpenCodeConfigRequest,
|
||||
OpenCodeConfigContent,
|
||||
} from '../types/settings'
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
@@ -50,6 +51,7 @@ interface OpenCodeServerPasswordState {
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export const DEFAULT_SEED_OPENCODE_CONFIG = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
|
||||
export class SettingsService {
|
||||
private static lastKnownGoodConfigContent: string | null = null
|
||||
@@ -226,6 +228,11 @@ export class SettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
validateOpenCodeConfigContent(rawContent: string): OpenCodeConfigContent {
|
||||
const parsedContent = parseJsonc(rawContent)
|
||||
return OpenCodeConfigSchema.parse(parsedContent)
|
||||
}
|
||||
|
||||
createOpenCodeConfig(
|
||||
request: CreateOpenCodeConfigRequest,
|
||||
userId: string = 'default',
|
||||
@@ -240,12 +247,8 @@ export class SettingsService {
|
||||
const rawContent = typeof request.content === 'string'
|
||||
? request.content
|
||||
: JSON.stringify(request.content, null, 2)
|
||||
|
||||
const parsedContent = typeof request.content === 'string'
|
||||
? parseJsonc(request.content)
|
||||
: request.content
|
||||
|
||||
const contentValidated = OpenCodeConfigSchema.parse(parsedContent)
|
||||
|
||||
const contentValidated = this.validateOpenCodeConfigContent(rawContent)
|
||||
const now = Date.now()
|
||||
|
||||
const existingCount = this.db
|
||||
@@ -310,12 +313,8 @@ export class SettingsService {
|
||||
const rawContent = typeof request.content === 'string'
|
||||
? request.content
|
||||
: JSON.stringify(request.content, null, 2)
|
||||
|
||||
const parsedContent = typeof request.content === 'string'
|
||||
? parseJsonc(request.content)
|
||||
: request.content
|
||||
|
||||
const contentValidated = OpenCodeConfigSchema.parse(parsedContent)
|
||||
const contentValidated = this.validateOpenCodeConfigContent(rawContent)
|
||||
const now = Date.now()
|
||||
|
||||
if (request.isDefault) {
|
||||
|
||||
@@ -131,14 +131,16 @@ import { SettingsService } from '../../src/services/settings'
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { restartOpenCode } from '../../src/services/opencode-restart'
|
||||
import { replaceOpenCodeConfigDirectory } from '../../src/services/opencode-config-directory'
|
||||
import { writeFileContent, fileExists } from '../../src/services/file-operations'
|
||||
|
||||
const mockReplace = replaceOpenCodeConfigDirectory as ReturnType<typeof vi.fn>
|
||||
const mockRestartOpenCode = restartOpenCode as ReturnType<typeof vi.fn>
|
||||
const mockMarkRestartPending = opencodeServerManager.markRestartPending as ReturnType<typeof vi.fn>
|
||||
const mockClearStartupError = opencodeServerManager.clearStartupError as ReturnType<typeof vi.fn>
|
||||
const mockWriteFileContent = writeFileContent as ReturnType<typeof vi.fn>
|
||||
const mockFileExists = fileExists as ReturnType<typeof vi.fn>
|
||||
|
||||
const mockReplaceResult = {
|
||||
configDirectory: '/tmp/test-workspace/config',
|
||||
configSourceFilename: 'opencode.json',
|
||||
filesInstalled: ['opencode.json', 'agents/team/lead.md'],
|
||||
skippedPaths: ['node_modules/package/dist/index.js'],
|
||||
@@ -164,6 +166,7 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
|
||||
vi.clearAllMocks()
|
||||
mockReplace.mockResolvedValue(mockReplaceResult)
|
||||
mockRestartOpenCode.mockResolvedValue({ resumedSessionIDs: [] })
|
||||
mockFileExists.mockResolvedValue(false)
|
||||
|
||||
testDb = {} as any
|
||||
settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any, createStubOpenCodeClient())
|
||||
@@ -183,7 +186,7 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
|
||||
}
|
||||
|
||||
describe('POST /opencode-config-directory/replace', () => {
|
||||
it('replaces the config directory and marks a restart required', async () => {
|
||||
it('replaces the config directory, re-ensures AGENTS.md, and restarts the server', async () => {
|
||||
const res = await settingsApp.request('/opencode-config-directory/replace?userId=custom', {
|
||||
method: 'POST',
|
||||
body: buildFormData(),
|
||||
@@ -191,18 +194,21 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as Record<string, unknown>
|
||||
expect(body).toEqual({ ...mockReplaceResult, restartRequired: true })
|
||||
expect(body).toEqual(mockReplaceResult)
|
||||
expect('restartRequired' in body).toBe(false)
|
||||
expect('configDirectory' in body).toBe(false)
|
||||
|
||||
expect(mockReplace).toHaveBeenCalledTimes(1)
|
||||
expect(mockReplace).toHaveBeenCalledWith(
|
||||
testDb,
|
||||
[
|
||||
expect.objectContaining({ relativePath: 'opencode.json', content: expect.any(Buffer) }),
|
||||
expect.objectContaining({ relativePath: 'agents/team/lead.md', content: expect.any(Buffer) }),
|
||||
expect.objectContaining({ relativePath: 'opencode.json', file: expect.any(File) }),
|
||||
expect.objectContaining({ relativePath: 'agents/team/lead.md', file: expect.any(File) }),
|
||||
],
|
||||
'custom',
|
||||
)
|
||||
expect(mockSaveLastKnownGoodConfig).toHaveBeenCalledWith('custom')
|
||||
expect(mockWriteFileContent).toHaveBeenCalledWith('/tmp/test-workspace/AGENTS.md', '# Test Agents MD')
|
||||
expect(mockMarkRestartPending).toHaveBeenCalledTimes(1)
|
||||
expect(mockClearStartupError).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestartOpenCode).toHaveBeenCalledTimes(1)
|
||||
@@ -263,6 +269,25 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
|
||||
expect(body.error).toBe('Uploaded config directory contains too many files (max 5000)')
|
||||
})
|
||||
|
||||
it('rejects an over-count manifest with 400 before reading any file content', async () => {
|
||||
const manifest = Array.from({ length: 5001 }, (_, index) => ({
|
||||
fieldName: `file${index}`,
|
||||
relativePath: `dir/file${index}.md`,
|
||||
}))
|
||||
const formData = new FormData()
|
||||
formData.append('fileManifest', JSON.stringify(manifest))
|
||||
|
||||
const res = await settingsApp.request('/opencode-config-directory/replace', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('Uploaded config directory contains too many files (max 5000)')
|
||||
expect(mockReplace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports invalid config content as a ZodError 400 with issue details', async () => {
|
||||
mockReplace.mockRejectedValue(createZodError())
|
||||
|
||||
@@ -325,7 +350,20 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
|
||||
expect(mockReplace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves restartRequired false when the replace itself fails', async () => {
|
||||
it('maps a "." manifest relative path to 400 instead of 500', async () => {
|
||||
mockReplace.mockRejectedValue(new Error('Path must not be empty'))
|
||||
|
||||
const res = await settingsApp.request('/opencode-config-directory/replace', {
|
||||
method: 'POST',
|
||||
body: buildFormData(),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('Path must not be empty')
|
||||
})
|
||||
|
||||
it('returns 500 when the replace itself fails without restarting', async () => {
|
||||
mockReplace.mockRejectedValue(new Error('unexpected failure'))
|
||||
|
||||
const res = await settingsApp.request('/opencode-config-directory/replace', {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { promises as fs } from 'fs'
|
||||
import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'fs/promises'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { z } from 'zod'
|
||||
@@ -16,10 +17,13 @@ vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
const mockValidateOpenCodeConfigContent = vi.fn()
|
||||
const mockUpsertDefaultOpenCodeConfig = vi.fn()
|
||||
const mockBunWrite = vi.fn()
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn(() => ({
|
||||
validateOpenCodeConfigContent: mockValidateOpenCodeConfigContent,
|
||||
upsertDefaultOpenCodeConfig: mockUpsertDefaultOpenCodeConfig,
|
||||
})),
|
||||
}))
|
||||
@@ -28,13 +32,13 @@ import { SettingsService } from '../../src/services/settings'
|
||||
|
||||
interface TestUploadFile {
|
||||
relativePath: string
|
||||
content: Buffer
|
||||
file: File
|
||||
}
|
||||
|
||||
function payload(files: Array<[string, string]>): TestUploadFile[] {
|
||||
return files.map(([relativePath, content]) => ({
|
||||
relativePath,
|
||||
content: Buffer.from(content),
|
||||
file: new File([content], relativePath.split('/').pop() ?? relativePath),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -66,12 +70,18 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
configDir = join(tempDir, '.config', 'opencode')
|
||||
vi.spyOn(await import('@opencode-manager/shared/config/env'), 'getConfigPath').mockReturnValue(configDir)
|
||||
mockDb = { query: vi.fn() } as unknown as Database
|
||||
mockValidateOpenCodeConfigContent.mockReturnValue({})
|
||||
mockUpsertDefaultOpenCodeConfig.mockReturnValue({ name: 'default', isDefault: true })
|
||||
mockBunWrite.mockImplementation(async (targetPath: string, file: File) => {
|
||||
await writeFile(targetPath, Buffer.from(await file.arrayBuffer()))
|
||||
})
|
||||
vi.stubGlobal('Bun', { write: mockBunWrite })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('replaces the directory with the uploaded tree, normalizing the config and restoring executables', async () => {
|
||||
@@ -97,8 +107,8 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
]))
|
||||
|
||||
expect(SettingsService).toHaveBeenCalledWith(mockDb)
|
||||
expect(mockValidateOpenCodeConfigContent).toHaveBeenCalledWith(jsonc)
|
||||
expect(mockUpsertDefaultOpenCodeConfig).toHaveBeenCalledWith(jsonc, 'default')
|
||||
expect(result.configDirectory).toBe(configDir)
|
||||
expect(result.configSourceFilename).toBe('opencode.jsonc')
|
||||
expect(result.filesInstalled).toEqual([
|
||||
'opencode.json',
|
||||
@@ -111,7 +121,7 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
'vendor/x.js',
|
||||
'postgres-mcp-manager.sh',
|
||||
])
|
||||
expect(result.executablesRestored).toEqual(['skills/quo-api/scripts/quo-spec.sh', 'postgres-mcp-manager.sh'])
|
||||
expect(result.executablesRestored).toEqual(['postgres-mcp-manager.sh', 'skills/quo-api/scripts/quo-spec.sh'])
|
||||
expect(result.skippedPaths).toEqual([])
|
||||
expect(result.preservedEntries).toEqual([])
|
||||
|
||||
@@ -172,6 +182,21 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
await expect(readFile(join(configDir, '.DS_Store'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('computes the common upload root from kept paths, ignoring excluded siblings', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
const result = await replaceOpenCodeConfigDirectory(mockDb, payload([
|
||||
['my-config/opencode.json', '{"theme":"dark"}'],
|
||||
['my-config/AGENTS.md', '# Project'],
|
||||
['other/node_modules/installed.js', 'x'],
|
||||
]))
|
||||
|
||||
expect(result.filesInstalled).toEqual(['opencode.json', 'AGENTS.md'])
|
||||
expect(result.skippedPaths).toEqual(['other/node_modules/installed.js'])
|
||||
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"dark"}')
|
||||
expect(await readFile(join(configDir, 'AGENTS.md'), 'utf8')).toBe('# Project')
|
||||
await expect(readFile(join(configDir, 'other', 'node_modules', 'installed.js'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('rejects a payload with no root config file, leaving the old directory untouched', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
await mkdir(join(configDir, 'agents'), { recursive: true })
|
||||
@@ -192,7 +217,7 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
|
||||
it('rejects when the config fails validation before touching disk', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
mockUpsertDefaultOpenCodeConfig.mockImplementationOnce(() => {
|
||||
mockValidateOpenCodeConfigContent.mockImplementationOnce(() => {
|
||||
throw createConfigZodError()
|
||||
})
|
||||
await mkdir(join(configDir, 'agents'), { recursive: true })
|
||||
@@ -205,13 +230,64 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
])).catch((caught) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(z.ZodError)
|
||||
expect(mockUpsertDefaultOpenCodeConfig).toHaveBeenCalledWith('{"theme": 42}', 'default')
|
||||
expect(mockValidateOpenCodeConfigContent).toHaveBeenCalledWith('{"theme": 42}')
|
||||
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"old"}')
|
||||
expect(await readFile(join(configDir, 'agents', 'existing.md'), 'utf8')).toBe('keep me')
|
||||
const parentEntries = await listParentEntries(join(tempDir, '.config'))
|
||||
expect(parentEntries.filter((name) => name.startsWith('.opencode-config-staging-') || name.startsWith('.opencode-config-backup-'))).toEqual([])
|
||||
})
|
||||
|
||||
it('does not persist to the database when the filesystem phase fails', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
await mkdir(join(configDir, 'agents'), { recursive: true })
|
||||
await writeFile(join(configDir, 'agents', 'existing.md'), 'keep me')
|
||||
await writeFile(join(configDir, 'opencode.json'), '{"theme":"old"}')
|
||||
mockBunWrite.mockImplementationOnce(() => {
|
||||
throw new Error('ENOSPC: no space left on device')
|
||||
})
|
||||
|
||||
const error = await replaceOpenCodeConfigDirectory(mockDb, payload([
|
||||
['opencode.json', '{"theme":"new"}'],
|
||||
['agents/planner.md', '# Planner'],
|
||||
])).catch((caught) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
expect((error as Error).message).toContain('ENOSPC')
|
||||
expect(mockValidateOpenCodeConfigContent).toHaveBeenCalledWith('{"theme":"new"}')
|
||||
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"old"}')
|
||||
expect(await readFile(join(configDir, 'agents', 'existing.md'), 'utf8')).toBe('keep me')
|
||||
const parentEntries = await listParentEntries(join(tempDir, '.config'))
|
||||
expect(parentEntries.filter((name) => name.startsWith('.opencode-config-staging-') || name.startsWith('.opencode-config-backup-'))).toEqual([])
|
||||
})
|
||||
|
||||
it('reports success when a post-swap node_modules preservation step fails', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
await mkdir(join(configDir, 'node_modules', 'dep'), { recursive: true })
|
||||
await writeFile(join(configDir, 'node_modules', 'dep', 'index.js'), 'module.exports = 1')
|
||||
|
||||
const realRename = fs.rename.bind(fs)
|
||||
vi.spyOn(fs, 'rename').mockImplementation(async (oldPath, newPath) => {
|
||||
if (String(newPath).includes('node_modules')) {
|
||||
throw new Error('EACCES: permission denied')
|
||||
}
|
||||
return realRename(oldPath, newPath)
|
||||
})
|
||||
|
||||
const result = await replaceOpenCodeConfigDirectory(mockDb, payload([
|
||||
['opencode.json', '{"theme":"dark"}'],
|
||||
]))
|
||||
|
||||
expect(result.filesInstalled).toEqual(['opencode.json'])
|
||||
expect(result.preservedEntries).toEqual([])
|
||||
expect(mockUpsertDefaultOpenCodeConfig).toHaveBeenCalledWith('{"theme":"dark"}', 'default')
|
||||
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"dark"}')
|
||||
await expect(readFile(join(configDir, 'node_modules', 'dep', 'index.js'), 'utf8')).rejects.toThrow()
|
||||
const parentEntries = await listParentEntries(join(tempDir, '.config'))
|
||||
expect(parentEntries.filter((name) => name.startsWith('.opencode-config-staging-') || name.startsWith('.opencode-config-backup-'))).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a path containing .. before any disk mutation', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
await mkdir(configDir, { recursive: true })
|
||||
@@ -226,6 +302,20 @@ describe('replaceOpenCodeConfigDirectory', () => {
|
||||
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a "." manifest relative path before any disk mutation', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
await mkdir(configDir, { recursive: true })
|
||||
await writeFile(join(configDir, 'opencode.json'), '{"theme":"old"}')
|
||||
|
||||
await expect(replaceOpenCodeConfigDirectory(mockDb, payload([
|
||||
['opencode.json', '{"theme":"new"}'],
|
||||
['.', 'x'],
|
||||
]))).rejects.toThrow('Path must not be empty')
|
||||
|
||||
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"old"}')
|
||||
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects payloads exceeding the upload size limit', async () => {
|
||||
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
|
||||
await mkdir(configDir, { recursive: true })
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { ensureDirectoryExists, writeFileContent } from '../../src/services/file-operations'
|
||||
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
|
||||
import { DEFAULT_SEED_OPENCODE_CONFIG } from '../../src/services/settings'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
@@ -18,6 +19,7 @@ vi.mock('../../src/services/file-operations', () => ({
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getWorkspacePath: vi.fn(() => '/tmp/opencode-workspace'),
|
||||
getOpenCodeConfigFilePath: vi.fn(() => '/tmp/opencode-workspace/.config/opencode.json'),
|
||||
getConfigPath: vi.fn(() => '/tmp/opencode-workspace/.config/opencode'),
|
||||
ENV: {
|
||||
OPENCODE: {
|
||||
HEALTH_POLL_MS: 200,
|
||||
@@ -48,6 +50,7 @@ interface FakeSettingsService {
|
||||
getDefaultOpenCodeConfig: ReturnType<typeof vi.fn>
|
||||
updateOpenCodeConfig: ReturnType<typeof vi.fn>
|
||||
createOpenCodeConfig: ReturnType<typeof vi.fn>
|
||||
upsertDefaultOpenCodeConfig: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
describe('OpenCodeSupervisor', () => {
|
||||
@@ -85,6 +88,12 @@ describe('OpenCodeSupervisor', () => {
|
||||
isDefault: true,
|
||||
})),
|
||||
createOpenCodeConfig: vi.fn(),
|
||||
upsertDefaultOpenCodeConfig: vi.fn(() => ({
|
||||
name: 'default',
|
||||
content: { $schema: 'https://opencode.ai/config.json' },
|
||||
rawContent: DEFAULT_SEED_OPENCODE_CONFIG,
|
||||
isDefault: true,
|
||||
})),
|
||||
})
|
||||
|
||||
it('recovers a startup failure through rollback and keeps watching', async () => {
|
||||
@@ -171,4 +180,32 @@ describe('OpenCodeSupervisor', () => {
|
||||
|
||||
expect(manager.checkHealth).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('seeds the default config via upsert when recovery reaches seed_default_config', async () => {
|
||||
const manager = createManager()
|
||||
const settings = createSettings()
|
||||
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
|
||||
failureThreshold: 1,
|
||||
userId: 'default',
|
||||
})
|
||||
|
||||
manager.start.mockRejectedValueOnce(new Error('startup failed'))
|
||||
manager.checkHealth
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(false)
|
||||
.mockResolvedValueOnce(true)
|
||||
|
||||
const status = await supervisor.start()
|
||||
|
||||
expect(status.healthy).toBe(true)
|
||||
expect(settings.upsertDefaultOpenCodeConfig).toHaveBeenCalledWith(DEFAULT_SEED_OPENCODE_CONFIG, 'default')
|
||||
expect(writeFileContent).toHaveBeenCalledWith(
|
||||
'/tmp/opencode-workspace/.config/opencode.json',
|
||||
DEFAULT_SEED_OPENCODE_CONFIG,
|
||||
)
|
||||
expect(manager.restart).toHaveBeenCalledTimes(4)
|
||||
|
||||
await supervisor.stop()
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,7 @@ vi.mock('bun:sqlite', () => ({
|
||||
})),
|
||||
}))
|
||||
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { SettingsService, DEFAULT_SEED_OPENCODE_CONFIG } from '../../src/services/settings'
|
||||
|
||||
describe('SettingsService - upsertDefaultOpenCodeConfig', () => {
|
||||
let settingsService: SettingsService
|
||||
@@ -54,4 +54,21 @@ describe('SettingsService - upsertDefaultOpenCodeConfig', () => {
|
||||
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
|
||||
expect(result.isDefault).toBe(true)
|
||||
})
|
||||
|
||||
it('seeds a default config row marked isDefault when no config exists (index seed path)', () => {
|
||||
expect(JSON.parse(DEFAULT_SEED_OPENCODE_CONFIG)).toEqual({ $schema: 'https://opencode.ai/config.json' })
|
||||
|
||||
mockGetOpenCodeConfigByName.mockReturnValue(null)
|
||||
mockCreateOpenCodeConfig.mockReturnValue({ name: 'default', isDefault: true })
|
||||
|
||||
const result = settingsService.upsertDefaultOpenCodeConfig(DEFAULT_SEED_OPENCODE_CONFIG)
|
||||
|
||||
expect(mockCreateOpenCodeConfig).toHaveBeenCalledWith({
|
||||
name: 'default',
|
||||
content: DEFAULT_SEED_OPENCODE_CONFIG,
|
||||
isDefault: true,
|
||||
}, 'default')
|
||||
expect(result.name).toBe('default')
|
||||
expect(result.isDefault).toBe(true)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user