feat: refactor skill installer with extracted SkillLibraryList component

This commit is contained in:
Chris Scott committed 2026-06-17 18:00:21 -04:00
1 parent 50546af8cb
commit 75b5ca60b4
7 files changed
+293 -235

No files matched your search

@@ -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,15 @@
import { useState } from 'react'
import { useMutation, 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 type { SkillFileInfo } from '@opencode-manager/shared'
import { useMemo, useState, useEffect } from 'react'
import { toast } from 'sonner'
type RepoSkillsDialogBaseProps = {
open: boolean
@@ -27,36 +31,33 @@ export function RepoSkillsDialog({
directory,
onSkillLoaded,
}: RepoSkillsDialogProps) {
const queryClient = useQueryClient()
const [installDialogOpen, setInstallDialogOpen] = useState(false)
const [deleteSkill, setDeleteSkill] = useState<SkillFileInfo | null>(null)
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 deleteMutation = useMutation({
mutationFn: ({ name, scope, repoId }: { name: string; scope: SkillFileInfo['scope']; repoId?: number }) =>
settingsApi.deleteSkill(name, scope, repoId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: skillsQueryKey })
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
toast.success('Skill deleted successfully')
},
onError: (deleteError) => {
toast.error(deleteError instanceof Error ? deleteError.message : 'Failed to delete skill')
},
})
const handleLoad = (skill: SkillFileInfo) => {
loadSkill.mutate({ skillName: skill.name })
@@ -64,46 +65,75 @@ export function RepoSkillsDialog({
onOpenChange(false)
}
const confirmDelete = () => {
if (!deleteSkill) return
deleteMutation.mutate({
name: deleteSkill.name,
scope: deleteSkill.scope,
repoId: deleteSkill.scope === 'project' ? deleteSkill.repoId : undefined,
}, {
onSettled: () => setDeleteSkill(null),
})
}
const handleInstalled = () => {
queryClient.invalidateQueries({ queryKey: skillsQueryKey })
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
}
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/&lt;name&gt;/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={deleteMutation.isPending}
/>
</>
)
}
@@ -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>
)
}
@@ -141,7 +141,7 @@ export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillIns
<Input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://github.com/mattpocock/skills/tree/main/skills/productivity/teach"
placeholder="Paste a GitHub skill URL"
/>
</div>
</TabsContent>
@@ -81,9 +81,7 @@ describe('SkillsEditor', () => {
await user.click(screen.getByText('Install Skill'))
const urlInput = screen.getByPlaceholderText(
'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach'
)
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'))
@@ -144,9 +142,7 @@ describe('SkillsEditor', () => {
await user.click(screen.getByText('Install Skill'))
const urlInput = screen.getByPlaceholderText(
'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach'
)
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'))
@@ -178,11 +174,8 @@ describe('SkillsEditor', () => {
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 user.click(screen.getByLabelText('Actions for test-skill'))
await user.click(screen.getByText('Delete'))
await waitFor(() => {
expect(screen.getByText(/bundled files/)).toBeInTheDocument()
@@ -1,14 +1,14 @@
import { useState, useEffect } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X, Download } from 'lucide-react'
import { Plus, Trash2, 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 { SkillLibraryList } from '@/components/skills/SkillLibraryList'
import { settingsApi } from '@/api/settings'
import type { OpenCodeConfigInput, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared'
import { toast } from 'sonner'
@@ -200,17 +200,6 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
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">
@@ -240,65 +229,15 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
</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 or install 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>
)}
</>
<SkillLibraryList
isLoading={false}
data={managedSkills}
error={null}
primaryAction={{ label: 'Edit', onClick: handleEdit }}
rowActions={[{ label: 'Delete', onClick: handleDelete, destructive: true }]}
emptyTitle="No skills created"
emptyHint="Create or install your first skill to get started."
/>
)}
<div className="space-y-3">
@@ -403,4 +342,3 @@ export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEdi
</div>
)
}
@@ -0,0 +1,177 @@
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 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">
<Button type="button" variant={filter === 'all' ? 'secondary' : 'ghost'} size="sm" onClick={() => setFilter('all')}>
<span>All</span>
<span>{counts.all}</span>
</Button>
<Button type="button" variant={filter === 'project' ? 'secondary' : 'ghost'} size="sm" onClick={() => setFilter('project')}>
<span>Project</span>
<span>{counts.project}</span>
</Button>
<Button type="button" variant={filter === 'global' ? 'secondary' : 'ghost'} size="sm" onClick={() => setFilter('global')}>
<span>Global</span>
<span>{counts.global}</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 items-center gap-3 bg-card px-3 py-3 hover:bg-accent/50 ${primaryAction ? 'cursor-pointer' : ''}`}
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="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">
{getScopeLabel(skill)}
</Badge>
</div>
{skill.description && (
<p className="mt-1 truncate text-xs text-muted-foreground">{skill.description}</p>
)}
</div>
<div className="flex shrink-0 items-center gap-1" onClick={(event) => event.stopPropagation()}>
{primaryAction && (
<Button type="button" size="sm" onClick={() => primaryAction.onClick(skill)}>
{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>
)
}