Add skills editor UI, backend service, shared schema, and promote unused-vars to error

This commit is contained in:
Chris Scott committed 2026-03-22 11:37:02 -04:00
1 parent 7d65e20c55
commit 4bd0940ab9
7 files changed
+1394 -2

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ export default defineConfig([
rules: {
'no-console': ['warn', { allow: ['warn', 'error'] }],
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/no-unused-vars': 'error',
'no-useless-escape': 'warn',
},
},
+369
View File
@@ -0,0 +1,369 @@
import os from 'os'
import path from 'path'
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 { getRepoById } from '../db/queries'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations'
import { logger } from '../utils/logger'
const GLOBAL_SKILLS_PATH = path.join(os.homedir(), '.config', 'opencode', 'skills')
interface ParsedSkillFile {
frontmatter: {
name: string
description: string
license?: string
compatibility?: string
metadata?: Record<string, string>
}
body: string
}
function parseSkillFile(content: string): ParsedSkillFile {
const firstDelim = content.indexOf('---')
if (firstDelim === -1) {
throw new Error('Invalid SKILL.md format: missing frontmatter delimiters')
}
const afterFirst = firstDelim + 3
const secondDelim = content.indexOf('\n---', afterFirst)
if (secondDelim === -1) {
throw new Error('Invalid SKILL.md format: missing closing frontmatter delimiter')
}
const frontmatterStr = content.substring(afterFirst, secondDelim).trim()
const afterSecond = secondDelim + 4
const body = content.substring(afterSecond).trim()
const frontmatter: Record<string, unknown> = {}
const lines = frontmatterStr.split('\n')
let currentKey: string | null = null
const metadataObj: Record<string, string> = {}
for (const line of lines) {
const trimmedLine = line.trim()
if (!trimmedLine) continue
const kvMatch = trimmedLine.match(/^([^:]+):\s*(.*)$/)
if (kvMatch) {
const key = kvMatch[1]?.trim()
const value = kvMatch[2]?.trim()
if (key === 'metadata') {
currentKey = 'metadata'
continue
}
if (key && value !== undefined) {
frontmatter[key] = value
currentKey = null
}
} else if (currentKey === 'metadata' && trimmedLine) {
const metaMatch = trimmedLine.match(/^\s*([^:]+):\s*(.*)$/)
if (metaMatch) {
const metaKey = metaMatch[1]?.trim()
const metaValue = metaMatch[2]?.trim()
if (metaKey && metaValue !== undefined) {
metadataObj[metaKey] = metaValue
}
}
}
}
if (Object.keys(metadataObj).length > 0) {
frontmatter.metadata = metadataObj
}
return {
frontmatter: {
name: frontmatter.name as string || '',
description: frontmatter.description as string || '',
license: frontmatter.license as string | undefined,
compatibility: frontmatter.compatibility as string | undefined,
metadata: frontmatter.metadata as Record<string, string> | undefined,
},
body,
}
}
function generateSkillFrontmatter(
name: string,
description: string,
license?: string,
compatibility?: string,
metadata?: Record<string, string>
): string {
let frontmatter = `name: ${name}\ndescription: ${description}`
if (license) {
frontmatter += `\nlicense: ${license}`
}
if (compatibility) {
frontmatter += `\ncompatibility: ${compatibility}`
}
if (metadata && Object.keys(metadata).length > 0) {
frontmatter += '\nmetadata:'
for (const [key, value] of Object.entries(metadata)) {
frontmatter += `\n ${key}: ${value}`
}
}
return frontmatter
}
function getSkillDirectoryPath(db: Database, scope: SkillScope, repoId?: number): string {
if (scope === 'global') {
return GLOBAL_SKILLS_PATH
}
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(repo.fullPath, '.opencode', 'skills')
}
function validateSkillName(name: string): void {
if (!SKILL_NAME_REGEX.test(name)) {
throw new Error('Invalid skill name. Must be lowercase alphanumeric with hyphens only.')
}
}
function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string {
validateSkillName(name)
const skillsDir = getSkillDirectoryPath(db, scope, repoId)
return path.join(skillsDir, name, 'SKILL.md')
}
export async function listManagedSkills(db: Database, repoId?: number): Promise<SkillFileInfo[]> {
const skills: SkillFileInfo[] = []
const globalSkillsDir = GLOBAL_SKILLS_PATH
const globalSkillsExist = await fileExists(globalSkillsDir)
if (globalSkillsExist) {
const entries = await listDirectory(globalSkillsDir)
for (const entry of entries) {
if (entry.isDirectory) {
const skillPath = path.join(entry.path, 'SKILL.md')
const skillExists = await fileExists(skillPath)
if (skillExists) {
const skillInfo = await readSkillFile(db, 'global', entry.name)
if (skillInfo) {
skills.push(skillInfo)
}
}
}
}
}
if (repoId) {
const repo = getRepoById(db, repoId)
if (repo) {
const projectSkillsDir = path.join(repo.fullPath, '.opencode', 'skills')
const projectSkillsExist = await fileExists(projectSkillsDir)
if (projectSkillsExist) {
const entries = await listDirectory(projectSkillsDir)
for (const entry of entries) {
if (entry.isDirectory) {
const skillPath = path.join(entry.path, 'SKILL.md')
const skillExists = await fileExists(skillPath)
if (skillExists) {
const skillInfo = await readSkillFile(db, 'project', entry.name, repoId)
if (skillInfo) {
skills.push(skillInfo)
}
}
}
}
}
}
}
return skills
}
export async function getSkill(
db: Database,
name: string,
scope: SkillScope,
repoId?: number
): Promise<SkillFileInfo> {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (!exists) {
throw new Error(`Skill "${name}" not found in ${scope} scope`)
}
const skillInfo = await readSkillFile(db, scope, name, repoId)
if (!skillInfo) {
throw new Error(`Failed to read skill "${name}"`)
}
return skillInfo
}
async function readSkillFile(
db: Database,
scope: SkillScope,
name: string,
repoId?: number
): Promise<SkillFileInfo | null> {
try {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const content = await readFileContent(skillPath)
const parsed = parseSkillFile(content)
const repo = repoId ? getRepoById(db, repoId) : null
return {
name: parsed.frontmatter.name,
description: parsed.frontmatter.description,
body: parsed.body,
license: parsed.frontmatter.license,
compatibility: parsed.frontmatter.compatibility,
metadata: parsed.frontmatter.metadata,
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
repoName: repo?.localPath,
}
} catch (error) {
logger.error(`Failed to read skill ${name}:`, error)
return null
}
}
export async function createSkill(
db: Database,
input: CreateSkillRequest
): Promise<SkillFileInfo> {
const { name, description, body, license, compatibility, metadata, scope, repoId } = input
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (exists) {
throw new Error(`Skill "${name}" already exists in ${scope} scope`)
}
const skillDir = path.dirname(skillPath)
await ensureDirectoryExists(skillDir)
const frontmatter = generateSkillFrontmatter(
name,
description,
license,
compatibility,
metadata
)
const content = `---\n${frontmatter}\n---\n${body}`
await writeFileContent(skillPath, content)
logger.info(`Created skill "${name}" at ${skillPath}`)
const repo = repoId ? getRepoById(db, repoId) : null
return {
name,
description,
body,
license,
compatibility,
metadata,
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
repoName: repo?.localPath,
}
}
export async function updateSkill(
db: Database,
name: string,
scope: SkillScope,
input: UpdateSkillRequest,
repoId?: number
): Promise<SkillFileInfo> {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (!exists) {
throw new Error(`Skill "${name}" not found in ${scope} scope`)
}
const existingContent = await readFileContent(skillPath)
const parsed = parseSkillFile(existingContent)
const resolveField = <T>(field: T | null | undefined, existing: T | undefined): T | undefined => {
if (field === null) return undefined
if (field === undefined) return existing
return field
}
const updatedFrontmatter = {
name: parsed.frontmatter.name,
description: input.description ?? parsed.frontmatter.description,
license: resolveField(input.license, parsed.frontmatter.license),
compatibility: resolveField(input.compatibility, parsed.frontmatter.compatibility),
metadata: resolveField(input.metadata, parsed.frontmatter.metadata),
}
const updatedBody = input.body ?? parsed.body
const frontmatter = generateSkillFrontmatter(
updatedFrontmatter.name,
updatedFrontmatter.description,
updatedFrontmatter.license,
updatedFrontmatter.compatibility,
updatedFrontmatter.metadata
)
const content = `---\n${frontmatter}\n---\n${updatedBody}`
await writeFileContent(skillPath, content)
logger.info(`Updated skill "${name}" at ${skillPath}`)
const repo = repoId ? getRepoById(db, repoId) : null
return {
name: updatedFrontmatter.name,
description: updatedFrontmatter.description,
body: updatedBody,
license: updatedFrontmatter.license,
compatibility: updatedFrontmatter.compatibility,
metadata: updatedFrontmatter.metadata,
scope,
location: skillPath,
repoId: scope === 'project' ? repoId : undefined,
repoName: repo?.localPath,
}
}
export async function deleteSkill(
db: Database,
name: string,
scope: SkillScope,
repoId?: number
): Promise<void> {
const skillPath = getSkillFilePath(db, scope, name, repoId)
const exists = await fileExists(skillPath)
if (!exists) {
throw new Error(`Skill "${name}" not found in ${scope} scope`)
}
const skillDir = path.dirname(skillPath)
await deletePath(skillDir)
logger.info(`Deleted skill "${name}" from ${skillDir}`)
}
+277
View File
@@ -0,0 +1,277 @@
import { describe, expect, test, beforeEach, afterEach } from 'vitest'
import { join } from 'path'
import { tmpdir } from 'os'
import { mkdtemp, rm } from 'fs/promises'
describe('SkillService', () => {
let tempDir: string
let originalHome: string
beforeEach(async () => {
tempDir = await mkdtemp(join(tmpdir(), 'skills-test-'))
originalHome = process.env.HOME || ''
process.env.HOME = tempDir
})
afterEach(async () => {
await rm(tempDir, { recursive: true, force: true })
if (originalHome) {
process.env.HOME = originalHome
}
})
const mockDb = null as unknown as any
test('generates correct YAML frontmatter format', async () => {
const { createSkill } = await import('../../src/services/skills')
const input = {
name: `test-skill-${Date.now()}`,
description: 'A test skill',
body: '## Test Body\n\nContent here',
scope: 'global' as const,
license: 'MIT',
compatibility: 'opencode',
metadata: { key: 'value' },
}
const result = await createSkill(mockDb, input)
expect(result.name).toBe(input.name)
expect(result.description).toBe('A test skill')
expect(result.body).toBe('## Test Body\n\nContent here')
expect(result.license).toBe('MIT')
expect(result.compatibility).toBe('opencode')
expect(result.metadata).toEqual({ key: 'value' })
})
test('parses frontmatter and body correctly', async () => {
const { createSkill, getSkill } = await import('../../src/services/skills')
const name = `parse-test-${Date.now()}`
const input = {
name,
description: 'Test description',
body: '## Body\n\nSome content',
scope: 'global' as const,
}
await createSkill(mockDb, input)
const skill = await getSkill(mockDb, name, 'global')
expect(skill.name).toBe(name)
expect(skill.description).toBe('Test description')
expect(skill.body).toBe('## Body\n\nSome content')
})
test('accepts valid skill names', async () => {
const { createSkill } = await import('../../src/services/skills')
const validNames = ['my-skill', 'a', 'skill-1-2', 'test123', 'a-b-c']
for (const name of validNames) {
const input = {
name: `${name}-${Date.now()}`,
description: 'Test',
body: 'Body',
scope: 'global' as const,
}
await expect(createSkill(mockDb, input)).resolves.toBeDefined()
}
})
test('rejects invalid skill names', async () => {
const { createSkill } = await import('../../src/services/skills')
const invalidNames = ['My-Skill', '--bad', 'bad-', 'has spaces', 'has_underscore', 'has.dot', 'UPPERCASE']
for (const name of invalidNames) {
const input = {
name: `${name}-${Date.now()}`,
description: 'Test',
body: 'Body',
scope: 'global' as const,
}
await expect(createSkill(mockDb, input)).rejects.toThrow('Invalid skill name')
}
})
test('creates skill file at correct path', async () => {
const { createSkill } = await import('../../src/services/skills')
const name = `new-skill-${Date.now()}`
const input = {
name,
description: 'A new skill',
body: 'Skill body content',
scope: 'global' as const,
}
const result = await createSkill(mockDb, input)
expect(result.name).toBe(name)
expect(result.scope).toBe('global')
expect(result.location).toContain(`${name}/SKILL.md`)
})
test('throws error on duplicate name', async () => {
const { createSkill } = await import('../../src/services/skills')
const name = `duplicate-${Date.now()}`
const input = {
name,
description: 'First',
body: 'Body',
scope: 'global' as const,
}
await createSkill(mockDb, input)
const duplicate = {
name,
description: 'Second',
body: 'Body',
scope: 'global' as const,
}
await expect(createSkill(mockDb, duplicate)).rejects.toThrow('already exists')
})
test('reads skill correctly', async () => {
const { createSkill, getSkill } = await import('../../src/services/skills')
const name = `read-test-${Date.now()}`
const input = {
name,
description: 'Read test description',
body: 'Read test body',
scope: 'global' as const,
license: 'Apache-2.0',
}
await createSkill(mockDb, input)
const skill = await getSkill(mockDb, name, 'global')
expect(skill.name).toBe(name)
expect(skill.description).toBe('Read test description')
expect(skill.body).toBe('Read test body')
expect(skill.license).toBe('Apache-2.0')
})
test('throws error for missing skill', async () => {
const { getSkill } = await import('../../src/services/skills')
await expect(getSkill(mockDb, 'nonexistent', 'global')).rejects.toThrow('not found')
})
test('updates only changed fields', async () => {
const { createSkill, updateSkill } = await import('../../src/services/skills')
const name = `update-test-${Date.now()}`
const input = {
name,
description: 'Original description',
body: 'Original body',
scope: 'global' as const,
license: 'MIT',
}
await createSkill(mockDb, input)
const updated = await updateSkill(
mockDb,
name,
'global',
{ description: 'Updated description' },
undefined
)
expect(updated.description).toBe('Updated description')
expect(updated.body).toBe('Original body')
expect(updated.license).toBe('MIT')
})
test('throws error for missing skill on update', async () => {
const { updateSkill } = await import('../../src/services/skills')
await expect(
updateSkill(mockDb, 'nonexistent', 'global', { description: 'Test' }, undefined)
).rejects.toThrow('not found')
})
test('deletes skill directory', async () => {
const { createSkill, deleteSkill, getSkill } = await import('../../src/services/skills')
const name = `delete-test-${Date.now()}`
const input = {
name,
description: 'To be deleted',
body: 'Body',
scope: 'global' as const,
}
await createSkill(mockDb, input)
await deleteSkill(mockDb, name, 'global')
await expect(getSkill(mockDb, name, 'global')).rejects.toThrow('not found')
})
test('throws error for missing skill on delete', async () => {
const { deleteSkill } = await import('../../src/services/skills')
await expect(deleteSkill(mockDb, 'nonexistent', 'global')).rejects.toThrow('not found')
})
test('lists global skills', async () => {
const { createSkill, listManagedSkills, deleteSkill } = await import('../../src/services/skills')
const name1 = `list-test-1-${Date.now()}`
const name2 = `list-test-2-${Date.now()}`
try {
await createSkill(mockDb, {
name: name1,
description: 'Test 1',
body: 'Body',
scope: 'global' as const,
})
await createSkill(mockDb, {
name: name2,
description: 'Test 2',
body: 'Body',
scope: 'global' as const,
})
const skills = await listManagedSkills(mockDb)
const createdSkills = skills.filter(s => [name1, name2].includes(s.name))
expect(createdSkills.length).toBe(2)
expect(createdSkills.map(s => s.name)).toEqual(
expect.arrayContaining([name1, name2])
)
} finally {
await deleteSkill(mockDb, name1, 'global').catch(() => {})
await deleteSkill(mockDb, name2, 'global').catch(() => {})
}
})
test('should handle body content containing --- (horizontal rules)', async () => {
const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills')
const name = `hr-test-${Date.now()}`
const bodyWithHR = `This is the skill body.
---
This is after a horizontal rule.
---
Another section.`
await createSkill(mockDb, {
name,
description: 'Test horizontal rules in body',
body: bodyWithHR,
scope: 'global' as const,
})
const skill = await getSkill(mockDb, name, 'global')
expect(skill).not.toBeNull()
expect(skill!.body).toContain('---')
expect(skill!.body).toContain('This is after a horizontal rule.')
expect(skill!.body).toContain('Another section.')
await deleteSkill(mockDb, name, 'global')
})
})
+1 -1
View File
@@ -55,7 +55,7 @@ export default defineConfig([
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-unused-vars': ['warn', {
'@typescript-eslint/no-unused-vars': ['error', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_'
}],
@@ -0,0 +1,288 @@
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import type { SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
import type { Repo } from '@/api/types'
import { listRepos } from '@/api/repos'
import { useQuery } from '@tanstack/react-query'
const skillFormSchema = z.object({
name: z.string()
.min(1, 'Skill name is required')
.max(64, 'Skill name must be 64 characters or less')
.regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Must be lowercase letters, numbers, and hyphens only'),
description: z.string().min(1, 'Description is required').max(1024, 'Description must be 1024 characters or less'),
body: z.string().min(1, 'Skill body is required'),
scope: z.enum(['global', 'project']),
license: z.string().optional(),
compatibility: z.string().optional(),
metadata: z.record(z.string(), z.string()).optional(),
})
type SkillFormValues = z.infer<typeof skillFormSchema>
interface SkillDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSubmit: (data: CreateSkillRequest | (UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number })) => void
editingSkill?: SkillFileInfo | null
}
export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: SkillDialogProps) {
const { data: repos = [] } = useQuery<Repo[]>({
queryKey: ['repos'],
queryFn: listRepos,
enabled: open,
staleTime: 5 * 60 * 1000,
})
const [selectedRepoId, setSelectedRepoId] = useState<number | undefined>(undefined)
const getDefaultValues = (skill?: SkillFileInfo | null): SkillFormValues => {
return {
name: skill?.name || '',
description: skill?.description || '',
body: skill?.body || '',
scope: skill?.scope || 'global',
license: skill?.license || '',
compatibility: skill?.compatibility || '',
metadata: skill?.metadata || {},
}
}
const form = useForm<SkillFormValues>({
resolver: zodResolver(skillFormSchema),
defaultValues: getDefaultValues(editingSkill)
})
useEffect(() => {
if (open) {
form.reset(getDefaultValues(editingSkill))
if (editingSkill?.repoId) {
setSelectedRepoId(editingSkill.repoId)
}
}
}, [open, editingSkill, form])
const handleSubmit = (values: SkillFormValues) => {
if (!editingSkill && values.scope === 'project' && !selectedRepoId) {
form.setError('scope', { message: 'Please select a repository for project-scoped skills' })
return
}
if (editingSkill) {
onSubmit({
name: editingSkill.name,
scope: editingSkill.scope,
repoId: editingSkill.scope === 'project' ? editingSkill.repoId : undefined,
description: values.description,
body: values.body,
license: values.license || undefined,
compatibility: values.compatibility || undefined,
metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined,
})
} else {
onSubmit({
name: values.name,
description: values.description,
body: values.body,
scope: values.scope,
repoId: values.scope === 'project' ? selectedRepoId : undefined,
license: values.license || undefined,
compatibility: values.compatibility || undefined,
metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined,
})
}
form.reset()
onOpenChange(false)
}
const handleOpenChange = (isOpen: boolean) => {
if (!isOpen) {
form.reset()
}
onOpenChange(isOpen)
}
const scope = form.watch('scope')
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6">
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
<DialogTitle>{editingSkill ? 'Edit Skill' : 'Create Skill'}</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-y-auto p-2 sm:p-4">
<Form {...form}>
<div className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Skill Name</FormLabel>
<FormControl>
<Input
{...field}
placeholder="my-skill"
disabled={!!editingSkill}
className={editingSkill ? 'bg-muted' : ''}
/>
</FormControl>
<FormDescription>
Use lowercase letters, numbers, and hyphens only
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
{...field}
placeholder="Brief description of what this skill does"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="body"
render={({ field }) => (
<FormItem>
<FormLabel>Skill Body</FormLabel>
<FormControl>
<Textarea
{...field}
placeholder="## What I do&#10;&#10;- Step 1&#10;- Step 2&#10;&#10;## When to use me&#10;&#10;Use this when..."
rows={10}
className="font-mono md:text-sm"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="scope"
render={({ field }) => (
<FormItem>
<FormLabel>Scope</FormLabel>
<Select onValueChange={field.onChange} value={field.value} disabled={!!editingSkill}>
<FormControl>
<SelectTrigger className={editingSkill ? 'bg-muted' : ''}>
<SelectValue placeholder="Select scope" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="global">Global</SelectItem>
<SelectItem value="project">Project</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{scope === 'project' && (
<FormField
control={form.control}
name="metadata"
render={() => (
<FormItem>
<FormLabel>Repository</FormLabel>
<FormControl>
<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>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
<FormField
control={form.control}
name="license"
render={({ field }) => (
<FormItem>
<FormLabel>License (Optional)</FormLabel>
<FormControl>
<Input
{...field}
placeholder="MIT"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="compatibility"
render={({ field }) => (
<FormItem>
<FormLabel>Compatibility (Optional)</FormLabel>
<FormControl>
<Input
{...field}
placeholder="opencode"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</Form>
</div>
<DialogFooter className="p-3 sm:p-4 border-t gap-2 pb-4">
<Button variant="outline" onClick={() => handleOpenChange(false)} className="flex-1 sm:flex-none">
Cancel
</Button>
<Button
onClick={() => form.handleSubmit(handleSubmit)()}
disabled={!form.formState.isValid}
className="flex-1 sm:flex-none"
>
{editingSkill ? 'Update' : 'Create'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,401 @@
import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Trash2, Loader2, Pencil, ChevronDown, ChevronRight, Save, X } 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 { DeleteDialog } from '@/components/ui/delete-dialog'
import { settingsApi } from '@/api/settings'
import type { OpenCodeConfigInput, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
import { toast } from 'sonner'
interface SkillsEditorProps {
skills?: OpenCodeConfigInput['skills']
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, onChange }: SkillsEditorProps) {
const [dialogOpen, setDialogOpen] = 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 queryClient = useQueryClient()
const { data: managedSkills = [], isLoading: isLoadingManaged } = useQuery({
queryKey: ['managed-skills'],
queryFn: () => settingsApi.listManagedSkills(),
staleTime: 5 * 60 * 1000,
})
const createMutation = useMutation({
mutationFn: (data: CreateSkillRequest) => settingsApi.createSkill(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
toast.success('Skill created successfully')
setDialogOpen(false)
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : 'Failed to create skill')
},
})
const updateMutation = useMutation({
mutationFn: ({ name, scope, repoId, ...data }: UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number }) =>
settingsApi.updateSkill(name, scope, data, repoId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
toast.success('Skill updated successfully')
setDialogOpen(false)
setEditingSkill(null)
},
onError: (error) => {
toast.error(error instanceof Error ? error.message : 'Failed to update skill')
},
})
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)
}
const handleSubmit = (data: CreateSkillRequest | (UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number })) => {
if ('name' in data && editingSkill) {
updateMutation.mutate(data as UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number })
} else {
createMutation.mutate(data as CreateSkillRequest)
}
}
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 && (
<>
{isLoadingManaged ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : 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
</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>
<SkillDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
onSubmit={handleSubmit}
editingSkill={editingSkill}
/>
<DeleteDialog
open={deleteSkill !== null}
onOpenChange={(open) => !open && setDeleteSkill(null)}
onConfirm={confirmDelete}
onCancel={() => setDeleteSkill(null)}
title="Delete Skill"
description="Are you sure you want to delete this skill? This action cannot be undone."
itemName={deleteSkill?.name}
isDeleting={deleteMutation.isPending}
/>
</div>
)
}
+57
View File
@@ -0,0 +1,57 @@
import { z } from 'zod'
export const SKILL_NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/
export const SkillNameSchema = z.string()
.min(1)
.max(64)
.regex(SKILL_NAME_REGEX, 'Skill name must be lowercase alphanumeric with hyphens only (e.g., my-skill)')
export const SkillScopeSchema = z.enum(['global', 'project'])
export type SkillScope = z.infer<typeof SkillScopeSchema>
export const SkillFrontmatterSchema = z.object({
name: SkillNameSchema,
description: z.string().min(1).max(1024),
license: z.string().optional(),
compatibility: z.string().optional(),
metadata: z.record(z.string(), z.string()).optional(),
})
export type SkillFrontmatter = z.infer<typeof SkillFrontmatterSchema>
export const CreateSkillRequestSchema = z.object({
name: SkillNameSchema,
description: z.string().min(1).max(1024),
body: z.string(),
license: z.string().optional(),
compatibility: z.string().optional(),
metadata: z.record(z.string(), z.string()).optional(),
scope: SkillScopeSchema,
repoId: z.number().optional(),
})
export type CreateSkillRequest = z.infer<typeof CreateSkillRequestSchema>
export const UpdateSkillRequestSchema = z.object({
description: z.string().min(1).max(1024).optional(),
body: z.string().optional(),
license: z.string().nullable().optional(),
compatibility: z.string().nullable().optional(),
metadata: z.record(z.string(), z.string()).nullable().optional(),
})
export type UpdateSkillRequest = z.infer<typeof UpdateSkillRequestSchema>
export interface SkillFileInfo {
name: string
description: string
body: string
license?: string
compatibility?: string
metadata?: Record<string, string>
scope: SkillScope
location: string
repoId?: number
repoName?: string
}