mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +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)
|
||||
})
|
||||
})
|
||||
@@ -159,14 +159,15 @@ OpenCode's configuration lives in a directory — `workspace/.config/opencode`
|
||||
- The whole `workspace/.config/opencode` tree is replaced — the config file, `AGENTS.md`, `agents/`, `commands/`, `skills/`, `plugin/` and any other files the directory holds. The exact destination path is shown in the confirmation dialog before you confirm.
|
||||
- The folder must contain `opencode.json` or `opencode.jsonc` at its root. An uploaded `.jsonc` file is installed as `opencode.json` with its comments preserved; when both are uploaded, the `.jsonc` is skipped.
|
||||
- The uploaded config becomes the **default** config shown in the config manager.
|
||||
- `node_modules`, `.git` and `.DS_Store` entries are skipped. An existing `node_modules` directory at the root of the config directory is carried over unchanged across the replace, so plugin dependencies do not have to be re-uploaded; OpenCode installs the plugins declared in the config's `plugin` array on start.
|
||||
- `node_modules`, `.git` and `.DS_Store` entries are skipped. An existing `node_modules` directory at the root of the config directory is carried over unchanged across the replace, so dependencies of plugins kept inside the directory do not have to be re-uploaded. Plugins declared as packages in the config's `plugin` array are installed separately by OpenCode on start and do not depend on it.
|
||||
- Files whose contents start with a `#!` shebang are restored as executable.
|
||||
- At most 5000 files can be uploaded, with a combined upload size limited by `MAX_UPLOAD_SIZE_MB` (50 MB by default).
|
||||
- At most 5000 files can be uploaded, with a combined upload size limited by `MAX_UPLOAD_SIZE_MB` (50 MB by default). An upload beyond either limit is rejected before its contents are read.
|
||||
- If the uploaded folder contains no `AGENTS.md`, the default one is recreated, so the global instructions file is never left missing.
|
||||
- The OpenCode server restarts afterwards.
|
||||
|
||||
### Restart Required
|
||||
|
||||
Changes that need a restart surface as an amber notice pinned at the top of the **OpenCode** tab in Settings while a restart is pending. The notice appears when a change has been saved but not yet applied to the running server — a directory replace restarts the server for you, so it only shows up after one if that restart never came up healthy. The first time a pending restart is seen, a confirmation dialog opens automatically; you can dismiss it with **Later**. The **Restart Now** button restarts the server immediately when no sessions are working, and asks for confirmation first when sessions are working, reporting how many would be interrupted.
|
||||
Changes that need a restart surface as an amber notice pinned at the top of the **OpenCode** tab in Settings while a restart is pending. The notice appears when a change has been saved but not yet applied to the running server — a directory replace restarts the server for you, so it only shows up after one if that restart never came up healthy. A confirmation dialog opens automatically once per pending restart; dismissing it with **Later** keeps it closed, including across settings tab changes, until a new restart becomes pending. The **Restart Now** button restarts the server immediately when no sessions are working, and asks for confirmation first when sessions are working, reporting how many would be interrupted.
|
||||
|
||||
### If the Replacement Breaks Startup
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillResponse,
|
||||
OpenCodeDirectoryFileInfo,
|
||||
ReplaceOpenCodeConfigDirectoryResponse,
|
||||
ReplaceOpenCodeConfigDirectoryResult,
|
||||
} from './types/settings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
@@ -385,7 +385,7 @@ export const settingsApi = {
|
||||
|
||||
replaceOpenCodeConfigDirectory: async (
|
||||
items: DirectoryUploadItem[],
|
||||
): Promise<ReplaceOpenCodeConfigDirectoryResponse> => {
|
||||
): Promise<ReplaceOpenCodeConfigDirectoryResult> => {
|
||||
const formData = new FormData()
|
||||
appendUploadItemsWithManifest(formData, items)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config-directory/replace`, {
|
||||
|
||||
@@ -18,9 +18,9 @@ import {
|
||||
type InstallSkillFromGithubRequest,
|
||||
type InstallSkillResponse,
|
||||
} from '@opencode-manager/shared'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
import type { NotificationPreferences, ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse, ReplaceOpenCodeConfigDirectoryResult }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
|
||||
|
||||
export interface CustomCommand {
|
||||
@@ -147,13 +147,3 @@ export interface OpenCodeDirectoryFileInfo {
|
||||
name: string
|
||||
relativePath: string
|
||||
}
|
||||
|
||||
export interface ReplaceOpenCodeConfigDirectoryResponse {
|
||||
configDirectory: string
|
||||
configSourceFilename: string
|
||||
filesInstalled: string[]
|
||||
skippedPaths: string[]
|
||||
preservedEntries: string[]
|
||||
executablesRestored: string[]
|
||||
restartRequired: boolean
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { getFileApiUrl, useFile } from '@/api/files'
|
||||
import { getUploadItemsFromDataTransfer, getUploadItemsFromFileList, type DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
import { useDirectoryDropZone, getUploadItemsFromFileList, type DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
|
||||
export interface FileBrowserHandle {
|
||||
goBack: () => void
|
||||
@@ -54,11 +54,9 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false)
|
||||
const [uploadProgress, setUploadProgress] = useState<UploadProgress | null>(null)
|
||||
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const uploadCancelledRef = useRef(false)
|
||||
const isMobile = useMobile()
|
||||
|
||||
@@ -273,6 +271,10 @@ useEffect(() => {
|
||||
await handleUploadItems(items)
|
||||
}, [handleUploadItems])
|
||||
|
||||
const { dropZoneRef, isDragging, dropHandlers } = useDirectoryDropZone({
|
||||
onItems: handleUploadItems,
|
||||
})
|
||||
|
||||
const cancelUpload = useCallback(() => {
|
||||
uploadCancelledRef.current = true
|
||||
}, [])
|
||||
@@ -330,36 +332,6 @@ useEffect(() => {
|
||||
}
|
||||
}, [currentPath, loadFiles])
|
||||
|
||||
const handleDragEnter = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.currentTarget === dropZoneRef.current) {
|
||||
setIsDragging(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(false)
|
||||
|
||||
const items = await getUploadItemsFromDataTransfer(e.dataTransfer)
|
||||
if (items.length > 0) {
|
||||
await handleUploadItems(items)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles(basePath)
|
||||
}, [basePath, loadFiles])
|
||||
@@ -476,10 +448,7 @@ useEffect(() => {
|
||||
<div
|
||||
className="h-full flex flex-col bg-background"
|
||||
ref={dropZoneRef}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop}
|
||||
{...dropHandlers}
|
||||
>
|
||||
{isDragging && (
|
||||
<div className="absolute inset-0 z-50 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center">
|
||||
@@ -569,10 +538,7 @@ useEffect(() => {
|
||||
<div
|
||||
className="h-full flex flex-col"
|
||||
ref={dropZoneRef}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop}
|
||||
{...dropHandlers}
|
||||
>
|
||||
<Card className="flex-1 relative">
|
||||
{isDragging && (
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { FileInfo } from '@/types/files'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
|
||||
import { MarkdownRenderer } from './MarkdownRenderer'
|
||||
import { formatBytes } from '@/lib/utils'
|
||||
|
||||
|
||||
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
|
||||
@@ -81,14 +82,6 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
}
|
||||
}, [initialLineNumber, shouldVirtualize, file.content])
|
||||
|
||||
const formatFileSize = (bytes: number) => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
const k = 1024
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
return new Date(date).toLocaleString()
|
||||
}
|
||||
@@ -369,7 +362,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-1 flex-wrap">
|
||||
<span className="bg-muted px-1.5 py-0.5 rounded text-xs truncate max-w-[80px] flex-shrink-0">{file.mimeType || 'Unknown'}</span>
|
||||
<span className="truncate flex-shrink-0">{formatFileSize(file.size)}</span>
|
||||
<span className="truncate flex-shrink-0">{formatBytes(file.size)}</span>
|
||||
<span className="hidden sm:inline truncate flex-shrink-0">{formatDate(file.lastModified)}</span>
|
||||
{shouldVirtualize && (
|
||||
<span className="text-xs text-blue-500 flex-shrink-0">Virtualized</span>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { FILE_LIMITS } from '@/config'
|
||||
import { OpenCodeConfigDirectoryUpload } from './OpenCodeConfigDirectoryUpload'
|
||||
import type { DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResponse } from '@/api/types/settings'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
|
||||
const {
|
||||
mockReplaceOpenCodeConfigDirectory,
|
||||
@@ -43,18 +43,34 @@ vi.mock('@/lib/directoryUpload', () => ({
|
||||
DIRECTORY_INPUT_PROPS: { webkitdirectory: '', directory: '' },
|
||||
getUploadItemsFromDataTransfer: mockGetUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList: mockGetUploadItemsFromFileList,
|
||||
openPicker: vi.fn(),
|
||||
readUploadItemsFromInput: () => mockGetUploadItemsFromFileList(),
|
||||
useDirectoryDropZone: (options: {
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean
|
||||
onItems: (items: DirectoryUploadItem[]) => void | Promise<void>
|
||||
}) => ({
|
||||
dropZoneRef: { current: null },
|
||||
isDragging: false,
|
||||
dropHandlers: {
|
||||
onDragEnter: vi.fn(),
|
||||
onDragOver: vi.fn(),
|
||||
onDragLeave: vi.fn(),
|
||||
onDrop: async (e: React.DragEvent) => {
|
||||
const items = await mockGetUploadItemsFromDataTransfer(e.dataTransfer)
|
||||
await options.onItems(items)
|
||||
},
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
const IMPORT_STATUS = { workspaceConfigDirectory: '/workspace/.config/opencode' }
|
||||
|
||||
const RESULT: ReplaceOpenCodeConfigDirectoryResponse = {
|
||||
configDirectory: '/workspace/.config/opencode',
|
||||
const RESULT: ReplaceOpenCodeConfigDirectoryResult = {
|
||||
configSourceFilename: 'opencode.jsonc',
|
||||
filesInstalled: ['opencode.json', 'skills/x/SKILL.md', 'plugin/p.js'],
|
||||
skippedPaths: ['node_modules/pkg/index.js'],
|
||||
preservedEntries: ['node_modules'],
|
||||
executablesRestored: ['scripts/run.sh'],
|
||||
restartRequired: true,
|
||||
}
|
||||
|
||||
function makeItem(relativePath: string, size = 10): DirectoryUploadItem {
|
||||
@@ -62,11 +78,11 @@ function makeItem(relativePath: string, size = 10): DirectoryUploadItem {
|
||||
return { file: new File([new Uint8Array(size)], name), relativePath }
|
||||
}
|
||||
|
||||
function renderComponent() {
|
||||
function renderComponent(props?: { onReplaced?: () => void }) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OpenCodeConfigDirectoryUpload />
|
||||
<OpenCodeConfigDirectoryUpload {...props} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
@@ -96,7 +112,7 @@ describe('OpenCodeConfigDirectoryUpload', () => {
|
||||
await dropItems(items)
|
||||
|
||||
expect(screen.getByText('/workspace/.config/opencode')).toBeInTheDocument()
|
||||
expect(screen.getByText('3 files (30 B)')).toBeInTheDocument()
|
||||
expect(screen.getByText('3 files (30 Bytes)')).toBeInTheDocument()
|
||||
expect(screen.getByText('opencode.jsonc')).toBeInTheDocument()
|
||||
expect(screen.getByText('plugin')).toBeInTheDocument()
|
||||
expect(screen.getByText('skills')).toBeInTheDocument()
|
||||
@@ -204,7 +220,7 @@ describe('OpenCodeConfigDirectoryUpload', () => {
|
||||
fireEvent.change(input, { target: { files: [] } })
|
||||
|
||||
await screen.findByText('Replace OpenCode Config Directory?')
|
||||
expect(screen.getByText('2 files (20 B)')).toBeInTheDocument()
|
||||
expect(screen.getByText('2 files (20 Bytes)')).toBeInTheDocument()
|
||||
expect(screen.getByText('opencode.jsonc')).toBeInTheDocument()
|
||||
expect(screen.getByText('skills')).toBeInTheDocument()
|
||||
expect(screen.queryByText('node_modules')).not.toBeInTheDocument()
|
||||
@@ -231,6 +247,18 @@ describe('OpenCodeConfigDirectoryUpload', () => {
|
||||
expect(screen.queryByText('Replace OpenCode Config Directory?')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('invokes onReplaced after a successful replace so the parent refetches configs', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onReplaced = vi.fn()
|
||||
renderComponent({ onReplaced })
|
||||
|
||||
await dropItems([makeItem('opencode/opencode.jsonc')])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Replace and Restart' }))
|
||||
|
||||
await waitFor(() => expect(onReplaced).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('surfaces a failed replace through an error toast', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockReplaceOpenCodeConfigDirectory.mockRejectedValue(new Error('boom'))
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { FolderUp, UploadCloud, Loader2 } from 'lucide-react'
|
||||
import {
|
||||
EXCLUDED_OPENCODE_CONFIG_UPLOAD_FILENAMES,
|
||||
EXCLUDED_OPENCODE_CONFIG_UPLOAD_SEGMENTS,
|
||||
MAX_OPENCODE_CONFIG_DIRECTORY_FILES,
|
||||
OPENCODE_CONFIG_UPLOAD_ERRORS,
|
||||
PRESERVED_OPENCODE_CONFIG_ENTRIES,
|
||||
getCommonUploadRootDirectory,
|
||||
isExcludedOpenCodeConfigUploadPath,
|
||||
isOpenCodeConfigUploadPath,
|
||||
stripUploadRootDirectory,
|
||||
} from '@opencode-manager/shared/utils'
|
||||
import { FILE_LIMITS } from '@/config'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { cn, formatBytes } from '@/lib/utils'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
@@ -17,33 +23,31 @@ import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import {
|
||||
DIRECTORY_INPUT_PROPS,
|
||||
getUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList,
|
||||
openPicker,
|
||||
readUploadItemsFromInput,
|
||||
useDirectoryDropZone,
|
||||
type DirectoryUploadItem,
|
||||
} from '@/lib/directoryUpload'
|
||||
import type { OpenCodeImportStatus, ReplaceOpenCodeConfigDirectoryResponse } from '@/api/types/settings'
|
||||
import type { OpenCodeImportStatus } from '@/api/types/settings'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
|
||||
const MAX_CONFIG_DIRECTORY_FILES = 5000
|
||||
const MAX_CONFIG_UPLOAD_BYTES = FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES
|
||||
const EXCLUDED_ENTRIES_DISPLAY = [
|
||||
...EXCLUDED_OPENCODE_CONFIG_UPLOAD_SEGMENTS,
|
||||
...EXCLUDED_OPENCODE_CONFIG_UPLOAD_FILENAMES,
|
||||
].join(', ')
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
interface OpenCodeConfigDirectoryUploadProps {
|
||||
onReplaced?: () => void
|
||||
}
|
||||
|
||||
function stripCommonRoot(relativePath: string, commonRoot: string | null): string {
|
||||
return commonRoot ? relativePath.slice(commonRoot.length + 1) : relativePath
|
||||
}
|
||||
|
||||
export function OpenCodeConfigDirectoryUpload() {
|
||||
export function OpenCodeConfigDirectoryUpload({ onReplaced }: OpenCodeConfigDirectoryUploadProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [stagedItems, setStagedItems] = useState<DirectoryUploadItem[] | null>(null)
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false)
|
||||
const [lastResult, setLastResult] = useState<ReplaceOpenCodeConfigDirectoryResponse | null>(null)
|
||||
const [lastResult, setLastResult] = useState<ReplaceOpenCodeConfigDirectoryResult | null>(null)
|
||||
const deferredConfigInvalidationRef = useRef(false)
|
||||
|
||||
const { data: importStatus } = useQuery<OpenCodeImportStatus>({
|
||||
queryKey: ['opencode-import-status'],
|
||||
@@ -54,8 +58,10 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
const replaceMutation = useMutation({
|
||||
mutationFn: (items: DirectoryUploadItem[]) => settingsApi.replaceOpenCodeConfigDirectory(items),
|
||||
onSuccess: (result) => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
onReplaced?.()
|
||||
deferredConfigInvalidationRef.current = true
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-import-status'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
setLastResult(result)
|
||||
setStagedItems(null)
|
||||
setIsConfirmOpen(false)
|
||||
@@ -68,6 +74,18 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event.type !== 'updated') return
|
||||
if (event.query.queryKey[0] !== 'health') return
|
||||
const health = queryClient.getQueryData<{ opencode?: 'healthy' | 'unhealthy' }>(['health'])
|
||||
if (!deferredConfigInvalidationRef.current || health?.opencode !== 'healthy') return
|
||||
deferredConfigInvalidationRef.current = false
|
||||
invalidateConfigCaches(queryClient)
|
||||
})
|
||||
return unsubscribe
|
||||
}, [queryClient])
|
||||
|
||||
const stageItems = (items: DirectoryUploadItem[]) => {
|
||||
if (items.length === 0) {
|
||||
showToast.error('No files were provided. Drop a folder containing opencode.json or opencode.jsonc at its root.')
|
||||
@@ -76,21 +94,21 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
|
||||
const commonRoot = getCommonUploadRootDirectory(items.map((item) => item.relativePath))
|
||||
const hasRootConfig = items.some((item) =>
|
||||
isOpenCodeConfigUploadPath(stripCommonRoot(item.relativePath, commonRoot)),
|
||||
isOpenCodeConfigUploadPath(stripUploadRootDirectory(item.relativePath, commonRoot)),
|
||||
)
|
||||
if (!hasRootConfig) {
|
||||
showToast.error('Uploaded directory must contain opencode.json or opencode.jsonc at its root')
|
||||
showToast.error(OPENCODE_CONFIG_UPLOAD_ERRORS.MISSING_ROOT_CONFIG)
|
||||
return
|
||||
}
|
||||
|
||||
if (items.length > MAX_CONFIG_DIRECTORY_FILES) {
|
||||
showToast.error(`Uploaded config directory contains too many files (max ${MAX_CONFIG_DIRECTORY_FILES})`)
|
||||
if (items.length > MAX_OPENCODE_CONFIG_DIRECTORY_FILES) {
|
||||
showToast.error(OPENCODE_CONFIG_UPLOAD_ERRORS.TOO_MANY_FILES)
|
||||
return
|
||||
}
|
||||
|
||||
const totalBytes = items.reduce((sum, item) => sum + item.file.size, 0)
|
||||
if (totalBytes > MAX_CONFIG_UPLOAD_BYTES) {
|
||||
showToast.error('Uploaded config directory files exceed maximum upload size')
|
||||
showToast.error(OPENCODE_CONFIG_UPLOAD_ERRORS.EXCEEDS_MAX_UPLOAD_SIZE)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -99,56 +117,35 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
setIsConfirmOpen(true)
|
||||
}
|
||||
|
||||
const handleDragEnter = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.currentTarget === dropZoneRef.current) {
|
||||
setIsDragging(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(false)
|
||||
|
||||
const items = await getUploadItemsFromDataTransfer(e.dataTransfer, {
|
||||
shouldSkip: (relativePath) => isExcludedOpenCodeConfigUploadPath(relativePath),
|
||||
})
|
||||
stageItems(items)
|
||||
}
|
||||
|
||||
const openFolderPicker = () => {
|
||||
requestAnimationFrame(() => folderInputRef.current?.click())
|
||||
}
|
||||
const { dropZoneRef, isDragging, dropHandlers } = useDirectoryDropZone({
|
||||
shouldSkip: (relativePath) => isExcludedOpenCodeConfigUploadPath(relativePath),
|
||||
onItems: stageItems,
|
||||
})
|
||||
|
||||
const handleFolderChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const fileList = event.target.files
|
||||
const items = fileList
|
||||
? getUploadItemsFromFileList(fileList).filter((item) => !isExcludedOpenCodeConfigUploadPath(item.relativePath))
|
||||
: []
|
||||
event.target.value = ''
|
||||
const items = readUploadItemsFromInput(event).filter((item) =>
|
||||
!isExcludedOpenCodeConfigUploadPath(item.relativePath),
|
||||
)
|
||||
stageItems(items)
|
||||
}
|
||||
|
||||
const stagedRoot = stagedItems ? getCommonUploadRootDirectory(stagedItems.map((item) => item.relativePath)) : null
|
||||
const topLevelEntries = stagedItems
|
||||
? Array.from(new Set(
|
||||
stagedItems.map((item) => stripCommonRoot(item.relativePath, stagedRoot).split('/')[0]),
|
||||
)).sort()
|
||||
: []
|
||||
const stagedTotalBytes = stagedItems?.reduce((sum, item) => sum + item.file.size, 0) ?? 0
|
||||
const stagedRoot = useMemo(
|
||||
() => (stagedItems ? getCommonUploadRootDirectory(stagedItems.map((item) => item.relativePath)) : null),
|
||||
[stagedItems],
|
||||
)
|
||||
const topLevelEntries = useMemo(
|
||||
() =>
|
||||
stagedItems
|
||||
? Array.from(new Set(
|
||||
stagedItems.map((item) => stripUploadRootDirectory(item.relativePath, stagedRoot).split('/')[0]),
|
||||
)).sort()
|
||||
: [],
|
||||
[stagedItems, stagedRoot],
|
||||
)
|
||||
const stagedTotalBytes = useMemo(
|
||||
() => stagedItems?.reduce((sum, item) => sum + item.file.size, 0) ?? 0,
|
||||
[stagedItems],
|
||||
)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
@@ -164,10 +161,7 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
<div
|
||||
ref={dropZoneRef}
|
||||
data-testid="config-directory-drop-zone"
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
{...dropHandlers}
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-6 text-center',
|
||||
isDragging ? 'border-primary bg-primary/5' : 'border-border',
|
||||
@@ -176,14 +170,14 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
<UploadCloud className="h-8 w-8 text-muted-foreground" />
|
||||
<p className="text-sm font-medium">Drag and drop your OpenCode config folder here</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The folder must contain opencode.json or opencode.jsonc at its root. node_modules, .git and .DS_Store
|
||||
entries are excluded automatically.
|
||||
The folder must contain opencode.json or opencode.jsonc at its root. {EXCLUDED_ENTRIES_DISPLAY} entries are
|
||||
excluded automatically.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={openFolderPicker}
|
||||
onClick={() => openPicker(folderInputRef)}
|
||||
disabled={replaceMutation.isPending}
|
||||
>
|
||||
{replaceMutation.isPending ? (
|
||||
@@ -264,7 +258,7 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
warning="Every file currently in the destination directory except node_modules will be deleted."
|
||||
warning={`Every file currently in the destination directory except ${PRESERVED_OPENCODE_CONFIG_ENTRIES.join(', ')} will be deleted.`}
|
||||
confirmLabel="Replace and Restart"
|
||||
pendingLabel="Replacing..."
|
||||
isPending={replaceMutation.isPending}
|
||||
|
||||
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeConfigManager } from './OpenCodeConfigManager'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
import type { DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
|
||||
const {
|
||||
mockGetOpenCodeConfigs,
|
||||
@@ -11,12 +12,16 @@ const {
|
||||
mockGetOpenCodeImportStatus,
|
||||
mockListManagedSkills,
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
mockReplaceOpenCodeConfigDirectory,
|
||||
mockGetUploadItemsFromDataTransfer,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfigs: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockGetOpenCodeImportStatus: vi.fn(),
|
||||
mockListManagedSkills: vi.fn(),
|
||||
mockListOpenCodeDirectoryFiles: vi.fn(),
|
||||
mockReplaceOpenCodeConfigDirectory: vi.fn(),
|
||||
mockGetUploadItemsFromDataTransfer: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
@@ -31,9 +36,34 @@ vi.mock('@/api/settings', () => ({
|
||||
listManagedSkills: mockListManagedSkills,
|
||||
listOpenCodeDirectoryFiles: mockListOpenCodeDirectoryFiles,
|
||||
syncOpenCodeImport: vi.fn(),
|
||||
replaceOpenCodeConfigDirectory: mockReplaceOpenCodeConfigDirectory,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/directoryUpload', () => ({
|
||||
DIRECTORY_INPUT_PROPS: { webkitdirectory: '', directory: '' },
|
||||
getUploadItemsFromDataTransfer: mockGetUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList: vi.fn(),
|
||||
openPicker: vi.fn(),
|
||||
readUploadItemsFromInput: vi.fn(),
|
||||
useDirectoryDropZone: (options: {
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean
|
||||
onItems: (items: DirectoryUploadItem[]) => void | Promise<void>
|
||||
}) => ({
|
||||
dropZoneRef: { current: null },
|
||||
isDragging: false,
|
||||
dropHandlers: {
|
||||
onDragEnter: vi.fn(),
|
||||
onDragOver: vi.fn(),
|
||||
onDragLeave: vi.fn(),
|
||||
onDrop: async (e: React.DragEvent) => {
|
||||
const items = await mockGetUploadItemsFromDataTransfer(e.dataTransfer)
|
||||
await options.onItems(items)
|
||||
},
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
const defaultConfig: OpenCodeConfig = {
|
||||
id: 1,
|
||||
name: 'default',
|
||||
@@ -183,4 +213,30 @@ describe('OpenCodeConfigManager', () => {
|
||||
resolveRefresh()
|
||||
await waitFor(() => expect(screen.queryByText('Edit Config: default')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('refetches the imperative config list after a config-directory replace', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockReplaceOpenCodeConfigDirectory.mockResolvedValue({
|
||||
configSourceFilename: 'opencode.json',
|
||||
filesInstalled: ['opencode.json'],
|
||||
skippedPaths: [],
|
||||
preservedEntries: [],
|
||||
executablesRestored: [],
|
||||
})
|
||||
mockGetUploadItemsFromDataTransfer.mockResolvedValue([
|
||||
{ file: new File(['{}'], 'opencode.json'), relativePath: 'opencode/opencode.json' },
|
||||
])
|
||||
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
expect(mockGetOpenCodeConfigs).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.drop(screen.getByTestId('config-directory-drop-zone'), { dataTransfer: { items: [] } })
|
||||
await screen.findByText('Replace OpenCode Config Directory?')
|
||||
await user.click(screen.getByRole('button', { name: 'Replace and Restart' }))
|
||||
|
||||
await waitFor(() => expect(mockReplaceOpenCodeConfigDirectory).toHaveBeenCalledTimes(1))
|
||||
await waitFor(() => expect(mockGetOpenCodeConfigs).toHaveBeenCalledTimes(2))
|
||||
})
|
||||
})
|
||||
@@ -418,7 +418,7 @@ export function OpenCodeConfigManager() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<OpenCodeConfigDirectoryUpload />
|
||||
<OpenCodeConfigDirectoryUpload onReplaced={() => void fetchConfigs(true)} />
|
||||
|
||||
|
||||
<CreateConfigDialog
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeRestartPendingNotice } from './OpenCodeRestartPendingNotice'
|
||||
|
||||
const {
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
healthState: { data: { opencode: 'healthy', opencodeRestartPending: false } as Record<string, unknown> },
|
||||
}))
|
||||
|
||||
@@ -18,107 +13,84 @@ vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: () => healthState,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
restartOpenCodeServer: mockRestartOpenCodeServer,
|
||||
getActiveOpenCodeSessions: mockGetActiveOpenCodeSessions,
|
||||
},
|
||||
}))
|
||||
|
||||
const NOTICE_TEXT = 'Configuration changes are saved but require a server restart to take effect.'
|
||||
|
||||
function renderWithQuery(ui: React.ReactElement) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(ui, {
|
||||
wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>,
|
||||
})
|
||||
interface NoticeProps {
|
||||
hasAutoPromptedRef: { current: boolean }
|
||||
openRestartPrompt: () => Promise<void>
|
||||
requestRestart: () => Promise<void>
|
||||
restartIsPending: boolean
|
||||
}
|
||||
|
||||
function renderNotice(overrides: Partial<NoticeProps> = {}) {
|
||||
const props: NoticeProps = {
|
||||
hasAutoPromptedRef: { current: false },
|
||||
openRestartPrompt: vi.fn().mockResolvedValue(undefined),
|
||||
requestRestart: vi.fn().mockResolvedValue(undefined),
|
||||
restartIsPending: false,
|
||||
...overrides,
|
||||
}
|
||||
const result = render(<OpenCodeRestartPendingNotice {...props} />)
|
||||
return { ...result, props }
|
||||
}
|
||||
|
||||
describe('OpenCodeRestartPendingNotice', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
})
|
||||
|
||||
it('renders nothing when no restart is pending', () => {
|
||||
renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
const { props } = renderNotice()
|
||||
|
||||
expect(screen.queryByText(NOTICE_TEXT)).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /restart now/i })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-opens the restart dialog when the pending flag flips to true', async () => {
|
||||
const { rerender } = renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
it('auto-opens the restart prompt when the pending flag flips to true', async () => {
|
||||
const { props, rerender } = renderNotice()
|
||||
expect(props.openRestartPrompt).not.toHaveBeenCalled()
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
rerender(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
expect(await screen.findByText('Restart OpenCode Server?')).toBeInTheDocument()
|
||||
expect(screen.getByText(/2 sessions are currently working/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('closes the dialog with "Later" without issuing a restart', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
rerender(<OpenCodeRestartPendingNotice {...props} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('restarts exactly once via the notice button plus dialog confirmation', async () => {
|
||||
it('does not re-prompt on re-render while the shared flag stays set', async () => {
|
||||
const { props, rerender } = renderNotice()
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
rerender(<OpenCodeRestartPendingNotice {...props} />)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /restart now/i }))
|
||||
expect(await screen.findByText('Restart OpenCode Server?')).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(2)
|
||||
rerender(<OpenCodeRestartPendingNotice {...props} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /restart now/i }))
|
||||
await waitFor(() => {
|
||||
expect(mockRestartOpenCodeServer).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not re-open a dismissed dialog on re-render while the flag stays true', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const user = userEvent.setup()
|
||||
const { rerender } = renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
rerender(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).toHaveBeenCalledTimes(1)
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requests a restart via the notice button', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const { props } = renderNotice()
|
||||
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: /restart now/i }))
|
||||
|
||||
expect(props.requestRestart).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('disables the restart button while a restart is in flight', () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
renderNotice({ restartIsPending: true })
|
||||
|
||||
expect(screen.getByRole('button', { name: /restart now/i })).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -1,33 +1,29 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, type RefObject } from 'react'
|
||||
import { AlertTriangle, Loader2, RotateCcw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
|
||||
export function OpenCodeRestartPendingNotice() {
|
||||
interface OpenCodeRestartPendingNoticeProps {
|
||||
hasAutoPromptedRef: RefObject<boolean>
|
||||
openRestartPrompt: () => void
|
||||
requestRestart: () => void
|
||||
restartIsPending: boolean
|
||||
}
|
||||
|
||||
export function OpenCodeRestartPendingNotice({
|
||||
hasAutoPromptedRef,
|
||||
openRestartPrompt,
|
||||
requestRestart,
|
||||
restartIsPending,
|
||||
}: OpenCodeRestartPendingNoticeProps) {
|
||||
const { data: health } = useServerHealth()
|
||||
const {
|
||||
restartServerMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
openRestartPrompt,
|
||||
} = useOpenCodeServerActions()
|
||||
const hasPromptedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (health?.opencodeRestartPending) {
|
||||
if (!hasPromptedRef.current) {
|
||||
hasPromptedRef.current = true
|
||||
void openRestartPrompt()
|
||||
}
|
||||
} else {
|
||||
hasPromptedRef.current = false
|
||||
if (health?.opencodeRestartPending && !hasAutoPromptedRef.current) {
|
||||
hasAutoPromptedRef.current = true
|
||||
void openRestartPrompt()
|
||||
}
|
||||
}, [health?.opencodeRestartPending, openRestartPrompt])
|
||||
}, [health?.opencodeRestartPending, hasAutoPromptedRef, openRestartPrompt])
|
||||
|
||||
if (!health?.opencodeRestartPending) {
|
||||
return null
|
||||
@@ -45,10 +41,10 @@ export function OpenCodeRestartPendingNotice() {
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
disabled={restartIsPending}
|
||||
className="shrink-0"
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
{restartIsPending ? (
|
||||
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 mr-1" />
|
||||
@@ -56,14 +52,6 @@ export function OpenCodeRestartPendingNotice() {
|
||||
Restart Now
|
||||
</Button>
|
||||
</div>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,25 +3,23 @@ import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Loader2, ArrowUpCircle, RotateCcw, History } from 'lucide-react'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
|
||||
interface ServerHealthStatusProps {
|
||||
onOpenVersionDialog?: () => void
|
||||
requestRestart: () => void
|
||||
restartIsPending: boolean
|
||||
performUpgrade: () => void
|
||||
upgradeIsPending: boolean
|
||||
}
|
||||
|
||||
export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusProps) {
|
||||
export function ServerHealthStatus({
|
||||
onOpenVersionDialog,
|
||||
requestRestart,
|
||||
restartIsPending,
|
||||
performUpgrade,
|
||||
upgradeIsPending,
|
||||
}: ServerHealthStatusProps) {
|
||||
const { data: health } = useServerHealth()
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
if (!health) {
|
||||
return (
|
||||
@@ -68,9 +66,9 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={performUpgrade}
|
||||
disabled={upgradeOpenCodeMutation.isPending}
|
||||
disabled={upgradeIsPending}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
{upgradeIsPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<ArrowUpCircle className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
@@ -81,9 +79,9 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
disabled={restartIsPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
{restartIsPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
@@ -101,14 +99,6 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -9,13 +9,15 @@ import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
const {
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
healthState: { data: { opencode: 'healthy', opencodeRestartPending: true } as Record<string, unknown> },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: () => ({ data: { opencode: 'healthy', opencodeRestartPending: true } }),
|
||||
useServerHealth: () => healthState,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
@@ -92,10 +94,18 @@ vi.mock('@/hooks/useMobile', () => ({
|
||||
describe('SettingsDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
})
|
||||
|
||||
function renderWithSettingsContext(ui: React.ReactElement) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(ui, {
|
||||
wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>,
|
||||
})
|
||||
}
|
||||
|
||||
it('resets to menu state when dialog closes and reopens', () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
@@ -114,7 +124,7 @@ describe('SettingsDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
@@ -147,7 +157,7 @@ describe('SettingsDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
@@ -182,10 +192,10 @@ describe('SettingsDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/?settings=open']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>,
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
@@ -197,7 +207,89 @@ describe('SettingsDialog', () => {
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('mounts a single restart-pending notice and dialog on the OpenCode tab', async () => {
|
||||
it('mounts a single restart-pending dialog on the OpenCode tab', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const isOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate('?settings=open')}>Open Settings</button>
|
||||
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByText('Open Settings'))
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
expect(screen.getAllByText('Restart OpenCode Server?')).toHaveLength(1)
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(2)
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByText('Restart OpenCode Server?')).toHaveLength(0)
|
||||
})
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(2)
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not re-open the auto-prompted dialog after Later when switching tabs away and back', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const isOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate('?settings=open')}>Open Settings</button>
|
||||
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByText('Open Settings'))
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByText('Restart OpenCode Server?')).toHaveLength(0)
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Git' }))
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(2)
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('re-prompts when a new pending restart arrives after the previous one cleared', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
@@ -214,7 +306,7 @@ describe('SettingsDialog', () => {
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
render(
|
||||
const { rerender } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
@@ -227,14 +319,30 @@ describe('SettingsDialog', () => {
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
expect(screen.getAllByText('Restart OpenCode Server?')).toHaveLength(1)
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(1)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByText('Restart OpenCode Server?')).toHaveLength(0)
|
||||
})
|
||||
expect(screen.getByText('Configuration changes are saved but require a server restart to take effect.')).toBeInTheDocument()
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
expect(await screen.findByText('Restart OpenCode Server?')).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { GeneralSettings } from '@/components/settings/GeneralSettings'
|
||||
import { GitSettings } from '@/components/settings/GitSettings'
|
||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
@@ -6,6 +6,7 @@ import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManag
|
||||
import { OpenCodeRestartPendingNotice } from '@/components/settings/OpenCodeRestartPendingNotice'
|
||||
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
|
||||
import { ManagerTokenSettings } from '@/components/settings/ManagerTokenSettings'
|
||||
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
|
||||
import { ServerEnvVarsSettings } from '@/components/settings/ServerEnvVarsSettings'
|
||||
import { ServerHealthStatus } from '@/components/settings/ServerHealthStatus'
|
||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||
@@ -18,17 +19,38 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Settings2, Keyboard, Code, ChevronLeft, Key, GitBranch, User, Volume2, Bell, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications'
|
||||
|
||||
export function SettingsDialog() {
|
||||
const { isOpen, close, activeTab, setActiveTab } = useSettingsDialog()
|
||||
const { data: health } = useServerHealth()
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
openRestartPrompt,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
const hasAutoPromptedRef = useRef(false)
|
||||
const [mobileView, setMobileView] = useState<SettingsView>('menu')
|
||||
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
|
||||
const [sectionHistory, setSectionHistory] = useState<SettingsView[]>([])
|
||||
const [authSectionsOpen, setAuthSectionsOpen] = useState(true)
|
||||
const toggleAuthSections = useCallback(() => setAuthSectionsOpen((open) => !open), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!health?.opencodeRestartPending) {
|
||||
hasAutoPromptedRef.current = false
|
||||
}
|
||||
}, [health?.opencodeRestartPending])
|
||||
|
||||
const pushSectionHistory = useCallback((view: SettingsView) => {
|
||||
if (view === 'menu') return
|
||||
setSectionHistory((history) => {
|
||||
@@ -119,7 +141,6 @@ export function SettingsDialog() {
|
||||
data-settings-dialog
|
||||
>
|
||||
<DialogTitle className="sr-only">Settings</DialogTitle>
|
||||
{activeTab === 'opencode' && <OpenCodeRestartPendingNotice />}
|
||||
<div className="hidden sm:flex sm:flex-col sm:h-full sm:min-h-0">
|
||||
<div className="sticky top-0 z-10 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-6 py-4 flex-shrink-0 flex items-center justify-between">
|
||||
<h2 className="text-2xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
|
||||
@@ -133,7 +154,15 @@ export function SettingsDialog() {
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{activeTab === 'opencode' && (
|
||||
<OpenCodeRestartPendingNotice
|
||||
hasAutoPromptedRef={hasAutoPromptedRef}
|
||||
openRestartPrompt={openRestartPrompt}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
<Tabs defaultValue="account" value={activeTab} onValueChange={handleTabChange} className="w-full flex flex-col flex-1 min-h-0">
|
||||
<div className="px-6 pt-6 pb-4 flex-shrink-0">
|
||||
<TabsList className="grid w-full grid-cols-8 bg-card p-1">
|
||||
@@ -174,7 +203,13 @@ export function SettingsDialog() {
|
||||
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||
<TabsContent key="opencode" value="opencode" className="mt-0">
|
||||
<div className="space-y-6">
|
||||
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
<ServerHealthStatus
|
||||
onOpenVersionDialog={() => setIsVersionDialogOpen(true)}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
performUpgrade={performUpgrade}
|
||||
upgradeIsPending={upgradeOpenCodeMutation.isPending}
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<OpenCodeServerAuthSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
@@ -216,6 +251,15 @@ export function SettingsDialog() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{mobileView === 'opencode' && (
|
||||
<OpenCodeRestartPendingNotice
|
||||
hasAutoPromptedRef={hasAutoPromptedRef}
|
||||
openRestartPrompt={openRestartPrompt}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-3 pb-[calc(env(safe-area-inset-bottom)+1rem)]">
|
||||
{mobileView === 'menu' && (
|
||||
<div className="space-y-3">
|
||||
@@ -247,7 +291,13 @@ export function SettingsDialog() {
|
||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-4">
|
||||
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
<ServerHealthStatus
|
||||
onOpenVersionDialog={() => setIsVersionDialogOpen(true)}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
performUpgrade={performUpgrade}
|
||||
upgradeIsPending={upgradeOpenCodeMutation.isPending}
|
||||
/>
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<ServerEnvVarsSettings />
|
||||
@@ -263,6 +313,14 @@ export function SettingsDialog() {
|
||||
open={isVersionDialogOpen}
|
||||
onOpenChange={setIsVersionDialogOpen}
|
||||
/>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { DIRECTORY_INPUT_PROPS, getUploadItemsFromFileList } from '@/lib/directoryUpload'
|
||||
import { DIRECTORY_INPUT_PROPS, openPicker, readUploadItemsFromInput } from '@/lib/directoryUpload'
|
||||
|
||||
const KIND_NOUN: Record<'agents' | 'commands', string> = {
|
||||
agents: 'agent',
|
||||
@@ -29,14 +29,8 @@ export function UploadFolderButton({ kind }: UploadFolderButtonProps) {
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
const noun = KIND_NOUN[kind]
|
||||
|
||||
const openPicker = (inputRef: React.RefObject<HTMLInputElement | null>) => {
|
||||
requestAnimationFrame(() => inputRef.current?.click())
|
||||
}
|
||||
|
||||
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const fileList = event.target.files
|
||||
const items = fileList ? getUploadItemsFromFileList(fileList) : []
|
||||
event.target.value = ''
|
||||
const items = readUploadItemsFromInput(event)
|
||||
if (items.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -78,17 +78,20 @@ export function useOpenCodeServerActions() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
const openRestartPrompt = useCallback(async () => {
|
||||
const count = await probeActiveSessionCount()
|
||||
const showRestartConfirmation = useCallback((count: number) => {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
}, [probeActiveSessionCount, setActiveSessionCount, setConfirmOpen])
|
||||
}, [setActiveSessionCount, setConfirmOpen])
|
||||
|
||||
const openRestartPrompt = useCallback(async () => {
|
||||
const count = await probeActiveSessionCount()
|
||||
showRestartConfirmation(count)
|
||||
}, [probeActiveSessionCount, showRestartConfirmation])
|
||||
|
||||
const requestRestart = async () => {
|
||||
const count = await probeActiveSessionCount()
|
||||
if (count > 0) {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
showRestartConfirmation(count)
|
||||
return
|
||||
}
|
||||
await performRestart()
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getUploadItemsFromDataTransfer, getUploadItemsFromFileList } from './directoryUpload'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import type { DragEvent } from 'react'
|
||||
import { isExcludedOpenCodeConfigUploadPath } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
getUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList,
|
||||
useDirectoryDropZone,
|
||||
type DirectoryUploadItem,
|
||||
} from './directoryUpload'
|
||||
|
||||
interface StubFileEntry {
|
||||
name: string
|
||||
@@ -44,6 +52,15 @@ function createDirReader(children: FileSystemEntry[]): FileSystemDirectoryReader
|
||||
} as unknown as FileSystemDirectoryReader
|
||||
}
|
||||
|
||||
function createBatchedDirReader(batches: FileSystemEntry[][]): FileSystemDirectoryReader {
|
||||
let index = 0
|
||||
return {
|
||||
readEntries: (successCallback: (entries: FileSystemEntry[]) => void) => {
|
||||
successCallback(index < batches.length ? batches[index++] : [])
|
||||
},
|
||||
} as unknown as FileSystemDirectoryReader
|
||||
}
|
||||
|
||||
function createDirectoryEntry(name: string, children: FileSystemEntry[]): { entry: FileSystemDirectoryEntry; readerCreated: () => number } {
|
||||
let readerCreated = 0
|
||||
const entry = {
|
||||
@@ -58,6 +75,20 @@ function createDirectoryEntry(name: string, children: FileSystemEntry[]): { entr
|
||||
return { entry, readerCreated: () => readerCreated }
|
||||
}
|
||||
|
||||
function createBatchedDirectoryEntry(name: string, batches: FileSystemEntry[][]): { entry: FileSystemDirectoryEntry; readerCreated: () => number } {
|
||||
let readerCreated = 0
|
||||
const entry = {
|
||||
name,
|
||||
isFile: false,
|
||||
isDirectory: true,
|
||||
createReader: () => {
|
||||
readerCreated++
|
||||
return createBatchedDirReader(batches)
|
||||
},
|
||||
} as StubDirectoryEntry as unknown as FileSystemDirectoryEntry
|
||||
return { entry, readerCreated: () => readerCreated }
|
||||
}
|
||||
|
||||
function createDataTransfer(entries: FileSystemEntry[]): DataTransfer {
|
||||
return {
|
||||
items: entries.map((entry) => ({ webkitGetAsEntry: () => entry })),
|
||||
@@ -92,6 +123,77 @@ describe('getUploadItemsFromDataTransfer', () => {
|
||||
expect(junk.readCount()).toBe(0)
|
||||
expect(nodeModules.readerCreated()).toBe(0)
|
||||
})
|
||||
|
||||
it('returns the complete file set across readEntries batches while pruning skipped subtrees', async () => {
|
||||
const files: FileSystemEntry[] = []
|
||||
const expectedPaths: string[] = []
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const file = createFileEntry(`file${i}.md`)
|
||||
files.push(file.entry)
|
||||
expectedPaths.push(`root/file${i}.md`)
|
||||
}
|
||||
const junk = createFileEntry('junk.js')
|
||||
const nodeModules = createDirectoryEntry('node_modules', [junk.entry])
|
||||
const root = createBatchedDirectoryEntry('root', [files.slice(0, 100), files.slice(100), [nodeModules.entry]])
|
||||
|
||||
const items = await getUploadItemsFromDataTransfer(createDataTransfer([root.entry]), {
|
||||
shouldSkip: (relativePath) => relativePath.split('/').includes('node_modules'),
|
||||
})
|
||||
|
||||
expect(items.map((item) => item.relativePath)).toEqual(expectedPaths)
|
||||
expect(items).toHaveLength(120)
|
||||
expect(junk.readCount()).toBe(0)
|
||||
expect(nodeModules.readerCreated()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDirectoryDropZone', () => {
|
||||
function dropOnZone(handlers: ReturnType<typeof useDirectoryDropZone>['dropHandlers'], entries: FileSystemEntry[]) {
|
||||
return act(async () => {
|
||||
await handlers.onDrop({
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
dataTransfer: createDataTransfer(entries),
|
||||
} as unknown as DragEvent)
|
||||
})
|
||||
}
|
||||
|
||||
it('passes the traversed items to onItems without applying skips, as the file browser consumes it', async () => {
|
||||
const onItems = vi.fn()
|
||||
const { result } = renderHook(() => useDirectoryDropZone({ onItems }))
|
||||
const keep = createFileEntry('keep.md')
|
||||
const junk = createFileEntry('junk.js')
|
||||
const nodeModules = createDirectoryEntry('node_modules', [junk.entry])
|
||||
const root = createDirectoryEntry('root', [keep.entry, nodeModules.entry])
|
||||
|
||||
await dropOnZone(result.current.dropHandlers, [root.entry])
|
||||
|
||||
expect(onItems).toHaveBeenCalledTimes(1)
|
||||
const items = onItems.mock.calls[0][0] as DirectoryUploadItem[]
|
||||
expect(items.map((item) => item.relativePath)).toEqual(['root/keep.md', 'root/node_modules/junk.js'])
|
||||
})
|
||||
|
||||
it('applies the shouldSkip filter for the config-directory consumer', async () => {
|
||||
const onItems = vi.fn()
|
||||
const { result } = renderHook(() =>
|
||||
useDirectoryDropZone({
|
||||
shouldSkip: (relativePath) => isExcludedOpenCodeConfigUploadPath(relativePath),
|
||||
onItems,
|
||||
}),
|
||||
)
|
||||
const keep = createFileEntry('keep.md')
|
||||
const junk = createFileEntry('junk.js')
|
||||
const dotGit = createFileEntry('config')
|
||||
const nodeModules = createDirectoryEntry('node_modules', [junk.entry])
|
||||
const gitDir = createDirectoryEntry('.git', [dotGit.entry])
|
||||
const root = createDirectoryEntry('root', [keep.entry, nodeModules.entry, gitDir.entry])
|
||||
|
||||
await dropOnZone(result.current.dropHandlers, [root.entry])
|
||||
|
||||
expect(onItems).toHaveBeenCalledTimes(1)
|
||||
const items = onItems.mock.calls[0][0] as DirectoryUploadItem[]
|
||||
expect(items.map((item) => item.relativePath)).toEqual(['root/keep.md'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getUploadItemsFromFileList', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { InputHTMLAttributes } from 'react'
|
||||
import { useRef, useState } from 'react'
|
||||
import type { ChangeEvent, DragEvent, InputHTMLAttributes, RefObject } from 'react'
|
||||
|
||||
export interface DirectoryUploadItem {
|
||||
file: File
|
||||
@@ -11,6 +12,8 @@ export const DIRECTORY_INPUT_PROPS = {
|
||||
mozdirectory: '',
|
||||
} as InputHTMLAttributes<HTMLInputElement>
|
||||
|
||||
const DIRECTORY_TRAVERSAL_CONCURRENCY = 25
|
||||
|
||||
async function readFileEntry(entry: FileSystemFileEntry): Promise<File> {
|
||||
return new Promise((resolve, reject) => {
|
||||
entry.file(resolve, reject)
|
||||
@@ -23,7 +26,7 @@ async function readDirectoryEntries(dirReader: FileSystemDirectoryReader): Promi
|
||||
})
|
||||
}
|
||||
|
||||
export async function traverseFileSystemEntry(
|
||||
async function traverseFileSystemEntry(
|
||||
entry: FileSystemEntry,
|
||||
basePath: string = '',
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean,
|
||||
@@ -48,9 +51,14 @@ export async function traverseFileSystemEntry(
|
||||
entries = entries.concat(batch)
|
||||
} while (batch.length > 0)
|
||||
|
||||
for (const childEntry of entries) {
|
||||
const childItems = await traverseFileSystemEntry(childEntry, relativePath, shouldSkip)
|
||||
items.push(...childItems)
|
||||
for (let i = 0; i < entries.length; i += DIRECTORY_TRAVERSAL_CONCURRENCY) {
|
||||
const childBatch = entries.slice(i, i + DIRECTORY_TRAVERSAL_CONCURRENCY)
|
||||
const childBatchItems = await Promise.all(
|
||||
childBatch.map((childEntry) => traverseFileSystemEntry(childEntry, relativePath, shouldSkip)),
|
||||
)
|
||||
for (const childItems of childBatchItems) {
|
||||
items.push(...childItems)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,3 +105,63 @@ export function getUploadItemsFromFileList(fileList: FileList): DirectoryUploadI
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export function openPicker(inputRef: RefObject<HTMLInputElement | null>): void {
|
||||
requestAnimationFrame(() => inputRef.current?.click())
|
||||
}
|
||||
|
||||
export function readUploadItemsFromInput(event: ChangeEvent<HTMLInputElement>): DirectoryUploadItem[] {
|
||||
const fileList = event.target.files
|
||||
const items = fileList ? getUploadItemsFromFileList(fileList) : []
|
||||
event.target.value = ''
|
||||
return items
|
||||
}
|
||||
|
||||
interface DirectoryDropZoneOptions {
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean
|
||||
onItems: (items: DirectoryUploadItem[]) => void | Promise<void>
|
||||
}
|
||||
|
||||
export function useDirectoryDropZone(options: DirectoryDropZoneOptions) {
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const { shouldSkip, onItems } = options
|
||||
|
||||
const handleDragEnter = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.currentTarget === dropZoneRef.current) {
|
||||
setIsDragging(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDrop = async (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(false)
|
||||
const items = await getUploadItemsFromDataTransfer(e.dataTransfer, shouldSkip ? { shouldSkip } : undefined)
|
||||
await onItems(items)
|
||||
}
|
||||
|
||||
return {
|
||||
dropZoneRef,
|
||||
isDragging,
|
||||
dropHandlers: {
|
||||
onDragEnter: handleDragEnter,
|
||||
onDragOver: handleDragOver,
|
||||
onDragLeave: handleDragLeave,
|
||||
onDrop: handleDrop,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ export function invalidateConfigCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-directory-files'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
invalidateProviderCaches(queryClient)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,14 @@ export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
const k = 1024
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'] as const
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
|
||||
}
|
||||
|
||||
export function randomId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
|
||||
Generated
-3
@@ -47,9 +47,6 @@ importers:
|
||||
hono:
|
||||
specifier: ^4.11.7
|
||||
version: 4.11.7
|
||||
jsonc-parser:
|
||||
specifier: ^3.3.1
|
||||
version: 3.3.1
|
||||
typescript:
|
||||
specifier: ^5
|
||||
version: 5.9.3
|
||||
|
||||
@@ -104,6 +104,7 @@ export type AssistantSettingsPatch = z.infer<typeof AssistantSettingsPatchSchema
|
||||
export { FetchError } from './errors'
|
||||
export type { ApiErrorResponse, ApiErrorCode, GitErrorCode } from './errors'
|
||||
export { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '../schemas/settings'
|
||||
export type { ReplaceOpenCodeConfigDirectoryResult } from './settings'
|
||||
|
||||
export interface SuccessResponse {
|
||||
success: boolean
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface ReplaceOpenCodeConfigDirectoryResult {
|
||||
configSourceFilename: string
|
||||
filesInstalled: string[]
|
||||
skippedPaths: string[]
|
||||
preservedEntries: string[]
|
||||
executablesRestored: string[]
|
||||
}
|
||||
@@ -1,13 +1,27 @@
|
||||
export const OPENCODE_CONFIG_FILENAMES = ['opencode.json', 'opencode.jsonc'] as const
|
||||
const OPENCODE_CONFIG_FILENAMES = ['opencode.json', 'opencode.jsonc'] as const
|
||||
|
||||
export const OPENCODE_CANONICAL_CONFIG_FILENAME = 'opencode.json'
|
||||
|
||||
export const MAX_OPENCODE_CONFIG_DIRECTORY_FILES = 5000
|
||||
|
||||
export const EXCLUDED_OPENCODE_CONFIG_UPLOAD_SEGMENTS = ['node_modules', '.git'] as const
|
||||
|
||||
export const EXCLUDED_OPENCODE_CONFIG_UPLOAD_FILENAMES = ['.DS_Store'] as const
|
||||
|
||||
export const PRESERVED_OPENCODE_CONFIG_ENTRIES = ['node_modules'] as const
|
||||
|
||||
export const OPENCODE_CONFIG_STAGING_PREFIX = '.opencode-config-staging-'
|
||||
|
||||
export const OPENCODE_CONFIG_BACKUP_PREFIX = '.opencode-config-backup-'
|
||||
|
||||
export const OPENCODE_CONFIG_UPLOAD_ERRORS = {
|
||||
NO_FILES_PROVIDED: 'No files were provided for the OpenCode config directory replace',
|
||||
TOO_MANY_FILES: `Uploaded config directory contains too many files (max ${MAX_OPENCODE_CONFIG_DIRECTORY_FILES})`,
|
||||
EXCEEDS_MAX_UPLOAD_SIZE: 'Uploaded config directory files exceed maximum upload size',
|
||||
MISSING_ROOT_CONFIG: 'Uploaded directory must contain opencode.json or opencode.jsonc at its root',
|
||||
} as const
|
||||
|
||||
export function isOpenCodeConfigUploadPath(relativePath: string): boolean {
|
||||
if (relativePath.includes('/')) return false
|
||||
return OPENCODE_CONFIG_FILENAMES.some((filename) => filename === relativePath)
|
||||
}
|
||||
|
||||
@@ -28,3 +42,7 @@ export function getCommonUploadRootDirectory(relativePaths: string[]): string |
|
||||
if (!relativePaths.some((relativePath) => relativePath.includes('/'))) return null
|
||||
return root
|
||||
}
|
||||
|
||||
export function stripUploadRootDirectory(relativePath: string, commonRoot: string | null): string {
|
||||
return commonRoot ? relativePath.slice(commonRoot.length + 1) : relativePath
|
||||
}
|
||||
Reference in new issue
Block a user