mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat: directory files upload system, deferred restart model, cache invalidation consolidation, and misc improvements (#281)
* feat: show variant label on model picker and add folder upload for agents/commands
- Replace three-dot variant menu trigger with selected variant label
- Add POST /api/settings/opencode-directory-files/install endpoint
- Upload agents/commands markdown folders into .config/opencode/{agents,commands}/
- Reload OpenCode server after upload so files are picked up
* fix: revalidate branch/git caches when mobile sheet opens and on vcs.branch.updated SSE
- add shared invalidateRepoGitCaches() helper for consistent invalidation
- revalidate repo list when mobile repo quick-switch sheet opens
- revalidate current repo when mobile More drawer opens
- revalidate repo/git caches when Source Control dialog opens
- handle vcs.branch.updated SSE event with optimistic cache update
- use helper in branch create/switch mutations in useGit and BranchesTab
* style: make variant selector look more like a button with chevron and compact sizing
* refactor: consolidate settings editors, add folder upload support, and clean up unused code
* refactor: consolidate settings editors, add folder upload support, and clean up unused code
* feat: add opencode-directory-files listing service and consolidate settings editors
* fix: distinguish scroll from tap in suggestion popups on touch devices
* refactor: consolidate settings editors and add DirectoryFilesList component
* refactor: target repo status cache updates only to affected batch entries
* refactor: streamline settings, git hooks, and query invalidation logic
This commit is contained in:
1 parent
e53b4fd32c
commit
617962f2dd
48 files changed
+1522
-293
No files matched your search
@@ -91,6 +91,7 @@ export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSu
|
||||
opencodeMinVersion: opencodeServerManager.getMinVersion(),
|
||||
opencodeVersionSupported: opencodeServerManager.isVersionSupported(),
|
||||
opencodeManagerVersion,
|
||||
opencodeRestartPending: opencodeServerManager.isRestartPending(),
|
||||
}
|
||||
|
||||
if (lifecycle) {
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createSettingsRoutes } from './settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
|
||||
interface TestUserPreferenceRow {
|
||||
@@ -205,9 +210,9 @@ function createTestDb(): Database {
|
||||
return db
|
||||
}
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
function createTestApp(db: Database, openCodeSupervisor?: OpenCodeSupervisor): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient()))
|
||||
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient(), openCodeSupervisor))
|
||||
return app
|
||||
}
|
||||
|
||||
@@ -291,3 +296,78 @@ describe('settings routes — serverEnvVars', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings routes — OpenCode directory file upload', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let originalWorkspacePath: string | undefined
|
||||
let workspacePath: string
|
||||
const restart = vi.fn(async () => undefined)
|
||||
let markRestartPendingSpy: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(async () => {
|
||||
db = createTestDb()
|
||||
restart.mockClear()
|
||||
markRestartPendingSpy = vi.spyOn(opencodeServerManager, 'markRestartPending').mockImplementation(() => undefined)
|
||||
originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
workspacePath = await mkdtemp(join(tmpdir(), 'ocm-command-upload-'))
|
||||
process.env.WORKSPACE_PATH = workspacePath
|
||||
app = createTestApp(db, { restart } as unknown as OpenCodeSupervisor)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalWorkspacePath) {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
} else {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
}
|
||||
await rm(workspacePath, { recursive: true, force: true })
|
||||
db.close()
|
||||
markRestartPendingSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('installs uploaded command markdown files into the OpenCode commands directory', async () => {
|
||||
const formData = new FormData()
|
||||
formData.append('kind', 'commands')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'commands/git/commit.md' },
|
||||
{ fieldName: 'file1', relativePath: 'commands/.DS_Store' },
|
||||
]))
|
||||
formData.append('file0', new File(['commit body'], 'commit.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await app.request('/settings/opencode-directory-files/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
kind: 'commands',
|
||||
filesInstalled: ['git/commit.md'],
|
||||
restartRequired: true,
|
||||
})
|
||||
await expect(readFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'utf8')).resolves.toBe('commit body')
|
||||
expect(restart).not.toHaveBeenCalled()
|
||||
expect(markRestartPendingSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('lists uploaded command and agent directory files', async () => {
|
||||
await mkdir(join(workspacePath, '.config/opencode/commands/git'), { recursive: true })
|
||||
await mkdir(join(workspacePath, '.config/opencode/agents/team'), { recursive: true })
|
||||
await writeFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'commit body')
|
||||
await writeFile(join(workspacePath, '.config/opencode/commands/git/.DS_Store'), 'metadata')
|
||||
await writeFile(join(workspacePath, '.config/opencode/agents/team/planner.md'), 'planner body')
|
||||
|
||||
const commandsRes = await app.request('/settings/opencode-directory-files?kind=commands')
|
||||
const agentsRes = await app.request('/settings/opencode-directory-files?kind=agents')
|
||||
|
||||
expect(commandsRes.status).toBe(200)
|
||||
expect(agentsRes.status).toBe(200)
|
||||
await expect(commandsRes.json()).resolves.toEqual([
|
||||
{ kind: 'commands', name: 'commit', relativePath: 'git/commit.md' },
|
||||
])
|
||||
await expect(agentsRes.json()).resolves.toEqual([
|
||||
{ kind: 'agents', name: 'planner', relativePath: 'team/planner.md' },
|
||||
])
|
||||
})
|
||||
})
|
||||
+185
-54
@@ -1,4 +1,4 @@
|
||||
import { Hono } from 'hono'
|
||||
import { Hono, type Context } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { execSync, spawnSync } from 'child_process'
|
||||
import { existsSync } from 'fs'
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
SkillScopeSchema,
|
||||
InstallSkillFromGithubRequestSchema,
|
||||
InstallSkillUploadRequestSchema,
|
||||
InstallSkillUploadManifestEntrySchema,
|
||||
type SkillScope,
|
||||
} from '@opencode-manager/shared'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -45,6 +44,14 @@ import {
|
||||
installSkillFromGithubTree,
|
||||
installSkillFromUploadedFiles,
|
||||
} from '../services/skills'
|
||||
import {
|
||||
installOpenCodeDirectoryFiles,
|
||||
listOpenCodeDirectoryFiles,
|
||||
getOpenCodeDirectoryFile,
|
||||
updateOpenCodeDirectoryFile,
|
||||
deleteOpenCodeDirectoryFile,
|
||||
} from '../services/opencode-directory-files'
|
||||
import { parseUploadManifest, readUploadedManifestFiles, UploadValidationError } from './upload-utils'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { githubFetch } from '../utils/github'
|
||||
|
||||
@@ -103,9 +110,9 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info(`Restarted OpenCode server after skill ${context}`)
|
||||
logger.info(`Restarted OpenCode server after ${context}`)
|
||||
} catch (restartError) {
|
||||
logger.warn(`Failed to restart OpenCode server after skill ${context}:`, restartError)
|
||||
logger.warn(`Failed to restart OpenCode server after ${context}:`, restartError)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +128,7 @@ async function dispatchSkillReload(
|
||||
return
|
||||
}
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'install')
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'skill install')
|
||||
|
||||
try {
|
||||
await openCodeClient.forward({
|
||||
@@ -141,12 +148,53 @@ async function reloadAfterSkillInstall(
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
scope: SkillScope,
|
||||
repoId: number | undefined,
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
if (scope === 'project' && repoId !== undefined) {
|
||||
await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, repoId)
|
||||
} else {
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'install')
|
||||
return false
|
||||
}
|
||||
|
||||
opencodeServerManager.markRestartPending()
|
||||
return true
|
||||
}
|
||||
|
||||
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],
|
||||
]
|
||||
|
||||
function matchErrorStatus<T extends number>(
|
||||
table: ReadonlyArray<readonly [string, T]>,
|
||||
error: Error,
|
||||
): T | null {
|
||||
const match = table.find(([needle]) => error.message.includes(needle))
|
||||
return match ? match[1] : null
|
||||
}
|
||||
|
||||
function handleOpenCodeDirectoryFileError(c: Context, error: unknown, operation: string) {
|
||||
logger.error(`Failed to ${operation} OpenCode directory file:`, error)
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
if ('code' in error && error.code === 'ENOENT') {
|
||||
return c.json({ error: 'File not found' }, 404)
|
||||
}
|
||||
|
||||
const status = matchErrorStatus(OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS, error)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ error: `Failed to ${operation} OpenCode directory file` }, 500)
|
||||
}
|
||||
|
||||
const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 404 | 409]> = [
|
||||
@@ -194,6 +242,10 @@ function parseBooleanFormValue(value: unknown): boolean | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
function getMarkdownUploadManifest(manifest: ReturnType<typeof parseUploadManifest>) {
|
||||
return manifest.filter(entry => entry.relativePath.toLowerCase().endsWith('.md'))
|
||||
}
|
||||
|
||||
function hasConfiguredPlugins(config: Record<string, unknown> | undefined): boolean {
|
||||
return Array.isArray(config?.plugin) && config.plugin.length > 0
|
||||
}
|
||||
@@ -522,9 +574,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
if (restartRequired) {
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
logger.info('OpenCode configuration requires process restart')
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('OpenCode configuration change requires a server restart; deferring until requested')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ ...config, restartRequired: true })
|
||||
} else {
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
|
||||
if (!patchResult.success) {
|
||||
@@ -1217,6 +1269,109 @@ 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 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)
|
||||
}
|
||||
|
||||
const files = await readUploadedManifestFiles(formData, markdownManifest)
|
||||
|
||||
const result = await installOpenCodeDirectoryFiles(kind, files)
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ ...result, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to install OpenCode directory files:', error)
|
||||
|
||||
if (error instanceof UploadValidationError) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid upload data', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const status = matchErrorStatus(OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS, error)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ error: 'Failed to install OpenCode directory files' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-directory-files', async (c) => {
|
||||
try {
|
||||
const kind = z.enum(['agents', 'commands']).parse(c.req.query('kind'))
|
||||
return c.json(await listOpenCodeDirectoryFiles(kind))
|
||||
} catch (error) {
|
||||
logger.error('Failed to list OpenCode directory files:', error)
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid file kind', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
return c.json({ error: 'Failed to list OpenCode directory files' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-directory-files/content', async (c) => {
|
||||
try {
|
||||
const kind = z.enum(['agents', 'commands']).parse(c.req.query('kind'))
|
||||
const relativePath = z.string().min(1).parse(c.req.query('relativePath'))
|
||||
return c.json(await getOpenCodeDirectoryFile(kind, relativePath))
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'read')
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/opencode-directory-files', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { kind, relativePath, content } = z
|
||||
.object({
|
||||
kind: z.enum(['agents', 'commands']),
|
||||
relativePath: z.string().min(1),
|
||||
content: z.string(),
|
||||
})
|
||||
.parse(body)
|
||||
|
||||
const result = await updateOpenCodeDirectoryFile(kind, relativePath, content)
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ ...result, restartRequired: true })
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'update')
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/opencode-directory-files', async (c) => {
|
||||
try {
|
||||
const kind = z.enum(['agents', 'commands']).parse(c.req.query('kind'))
|
||||
const relativePath = z.string().min(1).parse(c.req.query('relativePath'))
|
||||
|
||||
await deleteOpenCodeDirectoryFile(kind, relativePath)
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ kind, relativePath, restartRequired: true })
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'delete')
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/skills/install', async (c) => {
|
||||
try {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
@@ -1231,9 +1386,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installSkillFromGithubTree(db, validated)
|
||||
|
||||
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId)
|
||||
const restartRequired = await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId)
|
||||
|
||||
return c.json(result)
|
||||
return c.json({ ...result, restartRequired })
|
||||
}
|
||||
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
@@ -1242,20 +1397,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const scope = formData['scope']
|
||||
const repoIdValue = formData['repoId']
|
||||
const overwriteValue = formData['overwrite']
|
||||
const fileManifestRaw = formData['fileManifest']
|
||||
|
||||
if (typeof fileManifestRaw !== 'string') {
|
||||
return c.json({ error: 'fileManifest is required as a JSON string' }, 400)
|
||||
}
|
||||
|
||||
let manifestEntries: unknown
|
||||
try {
|
||||
manifestEntries = JSON.parse(fileManifestRaw)
|
||||
} catch {
|
||||
return c.json({ error: 'fileManifest must be valid JSON' }, 400)
|
||||
}
|
||||
|
||||
const manifest = InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries)
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
|
||||
const repoId = parseOptionalRepoId(repoIdValue as string | undefined)
|
||||
const overwrite = parseBooleanFormValue(overwriteValue)
|
||||
@@ -1275,43 +1418,31 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json({ error: 'fileManifest must contain at least one entry' }, 400)
|
||||
}
|
||||
|
||||
const missingFields = manifest.filter((entry) => !formData[entry.fieldName])
|
||||
if (missingFields.length > 0) {
|
||||
return c.json({
|
||||
error: `Missing upload file(s): ${missingFields.map((e) => e.fieldName).join(', ')}`,
|
||||
}, 400)
|
||||
}
|
||||
|
||||
const files = await 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 }
|
||||
}),
|
||||
)
|
||||
const files = await readUploadedManifestFiles(formData, manifest)
|
||||
|
||||
const result = await installSkillFromUploadedFiles(db, uploadRequest, files)
|
||||
|
||||
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId)
|
||||
const restartRequired = await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId)
|
||||
|
||||
return c.json(result)
|
||||
return c.json({ ...result, restartRequired })
|
||||
}
|
||||
|
||||
return c.json({ error: 'Unsupported content type. Use application/json or multipart/form-data' }, 400)
|
||||
} catch (error) {
|
||||
logger.error('Failed to install skill:', error)
|
||||
|
||||
if (error instanceof UploadValidationError) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid skill install data', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const match = SKILL_INSTALL_ERROR_STATUS.find(([needle]) => error.message.includes(needle))
|
||||
if (match) {
|
||||
return c.json({ error: error.message }, match[1])
|
||||
const status = matchErrorStatus(SKILL_INSTALL_ERROR_STATUS, error)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1356,9 +1487,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const skill = await createSkill(db, validated)
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'creation')
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json(skill)
|
||||
return c.json({ ...skill, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to create skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1385,9 +1516,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId)
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'update')
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json(skill)
|
||||
return c.json({ ...skill, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1418,9 +1549,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
await deleteSkill(db, name, scope, repoId)
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'deletion')
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ success: true })
|
||||
return c.json({ success: true, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { InstallSkillUploadManifestEntrySchema, type InstallSkillUploadManifestEntry } from '@opencode-manager/shared'
|
||||
|
||||
export class UploadValidationError extends Error {}
|
||||
|
||||
type ParsedFormData = Record<string, unknown>
|
||||
|
||||
export function parseUploadManifest(fileManifestRaw: unknown): InstallSkillUploadManifestEntry[] {
|
||||
if (typeof fileManifestRaw !== 'string') {
|
||||
throw new UploadValidationError('fileManifest is required as a JSON string')
|
||||
}
|
||||
|
||||
let manifestEntries: unknown
|
||||
try {
|
||||
manifestEntries = JSON.parse(fileManifestRaw)
|
||||
} catch {
|
||||
throw new UploadValidationError('fileManifest must be valid JSON')
|
||||
}
|
||||
|
||||
return InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries)
|
||||
}
|
||||
|
||||
export async function readUploadedManifestFiles(
|
||||
formData: ParsedFormData,
|
||||
manifest: InstallSkillUploadManifestEntry[],
|
||||
): Promise<{ relativePath: string; content: Buffer }[]> {
|
||||
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 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 }
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -89,6 +89,35 @@ export async function getFileStats(filePath: string): Promise<{ size: number; la
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeUploadRelativePath(
|
||||
relativePath: string,
|
||||
options?: { collapseEmptySegments?: boolean },
|
||||
): string {
|
||||
const normalized = relativePath.replace(/\\/g, '/')
|
||||
if (path.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) {
|
||||
throw new Error(`Path must be relative, got absolute path: "${relativePath}"`)
|
||||
}
|
||||
if (normalized === '' || normalized === '.') {
|
||||
throw new Error('Path must not be empty')
|
||||
}
|
||||
const rawParts = normalized.split('/')
|
||||
const parts = options?.collapseEmptySegments ? rawParts.filter(Boolean) : rawParts
|
||||
for (const part of parts) {
|
||||
if (part === '..') {
|
||||
throw new Error(`Path must not contain "..": "${relativePath}"`)
|
||||
}
|
||||
}
|
||||
return options?.collapseEmptySegments ? parts.join('/') : normalized
|
||||
}
|
||||
|
||||
export function resolveWithinDirectory(rootDir: string, relativePath: string, escapeLabel: string): string {
|
||||
const resolved = path.resolve(rootDir, relativePath)
|
||||
if (!resolved.startsWith(rootDir + path.sep)) {
|
||||
throw new Error(`File "${relativePath}" escapes the ${escapeLabel}`)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
export async function listDirectory(dirPath: string): Promise<Array<{
|
||||
name: string
|
||||
path: string
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
|
||||
|
||||
export type OpenCodeDirectoryFileKind = 'agents' | 'commands'
|
||||
|
||||
interface UploadedOpenCodeFile {
|
||||
relativePath: string
|
||||
content: Buffer
|
||||
}
|
||||
|
||||
export interface InstallOpenCodeDirectoryFilesResult {
|
||||
kind: OpenCodeDirectoryFileKind
|
||||
filesInstalled: string[]
|
||||
}
|
||||
|
||||
export interface OpenCodeDirectoryFileInfo {
|
||||
kind: OpenCodeDirectoryFileKind
|
||||
name: string
|
||||
relativePath: string
|
||||
}
|
||||
|
||||
function getOpenCodeDirectoryRoot(kind: OpenCodeDirectoryFileKind): string {
|
||||
return path.join(getWorkspacePath(), '.config', 'opencode', kind)
|
||||
}
|
||||
|
||||
function getNameFromRelativePath(relativePath: string): string {
|
||||
return relativePath.replace(/\.md$/i, '').split('/').pop() ?? relativePath
|
||||
}
|
||||
|
||||
async function listMarkdownFiles(rootDir: string, currentDir = rootDir): Promise<string[]> {
|
||||
let entries
|
||||
try {
|
||||
entries = await fs.readdir(currentDir, { withFileTypes: true })
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return []
|
||||
throw error
|
||||
}
|
||||
|
||||
const files = await Promise.all(entries.map(async entry => {
|
||||
const absolutePath = path.join(currentDir, entry.name)
|
||||
if (entry.isDirectory()) return listMarkdownFiles(rootDir, absolutePath)
|
||||
if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) return []
|
||||
|
||||
return [path.relative(rootDir, absolutePath).replace(/\\/g, '/')]
|
||||
}))
|
||||
|
||||
return files.flat().sort((a, b) => a.localeCompare(b))
|
||||
}
|
||||
|
||||
function getTargetRelativePath(relativePath: string, kind: OpenCodeDirectoryFileKind): string | null {
|
||||
const normalized = normalizeUploadRelativePath(relativePath, { collapseEmptySegments: true })
|
||||
if (!normalized.toLowerCase().endsWith('.md')) return null
|
||||
|
||||
const parts = normalized.split('/')
|
||||
const kindIndex = parts.findIndex(part => part === kind)
|
||||
const targetParts = kindIndex >= 0 ? parts.slice(kindIndex + 1) : parts.slice(1)
|
||||
const fallbackParts = parts.length === 1 ? parts : targetParts
|
||||
const targetRelativePath = fallbackParts.join('/')
|
||||
|
||||
return targetRelativePath || null
|
||||
}
|
||||
|
||||
export async function installOpenCodeDirectoryFiles(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
files: UploadedOpenCodeFile[],
|
||||
): Promise<InstallOpenCodeDirectoryFilesResult> {
|
||||
const targetRoot = getOpenCodeDirectoryRoot(kind)
|
||||
const preparedFiles = files.flatMap(file => {
|
||||
const relativePath = getTargetRelativePath(file.relativePath, kind)
|
||||
return relativePath ? [{ relativePath, content: file.content }] : []
|
||||
})
|
||||
|
||||
if (preparedFiles.length === 0) {
|
||||
throw new Error(`No markdown ${kind} files found`)
|
||||
}
|
||||
|
||||
const targets = preparedFiles.map(file => ({
|
||||
relativePath: file.relativePath,
|
||||
content: file.content,
|
||||
targetFilePath: resolveWithinDirectory(targetRoot, file.relativePath, `${kind} directory`),
|
||||
}))
|
||||
|
||||
await fs.mkdir(targetRoot, { recursive: true })
|
||||
|
||||
await Promise.all(
|
||||
targets.map(async target => {
|
||||
await fs.mkdir(path.dirname(target.targetFilePath), { recursive: true })
|
||||
await fs.writeFile(target.targetFilePath, target.content)
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
kind,
|
||||
filesInstalled: preparedFiles.map(file => file.relativePath),
|
||||
}
|
||||
}
|
||||
|
||||
export async function listOpenCodeDirectoryFiles(kind: OpenCodeDirectoryFileKind): Promise<OpenCodeDirectoryFileInfo[]> {
|
||||
const rootDir = getOpenCodeDirectoryRoot(kind)
|
||||
const files = await listMarkdownFiles(rootDir)
|
||||
|
||||
return files.map(relativePath => ({
|
||||
kind,
|
||||
name: getNameFromRelativePath(relativePath),
|
||||
relativePath,
|
||||
}))
|
||||
}
|
||||
|
||||
function resolveDirectoryFilePath(kind: OpenCodeDirectoryFileKind, relativePath: string): string {
|
||||
const normalized = normalizeUploadRelativePath(relativePath, { collapseEmptySegments: true })
|
||||
if (!normalized.toLowerCase().endsWith('.md')) {
|
||||
throw new Error(`Path must reference a markdown file: "${relativePath}"`)
|
||||
}
|
||||
return resolveWithinDirectory(getOpenCodeDirectoryRoot(kind), normalized, `${kind} directory`)
|
||||
}
|
||||
|
||||
export async function getOpenCodeDirectoryFile(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
relativePath: string,
|
||||
): Promise<OpenCodeDirectoryFileInfo & { content: string }> {
|
||||
const filePath = resolveDirectoryFilePath(kind, relativePath)
|
||||
const content = await fs.readFile(filePath, 'utf8')
|
||||
|
||||
return {
|
||||
kind,
|
||||
name: getNameFromRelativePath(relativePath),
|
||||
relativePath,
|
||||
content,
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateOpenCodeDirectoryFile(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
relativePath: string,
|
||||
content: string,
|
||||
): Promise<OpenCodeDirectoryFileInfo> {
|
||||
const filePath = resolveDirectoryFilePath(kind, relativePath)
|
||||
await fs.access(filePath)
|
||||
await fs.writeFile(filePath, content, 'utf8')
|
||||
|
||||
return {
|
||||
kind,
|
||||
name: getNameFromRelativePath(relativePath),
|
||||
relativePath,
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOpenCodeDirectoryFile(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
relativePath: string,
|
||||
): Promise<void> {
|
||||
const filePath = resolveDirectoryFilePath(kind, relativePath)
|
||||
await fs.unlink(filePath)
|
||||
}
|
||||
@@ -30,6 +30,8 @@ const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
const HEALTH_CHECK_TIMEOUT_MS = 3000
|
||||
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
|
||||
const PROCESS_EXIT_GRACE_MS = 2000
|
||||
const PROCESS_EXIT_POLL_MS = 50
|
||||
const DEPRECATED_PLUGIN_PACKAGES = ['opencode-openai-codex-auth', 'opencode-copilot-auth']
|
||||
|
||||
type StartupValidationIssue = {
|
||||
@@ -106,6 +108,7 @@ class OpenCodeServerManager {
|
||||
private db: Database | null = null
|
||||
private version: string | null = null
|
||||
private lastStartupError: string | null = null
|
||||
private restartPending: boolean = false
|
||||
private opInProgress: boolean = false
|
||||
private openCodeClient: OpenCodeClient | null = null
|
||||
|
||||
@@ -405,6 +408,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
this.isHealthy = true
|
||||
this.restartPending = false
|
||||
logger.info('OpenCode server is healthy')
|
||||
|
||||
await this.fetchVersion()
|
||||
@@ -441,16 +445,18 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
const exited = await this.waitForProcessExit(this.serverPid, PROCESS_EXIT_GRACE_MS)
|
||||
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${this.serverPid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
|
||||
if (!exited) {
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${this.serverPid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,7 +623,6 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
logger.info('Restarting OpenCode server (full process restart)')
|
||||
await this.stop(true)
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
await this.start(false, true)
|
||||
} finally {
|
||||
this.releaseOp(acquired)
|
||||
@@ -698,6 +703,14 @@ class OpenCodeServerManager {
|
||||
this.lastStartupError = null
|
||||
}
|
||||
|
||||
isRestartPending(): boolean {
|
||||
return this.restartPending
|
||||
}
|
||||
|
||||
markRestartPending(): void {
|
||||
this.restartPending = true
|
||||
}
|
||||
|
||||
async reinitializeBinDirectory(): Promise<void> {
|
||||
logger.info('Reinitializing OpenCode bin directory')
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
@@ -733,6 +746,22 @@ class OpenCodeServerManager {
|
||||
return null
|
||||
}
|
||||
|
||||
private async waitForProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
await new Promise(r => setTimeout(r, PROCESS_EXIT_POLL_MS))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private async waitForHealth(timeoutMs: number): Promise<boolean> {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shar
|
||||
import { getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env'
|
||||
import { getRepoById, listRepos } from '../db/queries'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { githubFetchJson, githubFetchBinary, type GithubFetchFn } from '../utils/github'
|
||||
@@ -46,23 +46,6 @@ function getSkillTargetRoot(db: Database, scope: SkillScope, repoId?: number): s
|
||||
return getProjectSkillsPath(repo)
|
||||
}
|
||||
|
||||
function normalizeInstallRelativePath(relativePath: string): string {
|
||||
const normalized = relativePath.replace(/\\/g, '/')
|
||||
if (path.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) {
|
||||
throw new Error(`Path must be relative, got absolute path: "${relativePath}"`)
|
||||
}
|
||||
if (normalized === '' || normalized === '.') {
|
||||
throw new Error('Path must not be empty')
|
||||
}
|
||||
const parts = normalized.split('/')
|
||||
for (const part of parts) {
|
||||
if (part === '..') {
|
||||
throw new Error(`Path must not contain "..": "${relativePath}"`)
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function parseSkillMarkdown(content: string): { name: string; description: string; body: string } {
|
||||
if (!content.startsWith('---\n')) {
|
||||
throw new Error('Skill markdown must start with a frontmatter block')
|
||||
@@ -99,7 +82,7 @@ function parseSkillMarkdown(content: string): { name: string; description: strin
|
||||
function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles {
|
||||
const normalized = files.map(f => ({
|
||||
...f,
|
||||
relativePath: normalizeInstallRelativePath(f.relativePath),
|
||||
relativePath: normalizeUploadRelativePath(f.relativePath),
|
||||
}))
|
||||
const skillMdFiles = normalized.filter(f => path.basename(f.relativePath) === 'SKILL.md')
|
||||
if (skillMdFiles.length === 0) {
|
||||
@@ -119,7 +102,7 @@ function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles
|
||||
relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length),
|
||||
}))
|
||||
for (const f of strippedFiles) {
|
||||
const checkPath = normalizeInstallRelativePath(f.relativePath)
|
||||
const checkPath = normalizeUploadRelativePath(f.relativePath)
|
||||
if (checkPath.startsWith('..')) {
|
||||
throw new Error(`File "${f.relativePath}" escapes the skill directory`)
|
||||
}
|
||||
@@ -157,10 +140,7 @@ async function installSkillFiles(
|
||||
|
||||
try {
|
||||
for (const file of prepared.files) {
|
||||
const targetFilePath = path.resolve(stagingDir, file.relativePath)
|
||||
if (!targetFilePath.startsWith(stagingDir + path.sep)) {
|
||||
throw new Error(`File "${file.relativePath}" escapes the staging directory`)
|
||||
}
|
||||
const targetFilePath = resolveWithinDirectory(stagingDir, file.relativePath, 'staging directory')
|
||||
await fs.mkdir(path.dirname(targetFilePath), { recursive: true })
|
||||
await fs.writeFile(targetFilePath, file.content)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user