mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: add skill installer (#279)
* feat: add skill installer with install/uninstall and settings UI * feat: refactor skill installer with extracted SkillLibraryList component * feat: simplify SkillsEditor, extract SkillLibraryList * feat: refactor skill installer components and add github utility
This commit is contained in:
1 parent
24d34f28a3
commit
6e80cdfb8c
24 files changed
+2381
-577
No files matched your search
@@ -4,6 +4,7 @@ import { readFile } from 'fs/promises'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import { githubFetch } from '../utils/github'
|
||||
|
||||
const GITHUB_REPO_OWNER = 'chriswritescode-dev'
|
||||
const GITHUB_REPO_NAME = 'opencode-manager'
|
||||
@@ -24,14 +25,8 @@ async function fetchLatestRelease(): Promise<CachedRelease | null> {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
const response = await githubFetch(
|
||||
`https://api.github.com/repos/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}/releases/latest`,
|
||||
{
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'User-Agent': 'OpenCode-Manager'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
|
||||
+213
-49
@@ -18,6 +18,10 @@ import {
|
||||
CreateSkillRequestSchema,
|
||||
UpdateSkillRequestSchema,
|
||||
SkillScopeSchema,
|
||||
InstallSkillFromGithubRequestSchema,
|
||||
InstallSkillUploadRequestSchema,
|
||||
InstallSkillUploadManifestEntrySchema,
|
||||
type SkillScope,
|
||||
} from '@opencode-manager/shared'
|
||||
import { logger } from '../utils/logger'
|
||||
import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server'
|
||||
@@ -38,7 +42,11 @@ import {
|
||||
createSkill,
|
||||
updateSkill,
|
||||
deleteSkill,
|
||||
installSkillFromGithubTree,
|
||||
installSkillFromUploadedFiles,
|
||||
} from '../services/skills'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { githubFetch } from '../utils/github'
|
||||
|
||||
function getOpenCodeInstallMethod(): string {
|
||||
const homePath = process.env.HOME || ''
|
||||
@@ -92,6 +100,72 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info(`Restarted OpenCode server after skill ${context}`)
|
||||
} catch (restartError) {
|
||||
logger.warn(`Failed to restart OpenCode server after skill ${context}:`, restartError)
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatchSkillReload(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
repoId: number,
|
||||
): Promise<void> {
|
||||
const repo = getRepoById(db, repoId)
|
||||
if (!repo) {
|
||||
logger.warn(`Cannot dispatch skill reload: repo ${repoId} not found`)
|
||||
return
|
||||
}
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'install')
|
||||
|
||||
try {
|
||||
await openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/skill',
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
logger.info(`Dispatched skill reload for project ${repo.fullPath}`)
|
||||
} catch (dispatchError) {
|
||||
logger.warn('Failed to dispatch skill reload:', dispatchError)
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadAfterSkillInstall(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
scope: SkillScope,
|
||||
repoId: number | undefined,
|
||||
): Promise<void> {
|
||||
if (scope === 'project' && repoId !== undefined) {
|
||||
await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, repoId)
|
||||
} else {
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'install')
|
||||
}
|
||||
}
|
||||
|
||||
const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 404 | 409]> = [
|
||||
['already exists', 409],
|
||||
['404', 404],
|
||||
['Invalid GitHub tree URL', 400],
|
||||
['Invalid skill name', 400],
|
||||
['Only one skill', 400],
|
||||
['Skill source must contain', 400],
|
||||
['Path must be relative', 400],
|
||||
['Path must not contain', 400],
|
||||
['escapes', 400],
|
||||
['no downloadable files', 400],
|
||||
['repoId is required', 400],
|
||||
['Missing upload file', 400],
|
||||
['Invalid repoId', 400],
|
||||
['not a valid file', 400],
|
||||
]
|
||||
|
||||
function didConfigFieldChange(
|
||||
previous: Record<string, unknown> | undefined,
|
||||
next: Record<string, unknown> | undefined,
|
||||
@@ -107,6 +181,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
|
||||
}
|
||||
@@ -855,11 +942,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
try {
|
||||
logger.info('Fetching available OpenCode versions from GitHub')
|
||||
|
||||
const response = await fetch('https://api.github.com/repos/sst/opencode/releases?per_page=20', {
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
'User-Agent': 'opencode-manager'
|
||||
}
|
||||
const response = await githubFetch('https://api.github.com/repos/sst/opencode/releases?per_page=20', {
|
||||
accept: 'application/vnd.github.v3+json',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -1122,11 +1206,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
app.get('/skills', async (c) => {
|
||||
try {
|
||||
const repoIdParam = c.req.query('repoId')
|
||||
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
|
||||
if (repoId !== undefined && isNaN(repoId)) {
|
||||
return c.json({ error: 'Invalid repoId' }, 400)
|
||||
}
|
||||
const repoId = parseOptionalRepoId(c.req.query('repoId'))
|
||||
const directory = c.req.query('directory')
|
||||
|
||||
const skills = await listManagedSkills(db, openCodeClient, repoId, directory)
|
||||
@@ -1137,15 +1217,113 @@ 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)
|
||||
|
||||
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId)
|
||||
|
||||
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)
|
||||
|
||||
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId)
|
||||
|
||||
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) {
|
||||
const match = SKILL_INSTALL_ERROR_STATUS.find(([needle]) => error.message.includes(needle))
|
||||
if (match) {
|
||||
return c.json({ error: error.message }, match[1])
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ error: 'Failed to install skill' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/skills/:name', async (c) => {
|
||||
try {
|
||||
const name = c.req.param('name')
|
||||
const scope = SkillScopeSchema.parse(c.req.query('scope'))
|
||||
const repoIdParam = c.req.query('repoId')
|
||||
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
|
||||
if (repoId !== undefined && isNaN(repoId)) {
|
||||
return c.json({ error: 'Invalid repoId' }, 400)
|
||||
}
|
||||
const repoId = parseOptionalRepoId(c.req.query('repoId'))
|
||||
|
||||
if (scope === 'project' && !repoId) {
|
||||
return c.json({ error: 'repoId is required for project scope' }, 400)
|
||||
@@ -1158,6 +1336,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('Invalid repoId')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('not found')) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
@@ -1174,14 +1355,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const validated = CreateSkillRequestSchema.parse(body)
|
||||
|
||||
const skill = await createSkill(db, validated)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill creation')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill creation:', restartError)
|
||||
}
|
||||
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'creation')
|
||||
|
||||
return c.json(skill)
|
||||
} catch (error) {
|
||||
logger.error('Failed to create skill:', error)
|
||||
@@ -1199,11 +1375,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
try {
|
||||
const name = c.req.param('name')
|
||||
const scope = SkillScopeSchema.parse(c.req.query('scope'))
|
||||
const repoIdParam = c.req.query('repoId')
|
||||
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
|
||||
if (repoId !== undefined && isNaN(repoId)) {
|
||||
return c.json({ error: 'Invalid repoId' }, 400)
|
||||
}
|
||||
const repoId = parseOptionalRepoId(c.req.query('repoId'))
|
||||
const body = await c.req.json()
|
||||
const validated = UpdateSkillRequestSchema.parse(body)
|
||||
|
||||
@@ -1212,20 +1384,18 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill update')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill update:', restartError)
|
||||
}
|
||||
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'update')
|
||||
|
||||
return c.json(skill)
|
||||
} catch (error) {
|
||||
logger.error('Failed to update skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('Invalid repoId')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('not found')) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
@@ -1240,31 +1410,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
try {
|
||||
const name = c.req.param('name')
|
||||
const scope = SkillScopeSchema.parse(c.req.query('scope'))
|
||||
const repoIdParam = c.req.query('repoId')
|
||||
const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined
|
||||
if (repoId !== undefined && isNaN(repoId)) {
|
||||
return c.json({ error: 'Invalid repoId' }, 400)
|
||||
}
|
||||
const repoId = parseOptionalRepoId(c.req.query('repoId'))
|
||||
|
||||
if (scope === 'project' && !repoId) {
|
||||
return c.json({ error: 'repoId is required for project scope' }, 400)
|
||||
}
|
||||
|
||||
await deleteSkill(db, name, scope, repoId)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill deletion')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill deletion:', restartError)
|
||||
}
|
||||
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'deletion')
|
||||
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('Invalid repoId')) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('not found')) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
|
||||
+383
-24
@@ -1,14 +1,16 @@
|
||||
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'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { githubFetchJson, githubFetchBinary, type GithubFetchFn } from '../utils/github'
|
||||
|
||||
interface OpenCodeSkillInfo {
|
||||
name: string
|
||||
@@ -17,6 +19,308 @@ 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) || /^[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)
|
||||
}
|
||||
|
||||
interface GithubTreeSource {
|
||||
owner: string
|
||||
repo: string
|
||||
ref: string
|
||||
path: string
|
||||
}
|
||||
|
||||
interface GithubContentEntry {
|
||||
name: string
|
||||
path: string
|
||||
type: 'file' | 'dir'
|
||||
download_url?: string | null
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
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 githubFetchJson(apiUrl, {}, fetchFn)
|
||||
|
||||
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 githubFetchBinary(entry.download_url!, {}, fetchFn)
|
||||
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 MAX_FILES = 100
|
||||
|
||||
async function collectFileEntries(entries: GithubContentEntry[]): Promise<GithubContentEntry[]> {
|
||||
const fileEntries = entries.filter((entry) => entry.type === 'file' && entry.download_url)
|
||||
const dirEntries = entries.filter((entry) => entry.type === 'dir')
|
||||
const nested = await Promise.all(
|
||||
dirEntries.map(async (dir) => {
|
||||
const dirData = await githubFetchJson(githubContentsApiUrl(source, dir.path), {}, fetchFn)
|
||||
return Array.isArray(dirData) ? collectFileEntries(dirData as GithubContentEntry[]) : []
|
||||
}),
|
||||
)
|
||||
return [...fileEntries, ...nested.flat()]
|
||||
}
|
||||
|
||||
const collected = await collectFileEntries(data as GithubContentEntry[])
|
||||
|
||||
if (collected.length > MAX_FILES) {
|
||||
throw new Error(`Skill contains too many files (max ${MAX_FILES})`)
|
||||
}
|
||||
|
||||
const files = await Promise.all(
|
||||
collected.map(async (entry) => {
|
||||
const relativePath = entry.path.startsWith(source.path + '/')
|
||||
? entry.path.substring(source.path.length + 1)
|
||||
: entry.path
|
||||
const arrayBuffer = await githubFetchBinary(entry.download_url!, {}, fetchFn)
|
||||
return { relativePath, content: Buffer.from(arrayBuffer) }
|
||||
}),
|
||||
)
|
||||
|
||||
const totalBytes = files.reduce((sum, file) => sum + file.content.length, 0)
|
||||
if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) {
|
||||
throw new Error('Skill files exceed maximum upload size')
|
||||
}
|
||||
|
||||
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 +393,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 {
|
||||
@@ -133,18 +428,18 @@ function classifySkillLocation(
|
||||
if (location.startsWith(globalPrefix + path.sep)) {
|
||||
return { scope: 'global' }
|
||||
}
|
||||
if (customDirectory) {
|
||||
const projectPrefix = path.join(customDirectory, '.opencode', 'skills')
|
||||
if (location.startsWith(projectPrefix + path.sep)) {
|
||||
return { scope: 'project' }
|
||||
}
|
||||
}
|
||||
for (const repo of repos) {
|
||||
const projectPrefix = getProjectSkillsPath(repo)
|
||||
if (location.startsWith(projectPrefix + path.sep)) {
|
||||
return { scope: 'project', repo }
|
||||
}
|
||||
}
|
||||
if (customDirectory) {
|
||||
const projectPrefix = path.join(customDirectory, '.opencode', 'skills')
|
||||
if (location.startsWith(projectPrefix + path.sep)) {
|
||||
return { scope: 'project' }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -163,6 +458,54 @@ function toSkillFileInfo(
|
||||
}
|
||||
}
|
||||
|
||||
async function scanSkillRoot(root: string, scope: SkillScope, repo?: Repo): Promise<SkillFileInfo[]> {
|
||||
if (!await fileExists(root)) {
|
||||
return []
|
||||
}
|
||||
|
||||
let entries: Awaited<ReturnType<typeof listDirectory>>
|
||||
try {
|
||||
entries = await listDirectory(root)
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to scan skills at ${root}:`, error)
|
||||
return []
|
||||
}
|
||||
|
||||
const scanned = await Promise.all(
|
||||
entries
|
||||
.filter((entry) => entry.isDirectory)
|
||||
.map(async (entry): Promise<SkillFileInfo | null> => {
|
||||
const skillPath = path.join(entry.path, 'SKILL.md')
|
||||
if (!await fileExists(skillPath)) return null
|
||||
|
||||
try {
|
||||
const content = await readFileContent(skillPath)
|
||||
const parsed = parseSkillMarkdown(content)
|
||||
return {
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
body: parsed.body,
|
||||
scope,
|
||||
location: skillPath,
|
||||
repoId: scope === 'project' ? repo?.id : undefined,
|
||||
repoName: scope === 'project' ? repo?.localPath : undefined,
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to read skill at ${skillPath}:`, error)
|
||||
return null
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return scanned.filter((skill): skill is SkillFileInfo => skill !== null)
|
||||
}
|
||||
|
||||
function addSkill(result: SkillFileInfo[], seenLocations: Set<string>, skill: SkillFileInfo): void {
|
||||
if (seenLocations.has(skill.location)) return
|
||||
seenLocations.add(skill.location)
|
||||
result.push(skill)
|
||||
}
|
||||
|
||||
export async function listManagedSkills(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
@@ -181,8 +524,16 @@ export async function listManagedSkills(
|
||||
if (seenLocations.has(skill.location)) continue
|
||||
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos, directory)
|
||||
if (!classification) continue
|
||||
seenLocations.add(skill.location)
|
||||
result.push(toSkillFileInfo(skill, classification))
|
||||
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
|
||||
}
|
||||
|
||||
const repo = allRepos.find(r => r.fullPath === directory)
|
||||
const fallbackSkills = (await Promise.all([
|
||||
scanSkillRoot(globalPrefix, 'global'),
|
||||
scanSkillRoot(path.join(directory, '.opencode', 'skills'), 'project', repo),
|
||||
])).flat()
|
||||
for (const skill of fallbackSkills) {
|
||||
addSkill(result, seenLocations, skill)
|
||||
}
|
||||
} else {
|
||||
const targetRepos = repoId
|
||||
@@ -203,10 +554,18 @@ export async function listManagedSkills(
|
||||
if (seenLocations.has(skill.location)) continue
|
||||
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos)
|
||||
if (!classification) continue
|
||||
seenLocations.add(skill.location)
|
||||
result.push(toSkillFileInfo(skill, classification))
|
||||
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
|
||||
}
|
||||
}
|
||||
|
||||
const [globalFallback, repoFallbacks] = await Promise.all([
|
||||
scanSkillRoot(globalPrefix, 'global'),
|
||||
Promise.all(targetRepos.map(repo => scanSkillRoot(getProjectSkillsPath(repo), 'project', repo))),
|
||||
])
|
||||
const fallbackSkills = [...globalFallback, ...repoFallbacks.flat()]
|
||||
for (const skill of fallbackSkills) {
|
||||
addSkill(result, seenLocations, skill)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
import { githubFetch } from './github'
|
||||
|
||||
export function isGitHubHttpsUrl(repoUrl: string): boolean {
|
||||
const url = normalizeGitCredentialUrl(repoUrl)
|
||||
@@ -202,20 +203,8 @@ export function createGitIdentityEnv(identity: GitIdentity): Record<string, stri
|
||||
export async function fetchGitHubUserInfo(token: string): Promise<GitHubUserInfo | null> {
|
||||
try {
|
||||
const [userResponse, emailsResponse] = await Promise.all([
|
||||
fetch('https://api.github.com/user', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28'
|
||||
}
|
||||
}),
|
||||
fetch('https://api.github.com/user/emails', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28'
|
||||
}
|
||||
})
|
||||
githubFetch('https://api.github.com/user', { token, apiVersion: '2022-11-28' }),
|
||||
githubFetch('https://api.github.com/user/emails', { token, apiVersion: '2022-11-28' }),
|
||||
])
|
||||
|
||||
if (!userResponse.ok) return null
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export type GithubFetchFn = (url: string | URL | Request, init?: RequestInit) => Promise<Response>
|
||||
|
||||
interface GithubRequestOptions {
|
||||
token?: string
|
||||
apiVersion?: string
|
||||
accept?: string
|
||||
}
|
||||
|
||||
export function githubFetch(
|
||||
url: string,
|
||||
options: GithubRequestOptions = {},
|
||||
fetchFn: GithubFetchFn = fetch,
|
||||
): Promise<Response> {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: options.accept ?? 'application/vnd.github+json',
|
||||
'User-Agent': 'opencode-manager',
|
||||
}
|
||||
if (options.token) headers.Authorization = `Bearer ${options.token}`
|
||||
if (options.apiVersion) headers['X-GitHub-Api-Version'] = options.apiVersion
|
||||
return fetchFn(url, { headers })
|
||||
}
|
||||
|
||||
export async function githubFetchJson<T = unknown>(
|
||||
url: string,
|
||||
options: GithubRequestOptions = {},
|
||||
fetchFn: GithubFetchFn = fetch,
|
||||
): Promise<T> {
|
||||
const response = await githubFetch(url, options, fetchFn)
|
||||
if (!response.ok) {
|
||||
throw new Error(`GitHub request failed with status ${response.status}`)
|
||||
}
|
||||
return response.json() as Promise<T>
|
||||
}
|
||||
|
||||
export async function githubFetchBinary(
|
||||
url: string,
|
||||
options: GithubRequestOptions = {},
|
||||
fetchFn: GithubFetchFn = fetch,
|
||||
): Promise<ArrayBuffer> {
|
||||
const response = await githubFetch(url, options, fetchFn)
|
||||
if (!response.ok) {
|
||||
throw new Error(`GitHub request failed with status ${response.status}`)
|
||||
}
|
||||
return response.arrayBuffer()
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,20 @@
|
||||
import { describe, expect, test, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { mkdtemp, rm, readFile } from 'fs/promises'
|
||||
import { mkdir, mkdtemp, rm, readFile, writeFile } from 'fs/promises'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
|
||||
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(),
|
||||
@@ -288,6 +300,43 @@ describe('SkillService', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('lists project skills from repo .opencode directory when OpenCode returns none', async () => {
|
||||
const { listManagedSkills } = await import('../../src/services/skills')
|
||||
const dbQueries = await import('../../src/db/queries')
|
||||
const projectPath = join(tempDir, 'project-zero')
|
||||
const skillDir = join(projectPath, '.opencode', 'skills', 'project-helper')
|
||||
const repo: Repo = {
|
||||
id: 123,
|
||||
localPath: 'Project Zero',
|
||||
fullPath: projectPath,
|
||||
sourcePath: projectPath,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
}
|
||||
|
||||
vi.mocked(dbQueries.listRepos).mockReturnValue([repo])
|
||||
await mkdir(skillDir, { recursive: true })
|
||||
await writeFile(
|
||||
join(skillDir, 'SKILL.md'),
|
||||
'---\nname: project-helper\ndescription: Helps project work\n---\nUse repo context.',
|
||||
)
|
||||
|
||||
const repoSkills = await listManagedSkills(mockDb, createMockClient([]), repo.id)
|
||||
const directorySkills = await listManagedSkills(mockDb, createMockClient([]), undefined, projectPath)
|
||||
|
||||
for (const skills of [repoSkills, directorySkills]) {
|
||||
expect(skills).toContainEqual(expect.objectContaining({
|
||||
name: 'project-helper',
|
||||
description: 'Helps project work',
|
||||
scope: 'project',
|
||||
repoId: repo.id,
|
||||
repoName: 'Project Zero',
|
||||
}))
|
||||
}
|
||||
})
|
||||
|
||||
test('preserves body content containing --- (horizontal rules)', async () => {
|
||||
const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills')
|
||||
const name = `hr-test-${Date.now()}`
|
||||
@@ -348,4 +397,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 },
|
||||
{ name: 'GLOSSARY-FORMAT.md', path: 'skills/productivity/teach/GLOSSARY-FORMAT.md', type: 'file', download_url: downloadUrl2 },
|
||||
]), { 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 },
|
||||
{ name: 'review', path: 'skills/review', type: 'dir', download_url: null },
|
||||
]), { 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' },
|
||||
]), { 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' },
|
||||
]), { 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 },
|
||||
]), { 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 },
|
||||
]), { 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 },
|
||||
]), { 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 },
|
||||
{ name: 'GLOSSARY-FORMAT.md', path: 'skill-with-bundle/GLOSSARY-FORMAT.md', type: 'file', download_url: bundleUrl },
|
||||
]), { 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,12 @@ import {
|
||||
type CreateSkillRequest,
|
||||
type UpdateSkillRequest,
|
||||
type SkillScope,
|
||||
type InstallSkillFromGithubRequest,
|
||||
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, 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 {
|
||||
|
||||
@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
listManagedSkills: mocks.listManagedSkills,
|
||||
deleteSkill: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -93,7 +94,7 @@ describe('RepoSkillsDialog', () => {
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-skill')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -116,7 +117,7 @@ describe('RepoSkillsDialog', () => {
|
||||
const globalTab = screen.getByText('Global')
|
||||
await userEvent.click(globalTab)
|
||||
|
||||
expect(screen.getByText('Global skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('global-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows empty state for project tab when no project skills', async () => {
|
||||
@@ -143,7 +144,7 @@ describe('RepoSkillsDialog', () => {
|
||||
await userEvent.click(projectTab)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No local skills found')).toBeInTheDocument()
|
||||
expect(screen.getByText('No skills found')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -170,10 +171,10 @@ describe('RepoSkillsDialog', () => {
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')
|
||||
const card = screen.getByText('test-skill').closest('[class*="cursor-pointer"]')
|
||||
expect(card).toBeTruthy()
|
||||
})
|
||||
|
||||
@@ -190,10 +191,10 @@ describe('RepoSkillsDialog', () => {
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')
|
||||
const card = screen.getByText('test-skill').closest('[class*="cursor-pointer"]')
|
||||
expect(card).toBeNull()
|
||||
})
|
||||
|
||||
@@ -219,10 +220,10 @@ describe('RepoSkillsDialog', () => {
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')!
|
||||
const card = screen.getByText('test-skill').closest('[class*="cursor-pointer"]')!
|
||||
await user.click(card)
|
||||
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||
@@ -254,10 +255,10 @@ describe('RepoSkillsDialog', () => {
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test skill')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
const card = screen.getByText('Test skill').closest('[class*="cursor-pointer"]')!
|
||||
const card = screen.getByText('test-skill').closest('[class*="cursor-pointer"]')!
|
||||
await user.click(card)
|
||||
|
||||
await waitFor(() => {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Download } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
|
||||
import { RepoSkillsList } from './RepoSkillsList'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { SkillLibraryList } from '@/components/skills/SkillLibraryList'
|
||||
import { SkillInstallDialog } from '@/components/settings/SkillInstallDialog'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useLoadSkill } from '@/hooks/useOpenCode'
|
||||
import { useDeleteSkill } from '@/hooks/useDeleteSkill'
|
||||
import { invalidateSkillCaches } from '@/lib/queryInvalidation'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
import { useMemo, useState, useEffect } from 'react'
|
||||
|
||||
type RepoSkillsDialogBaseProps = {
|
||||
open: boolean
|
||||
@@ -27,83 +32,84 @@ export function RepoSkillsDialog({
|
||||
directory,
|
||||
onSkillLoaded,
|
||||
}: RepoSkillsDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [installDialogOpen, setInstallDialogOpen] = useState(false)
|
||||
const { deleteSkill, setDeleteSkill, confirmDelete, isDeleting } = useDeleteSkill()
|
||||
const skillsQueryKey = directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId]
|
||||
|
||||
const { isLoading, data, error } = useQuery({
|
||||
queryKey: directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId],
|
||||
queryKey: skillsQueryKey,
|
||||
queryFn: () => settingsApi.listManagedSkills(repoId, directory),
|
||||
enabled: open && (!!repoId || !!directory),
|
||||
staleTime: 30000,
|
||||
})
|
||||
|
||||
const projectSkills = useMemo(
|
||||
() => data?.filter((s) => s.scope === 'project') ?? [],
|
||||
[data],
|
||||
)
|
||||
const globalSkills = useMemo(
|
||||
() => data?.filter((s) => s.scope === 'global') ?? [],
|
||||
[data],
|
||||
)
|
||||
|
||||
const canLoad = !!sessionId && !!opcodeUrl
|
||||
const loadSkill = useLoadSkill(opcodeUrl, sessionId, directory)
|
||||
|
||||
const [activeTab, setActiveTab] = useState<'project' | 'global'>('project')
|
||||
|
||||
useEffect(() => {
|
||||
if (data && projectSkills.length === 0 && globalSkills.length > 0) {
|
||||
setActiveTab('global')
|
||||
}
|
||||
}, [data, projectSkills.length, globalSkills.length])
|
||||
|
||||
const handleTabChange = (value: string) => {
|
||||
setActiveTab(value as 'project' | 'global')
|
||||
}
|
||||
|
||||
const handleLoad = (skill: SkillFileInfo) => {
|
||||
loadSkill.mutate({ skillName: skill.name })
|
||||
onSkillLoaded?.(skill)
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
const handleInstalled = () => {
|
||||
invalidateSkillCaches(queryClient)
|
||||
}
|
||||
|
||||
if (!repoId && !sessionId) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="sm:max-w-2xl 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 shrink-0">
|
||||
<DialogTitle>Skills</DialogTitle>
|
||||
<DialogDescription>
|
||||
{canLoad ? 'Load a skill into the current session' : 'Skills available for this repository'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Tabs value={activeTab} onValueChange={handleTabChange} className="flex-1 flex flex-col min-h-0">
|
||||
<TabsList className="mx-4 sm:mx-6 mt-3">
|
||||
<TabsTrigger value="project">Project</TabsTrigger>
|
||||
<TabsTrigger value="global">Global</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="project" className="flex-1 min-h-0 flex flex-col">
|
||||
<RepoSkillsList
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="sm:max-w-3xl 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 shrink-0">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<DialogTitle>Skills</DialogTitle>
|
||||
<DialogDescription>
|
||||
{canLoad ? 'Search and load a skill into the current session' : 'Skills available for this repository'}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setInstallDialogOpen(true)}>
|
||||
<Download className="h-4 w-4 mr-1" />
|
||||
Install Skill
|
||||
</Button>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<div className="flex-1 overflow-y-auto p-4 sm:p-6">
|
||||
<SkillLibraryList
|
||||
isLoading={isLoading}
|
||||
data={projectSkills}
|
||||
data={data}
|
||||
error={error as Error | null}
|
||||
emptyTitle="No local skills found"
|
||||
emptyHint="Add skills to .opencode/skills/<name>/SKILL.md in this repository."
|
||||
onLoad={canLoad ? handleLoad : undefined}
|
||||
primaryAction={canLoad ? { label: 'Load', onClick: handleLoad } : undefined}
|
||||
rowActions={[{ label: 'Delete', onClick: setDeleteSkill, destructive: true }]}
|
||||
emptyTitle="No skills found"
|
||||
emptyHint="Install a skill or add one to .opencode/skills/<name>/SKILL.md."
|
||||
maxHeightClassName="max-h-[55vh]"
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="global" className="flex-1 min-h-0 flex flex-col">
|
||||
<RepoSkillsList
|
||||
isLoading={isLoading}
|
||||
data={globalSkills}
|
||||
error={error as Error | null}
|
||||
emptyTitle="No global skills"
|
||||
emptyHint="Global skills live under ~/.config/opencode/skills/."
|
||||
onLoad={canLoad ? handleLoad : undefined}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<SkillInstallDialog
|
||||
open={installDialogOpen}
|
||||
onOpenChange={setInstallDialogOpen}
|
||||
onInstalled={handleInstalled}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={deleteSkill !== null}
|
||||
onOpenChange={(isOpen) => !isOpen && setDeleteSkill(null)}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteSkill(null)}
|
||||
title="Delete Skill"
|
||||
description="Delete this managed skill directory and bundled files? This action cannot be undone."
|
||||
itemName={deleteSkill?.name}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import { AlertCircle, Loader2 } from 'lucide-react'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
|
||||
interface RepoSkillsListProps {
|
||||
isLoading: boolean
|
||||
data: SkillFileInfo[] | undefined
|
||||
error: Error | null
|
||||
emptyTitle?: string
|
||||
emptyHint?: string
|
||||
onLoad?: (skill: SkillFileInfo) => void
|
||||
}
|
||||
|
||||
export function RepoSkillsList({
|
||||
isLoading,
|
||||
data,
|
||||
error,
|
||||
emptyTitle,
|
||||
emptyHint,
|
||||
onLoad,
|
||||
}: RepoSkillsListProps) {
|
||||
const formatSkillName = (name: string): string => {
|
||||
const formatted = name.replace(/-/g, ' ')
|
||||
return formatted.charAt(0).toUpperCase() + formatted.slice(1)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<AlertCircle className="w-10 h-10 mx-auto mb-3 opacity-50 text-red-500" />
|
||||
<p className="text-sm">Failed to load skills</p>
|
||||
<p className="text-xs mt-1">{error.message}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<p className="text-sm">{emptyTitle || 'No skills available'}</p>
|
||||
<p className="text-xs mt-1">
|
||||
{emptyHint ||
|
||||
'Skills will appear here when configured in the project\'s .opencode/skills/ directory'}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto min-h-0 px-2 sm:px-4 py-2">
|
||||
<div className="space-y-2">
|
||||
{data.map((skill) => (
|
||||
<div
|
||||
key={skill.name}
|
||||
onClick={onLoad ? () => onLoad(skill) : undefined}
|
||||
className={`p-2 rounded-lg border border-border bg-card flex items-center gap-2 ${onLoad ? 'cursor-pointer hover:bg-accent transition-colors' : ''}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate text-orange-600 dark:text-orange-400">
|
||||
{formatSkillName(skill.name)}
|
||||
</p>
|
||||
{skill.description && (
|
||||
<p className="text-xs text-muted-foreground truncate mt-0.5">
|
||||
{skill.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -874,7 +874,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.commands ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.commands ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-1 sm:p-4 max-h-[50vh] overflow-y-auto">
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<CommandsEditor
|
||||
commands={(selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}}
|
||||
onChange={(commands) => {
|
||||
@@ -911,7 +911,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.agents ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.agents ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4 max-h-[50vh] overflow-y-auto">
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<AgentsEditor
|
||||
agents={(selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}}
|
||||
onChange={(agents) => {
|
||||
@@ -941,25 +941,15 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Skills</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{managedSkills.length + (((selectedConfig.content?.skills as { paths?: string[]; urls?: string[] } | undefined)?.paths?.length) ?? 0) + (((selectedConfig.content?.skills as { paths?: string[]; urls?: string[] } | undefined)?.urls?.length) ?? 0)} configured
|
||||
{managedSkills.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4 max-h-[50vh] overflow-y-auto">
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<SkillsEditor
|
||||
skills={selectedConfig.content?.skills as { paths?: string[]; urls?: string[] } | undefined}
|
||||
managedSkills={managedSkills}
|
||||
onChange={(skills) => {
|
||||
const paths = skills?.paths?.filter(Boolean)
|
||||
const urls = skills?.urls?.filter(Boolean)
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
skills: (paths?.length || urls?.length) ? { paths: paths?.length ? paths : undefined, urls: urls?.length ? urls : undefined } : undefined
|
||||
}
|
||||
updateConfigContent(selectedConfig.name, updatedContent)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -987,7 +977,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.mcp ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.mcp ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4 max-h-[50vh] overflow-y-auto">
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<McpManager
|
||||
config={selectedConfig}
|
||||
onUpdate={(content) => updateConfigContent(selectedConfig.name, content)}
|
||||
@@ -1026,7 +1016,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.models ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.models ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-4 max-h-[50vh] overflow-y-auto">
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<OpenCodeModelsEditor
|
||||
providers={(selectedConfig.content?.provider as Record<string, ConfigProvider> | undefined) ?? {}}
|
||||
onChange={(providers) => {
|
||||
|
||||
@@ -335,6 +335,8 @@ export function OpenCodeModelDialog({
|
||||
|
||||
const isEditing = !!editingModel
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange} key={editingModel ? `edit-${editingModel.modelId}` : 'create'}>
|
||||
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6">
|
||||
|
||||
@@ -179,7 +179,7 @@ export function SettingsDialog() {
|
||||
</div>
|
||||
|
||||
<div className="sm:hidden flex flex-col h-full min-h-0">
|
||||
<div className="flex-shrink-0 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex-shrink-0 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-3 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
{mobileView !== 'menu' && (
|
||||
<Button
|
||||
@@ -205,7 +205,7 @@ export function SettingsDialog() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-32">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-3 pb-20">
|
||||
{mobileView === 'menu' && (
|
||||
<div className="space-y-3">
|
||||
{menuItems.map((item) => (
|
||||
@@ -235,7 +235,7 @@ export function SettingsDialog() {
|
||||
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
|
||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-6">
|
||||
<div key="opencode" className="space-y-4">
|
||||
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
|
||||
@@ -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 resetForm = () => {
|
||||
setUrl('')
|
||||
setScope('global')
|
||||
setSelectedRepoId(undefined)
|
||||
setFiles([])
|
||||
setOverwrite(false)
|
||||
}
|
||||
|
||||
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')
|
||||
resetForm()
|
||||
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) {
|
||||
resetForm()
|
||||
}
|
||||
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="Paste a GitHub skill URL"
|
||||
/>
|
||||
</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,184 @@
|
||||
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('Paste a GitHub skill URL')
|
||||
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('Paste a GitHub skill URL')
|
||||
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(),
|
||||
})
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for test-skill'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/bundled files/)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,108 +1,33 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X } from 'lucide-react'
|
||||
import { Plus, 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 { SkillLibraryList } from '@/components/skills/SkillLibraryList'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import type { OpenCodeConfigInput, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
|
||||
import { useDeleteSkill } from '@/hooks/useDeleteSkill'
|
||||
import { invalidateSkillCaches } from '@/lib/queryInvalidation'
|
||||
import type { SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface SkillsEditorProps {
|
||||
skills?: OpenCodeConfigInput['skills']
|
||||
managedSkills?: SkillFileInfo[]
|
||||
onChange?: (skills: OpenCodeConfigInput['skills']) => void
|
||||
}
|
||||
|
||||
interface SkillPathEditorProps {
|
||||
items: string[]
|
||||
onChange: (items: string[]) => void
|
||||
onAddItem: () => void
|
||||
onRemoveItem: (index: number) => void
|
||||
label: string
|
||||
placeholder: string
|
||||
}
|
||||
|
||||
function SkillPathEditor({ items, onChange, onAddItem, onRemoveItem, label, placeholder }: SkillPathEditorProps) {
|
||||
const handleItemChange = (index: number, value: string) => {
|
||||
const updated = [...items]
|
||||
updated[index] = value
|
||||
onChange(updated)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Label>{label}</Label>
|
||||
{items.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card/50 p-4 text-center">
|
||||
<p className="text-sm text-muted-foreground">No {label.toLowerCase()} configured. Add one to get started.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{items.map((item, index) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={item}
|
||||
onChange={(e) => handleItemChange(index, e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onRemoveItem(index)}
|
||||
className="h-9 w-9"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onAddItem}
|
||||
className="w-full"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add {label}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEditorProps) {
|
||||
export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) {
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [installDialogOpen, setInstallDialogOpen] = useState(false)
|
||||
const [editingSkill, setEditingSkill] = useState<SkillFileInfo | null>(null)
|
||||
const [collapsiblesOpen, setCollapsiblesOpen] = useState({
|
||||
managed: true,
|
||||
config: false,
|
||||
})
|
||||
const [localPaths, setLocalPaths] = useState<string[]>(skills?.paths ?? [])
|
||||
const [localUrls, setLocalUrls] = useState<string[]>(skills?.urls ?? [])
|
||||
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
|
||||
const [deleteSkill, setDeleteSkill] = useState<SkillFileInfo | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) {
|
||||
setLocalPaths(skills?.paths ?? [])
|
||||
setLocalUrls(skills?.urls ?? [])
|
||||
}
|
||||
}, [skills?.paths, skills?.urls, hasUnsavedChanges])
|
||||
const { deleteSkill, setDeleteSkill, confirmDelete, isDeleting } = useDeleteSkill()
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: CreateSkillRequest) => settingsApi.createSkill(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
invalidateSkillCaches(queryClient)
|
||||
toast.success('Skill created successfully')
|
||||
setDialogOpen(false)
|
||||
},
|
||||
@@ -115,7 +40,7 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
mutationFn: ({ name, scope, repoId, ...data }: UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number }) =>
|
||||
settingsApi.updateSkill(name, scope, data, repoId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
invalidateSkillCaches(queryClient)
|
||||
toast.success('Skill updated successfully')
|
||||
setDialogOpen(false)
|
||||
setEditingSkill(null)
|
||||
@@ -125,38 +50,11 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: ({ name, scope, repoId }: { name: string; scope: SkillScope; repoId?: number }) =>
|
||||
settingsApi.deleteSkill(name, scope, repoId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
toast.success('Skill deleted successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete skill')
|
||||
},
|
||||
})
|
||||
|
||||
const handleEdit = (skill: SkillFileInfo) => {
|
||||
setEditingSkill(skill)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleDelete = (skill: SkillFileInfo) => {
|
||||
setDeleteSkill(skill)
|
||||
}
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (!deleteSkill) return
|
||||
deleteMutation.mutate({
|
||||
name: deleteSkill.name,
|
||||
scope: deleteSkill.scope,
|
||||
repoId: deleteSkill.scope === 'project' ? deleteSkill.repoId : undefined,
|
||||
}, {
|
||||
onSettled: () => setDeleteSkill(null),
|
||||
})
|
||||
}
|
||||
|
||||
const handleCreate = () => {
|
||||
setEditingSkill(null)
|
||||
setDialogOpen(true)
|
||||
@@ -170,205 +68,38 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
|
||||
}
|
||||
}
|
||||
|
||||
const handlePathsChange = (paths: string[]) => {
|
||||
setLocalPaths(paths)
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const handleUrlsChange = (urls: string[]) => {
|
||||
setLocalUrls(urls)
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
const filteredPaths = localPaths.filter(p => p.trim() !== '')
|
||||
const filteredUrls = localUrls.filter(u => u.trim() !== '')
|
||||
|
||||
onChange?.({
|
||||
paths: filteredPaths.length > 0 ? filteredPaths : undefined,
|
||||
urls: filteredUrls.length > 0 ? filteredUrls : undefined,
|
||||
})
|
||||
setHasUnsavedChanges(false)
|
||||
toast.success('Skills configuration saved')
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
setLocalPaths(skills?.paths ?? [])
|
||||
setLocalUrls(skills?.urls ?? [])
|
||||
setHasUnsavedChanges(false)
|
||||
}
|
||||
|
||||
const getScopeBadge = (skill: SkillFileInfo) => {
|
||||
if (skill.scope === 'global') {
|
||||
return <Badge variant="secondary">Global</Badge>
|
||||
}
|
||||
return (
|
||||
<Badge variant="outline">
|
||||
Project{skill.repoName ? `: ${skill.repoName}` : ''}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCollapsiblesOpen(prev => ({ ...prev, managed: !prev.managed }))}
|
||||
className="h-auto p-0 font-medium"
|
||||
>
|
||||
{collapsiblesOpen.managed ? <ChevronDown className="h-4 w-4 mr-1" /> : <ChevronRight className="h-4 w-4 mr-1" />}
|
||||
Managed Skills
|
||||
{managedSkills.length > 0 && (
|
||||
<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>
|
||||
|
||||
{collapsiblesOpen.managed && (
|
||||
<>
|
||||
{managedSkills.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<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.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="max-h-[400px] overflow-y-auto">
|
||||
<div className="grid gap-3">
|
||||
{managedSkills.map((skill) => (
|
||||
<Card key={`${skill.scope}-${skill.name}`}>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-sm">{skill.name}</CardTitle>
|
||||
<div className="flex items-center gap-1">
|
||||
{getScopeBadge(skill)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleEdit(skill)}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleDelete(skill)}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{skill.description && (
|
||||
<p className="text-sm text-muted-foreground">{skill.description}</p>
|
||||
)}
|
||||
{skill.body && (
|
||||
<div className="text-xs font-mono bg-muted rounded p-2 line-clamp-3 max-h-[60px] overflow-hidden whitespace-pre-wrap">
|
||||
{skill.body}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCollapsiblesOpen(prev => ({ ...prev, config: !prev.config }))}
|
||||
className="h-auto p-0 font-medium"
|
||||
>
|
||||
{collapsiblesOpen.config ? <ChevronDown className="h-4 w-4 mr-1" /> : <ChevronRight className="h-4 w-4 mr-1" />}
|
||||
Advanced: Custom Paths & URLs
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
<div className="flex items-center justify-end">
|
||||
<div className="flex w-full items-center gap-2 sm:w-auto">
|
||||
<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" className="flex-1 sm:flex-none">
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Create Skill
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{collapsiblesOpen.config && (
|
||||
<div className="space-y-4">
|
||||
<SkillPathEditor
|
||||
items={localPaths}
|
||||
onChange={handlePathsChange}
|
||||
onAddItem={() => {
|
||||
if (localPaths.length === 0 || localPaths[localPaths.length - 1] !== '') {
|
||||
handlePathsChange([...localPaths, ''])
|
||||
}
|
||||
}}
|
||||
onRemoveItem={(index) => {
|
||||
const updated = localPaths.filter((_, i) => i !== index)
|
||||
handlePathsChange(updated.length > 0 ? updated : [])
|
||||
}}
|
||||
label="Skill Paths"
|
||||
placeholder="e.g., .opencode/skills/"
|
||||
/>
|
||||
|
||||
<SkillPathEditor
|
||||
items={localUrls}
|
||||
onChange={handleUrlsChange}
|
||||
onAddItem={() => {
|
||||
if (localUrls.length === 0 || localUrls[localUrls.length - 1] !== '') {
|
||||
handleUrlsChange([...localUrls, ''])
|
||||
}
|
||||
}}
|
||||
onRemoveItem={(index) => {
|
||||
const updated = localUrls.filter((_, i) => i !== index)
|
||||
handleUrlsChange(updated.length > 0 ? updated : [])
|
||||
}}
|
||||
label="Skill URLs"
|
||||
placeholder="e.g., https://example.com/skills/"
|
||||
/>
|
||||
|
||||
{hasUnsavedChanges && (
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
className="flex-1"
|
||||
>
|
||||
<Save className="h-4 w-4 mr-1" />
|
||||
Save Changes
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCancel}
|
||||
className="flex-1"
|
||||
>
|
||||
<X className="h-4 w-4 mr-1" />
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SkillLibraryList
|
||||
isLoading={false}
|
||||
data={managedSkills}
|
||||
error={null}
|
||||
primaryAction={{ label: 'Edit', onClick: handleEdit }}
|
||||
rowActions={[{ label: 'Delete', onClick: setDeleteSkill, destructive: true }]}
|
||||
emptyTitle="No skills created"
|
||||
emptyHint="Create or install your first skill to get started."
|
||||
maxHeightClassName="max-h-[calc(100dvh-300px)] sm:max-h-[420px]"
|
||||
/>
|
||||
|
||||
<SkillInstallDialog
|
||||
open={installDialogOpen}
|
||||
onOpenChange={setInstallDialogOpen}
|
||||
onInstalled={() => invalidateSkillCaches(queryClient)}
|
||||
/>
|
||||
|
||||
<SkillDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
@@ -382,11 +113,10 @@ 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}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { AlertCircle, Loader2, MoreHorizontal, Search } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import type { SkillFileInfo, SkillScope } from '@opencode-manager/shared'
|
||||
|
||||
type SkillFilter = 'all' | SkillScope
|
||||
|
||||
interface SkillLibraryAction {
|
||||
label: string
|
||||
onClick: (skill: SkillFileInfo) => void
|
||||
destructive?: boolean
|
||||
}
|
||||
|
||||
interface SkillLibraryListProps {
|
||||
isLoading: boolean
|
||||
data: SkillFileInfo[] | undefined
|
||||
error: Error | null
|
||||
primaryAction?: {
|
||||
label: string
|
||||
onClick: (skill: SkillFileInfo) => void
|
||||
}
|
||||
rowActions?: SkillLibraryAction[]
|
||||
emptyTitle?: string
|
||||
emptyHint?: string
|
||||
maxHeightClassName?: string
|
||||
}
|
||||
|
||||
const getSkillKey = (skill: SkillFileInfo) => `${skill.scope}-${skill.repoId ?? 'global'}-${skill.name}`
|
||||
|
||||
const getScopeLabel = (skill: SkillFileInfo) => {
|
||||
if (skill.scope === 'global') return 'Global'
|
||||
return skill.repoName ? `Project: ${skill.repoName}` : 'Project'
|
||||
}
|
||||
|
||||
const getCompactScopeLabel = (skill: SkillFileInfo) => skill.scope === 'global' ? 'Global' : 'Project'
|
||||
|
||||
const matchesSkillSearch = (skill: SkillFileInfo, search: string) => {
|
||||
const query = search.trim().toLowerCase()
|
||||
if (!query) return true
|
||||
return [skill.name, skill.description, skill.location, skill.repoName]
|
||||
.filter(Boolean)
|
||||
.some((value) => value?.toLowerCase().includes(query))
|
||||
}
|
||||
|
||||
export function SkillLibraryList({
|
||||
isLoading,
|
||||
data,
|
||||
error,
|
||||
primaryAction,
|
||||
rowActions = [],
|
||||
emptyTitle,
|
||||
emptyHint,
|
||||
maxHeightClassName = 'max-h-[420px]',
|
||||
}: SkillLibraryListProps) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [filter, setFilter] = useState<SkillFilter>('all')
|
||||
|
||||
const counts = useMemo(() => {
|
||||
const skills = data ?? []
|
||||
return {
|
||||
all: skills.length,
|
||||
project: skills.filter((skill) => skill.scope === 'project').length,
|
||||
global: skills.filter((skill) => skill.scope === 'global').length,
|
||||
}
|
||||
}, [data])
|
||||
|
||||
const filteredSkills = useMemo(() => {
|
||||
return (data ?? [])
|
||||
.filter((skill) => filter === 'all' || skill.scope === filter)
|
||||
.filter((skill) => matchesSkillSearch(skill, search))
|
||||
}, [data, filter, search])
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Search skills..."
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 rounded-lg border border-border bg-muted/30 p-1">
|
||||
{(['all', 'project', 'global'] as const).map((key) => (
|
||||
<Button key={key} type="button" variant={filter === key ? 'secondary' : 'ghost'} size="sm" onClick={() => setFilter(key)}>
|
||||
<span>{key.charAt(0).toUpperCase() + key.slice(1)}</span>
|
||||
<span>{counts[key]}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<AlertCircle className="w-10 h-10 mx-auto mb-3 opacity-50 text-red-500" />
|
||||
<p className="text-sm">Failed to load skills</p>
|
||||
<p className="text-xs mt-1">{error.message}</p>
|
||||
</div>
|
||||
) : filteredSkills.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-center text-muted-foreground">
|
||||
<p className="text-sm font-medium text-foreground">{emptyTitle || 'No skills available'}</p>
|
||||
<p className="text-xs mt-1">{emptyHint || 'Create or install a skill to get started.'}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className={`${maxHeightClassName} overflow-y-auto rounded-lg border border-border`}>
|
||||
<div className="divide-y divide-border">
|
||||
{filteredSkills.map((skill) => (
|
||||
<div
|
||||
key={getSkillKey(skill)}
|
||||
onClick={primaryAction ? () => primaryAction.onClick(skill) : undefined}
|
||||
className={`group flex flex-col gap-2 bg-card px-3 py-3 hover:bg-accent/50 sm:flex-row sm:items-center sm:gap-3 ${primaryAction ? 'cursor-pointer' : ''}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1 self-stretch sm:self-auto">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<p className="min-w-0 flex-1 truncate text-sm font-medium text-orange-600 dark:text-orange-400">{skill.name}</p>
|
||||
<Badge variant={skill.scope === 'global' ? 'secondary' : 'outline'} className="shrink-0 sm:hidden">
|
||||
{getCompactScopeLabel(skill)}
|
||||
</Badge>
|
||||
<Badge variant={skill.scope === 'global' ? 'secondary' : 'outline'} className="hidden max-w-full truncate sm:inline-flex">
|
||||
{getScopeLabel(skill)}
|
||||
</Badge>
|
||||
</div>
|
||||
{skill.description && (
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">{skill.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex w-full shrink-0 items-center justify-end gap-1 sm:w-auto sm:justify-start" onClick={(event) => event.stopPropagation()}>
|
||||
{primaryAction && (
|
||||
<Button type="button" size="sm" onClick={() => primaryAction.onClick(skill)} className="flex-1 sm:flex-none">
|
||||
{primaryAction.label}
|
||||
</Button>
|
||||
)}
|
||||
{rowActions.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className="h-8 w-8" aria-label={`Actions for ${skill.name}`}>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{rowActions.map((action) => (
|
||||
<DropdownMenuItem
|
||||
key={action.label}
|
||||
onClick={() => action.onClick(skill)}
|
||||
className={action.destructive ? 'text-destructive focus:text-destructive' : undefined}
|
||||
>
|
||||
{action.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateSkillCaches } from '@/lib/queryInvalidation'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
|
||||
export function useDeleteSkill() {
|
||||
const queryClient = useQueryClient()
|
||||
const [deleteSkill, setDeleteSkill] = useState<SkillFileInfo | null>(null)
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: ({ name, scope, repoId }: { name: string; scope: SkillFileInfo['scope']; repoId?: number }) =>
|
||||
settingsApi.deleteSkill(name, scope, repoId),
|
||||
onSuccess: () => {
|
||||
invalidateSkillCaches(queryClient)
|
||||
toast.success('Skill deleted successfully')
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete skill')
|
||||
},
|
||||
})
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (!deleteSkill) return
|
||||
deleteMutation.mutate({
|
||||
name: deleteSkill.name,
|
||||
scope: deleteSkill.scope,
|
||||
repoId: deleteSkill.scope === 'project' ? deleteSkill.repoId : undefined,
|
||||
}, {
|
||||
onSettled: () => setDeleteSkill(null),
|
||||
})
|
||||
}
|
||||
|
||||
return { deleteSkill, setDeleteSkill, confirmDelete, isDeleting: deleteMutation.isPending }
|
||||
}
|
||||
@@ -28,6 +28,12 @@ export function invalidateConfigCaches(queryClient: QueryClient) {
|
||||
invalidateProviderCaches(queryClient)
|
||||
}
|
||||
|
||||
export function invalidateSkillCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', 'skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
}
|
||||
|
||||
export function invalidateSettingsCaches(queryClient: QueryClient, userId = 'default') {
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', userId] })
|
||||
invalidateConfigCaches(queryClient)
|
||||
|
||||
@@ -43,3 +43,33 @@ export interface SkillFileInfo {
|
||||
repoId?: number
|
||||
repoName?: string
|
||||
}
|
||||
|
||||
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,10 @@ export type {
|
||||
CreateSkillRequest,
|
||||
UpdateSkillRequest,
|
||||
SkillFileInfo,
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillUploadRequest,
|
||||
InstallSkillUploadManifestEntry,
|
||||
InstallSkillResponse,
|
||||
} from '../schemas/skills'
|
||||
export {
|
||||
SKILL_NAME_REGEX,
|
||||
@@ -135,4 +139,7 @@ export {
|
||||
SkillFrontmatterSchema,
|
||||
CreateSkillRequestSchema,
|
||||
UpdateSkillRequestSchema,
|
||||
InstallSkillFromGithubRequestSchema,
|
||||
InstallSkillUploadRequestSchema,
|
||||
InstallSkillUploadManifestEntrySchema,
|
||||
} from '../schemas/skills'
|
||||
Reference in new issue
Block a user