feat: add skill installer with install/uninstall and settings UI

This commit is contained in:
Chris Scott committed 2026-06-17 17:41:12 -04:00
1 parent 3e617c2df8
commit 50546af8cb
12 files changed
+1889 -22

No files matched your search

+95
View File
@@ -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')
})
})
})
+39
View File
@@ -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 {
+5 -1
View File
@@ -15,10 +15,14 @@ import {
type CreateSkillRequest,
type UpdateSkillRequest,
type SkillScope,
type InstallSkillFromGithubRequest,
type InstallSkillUploadRequest,
type InstallSkillUploadManifestEntry,
type InstallSkillResponse,
} from '@opencode-manager/shared'
import type { NotificationPreferences } from '@opencode-manager/shared/types'
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope }
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillUploadRequest, InstallSkillUploadManifestEntry, InstallSkillResponse }
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
export interface CustomCommand {
@@ -0,0 +1,231 @@
import { useState, useEffect } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { settingsApi } from '@/api/settings'
import { listRepos } from '@/api/repos'
import { FetchError } from '@/api/fetchWrapper'
import { toast } from 'sonner'
import type { SkillScope } from '@opencode-manager/shared'
import type { Repo } from '@/api/types'
interface SkillInstallDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onInstalled: () => void
}
export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillInstallDialogProps) {
const [sourceType, setSourceType] = useState<'github' | 'upload'>('github')
const [url, setUrl] = useState('')
const [scope, setScope] = useState<SkillScope>('global')
const [selectedRepoId, setSelectedRepoId] = useState<number | undefined>(undefined)
const [files, setFiles] = useState<File[]>([])
const [overwrite, setOverwrite] = useState(false)
useEffect(() => {
setOverwrite(false)
}, [url, files, sourceType, scope, selectedRepoId])
const { data: repos = [] } = useQuery<Repo[]>({
queryKey: ['repos'],
queryFn: listRepos,
enabled: open,
staleTime: 5 * 60 * 1000,
})
const installMutation = useMutation({
mutationFn: () => {
if (sourceType === 'github') {
return settingsApi.installSkillFromGithub({
sourceType,
url,
scope,
repoId: scope === 'project' ? selectedRepoId : undefined,
overwrite: overwrite || undefined,
})
}
return settingsApi.installSkillFromUpload({
files,
scope,
repoId: scope === 'project' ? selectedRepoId : undefined,
overwrite: overwrite || undefined,
})
},
onSuccess: () => {
toast.success('Skill installed successfully')
setUrl('')
setScope('global')
setSelectedRepoId(undefined)
setFiles([])
setOverwrite(false)
onInstalled()
onOpenChange(false)
},
onError: (error) => {
if (error instanceof FetchError && error.statusCode === 409) {
setOverwrite(true)
return
}
toast.error(error instanceof Error ? error.message : 'Failed to install skill')
},
})
const handleSubmit = () => {
if (sourceType === 'github' && !url.trim()) {
toast.error('Please enter a GitHub URL')
return
}
if (sourceType === 'upload' && files.length === 0) {
toast.error('Please select at least one file')
return
}
if (scope === 'project' && !selectedRepoId) {
toast.error('Please select a repository')
return
}
installMutation.mutate()
}
const handleOpenChange = (isOpen: boolean) => {
if (!isOpen) {
setUrl('')
setScope('global')
setSelectedRepoId(undefined)
setFiles([])
setOverwrite(false)
}
onOpenChange(isOpen)
}
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFiles = e.target.files
if (selectedFiles) {
setFiles(Array.from(selectedFiles))
}
}
const selectedFileSummary = () => {
if (files.length === 0) return null
const relPath = files[0].webkitRelativePath || files[0].name
return (
<p className="text-sm text-muted-foreground">
{files.length} file{files.length > 1 ? 's' : ''} selected (first: {relPath})
</p>
)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent mobileFullscreen className="sm:max-w-lg sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
<DialogTitle>Install Skill</DialogTitle>
</DialogHeader>
<div className="flex-1 overflow-y-auto p-2 sm:p-4">
<div className="space-y-4">
<Tabs value={sourceType} onValueChange={(v) => setSourceType(v as 'github' | 'upload')}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="github">GitHub URL</TabsTrigger>
<TabsTrigger value="upload">Upload</TabsTrigger>
</TabsList>
<TabsContent value="github" className="mt-4 space-y-4">
<div className="space-y-2">
<Label>GitHub URL</Label>
<Input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://github.com/mattpocock/skills/tree/main/skills/productivity/teach"
/>
</div>
</TabsContent>
<TabsContent value="upload" className="mt-4 space-y-4">
<div className="space-y-2">
<Label>Skill File</Label>
<Input
type="file"
accept=".md,text/markdown"
onChange={handleFileChange}
/>
</div>
<div className="space-y-2">
<Label>Skill Folder</Label>
<Input
type="file"
accept=".md,text/markdown"
{...{ webkitdirectory: '', directory: '' } as React.InputHTMLAttributes<HTMLInputElement>}
onChange={handleFileChange}
/>
</div>
{selectedFileSummary()}
</TabsContent>
</Tabs>
<div className="space-y-2">
<Label>Scope</Label>
<Select value={scope} onValueChange={(v) => setScope(v as SkillScope)}>
<SelectTrigger>
<SelectValue placeholder="Select scope" />
</SelectTrigger>
<SelectContent>
<SelectItem value="global">Global</SelectItem>
<SelectItem value="project">Project</SelectItem>
</SelectContent>
</Select>
</div>
{scope === 'project' && (
<div className="space-y-2">
<Label>Repository</Label>
<Select
value={selectedRepoId?.toString()}
onValueChange={(value) => setSelectedRepoId(value ? parseInt(value, 10) : undefined)}
>
<SelectTrigger>
<SelectValue placeholder="Select repository" />
</SelectTrigger>
<SelectContent>
{repos.map((repo) => (
<SelectItem key={repo.id} value={repo.id.toString()}>
{repo.localPath}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{overwrite && (
<Alert>
<AlertDescription>
A skill with this name already exists. Install again to overwrite the managed skill directory.
</AlertDescription>
</Alert>
)}
</div>
</div>
<DialogFooter className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end pb-4 p-3">
<Button variant="outline" onClick={() => handleOpenChange(false)} className="flex-1 sm:flex-none">
Cancel
</Button>
<Button
onClick={handleSubmit}
disabled={installMutation.isPending}
className="flex-1 sm:flex-none"
>
{installMutation.isPending && 'Installing...'}
{!installMutation.isPending && (overwrite ? 'Overwrite and install' : 'Install')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,191 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { FetchError } from '@opencode-manager/shared'
import type { ReactNode } from 'react'
import { SkillsEditor } from './SkillsEditor'
import type { SkillFileInfo } from '@opencode-manager/shared'
const mocks = vi.hoisted(() => ({
installSkillFromGithub: vi.fn(),
installSkillFromUpload: vi.fn(),
deleteSkill: vi.fn().mockResolvedValue({ success: true }),
listManagedSkills: vi.fn(),
listRepos: vi.fn().mockResolvedValue([]),
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
vi.mock('@/api/settings', () => ({
settingsApi: {
installSkillFromGithub: mocks.installSkillFromGithub,
installSkillFromUpload: mocks.installSkillFromUpload,
deleteSkill: mocks.deleteSkill,
listManagedSkills: mocks.listManagedSkills,
},
}))
vi.mock('@/api/repos', () => ({
listRepos: mocks.listRepos,
}))
vi.mock('sonner', () => ({
toast: mocks.toast,
}))
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
const mockSkill: SkillFileInfo = {
name: 'test-skill',
description: 'A test skill',
body: '# Test Skill\nSome content',
location: '/home/user/.config/opencode/skills/test-skill/SKILL.md',
scope: 'global',
}
describe('SkillsEditor', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('shows install skill button beside create skill', () => {
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
expect(screen.getByText('Install Skill')).toBeInTheDocument()
expect(screen.getByText('Create Skill')).toBeInTheDocument()
})
it('installs from GitHub URL', async () => {
mocks.installSkillFromGithub.mockResolvedValue({
skill: { name: 'teach', scope: 'global' },
overwritten: false,
sourceType: 'github',
filesInstalled: ['SKILL.md'],
})
const user = userEvent.setup()
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
await user.click(screen.getByText('Install Skill'))
const urlInput = screen.getByPlaceholderText(
'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach'
)
await user.type(urlInput, 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
await user.click(screen.getByText('Install'))
await waitFor(() => {
expect(mocks.installSkillFromGithub).toHaveBeenCalledWith({
sourceType: 'github',
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
scope: 'global',
})
})
})
it('uploads a single SKILL.md', async () => {
mocks.installSkillFromUpload.mockResolvedValue({
skill: { name: 'teach', scope: 'global' },
overwritten: false,
sourceType: 'upload',
filesInstalled: ['SKILL.md'],
})
const user = userEvent.setup()
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
await user.click(screen.getByText('Install Skill'))
const uploadTab = screen.getByText('Upload')
await user.click(uploadTab)
const file = new File(['# Test Skill'], 'SKILL.md', { type: 'text/markdown' })
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
await user.upload(fileInput, file)
await user.click(screen.getByText('Install'))
await waitFor(() => {
expect(mocks.installSkillFromUpload).toHaveBeenCalledWith({
files: expect.arrayContaining([expect.any(File)]),
scope: 'global',
})
})
})
it('prompts overwrite after 409 conflict', async () => {
mocks.installSkillFromGithub
.mockRejectedValueOnce(
new FetchError('Skill "teach" already exists in global scope', 409)
)
.mockResolvedValueOnce({
skill: { name: 'teach', scope: 'global' },
overwritten: true,
sourceType: 'github',
filesInstalled: ['SKILL.md'],
})
const user = userEvent.setup()
render(<SkillsEditor managedSkills={[]} />, { wrapper: createWrapper() })
await user.click(screen.getByText('Install Skill'))
const urlInput = screen.getByPlaceholderText(
'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach'
)
await user.type(urlInput, 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach')
await user.click(screen.getByText('Install'))
await waitFor(() => {
expect(
screen.getByText(
'A skill with this name already exists. Install again to overwrite the managed skill directory.'
)
).toBeInTheDocument()
})
await user.click(screen.getByText('Overwrite and install'))
await waitFor(() => {
expect(mocks.installSkillFromGithub).toHaveBeenCalledTimes(2)
expect(mocks.installSkillFromGithub).toHaveBeenLastCalledWith({
sourceType: 'github',
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
scope: 'global',
overwrite: true,
})
})
})
it('delete dialog mentions bundled files', async () => {
const user = userEvent.setup()
render(<SkillsEditor managedSkills={[mockSkill]} />, {
wrapper: createWrapper(),
})
const skillHeading = screen.getByText('test-skill')
const card = skillHeading.closest('[class*="card"]') || skillHeading.closest('[class*="border"]') || skillHeading.parentElement!.parentElement!
const deleteButtons = card.querySelectorAll('button')
const deleteButton = deleteButtons[deleteButtons.length - 1]
await user.click(deleteButton)
await waitFor(() => {
expect(screen.getByText(/bundled files/)).toBeInTheDocument()
})
})
})
@@ -1,12 +1,13 @@
import { useState, useEffect } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X } from 'lucide-react'
import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X, Download } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { SkillDialog } from './SkillDialog'
import { SkillInstallDialog } from './SkillInstallDialog'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { settingsApi } from '@/api/settings'
import type { OpenCodeConfigInput, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
@@ -80,6 +81,7 @@ function SkillPathEditor({ items, onChange, onAddItem, onRemoveItem, label, plac
export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEditorProps) {
const [dialogOpen, setDialogOpen] = useState(false)
const [installDialogOpen, setInstallDialogOpen] = useState(false)
const [editingSkill, setEditingSkill] = useState<SkillFileInfo | null>(null)
const [collapsiblesOpen, setCollapsiblesOpen] = useState({
managed: true,
@@ -225,10 +227,16 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
<Badge variant="secondary" className="ml-2">{managedSkills.length}</Badge>
)}
</Button>
<Button type="button" onClick={handleCreate} size="sm">
<Plus className="h-4 w-4 mr-1" />
Create Skill
</Button>
<div className="flex items-center gap-2">
<Button type="button" variant="outline" onClick={() => setInstallDialogOpen(true)} size="sm">
<Download className="h-4 w-4 mr-1" />
Install Skill
</Button>
<Button type="button" onClick={handleCreate} size="sm">
<Plus className="h-4 w-4 mr-1" />
Create Skill
</Button>
</div>
</div>
{collapsiblesOpen.managed && (
@@ -240,7 +248,7 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
<p className="text-sm font-medium">No skills created</p>
</div>
<p className="text-sm text-muted-foreground">
Create your first skill to get started.
Create or install your first skill to get started.
</p>
</CardContent>
</Card>
@@ -369,6 +377,12 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
)}
</div>
<SkillInstallDialog
open={installDialogOpen}
onOpenChange={setInstallDialogOpen}
onInstalled={() => queryClient.invalidateQueries({ queryKey: ['managed-skills'] })}
/>
<SkillDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
@@ -382,7 +396,7 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
onConfirm={confirmDelete}
onCancel={() => setDeleteSkill(null)}
title="Delete Skill"
description="Are you sure you want to delete this skill? This action cannot be undone."
description="Delete this managed skill directory and bundled files? This action cannot be undone."
itemName={deleteSkill?.name}
isDeleting={deleteMutation.isPending}
/>