mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat: add skill installer with install/uninstall and settings UI (#277)
* feat: add skill installer with install/uninstall and settings UI * feat: refactor skill installer with extracted SkillLibraryList component * feat: simplify SkillsEditor, extract SkillLibraryList
This commit is contained in:
1 parent
3e617c2df8
commit
9cb2bb156b
19 files changed
+2341
-475
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: ['settings', 'skills'] })
|
||||
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: ['settings', 'skills'] })
|
||||
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/<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={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>
|
||||
)
|
||||
}
|
||||
@@ -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 { 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="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,102 +1,25 @@
|
||||
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 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 queryClient = useQueryClient()
|
||||
|
||||
const createMutation = useMutation({
|
||||
@@ -170,205 +93,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: handleDelete, 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={() => queryClient.invalidateQueries({ queryKey: ['managed-skills'] })}
|
||||
/>
|
||||
|
||||
<SkillDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
@@ -382,11 +138,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}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
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">
|
||||
<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 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>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user