mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat: add skill installer with install/uninstall and settings UI
This commit is contained in:
1 parent
3e617c2df8
commit
50546af8cb
12 files changed
+1889
-22
No files matched your search
@@ -18,6 +18,9 @@ import {
|
||||
CreateSkillRequestSchema,
|
||||
UpdateSkillRequestSchema,
|
||||
SkillScopeSchema,
|
||||
InstallSkillFromGithubRequestSchema,
|
||||
InstallSkillUploadRequestSchema,
|
||||
InstallSkillUploadManifestEntrySchema,
|
||||
} from '@opencode-manager/shared'
|
||||
import { logger } from '../utils/logger'
|
||||
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
|
||||
@@ -38,6 +41,8 @@ import {
|
||||
createSkill,
|
||||
updateSkill,
|
||||
deleteSkill,
|
||||
installSkillFromGithubTree,
|
||||
installSkillFromUploadedFiles,
|
||||
} from '../services/skills'
|
||||
|
||||
function getOpenCodeInstallMethod(): string {
|
||||
@@ -107,6 +112,19 @@ function needsOpenCodeRestart(
|
||||
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
|
||||
}
|
||||
|
||||
function parseOptionalRepoId(value: string | undefined): number | undefined {
|
||||
if (value === undefined) return undefined
|
||||
const parsed = parseInt(value, 10)
|
||||
if (isNaN(parsed)) throw new Error('Invalid repoId')
|
||||
return parsed
|
||||
}
|
||||
|
||||
function parseBooleanFormValue(value: unknown): boolean | undefined {
|
||||
if (value === true || value === 'true') return true
|
||||
if (value === false || value === 'false') return false
|
||||
return undefined
|
||||
}
|
||||
|
||||
function hasConfiguredPlugins(config: Record<string, unknown> | undefined): boolean {
|
||||
return Array.isArray(config?.plugin) && config.plugin.length > 0
|
||||
}
|
||||
@@ -1137,6 +1155,150 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/skills/install', async (c) => {
|
||||
try {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await c.req.json()
|
||||
const validated = InstallSkillFromGithubRequestSchema.parse(body)
|
||||
|
||||
if (validated.scope === 'project' && validated.repoId === undefined) {
|
||||
return c.json({ error: 'repoId is required for project scope' }, 400)
|
||||
}
|
||||
|
||||
const result = await installSkillFromGithubTree(db, validated)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
}
|
||||
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
const formData = await c.req.parseBody({ all: true })
|
||||
|
||||
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 repoId = parseOptionalRepoId(repoIdValue as string | undefined)
|
||||
const overwrite = parseBooleanFormValue(overwriteValue)
|
||||
|
||||
const uploadRequest = InstallSkillUploadRequestSchema.parse({
|
||||
sourceType: 'upload',
|
||||
scope,
|
||||
repoId,
|
||||
overwrite,
|
||||
})
|
||||
|
||||
if (scope === 'project' && repoId === undefined) {
|
||||
return c.json({ error: 'repoId is required for project scope' }, 400)
|
||||
}
|
||||
|
||||
if (manifest.length === 0) {
|
||||
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 result = await installSkillFromUploadedFiles(db, uploadRequest, files)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
}
|
||||
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
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 z.ZodError) {
|
||||
return c.json({ error: 'Invalid skill install data', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('already exists')) {
|
||||
return c.json({ error: error.message }, 409)
|
||||
}
|
||||
if (error.message.includes('Invalid GitHub tree URL')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('Invalid skill name')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('Only one skill')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('Skill source must contain')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('Path must be relative') || error.message.includes('Path must not contain') || error.message.includes('escapes')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('no downloadable files')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('404')) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
if (error.message.includes('repoId is required')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('Missing upload file')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('Invalid repoId')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error.message.includes('not a valid file')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ error: 'Failed to install skill' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/skills/:name', async (c) => {
|
||||
try {
|
||||
const name = c.req.param('name')
|
||||
|
||||
+343
-14
@@ -1,9 +1,10 @@
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest } from '@opencode-manager/shared'
|
||||
import { SKILL_NAME_REGEX } from '@opencode-manager/shared'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest, InstallSkillUploadRequest, InstallSkillFromGithubRequest, InstallSkillResponse } from '@opencode-manager/shared'
|
||||
import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shared'
|
||||
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'
|
||||
@@ -17,6 +18,343 @@ interface OpenCodeSkillInfo {
|
||||
content: string
|
||||
}
|
||||
|
||||
interface SkillInstallFile {
|
||||
relativePath: string
|
||||
content: Buffer
|
||||
}
|
||||
|
||||
interface PreparedSkillFiles {
|
||||
skillName: string
|
||||
description: string
|
||||
body: string
|
||||
files: SkillInstallFile[]
|
||||
filesInstalled: string[]
|
||||
}
|
||||
|
||||
function getSkillTargetRoot(db: Database, scope: SkillScope, repoId?: number): string {
|
||||
if (scope === 'global') {
|
||||
return getGlobalSkillsPath()
|
||||
}
|
||||
if (repoId === undefined) {
|
||||
throw new Error('repoId is required for project-scoped skills')
|
||||
}
|
||||
const repo = getRepoById(db, repoId)
|
||||
if (!repo) {
|
||||
throw new Error(`Repository with id ${repoId} not found`)
|
||||
}
|
||||
return getProjectSkillsPath(repo)
|
||||
}
|
||||
|
||||
function normalizeInstallRelativePath(relativePath: string): string {
|
||||
const normalized = relativePath.replace(/\\/g, '/')
|
||||
if (path.isAbsolute(normalized)) {
|
||||
throw new Error(`Path must be relative, got absolute path: "${relativePath}"`)
|
||||
}
|
||||
if (/^[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')
|
||||
}
|
||||
const endIndex = content.indexOf('\n---\n', 4)
|
||||
if (endIndex === -1) {
|
||||
throw new Error('Skill markdown must have a closing frontmatter delimiter')
|
||||
}
|
||||
const frontmatterBlock = content.substring(4, endIndex)
|
||||
const body = content.substring(endIndex + 5)
|
||||
const lines = frontmatterBlock.split('\n')
|
||||
const frontmatter: Record<string, string> = {}
|
||||
for (const line of lines) {
|
||||
const colonIndex = line.indexOf(':')
|
||||
if (colonIndex === -1) continue
|
||||
const key = line.substring(0, colonIndex).trim()
|
||||
let value = line.substring(colonIndex + 1).trim()
|
||||
if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith('"') && value.endsWith('"'))) {
|
||||
value = value.substring(1, value.length - 1)
|
||||
}
|
||||
frontmatter[key] = value
|
||||
}
|
||||
const parsed = SkillFrontmatterSchema.parse({
|
||||
name: frontmatter.name,
|
||||
description: frontmatter.description,
|
||||
})
|
||||
return {
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles {
|
||||
const normalized = files.map(f => ({
|
||||
...f,
|
||||
relativePath: normalizeInstallRelativePath(f.relativePath),
|
||||
}))
|
||||
const skillMdFiles = normalized.filter(f => path.basename(f.relativePath) === 'SKILL.md')
|
||||
if (skillMdFiles.length === 0) {
|
||||
throw new Error('Skill source must contain SKILL.md')
|
||||
}
|
||||
if (skillMdFiles.length > 1) {
|
||||
throw new Error('Only one skill can be installed at a time')
|
||||
}
|
||||
const skillMd = skillMdFiles[0]!
|
||||
const skillDir = path.dirname(skillMd.relativePath)
|
||||
const { name, description, body } = parseSkillMarkdown(skillMd.content.toString('utf-8'))
|
||||
const prefix = skillDir === '.' ? '' : skillDir + '/'
|
||||
const strippedFiles = normalized
|
||||
.filter(f => f.relativePath === skillMd.relativePath || f.relativePath.startsWith(prefix))
|
||||
.map(f => ({
|
||||
...f,
|
||||
relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length),
|
||||
}))
|
||||
for (const f of strippedFiles) {
|
||||
const checkPath = normalizeInstallRelativePath(f.relativePath)
|
||||
if (checkPath.startsWith('..')) {
|
||||
throw new Error(`File "${f.relativePath}" escapes the skill directory`)
|
||||
}
|
||||
}
|
||||
const filesInstalled = strippedFiles.map(f => f.relativePath)
|
||||
return {
|
||||
skillName: name,
|
||||
description,
|
||||
body,
|
||||
files: strippedFiles,
|
||||
filesInstalled,
|
||||
}
|
||||
}
|
||||
|
||||
async function installSkillFiles(
|
||||
db: Database,
|
||||
input: InstallSkillUploadRequest | InstallSkillFromGithubRequest,
|
||||
files: SkillInstallFile[],
|
||||
): Promise<InstallSkillResponse> {
|
||||
const prepared = prepareSingleSkillFiles(files)
|
||||
const targetRoot = getSkillTargetRoot(db, input.scope, input.repoId)
|
||||
const targetDir = path.join(targetRoot, prepared.skillName)
|
||||
const skillPath = path.join(targetDir, 'SKILL.md')
|
||||
|
||||
const targetDirExists = await fileExists(targetDir)
|
||||
const targetSkillExists = await fileExists(skillPath)
|
||||
const existingTarget = targetDirExists || targetSkillExists
|
||||
|
||||
if (existingTarget && input.overwrite !== true) {
|
||||
throw new Error(`Skill "${prepared.skillName}" already exists in ${input.scope} scope`)
|
||||
}
|
||||
|
||||
await fs.mkdir(targetRoot, { recursive: true })
|
||||
const stagingDir = await fs.mkdtemp(path.join(targetRoot, `.${prepared.skillName}-install-`))
|
||||
|
||||
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`)
|
||||
}
|
||||
await fs.mkdir(path.dirname(targetFilePath), { recursive: true })
|
||||
await fs.writeFile(targetFilePath, file.content)
|
||||
}
|
||||
|
||||
if (existingTarget && input.overwrite === true) {
|
||||
await fs.rm(targetDir, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
await fs.rename(stagingDir, targetDir)
|
||||
|
||||
const repo = input.repoId !== undefined ? getRepoById(db, input.repoId) : null
|
||||
|
||||
return {
|
||||
skill: {
|
||||
name: prepared.skillName,
|
||||
description: prepared.description,
|
||||
body: prepared.body,
|
||||
scope: input.scope,
|
||||
location: skillPath,
|
||||
repoId: input.scope === 'project' ? input.repoId : undefined,
|
||||
repoName: repo?.localPath,
|
||||
},
|
||||
overwritten: Boolean(existingTarget),
|
||||
sourceType: input.sourceType,
|
||||
filesInstalled: prepared.filesInstalled,
|
||||
}
|
||||
} catch (error) {
|
||||
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function installSkillFromUploadedFiles(
|
||||
db: Database,
|
||||
input: InstallSkillUploadRequest,
|
||||
files: SkillInstallFile[],
|
||||
): Promise<InstallSkillResponse> {
|
||||
return installSkillFiles(db, input, files)
|
||||
}
|
||||
|
||||
type GithubFetchFn = (url: string | URL | Request, init?: RequestInit) => Promise<Response>
|
||||
|
||||
interface GithubTreeSource {
|
||||
owner: string
|
||||
repo: string
|
||||
ref: string
|
||||
path: string
|
||||
}
|
||||
|
||||
interface GithubContentEntry {
|
||||
name: string
|
||||
path: string
|
||||
type: 'file' | 'dir'
|
||||
download_url?: string | null
|
||||
url: string
|
||||
}
|
||||
|
||||
function parseGithubTreeUrl(url: string): GithubTreeSource {
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(url)
|
||||
} catch {
|
||||
throw new Error('Invalid GitHub tree URL')
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'https:' || parsed.host !== 'github.com') {
|
||||
throw new Error('Invalid GitHub tree URL: only https://github.com is supported')
|
||||
}
|
||||
|
||||
const segments = parsed.pathname.split('/').filter(Boolean)
|
||||
if (segments.length < 4 || segments[2] !== 'tree') {
|
||||
throw new Error('Invalid GitHub tree URL: must be a tree URL (github.com/owner/repo/tree/ref/path)')
|
||||
}
|
||||
|
||||
const owner = segments[0]!
|
||||
const repo = segments[1]!
|
||||
const ref = segments[3]!
|
||||
const path = segments.slice(4).join('/')
|
||||
|
||||
if (!path) {
|
||||
throw new Error('Invalid GitHub tree URL: path is required')
|
||||
}
|
||||
|
||||
return { owner, repo, ref, path }
|
||||
}
|
||||
|
||||
async function fetchGithubJson(fetchFn: GithubFetchFn, url: string): Promise<unknown> {
|
||||
const response = await fetchFn(url, {
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': 'opencode-manager',
|
||||
},
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`GitHub request failed with status ${response.status}`)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
async function fetchGithubFile(fetchFn: GithubFetchFn, url: string): Promise<ArrayBuffer> {
|
||||
const response = await fetchFn(url, {
|
||||
headers: {
|
||||
'User-Agent': 'opencode-manager',
|
||||
},
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`GitHub request failed with status ${response.status}`)
|
||||
}
|
||||
return response.arrayBuffer()
|
||||
}
|
||||
|
||||
function githubContentsApiUrl(source: GithubTreeSource, path: string): string {
|
||||
const encodedPath = path.split('/').map(encodeURIComponent).join('/')
|
||||
return `https://api.github.com/repos/${source.owner}/${source.repo}/contents/${encodedPath}?ref=${encodeURIComponent(source.ref)}`
|
||||
}
|
||||
|
||||
async function fetchGithubSkillFiles(
|
||||
source: GithubTreeSource,
|
||||
fetchFn: GithubFetchFn = fetch,
|
||||
): Promise<SkillInstallFile[]> {
|
||||
const apiUrl = githubContentsApiUrl(source, source.path)
|
||||
const data = await fetchGithubJson(fetchFn, apiUrl)
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
const entry = data as GithubContentEntry
|
||||
if (entry.name !== 'SKILL.md') {
|
||||
throw new Error('GitHub tree URL must point to a skill folder containing SKILL.md')
|
||||
}
|
||||
const buffer = await fetchGithubFile(fetchFn, entry.download_url!)
|
||||
const content = Buffer.from(buffer)
|
||||
if (content.length > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
|
||||
throw new Error('Skill files exceed maximum upload size')
|
||||
}
|
||||
return [{ relativePath: 'SKILL.md', content }]
|
||||
}
|
||||
|
||||
const files: SkillInstallFile[] = []
|
||||
let totalBytes = 0
|
||||
const MAX_FILES = 100
|
||||
|
||||
async function walk(entries: GithubContentEntry[]) {
|
||||
for (const entry of entries) {
|
||||
if (files.length >= MAX_FILES) {
|
||||
throw new Error(`Skill contains too many files (max ${MAX_FILES})`)
|
||||
}
|
||||
|
||||
if (entry.type === 'dir') {
|
||||
const dirUrl = githubContentsApiUrl(source, entry.path)
|
||||
const dirData = await fetchGithubJson(fetchFn, dirUrl)
|
||||
if (Array.isArray(dirData)) {
|
||||
await walk(dirData as GithubContentEntry[])
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (!entry.download_url) continue
|
||||
|
||||
const relativePath = entry.path.startsWith(source.path + '/')
|
||||
? entry.path.substring(source.path.length + 1)
|
||||
: entry.path
|
||||
|
||||
const arrayBuffer = await fetchGithubFile(fetchFn, entry.download_url)
|
||||
const buffer = Buffer.from(arrayBuffer)
|
||||
totalBytes += buffer.length
|
||||
|
||||
if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
|
||||
throw new Error('Skill files exceed maximum upload size')
|
||||
}
|
||||
|
||||
files.push({ relativePath, content: buffer })
|
||||
}
|
||||
}
|
||||
|
||||
await walk(data as GithubContentEntry[])
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error('GitHub tree URL contains no downloadable files')
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
export async function installSkillFromGithubTree(
|
||||
db: Database,
|
||||
input: InstallSkillFromGithubRequest,
|
||||
fetchFn: GithubFetchFn = fetch,
|
||||
): Promise<InstallSkillResponse> {
|
||||
const source = parseGithubTreeUrl(input.url)
|
||||
const files = await fetchGithubSkillFiles(source, fetchFn)
|
||||
return installSkillFiles(db, input, files)
|
||||
}
|
||||
|
||||
function getGlobalSkillsPath(): string {
|
||||
return path.join(getWorkspacePath(), '.config', 'opencode', 'skills')
|
||||
}
|
||||
@@ -89,17 +427,8 @@ function validateSkillName(name: string): void {
|
||||
|
||||
function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string {
|
||||
validateSkillName(name)
|
||||
if (scope === 'global') {
|
||||
return path.join(getGlobalSkillsPath(), name, 'SKILL.md')
|
||||
}
|
||||
if (!repoId) {
|
||||
throw new Error('repoId is required for project-scoped skills')
|
||||
}
|
||||
const repo = getRepoById(db, repoId)
|
||||
if (!repo) {
|
||||
throw new Error(`Repository with id ${repoId} not found`)
|
||||
}
|
||||
return path.join(getProjectSkillsPath(repo), name, 'SKILL.md')
|
||||
const targetRoot = getSkillTargetRoot(db, scope, repoId)
|
||||
return path.join(targetRoot, name, 'SKILL.md')
|
||||
}
|
||||
|
||||
function buildSkillFileContent(name: string, description: string, body: string): string {
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
existsSync: vi.fn(() => false),
|
||||
promises: {
|
||||
mkdir: vi.fn(),
|
||||
access: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
chmod: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rm: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
execSync: vi.fn(),
|
||||
spawnSync: vi.fn(),
|
||||
spawn: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/constants', () => ({
|
||||
DEFAULT_AGENTS_MD: '# Test Agents MD',
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
saveLastKnownGoodConfig: vi.fn(),
|
||||
createOpenCodeConfig: vi.fn(),
|
||||
updateOpenCodeConfig: vi.fn(),
|
||||
deleteOpenCodeConfig: vi.fn(),
|
||||
getOpenCodeConfigByName: vi.fn(),
|
||||
setDefaultOpenCodeConfig: vi.fn(),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/file-operations', () => ({
|
||||
writeFileContent: vi.fn(),
|
||||
readFileContent: vi.fn(),
|
||||
fileExists: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => {
|
||||
class MockConfigReloadError extends Error {
|
||||
validationIssues: Array<{ path: string; message: string }> = []
|
||||
removedFields: string[] = []
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'ConfigReloadError'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
opencodeServerManager: {
|
||||
getVersion: vi.fn(),
|
||||
fetchVersion: vi.fn(),
|
||||
reloadConfig: vi.fn(),
|
||||
restart: vi.fn(),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(),
|
||||
setDatabase: vi.fn(),
|
||||
reinitializeBinDirectory: vi.fn(),
|
||||
},
|
||||
ConfigReloadError: MockConfigReloadError,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../src/services/skills', () => ({
|
||||
listManagedSkills: vi.fn(),
|
||||
getSkill: vi.fn(),
|
||||
createSkill: vi.fn(),
|
||||
updateSkill: vi.fn(),
|
||||
deleteSkill: vi.fn(),
|
||||
installSkillFromGithubTree: vi.fn(),
|
||||
installSkillFromUploadedFiles: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos'),
|
||||
getOpenCodeConfigFilePath: vi.fn(() => '/tmp/test-workspace/.config/opencode.json'),
|
||||
getAgentsMdPath: vi.fn(() => '/tmp/test-workspace/AGENTS.md'),
|
||||
getDatabasePath: vi.fn(() => ':memory:'),
|
||||
getConfigPath: vi.fn(() => '/tmp/test-workspace/config'),
|
||||
ENV: {
|
||||
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
|
||||
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' },
|
||||
WORKSPACE: { BASE_PATH: '/tmp/test-workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' },
|
||||
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
|
||||
DATABASE: { PATH: ':memory:' },
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
|
||||
},
|
||||
},
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
|
||||
},
|
||||
}))
|
||||
|
||||
import { createSettingsRoutes } from '../../src/routes/settings'
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import {
|
||||
installSkillFromGithubTree,
|
||||
installSkillFromUploadedFiles,
|
||||
deleteSkill,
|
||||
} from '../../src/services/skills'
|
||||
|
||||
const mockInstallFromGithubTree = installSkillFromGithubTree as ReturnType<typeof vi.fn>
|
||||
const mockInstallFromUploadedFiles = installSkillFromUploadedFiles as ReturnType<typeof vi.fn>
|
||||
const mockDeleteSkill = deleteSkill as ReturnType<typeof vi.fn>
|
||||
const mockRestart = opencodeServerManager.restart as ReturnType<typeof vi.fn>
|
||||
|
||||
const mockSuccessResponse = {
|
||||
skill: {
|
||||
name: 'teach',
|
||||
description: 'A teaching skill',
|
||||
body: '## Teach\n\nContent',
|
||||
scope: 'global',
|
||||
location: '/tmp/test-workspace/.config/opencode/skills/teach/SKILL.md',
|
||||
},
|
||||
overwritten: false,
|
||||
sourceType: 'github' as const,
|
||||
filesInstalled: ['teach/SKILL.md'],
|
||||
}
|
||||
|
||||
describe('Settings Routes - Skill Install', () => {
|
||||
let settingsApp: ReturnType<typeof createSettingsRoutes>
|
||||
let testDb: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockRestart.mockResolvedValue(undefined)
|
||||
mockInstallFromGithubTree.mockResolvedValue(mockSuccessResponse)
|
||||
mockInstallFromUploadedFiles.mockResolvedValue({ ...mockSuccessResponse, sourceType: 'upload' })
|
||||
|
||||
testDb = {} as any
|
||||
settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any, createStubOpenCodeClient())
|
||||
})
|
||||
|
||||
describe('POST /skills/install', () => {
|
||||
it('installs from GitHub JSON', async () => {
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as Record<string, unknown>
|
||||
expect(body).toEqual(mockSuccessResponse)
|
||||
expect(mockInstallFromGithubTree).toHaveBeenCalledTimes(1)
|
||||
expect(mockInstallFromGithubTree).toHaveBeenCalledWith(testDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
})
|
||||
expect(mockRestart).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('installs from multipart upload', async () => {
|
||||
const formData = new FormData()
|
||||
formData.append('scope', 'global')
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'teach/SKILL.md' },
|
||||
]))
|
||||
formData.append('file0', new File(['---\nname: teach\ndescription: A teaching skill\n---\n## Teach\n\nContent'], 'SKILL.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { sourceType: string }
|
||||
expect(body.sourceType).toBe('upload')
|
||||
expect(mockInstallFromUploadedFiles).toHaveBeenCalledTimes(1)
|
||||
expect(mockInstallFromUploadedFiles).toHaveBeenCalledWith(
|
||||
testDb,
|
||||
{
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
repoId: undefined,
|
||||
overwrite: undefined,
|
||||
},
|
||||
[
|
||||
expect.objectContaining({
|
||||
relativePath: 'teach/SKILL.md',
|
||||
content: expect.any(Buffer),
|
||||
}),
|
||||
],
|
||||
)
|
||||
expect(mockRestart).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('returns 409 on existing skill', async () => {
|
||||
mockInstallFromGithubTree.mockRejectedValue(new Error('Skill "teach" already exists in global scope'))
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('already exists')
|
||||
expect(mockRestart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects project scope without repoId', async () => {
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'project',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('repoId is required')
|
||||
expect(mockInstallFromGithubTree).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects invalid repoId in multipart upload', async () => {
|
||||
const formData = new FormData()
|
||||
formData.append('scope', 'global')
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('repoId', 'abc')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'teach/SKILL.md' },
|
||||
]))
|
||||
formData.append('file0', new File(['content'], 'SKILL.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Invalid repoId')
|
||||
})
|
||||
|
||||
it('rejects multiple uploaded skills', async () => {
|
||||
mockInstallFromUploadedFiles.mockRejectedValue(new Error('Only one skill can be installed at a time'))
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append('scope', 'global')
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'teach/SKILL.md' },
|
||||
{ fieldName: 'file1', relativePath: 'review/SKILL.md' },
|
||||
]))
|
||||
formData.append('file0', new File(['---\nname: teach\n---\nBody'], 'SKILL.md', { type: 'text/markdown' }))
|
||||
formData.append('file1', new File(['---\nname: review\n---\nBody'], 'SKILL.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Only one skill')
|
||||
expect(mockRestart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects upload with missing SKILL.md', async () => {
|
||||
mockInstallFromUploadedFiles.mockRejectedValue(new Error('Skill source must contain SKILL.md'))
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append('scope', 'global')
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'teach/README.md' },
|
||||
]))
|
||||
formData.append('file0', new File(['# Readme'], 'README.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Skill source must contain')
|
||||
expect(mockRestart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects unsafe upload path', async () => {
|
||||
mockInstallFromUploadedFiles.mockRejectedValue(new Error('Path must not contain "..": "../SKILL.md"'))
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append('scope', 'global')
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: '../SKILL.md' },
|
||||
]))
|
||||
formData.append('file0', new File(['---\nname: teach\n---\nBody'], 'SKILL.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('Path must not contain')
|
||||
expect(mockRestart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects non-File manifest field in multipart upload', async () => {
|
||||
const formData = new FormData()
|
||||
formData.append('scope', 'global')
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'teach/SKILL.md' },
|
||||
]))
|
||||
formData.append('file0', 'not-a-file')
|
||||
|
||||
const res = await settingsApp.request('/skills/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toContain('not a valid file')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /skills/:name', () => {
|
||||
it('remains the deletion endpoint', async () => {
|
||||
mockDeleteSkill.mockResolvedValue(undefined)
|
||||
|
||||
const res = await settingsApp.request('/skills/test-skill?scope=global', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockDeleteSkill).toHaveBeenCalledWith(testDb, 'test-skill', 'global', undefined)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,17 @@ import { tmpdir } from 'os'
|
||||
import { mkdtemp, rm, readFile } from 'fs/promises'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@opencode-manager/shared/config/env')>()
|
||||
return {
|
||||
...actual,
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 500,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
listRepos: vi.fn(() => []),
|
||||
@@ -348,4 +359,382 @@ Another section.`
|
||||
const skills = await listManagedSkills(mockDb, client)
|
||||
expect(skills.length).toBe(0)
|
||||
})
|
||||
|
||||
describe('installSkillFromUploadedFiles', () => {
|
||||
test('installs a single SKILL.md upload globally', async () => {
|
||||
const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills')
|
||||
const content = '---\nname: teach\ndescription: Teach users\nargument-hint: "topic"\n---\nBody'
|
||||
const result = await installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'SKILL.md', content: Buffer.from(content) },
|
||||
])
|
||||
|
||||
try {
|
||||
expect(result.skill.name).toBe('teach')
|
||||
expect(result.skill.description).toBe('Teach users')
|
||||
expect(result.skill.body).toBe('Body')
|
||||
expect(result.sourceType).toBe('upload')
|
||||
expect(result.overwritten).toBe(false)
|
||||
expect(result.filesInstalled).toEqual(['SKILL.md'])
|
||||
|
||||
const fileContent = await readFile(result.skill.location, 'utf-8')
|
||||
expect(fileContent).toContain('argument-hint: "topic"')
|
||||
expect(fileContent).toContain('Body')
|
||||
} finally {
|
||||
await deleteSkill(mockDb, 'teach', 'global').catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
test('preserves bundled folder files', async () => {
|
||||
const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills')
|
||||
const skillMd = '---\nname: teach\ndescription: Teach users\n---\nBody'
|
||||
const glossaryMd = '# GLOSSARY-FORMAT\n\nFormat guidelines'
|
||||
|
||||
const result = await installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'teach/SKILL.md', content: Buffer.from(skillMd) },
|
||||
{ relativePath: 'teach/GLOSSARY-FORMAT.md', content: Buffer.from(glossaryMd) },
|
||||
])
|
||||
|
||||
try {
|
||||
expect(result.filesInstalled).toContain('SKILL.md')
|
||||
expect(result.filesInstalled).toContain('GLOSSARY-FORMAT.md')
|
||||
|
||||
const bundledFile = join(result.skill.location.replace('/SKILL.md', ''), 'GLOSSARY-FORMAT.md')
|
||||
const bundledContent = await readFile(bundledFile, 'utf-8')
|
||||
expect(bundledContent).toBe(glossaryMd)
|
||||
} finally {
|
||||
await deleteSkill(mockDb, 'teach', 'global').catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
test('rejects multiple skills', async () => {
|
||||
const { installSkillFromUploadedFiles } = await import('../../src/services/skills')
|
||||
|
||||
await expect(installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'teach/SKILL.md', content: Buffer.from('---\nname: teach\ndescription: Teach\n---\nBody') },
|
||||
{ relativePath: 'review/SKILL.md', content: Buffer.from('---\nname: review\ndescription: Review\n---\nBody') },
|
||||
])).rejects.toThrow('Only one skill')
|
||||
})
|
||||
|
||||
test('prompts overwrite through conflict', async () => {
|
||||
const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills')
|
||||
const content = '---\nname: overwrite-test\ndescription: Test\n---\nOriginal'
|
||||
|
||||
const first = await installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'SKILL.md', content: Buffer.from(content) },
|
||||
])
|
||||
expect(first.overwritten).toBe(false)
|
||||
|
||||
try {
|
||||
await expect(installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'SKILL.md', content: Buffer.from(content) },
|
||||
])).rejects.toThrow('already exists')
|
||||
|
||||
const newContent = '---\nname: overwrite-test\ndescription: Test\n---\nReplaced'
|
||||
const second = await installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
overwrite: true,
|
||||
}, [
|
||||
{ relativePath: 'SKILL.md', content: Buffer.from(newContent) },
|
||||
])
|
||||
expect(second.overwritten).toBe(true)
|
||||
expect(second.skill.body).toBe('Replaced')
|
||||
|
||||
const fileContent = await readFile(second.skill.location, 'utf-8')
|
||||
expect(fileContent).toContain('Replaced')
|
||||
} finally {
|
||||
await deleteSkill(mockDb, 'overwrite-test', 'global').catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
test('deleteSkill removes bundled files from installed skill', async () => {
|
||||
const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills')
|
||||
|
||||
const result = await installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'teach/SKILL.md', content: Buffer.from('---\nname: teach\ndescription: Teach\n---\nBody') },
|
||||
{ relativePath: 'teach/GLOSSARY-FORMAT.md', content: Buffer.from('# Glossary') },
|
||||
])
|
||||
|
||||
const skillDir = result.skill.location.replace('/SKILL.md', '')
|
||||
const bundledFile = join(skillDir, 'GLOSSARY-FORMAT.md')
|
||||
|
||||
await expect(readFile(bundledFile, 'utf-8')).resolves.toBe('# Glossary')
|
||||
|
||||
await deleteSkill(mockDb, 'teach', 'global')
|
||||
|
||||
await expect(readFile(bundledFile, 'utf-8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
test('rejects Windows drive-letter absolute paths', async () => {
|
||||
const { installSkillFromUploadedFiles } = await import('../../src/services/skills')
|
||||
|
||||
await expect(installSkillFromUploadedFiles(mockDb, {
|
||||
sourceType: 'upload',
|
||||
scope: 'global',
|
||||
}, [
|
||||
{ relativePath: 'C:\\temp\\SKILL.md', content: Buffer.from('---\nname: teach\ndescription: Teach\n---\nBody') },
|
||||
])).rejects.toThrow('Path must be relative')
|
||||
})
|
||||
})
|
||||
|
||||
describe('installSkillFromGithubTree', () => {
|
||||
test('downloads a public GitHub tree skill', async () => {
|
||||
const { installSkillFromGithubTree, deleteSkill } = await import('../../src/services/skills')
|
||||
|
||||
const contentsUrl = 'https://api.github.com/repos/mattpocock/skills/contents/skills/productivity/teach?ref=main'
|
||||
const downloadUrl1 = 'https://raw.githubusercontent.com/mattpocock/skills/main/skills/productivity/teach/SKILL.md'
|
||||
const downloadUrl2 = 'https://raw.githubusercontent.com/mattpocock/skills/main/skills/productivity/teach/GLOSSARY-FORMAT.md'
|
||||
|
||||
const mockFetch = vi.fn((url: string | URL | Request) => {
|
||||
const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
|
||||
if (urlStr === contentsUrl) {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'skills/productivity/teach/SKILL.md', type: 'file', download_url: downloadUrl1, url: contentsUrl },
|
||||
{ name: 'GLOSSARY-FORMAT.md', path: 'skills/productivity/teach/GLOSSARY-FORMAT.md', type: 'file', download_url: downloadUrl2, url: contentsUrl.replace('teach', 'teach/GLOSSARY-FORMAT') },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === downloadUrl1) {
|
||||
return Promise.resolve(new Response('---\nname: teach\ndescription: Teach users\n---\nBody content'))
|
||||
}
|
||||
if (urlStr === downloadUrl2) {
|
||||
return Promise.resolve(new Response('# Glossary'))
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }))
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
}, mockFetch)
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/repos/mattpocock/skills/contents/skills/productivity/teach?ref=main'),
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ Accept: 'application/vnd.github+json' }),
|
||||
}),
|
||||
)
|
||||
expect(result.skill.name).toBe('teach')
|
||||
expect(result.skill.description).toBe('Teach users')
|
||||
expect(result.sourceType).toBe('github')
|
||||
expect(result.filesInstalled).toContain('SKILL.md')
|
||||
expect(result.filesInstalled).toContain('GLOSSARY-FORMAT.md')
|
||||
} finally {
|
||||
await deleteSkill(mockDb, 'teach', 'global').catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
test('rejects non-tree GitHub URLs', async () => {
|
||||
const { installSkillFromGithubTree } = await import('../../src/services/skills')
|
||||
const mockFetch = vi.fn()
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/blob/main/skills/productivity/teach/SKILL.md',
|
||||
scope: 'global',
|
||||
}, mockFetch)).rejects.toThrow('Invalid GitHub tree URL')
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('rejects non-HTTPS GitHub tree URLs', async () => {
|
||||
const { installSkillFromGithubTree } = await import('../../src/services/skills')
|
||||
const mockFetch = vi.fn()
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'http://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
}, mockFetch)).rejects.toThrow('Invalid GitHub tree URL')
|
||||
|
||||
expect(mockFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('rejects parent folder with multiple skills', async () => {
|
||||
const { installSkillFromGithubTree } = await import('../../src/services/skills')
|
||||
|
||||
const parentContentsUrl = 'https://api.github.com/repos/user/repo/contents/skills?ref=main'
|
||||
|
||||
const mockFetch = vi.fn((url: string | URL | Request) => {
|
||||
const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
|
||||
if (urlStr === parentContentsUrl) {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'teach', path: 'skills/teach', type: 'dir', download_url: null, url: parentContentsUrl + '/teach' },
|
||||
{ name: 'review', path: 'skills/review', type: 'dir', download_url: null, url: parentContentsUrl + '/review' },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === 'https://api.github.com/repos/user/repo/contents/skills/teach?ref=main') {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'skills/teach/SKILL.md', type: 'file', download_url: 'https://raw.githubusercontent.com/user/repo/main/skills/teach/SKILL.md', url },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === 'https://api.github.com/repos/user/repo/contents/skills/review?ref=main') {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'skills/review/SKILL.md', type: 'file', download_url: 'https://raw.githubusercontent.com/user/repo/main/skills/review/SKILL.md', url },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === 'https://raw.githubusercontent.com/user/repo/main/skills/teach/SKILL.md') {
|
||||
return Promise.resolve(new Response('---\nname: teach\ndescription: Teach\n---\nBody'))
|
||||
}
|
||||
if (urlStr === 'https://raw.githubusercontent.com/user/repo/main/skills/review/SKILL.md') {
|
||||
return Promise.resolve(new Response('---\nname: review\ndescription: Review\n---\nBody'))
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }))
|
||||
})
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/skills',
|
||||
scope: 'global',
|
||||
}, mockFetch)).rejects.toThrow('Only one skill')
|
||||
})
|
||||
|
||||
test('enforces overwrite conflicts', async () => {
|
||||
const { installSkillFromGithubTree, deleteSkill } = await import('../../src/services/skills')
|
||||
|
||||
const contentsUrl = 'https://api.github.com/repos/user/repo/contents/my-skill?ref=main'
|
||||
const downloadUrl = 'https://raw.githubusercontent.com/user/repo/main/my-skill/SKILL.md'
|
||||
|
||||
const makeMockFetch = () => vi.fn((url: string | URL | Request) => {
|
||||
const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
|
||||
if (urlStr === contentsUrl) {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'my-skill/SKILL.md', type: 'file', download_url: downloadUrl, url: contentsUrl },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === downloadUrl) {
|
||||
return Promise.resolve(new Response('---\nname: overwrite-test\ndescription: Test\n---\nBody'))
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }))
|
||||
})
|
||||
|
||||
try {
|
||||
const first = await installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/my-skill',
|
||||
scope: 'global',
|
||||
}, makeMockFetch())
|
||||
expect(first.overwritten).toBe(false)
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/my-skill',
|
||||
scope: 'global',
|
||||
}, makeMockFetch())).rejects.toThrow('already exists')
|
||||
|
||||
const second = await installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/my-skill',
|
||||
scope: 'global',
|
||||
overwrite: true,
|
||||
}, makeMockFetch())
|
||||
expect(second.overwritten).toBe(true)
|
||||
} finally {
|
||||
await deleteSkill(mockDb, 'overwrite-test', 'global').catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
test('rejects oversized single-file download exceeding size limit', async () => {
|
||||
const { installSkillFromGithubTree } = await import('../../src/services/skills')
|
||||
|
||||
const contentsUrl = 'https://api.github.com/repos/user/repo/contents/huge-skill?ref=main'
|
||||
const downloadUrl = 'https://raw.githubusercontent.com/user/repo/main/huge-skill/SKILL.md'
|
||||
const oversizedContent = '# Big\n' + 'x'.repeat(600)
|
||||
|
||||
const mockFetch = vi.fn((url: string | URL | Request) => {
|
||||
const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
|
||||
if (urlStr === contentsUrl) {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'huge-skill/SKILL.md', type: 'file', download_url: downloadUrl, url: contentsUrl },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === downloadUrl) {
|
||||
return Promise.resolve(new Response(oversizedContent))
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }))
|
||||
})
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/huge-skill',
|
||||
scope: 'global',
|
||||
}, mockFetch)).rejects.toThrow('Skill files exceed maximum upload size')
|
||||
})
|
||||
|
||||
test('rejects single SKILL.md download failure with GitHub status', async () => {
|
||||
const { installSkillFromGithubTree } = await import('../../src/services/skills')
|
||||
|
||||
const contentsUrl = 'https://api.github.com/repos/user/repo/contents/failing-skill?ref=main'
|
||||
const downloadUrl = 'https://raw.githubusercontent.com/user/repo/main/failing-skill/SKILL.md'
|
||||
|
||||
const mockFetch = vi.fn((url: string | URL | Request) => {
|
||||
const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
|
||||
if (urlStr === contentsUrl) {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'failing-skill/SKILL.md', type: 'file', download_url: downloadUrl, url: contentsUrl },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === downloadUrl) {
|
||||
return Promise.resolve(new Response('Not Found', { status: 404 }))
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }))
|
||||
})
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/failing-skill',
|
||||
scope: 'global',
|
||||
}, mockFetch)).rejects.toThrow('GitHub request failed with status 404')
|
||||
})
|
||||
|
||||
test('rejects bundled file download failure with GitHub status', async () => {
|
||||
const { installSkillFromGithubTree } = await import('../../src/services/skills')
|
||||
|
||||
const contentsUrl = 'https://api.github.com/repos/user/repo/contents/skill-with-bundle?ref=main'
|
||||
const skillUrl = 'https://raw.githubusercontent.com/user/repo/main/skill-with-bundle/SKILL.md'
|
||||
const bundleUrl = 'https://raw.githubusercontent.com/user/repo/main/skill-with-bundle/GLOSSARY-FORMAT.md'
|
||||
|
||||
const mockFetch = vi.fn((url: string | URL | Request) => {
|
||||
const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
|
||||
if (urlStr === contentsUrl) {
|
||||
return Promise.resolve(new Response(JSON.stringify([
|
||||
{ name: 'SKILL.md', path: 'skill-with-bundle/SKILL.md', type: 'file', download_url: skillUrl, url: contentsUrl },
|
||||
{ name: 'GLOSSARY-FORMAT.md', path: 'skill-with-bundle/GLOSSARY-FORMAT.md', type: 'file', download_url: bundleUrl, url: contentsUrl },
|
||||
]), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
}
|
||||
if (urlStr === skillUrl) {
|
||||
return Promise.resolve(new Response('---\nname: bundled-fail\ndescription: Test\n---\nBody'))
|
||||
}
|
||||
if (urlStr === bundleUrl) {
|
||||
return Promise.resolve(new Response('Forbidden', { status: 403 }))
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }))
|
||||
})
|
||||
|
||||
await expect(installSkillFromGithubTree(mockDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/skill-with-bundle',
|
||||
scope: 'global',
|
||||
}, mockFetch)).rejects.toThrow('GitHub request failed with status 403')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { settingsApi } from './settings'
|
||||
|
||||
describe('settingsApi', () => {
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('installSkillFromGithub', () => {
|
||||
it('posts JSON to skills install endpoint', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ skill: { name: 'teach' }, overwritten: false, sourceType: 'github', filesInstalled: ['SKILL.md'] }), { status: 200 }),
|
||||
)
|
||||
|
||||
const result = await settingsApi.installSkillFromGithub({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
})
|
||||
|
||||
expect(result.skill.name).toBe('teach')
|
||||
|
||||
const callUrl = fetchMock.mock.calls[0][0]
|
||||
expect(callUrl).toEqual(expect.stringContaining('/api/settings/skills/install'))
|
||||
|
||||
const callOptions = fetchMock.mock.calls[0][1]
|
||||
expect(callOptions.method).toBe('POST')
|
||||
expect(callOptions.headers['Content-Type']).toBe('application/json')
|
||||
|
||||
const body = JSON.parse(callOptions.body)
|
||||
expect(body.sourceType).toBe('github')
|
||||
})
|
||||
|
||||
it('surfaces 409 conflict as FetchError', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'Skill "teach" already exists in global scope' }), { status: 409 }),
|
||||
)
|
||||
|
||||
await expect(
|
||||
settingsApi.installSkillFromGithub({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
}),
|
||||
).rejects.toThrow(FetchError)
|
||||
|
||||
await expect(
|
||||
settingsApi.installSkillFromGithub({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
}),
|
||||
).rejects.toMatchObject({ statusCode: 409 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('installSkillFromUpload', () => {
|
||||
it('posts FormData manifest and files', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ skill: { name: 'teach' }, overwritten: false, sourceType: 'upload', filesInstalled: ['teach/SKILL.md'] }), { status: 200 }),
|
||||
)
|
||||
|
||||
const file = new File(['# Teach Skill'], 'SKILL.md', { type: 'text/markdown' })
|
||||
Object.defineProperty(file, 'webkitRelativePath', { value: 'teach/SKILL.md' })
|
||||
|
||||
const result = await settingsApi.installSkillFromUpload({ files: [file], scope: 'global' })
|
||||
|
||||
expect(result.sourceType).toBe('upload')
|
||||
|
||||
const callUrl = fetchMock.mock.calls[0][0]
|
||||
expect(callUrl).toEqual(expect.stringContaining('/api/settings/skills/install'))
|
||||
|
||||
const callOptions = fetchMock.mock.calls[0][1]
|
||||
expect(callOptions.method).toBe('POST')
|
||||
expect(callOptions.headers?.hasOwnProperty).toBeFalsy()
|
||||
|
||||
const formData = callOptions.body as FormData
|
||||
expect(formData.get('sourceType')).toBe('upload')
|
||||
expect(formData.get('file0')).toBe(file)
|
||||
|
||||
const manifest = JSON.parse(formData.get('fileManifest') as string)
|
||||
expect(manifest).toHaveLength(1)
|
||||
expect(manifest[0].fieldName).toBe('file0')
|
||||
expect(manifest[0].relativePath).toBe('teach/SKILL.md')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,8 @@ import type {
|
||||
CreateSkillRequest,
|
||||
UpdateSkillRequest,
|
||||
SkillScope,
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillResponse,
|
||||
} from './types/settings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
@@ -268,6 +270,43 @@ export const settingsApi = {
|
||||
method: 'DELETE',
|
||||
})
|
||||
},
|
||||
|
||||
installSkillFromGithub: async (data: InstallSkillFromGithubRequest): Promise<InstallSkillResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
},
|
||||
|
||||
installSkillFromUpload: async (data: {
|
||||
files: File[]
|
||||
scope: SkillScope
|
||||
repoId?: number
|
||||
overwrite?: boolean
|
||||
}): Promise<InstallSkillResponse> => {
|
||||
const formData = new FormData()
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('scope', data.scope)
|
||||
if (data.repoId !== undefined) formData.append('repoId', String(data.repoId))
|
||||
if (data.overwrite !== undefined) formData.append('overwrite', String(data.overwrite))
|
||||
|
||||
const fileManifest: Array<{ fieldName: string; relativePath: string }> = []
|
||||
|
||||
data.files.forEach((file, index) => {
|
||||
const fieldName = `file${index}`
|
||||
const relativePath = file.webkitRelativePath || file.name
|
||||
fileManifest.push({ fieldName, relativePath })
|
||||
formData.append(fieldName, file)
|
||||
})
|
||||
|
||||
formData.append('fileManifest', JSON.stringify(fileManifest))
|
||||
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export interface VersionInfo {
|
||||
|
||||
@@ -15,10 +15,14 @@ import {
|
||||
type CreateSkillRequest,
|
||||
type UpdateSkillRequest,
|
||||
type SkillScope,
|
||||
type InstallSkillFromGithubRequest,
|
||||
type InstallSkillUploadRequest,
|
||||
type InstallSkillUploadManifestEntry,
|
||||
type InstallSkillResponse,
|
||||
} from '@opencode-manager/shared'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillUploadRequest, InstallSkillUploadManifestEntry, InstallSkillResponse }
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
import { toast } from 'sonner'
|
||||
import type { SkillScope } from '@opencode-manager/shared'
|
||||
import type { Repo } from '@/api/types'
|
||||
|
||||
interface SkillInstallDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onInstalled: () => void
|
||||
}
|
||||
|
||||
export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillInstallDialogProps) {
|
||||
const [sourceType, setSourceType] = useState<'github' | 'upload'>('github')
|
||||
const [url, setUrl] = useState('')
|
||||
const [scope, setScope] = useState<SkillScope>('global')
|
||||
const [selectedRepoId, setSelectedRepoId] = useState<number | undefined>(undefined)
|
||||
const [files, setFiles] = useState<File[]>([])
|
||||
const [overwrite, setOverwrite] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setOverwrite(false)
|
||||
}, [url, files, sourceType, scope, selectedRepoId])
|
||||
|
||||
const { data: repos = [] } = useQuery<Repo[]>({
|
||||
queryKey: ['repos'],
|
||||
queryFn: listRepos,
|
||||
enabled: open,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})
|
||||
|
||||
const installMutation = useMutation({
|
||||
mutationFn: () => {
|
||||
if (sourceType === 'github') {
|
||||
return settingsApi.installSkillFromGithub({
|
||||
sourceType,
|
||||
url,
|
||||
scope,
|
||||
repoId: scope === 'project' ? selectedRepoId : undefined,
|
||||
overwrite: overwrite || undefined,
|
||||
})
|
||||
}
|
||||
return settingsApi.installSkillFromUpload({
|
||||
files,
|
||||
scope,
|
||||
repoId: scope === 'project' ? selectedRepoId : undefined,
|
||||
overwrite: overwrite || undefined,
|
||||
})
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Skill installed successfully')
|
||||
setUrl('')
|
||||
setScope('global')
|
||||
setSelectedRepoId(undefined)
|
||||
setFiles([])
|
||||
setOverwrite(false)
|
||||
onInstalled()
|
||||
onOpenChange(false)
|
||||
},
|
||||
onError: (error) => {
|
||||
if (error instanceof FetchError && error.statusCode === 409) {
|
||||
setOverwrite(true)
|
||||
return
|
||||
}
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to install skill')
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (sourceType === 'github' && !url.trim()) {
|
||||
toast.error('Please enter a GitHub URL')
|
||||
return
|
||||
}
|
||||
if (sourceType === 'upload' && files.length === 0) {
|
||||
toast.error('Please select at least one file')
|
||||
return
|
||||
}
|
||||
if (scope === 'project' && !selectedRepoId) {
|
||||
toast.error('Please select a repository')
|
||||
return
|
||||
}
|
||||
installMutation.mutate()
|
||||
}
|
||||
|
||||
const handleOpenChange = (isOpen: boolean) => {
|
||||
if (!isOpen) {
|
||||
setUrl('')
|
||||
setScope('global')
|
||||
setSelectedRepoId(undefined)
|
||||
setFiles([])
|
||||
setOverwrite(false)
|
||||
}
|
||||
onOpenChange(isOpen)
|
||||
}
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFiles = e.target.files
|
||||
if (selectedFiles) {
|
||||
setFiles(Array.from(selectedFiles))
|
||||
}
|
||||
}
|
||||
|
||||
const selectedFileSummary = () => {
|
||||
if (files.length === 0) return null
|
||||
const relPath = files[0].webkitRelativePath || files[0].name
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{files.length} file{files.length > 1 ? 's' : ''} selected (first: {relPath})
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent mobileFullscreen className="sm:max-w-lg sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
|
||||
<DialogTitle>Install Skill</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-2 sm:p-4">
|
||||
<div className="space-y-4">
|
||||
<Tabs value={sourceType} onValueChange={(v) => setSourceType(v as 'github' | 'upload')}>
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="github">GitHub URL</TabsTrigger>
|
||||
<TabsTrigger value="upload">Upload</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="github" className="mt-4 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>GitHub URL</Label>
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="https://github.com/mattpocock/skills/tree/main/skills/productivity/teach"
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="upload" className="mt-4 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Skill File</Label>
|
||||
<Input
|
||||
type="file"
|
||||
accept=".md,text/markdown"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Skill Folder</Label>
|
||||
<Input
|
||||
type="file"
|
||||
accept=".md,text/markdown"
|
||||
{...{ webkitdirectory: '', directory: '' } as React.InputHTMLAttributes<HTMLInputElement>}
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</div>
|
||||
{selectedFileSummary()}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Scope</Label>
|
||||
<Select value={scope} onValueChange={(v) => setScope(v as SkillScope)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select scope" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="global">Global</SelectItem>
|
||||
<SelectItem value="project">Project</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{scope === 'project' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Repository</Label>
|
||||
<Select
|
||||
value={selectedRepoId?.toString()}
|
||||
onValueChange={(value) => setSelectedRepoId(value ? parseInt(value, 10) : undefined)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select repository" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{repos.map((repo) => (
|
||||
<SelectItem key={repo.id} value={repo.id.toString()}>
|
||||
{repo.localPath}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{overwrite && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
A skill with this name already exists. Install again to overwrite the managed skill directory.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end pb-4 p-3">
|
||||
<Button variant="outline" onClick={() => handleOpenChange(false)} className="flex-1 sm:flex-none">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={installMutation.isPending}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{installMutation.isPending && 'Installing...'}
|
||||
{!installMutation.isPending && (overwrite ? 'Overwrite and install' : 'Install')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
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 { FetchError } from '@opencode-manager/shared'
|
||||
import type { ReactNode } from 'react'
|
||||
import { SkillsEditor } from './SkillsEditor'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
installSkillFromGithub: vi.fn(),
|
||||
installSkillFromUpload: vi.fn(),
|
||||
deleteSkill: vi.fn().mockResolvedValue({ success: true }),
|
||||
listManagedSkills: vi.fn(),
|
||||
listRepos: vi.fn().mockResolvedValue([]),
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
installSkillFromGithub: mocks.installSkillFromGithub,
|
||||
installSkillFromUpload: mocks.installSkillFromUpload,
|
||||
deleteSkill: mocks.deleteSkill,
|
||||
listManagedSkills: mocks.listManagedSkills,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
listRepos: mocks.listRepos,
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: mocks.toast,
|
||||
}))
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const mockSkill: SkillFileInfo = {
|
||||
name: 'test-skill',
|
||||
description: 'A test skill',
|
||||
body: '# Test Skill\nSome content',
|
||||
location: '/home/user/.config/opencode/skills/test-skill/SKILL.md',
|
||||
scope: 'global',
|
||||
}
|
||||
|
||||
describe('SkillsEditor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows install skill button beside create skill', () => {
|
||||
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('Install Skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('Create Skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('installs from GitHub URL', async () => {
|
||||
mocks.installSkillFromGithub.mockResolvedValue({
|
||||
skill: { name: 'teach', scope: 'global' },
|
||||
overwritten: false,
|
||||
sourceType: 'github',
|
||||
filesInstalled: ['SKILL.md'],
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('Install Skill'))
|
||||
|
||||
const urlInput = screen.getByPlaceholderText(
|
||||
'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach'
|
||||
)
|
||||
await user.type(urlInput, 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
|
||||
|
||||
await user.click(screen.getByText('Install'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.installSkillFromGithub).toHaveBeenCalledWith({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('uploads a single SKILL.md', async () => {
|
||||
mocks.installSkillFromUpload.mockResolvedValue({
|
||||
skill: { name: 'teach', scope: 'global' },
|
||||
overwritten: false,
|
||||
sourceType: 'upload',
|
||||
filesInstalled: ['SKILL.md'],
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('Install Skill'))
|
||||
|
||||
const uploadTab = screen.getByText('Upload')
|
||||
await user.click(uploadTab)
|
||||
|
||||
const file = new File(['# Test Skill'], 'SKILL.md', { type: 'text/markdown' })
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
|
||||
await user.upload(fileInput, file)
|
||||
|
||||
await user.click(screen.getByText('Install'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.installSkillFromUpload).toHaveBeenCalledWith({
|
||||
files: expect.arrayContaining([expect.any(File)]),
|
||||
scope: 'global',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('prompts overwrite after 409 conflict', async () => {
|
||||
mocks.installSkillFromGithub
|
||||
.mockRejectedValueOnce(
|
||||
new FetchError('Skill "teach" already exists in global scope', 409)
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
skill: { name: 'teach', scope: 'global' },
|
||||
overwritten: true,
|
||||
sourceType: 'github',
|
||||
filesInstalled: ['SKILL.md'],
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('Install Skill'))
|
||||
|
||||
const urlInput = screen.getByPlaceholderText(
|
||||
'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach'
|
||||
)
|
||||
await user.type(urlInput, 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
|
||||
|
||||
await user.click(screen.getByText('Install'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(
|
||||
'A skill with this name already exists. Install again to overwrite the managed skill directory.'
|
||||
)
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
await user.click(screen.getByText('Overwrite and install'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.installSkillFromGithub).toHaveBeenCalledTimes(2)
|
||||
expect(mocks.installSkillFromGithub).toHaveBeenLastCalledWith({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
overwrite: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('delete dialog mentions bundled files', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<SkillsEditor managedSkills={[mockSkill]} />, {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
const skillHeading = screen.getByText('test-skill')
|
||||
const card = skillHeading.closest('[class*="card"]') || skillHeading.closest('[class*="border"]') || skillHeading.parentElement!.parentElement!
|
||||
const deleteButtons = card.querySelectorAll('button')
|
||||
const deleteButton = deleteButtons[deleteButtons.length - 1]
|
||||
await user.click(deleteButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/bundled files/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X } from 'lucide-react'
|
||||
import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X, Download } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { SkillDialog } from './SkillDialog'
|
||||
import { SkillInstallDialog } from './SkillInstallDialog'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import type { OpenCodeConfigInput, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
|
||||
@@ -80,6 +81,7 @@ function SkillPathEditor({ items, onChange, onAddItem, onRemoveItem, label, plac
|
||||
|
||||
export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEditorProps) {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [installDialogOpen, setInstallDialogOpen] = useState(false)
|
||||
const [editingSkill, setEditingSkill] = useState<SkillFileInfo | null>(null)
|
||||
const [collapsiblesOpen, setCollapsiblesOpen] = useState({
|
||||
managed: true,
|
||||
@@ -225,10 +227,16 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
<Badge variant="secondary" className="ml-2">{managedSkills.length}</Badge>
|
||||
)}
|
||||
</Button>
|
||||
<Button type="button" onClick={handleCreate} size="sm">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Create Skill
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => setInstallDialogOpen(true)} size="sm">
|
||||
<Download className="h-4 w-4 mr-1" />
|
||||
Install Skill
|
||||
</Button>
|
||||
<Button type="button" onClick={handleCreate} size="sm">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Create Skill
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{collapsiblesOpen.managed && (
|
||||
@@ -240,7 +248,7 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
<p className="text-sm font-medium">No skills created</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Create your first skill to get started.
|
||||
Create or install your first skill to get started.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -369,6 +377,12 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SkillInstallDialog
|
||||
open={installDialogOpen}
|
||||
onOpenChange={setInstallDialogOpen}
|
||||
onInstalled={() => queryClient.invalidateQueries({ queryKey: ['managed-skills'] })}
|
||||
/>
|
||||
|
||||
<SkillDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
@@ -382,7 +396,7 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteSkill(null)}
|
||||
title="Delete Skill"
|
||||
description="Are you sure you want to delete this skill? This action cannot be undone."
|
||||
description="Delete this managed skill directory and bundled files? This action cannot be undone."
|
||||
itemName={deleteSkill?.name}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
|
||||
@@ -43,3 +43,36 @@ export interface SkillFileInfo {
|
||||
repoId?: number
|
||||
repoName?: string
|
||||
}
|
||||
|
||||
export const SkillInstallSourceSchema = z.enum(['github', 'upload'])
|
||||
export type SkillInstallSource = z.infer<typeof SkillInstallSourceSchema>
|
||||
|
||||
export const InstallSkillFromGithubRequestSchema = z.object({
|
||||
sourceType: z.literal('github'),
|
||||
url: z.string().url(),
|
||||
scope: SkillScopeSchema,
|
||||
repoId: z.number().optional(),
|
||||
overwrite: z.boolean().optional(),
|
||||
})
|
||||
export type InstallSkillFromGithubRequest = z.infer<typeof InstallSkillFromGithubRequestSchema>
|
||||
|
||||
export const InstallSkillUploadManifestEntrySchema = z.object({
|
||||
fieldName: z.string().min(1),
|
||||
relativePath: z.string().min(1),
|
||||
})
|
||||
export type InstallSkillUploadManifestEntry = z.infer<typeof InstallSkillUploadManifestEntrySchema>
|
||||
|
||||
export const InstallSkillUploadRequestSchema = z.object({
|
||||
sourceType: z.literal('upload'),
|
||||
scope: SkillScopeSchema,
|
||||
repoId: z.number().optional(),
|
||||
overwrite: z.boolean().optional(),
|
||||
})
|
||||
export type InstallSkillUploadRequest = z.infer<typeof InstallSkillUploadRequestSchema>
|
||||
|
||||
export interface InstallSkillResponse {
|
||||
skill: SkillFileInfo
|
||||
overwritten: boolean
|
||||
sourceType: 'github' | 'upload'
|
||||
filesInstalled: string[]
|
||||
}
|
||||
@@ -127,6 +127,11 @@ export type {
|
||||
CreateSkillRequest,
|
||||
UpdateSkillRequest,
|
||||
SkillFileInfo,
|
||||
SkillInstallSource,
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillUploadRequest,
|
||||
InstallSkillUploadManifestEntry,
|
||||
InstallSkillResponse,
|
||||
} from '../schemas/skills'
|
||||
export {
|
||||
SKILL_NAME_REGEX,
|
||||
@@ -135,4 +140,8 @@ export {
|
||||
SkillFrontmatterSchema,
|
||||
CreateSkillRequestSchema,
|
||||
UpdateSkillRequestSchema,
|
||||
SkillInstallSourceSchema,
|
||||
InstallSkillFromGithubRequestSchema,
|
||||
InstallSkillUploadRequestSchema,
|
||||
InstallSkillUploadManifestEntrySchema,
|
||||
} from '../schemas/skills'
|
||||
Reference in new issue
Block a user