mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: simplify SkillsEditor, extract SkillLibraryList
This commit is contained in:
1 parent
75b5ca60b4
commit
c0f0a22260
9 files changed
+205
-264
No files matched your search
@@ -44,6 +44,7 @@ import {
|
||||
installSkillFromGithubTree,
|
||||
installSkillFromUploadedFiles,
|
||||
} from '../services/skills'
|
||||
import { getRepoById } from '../db/queries'
|
||||
|
||||
function getOpenCodeInstallMethod(): string {
|
||||
const homePath = process.env.HOME || ''
|
||||
@@ -97,6 +98,37 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
|
||||
async function dispatchSkillReload(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
repoId: number,
|
||||
): Promise<void> {
|
||||
const repo = getRepoById(db, repoId)
|
||||
if (!repo) {
|
||||
logger.warn(`Cannot dispatch skill reload: repo ${repoId} not found`)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
}
|
||||
|
||||
try {
|
||||
await openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/skill',
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
logger.info(`Dispatched skill reload for project ${repo.fullPath}`)
|
||||
} catch (dispatchError) {
|
||||
logger.warn('Failed to dispatch skill reload:', dispatchError)
|
||||
}
|
||||
}
|
||||
|
||||
function didConfigFieldChange(
|
||||
previous: Record<string, unknown> | undefined,
|
||||
next: Record<string, unknown> | undefined,
|
||||
@@ -1169,11 +1201,15 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installSkillFromGithubTree(db, validated)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
if (validated.scope === 'project' && validated.repoId) {
|
||||
await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, validated.repoId)
|
||||
} else {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(result)
|
||||
@@ -1238,11 +1274,15 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installSkillFromUploadedFiles(db, uploadRequest, files)
|
||||
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
if (uploadRequest.scope === 'project' && uploadRequest.repoId) {
|
||||
await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, uploadRequest.repoId)
|
||||
} else {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('Restarted OpenCode server after skill install')
|
||||
} catch (restartError) {
|
||||
logger.warn('Failed to restart OpenCode server after skill install:', restartError)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(result)
|
||||
|
||||
@@ -462,18 +462,18 @@ function classifySkillLocation(
|
||||
if (location.startsWith(globalPrefix + path.sep)) {
|
||||
return { scope: 'global' }
|
||||
}
|
||||
if (customDirectory) {
|
||||
const projectPrefix = path.join(customDirectory, '.opencode', 'skills')
|
||||
if (location.startsWith(projectPrefix + path.sep)) {
|
||||
return { scope: 'project' }
|
||||
}
|
||||
}
|
||||
for (const repo of repos) {
|
||||
const projectPrefix = getProjectSkillsPath(repo)
|
||||
if (location.startsWith(projectPrefix + path.sep)) {
|
||||
return { scope: 'project', repo }
|
||||
}
|
||||
}
|
||||
if (customDirectory) {
|
||||
const projectPrefix = path.join(customDirectory, '.opencode', 'skills')
|
||||
if (location.startsWith(projectPrefix + path.sep)) {
|
||||
return { scope: 'project' }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -492,6 +492,52 @@ function toSkillFileInfo(
|
||||
}
|
||||
}
|
||||
|
||||
async function scanSkillRoot(root: string, scope: SkillScope, repo?: Repo): Promise<SkillFileInfo[]> {
|
||||
if (!await fileExists(root)) {
|
||||
return []
|
||||
}
|
||||
|
||||
let entries: Awaited<ReturnType<typeof listDirectory>>
|
||||
try {
|
||||
entries = await listDirectory(root)
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to scan skills at ${root}:`, error)
|
||||
return []
|
||||
}
|
||||
|
||||
const skills: SkillFileInfo[] = []
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory) continue
|
||||
|
||||
const skillPath = path.join(entry.path, 'SKILL.md')
|
||||
if (!await fileExists(skillPath)) continue
|
||||
|
||||
try {
|
||||
const content = await readFileContent(skillPath)
|
||||
const parsed = parseSkillMarkdown(content)
|
||||
skills.push({
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
body: parsed.body,
|
||||
scope,
|
||||
location: skillPath,
|
||||
repoId: scope === 'project' ? repo?.id : undefined,
|
||||
repoName: scope === 'project' ? repo?.localPath : undefined,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to read skill at ${skillPath}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
return skills
|
||||
}
|
||||
|
||||
function addSkill(result: SkillFileInfo[], seenLocations: Set<string>, skill: SkillFileInfo): void {
|
||||
if (seenLocations.has(skill.location)) return
|
||||
seenLocations.add(skill.location)
|
||||
result.push(skill)
|
||||
}
|
||||
|
||||
export async function listManagedSkills(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient,
|
||||
@@ -510,8 +556,16 @@ export async function listManagedSkills(
|
||||
if (seenLocations.has(skill.location)) continue
|
||||
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos, directory)
|
||||
if (!classification) continue
|
||||
seenLocations.add(skill.location)
|
||||
result.push(toSkillFileInfo(skill, classification))
|
||||
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
|
||||
}
|
||||
|
||||
const repo = allRepos.find(r => r.fullPath === directory)
|
||||
const fallbackSkills = [
|
||||
...await scanSkillRoot(globalPrefix, 'global'),
|
||||
...await scanSkillRoot(path.join(directory, '.opencode', 'skills'), 'project', repo),
|
||||
]
|
||||
for (const skill of fallbackSkills) {
|
||||
addSkill(result, seenLocations, skill)
|
||||
}
|
||||
} else {
|
||||
const targetRepos = repoId
|
||||
@@ -532,10 +586,19 @@ export async function listManagedSkills(
|
||||
if (seenLocations.has(skill.location)) continue
|
||||
const classification = classifySkillLocation(skill.location, globalPrefix, allRepos)
|
||||
if (!classification) continue
|
||||
seenLocations.add(skill.location)
|
||||
result.push(toSkillFileInfo(skill, classification))
|
||||
addSkill(result, seenLocations, toSkillFileInfo(skill, classification))
|
||||
}
|
||||
}
|
||||
|
||||
const fallbackSkills = [
|
||||
...await scanSkillRoot(globalPrefix, 'global'),
|
||||
...(await Promise.all(
|
||||
targetRepos.map(repo => scanSkillRoot(getProjectSkillsPath(repo), 'project', repo)),
|
||||
)).flat(),
|
||||
]
|
||||
for (const skill of fallbackSkills) {
|
||||
addSkill(result, seenLocations, skill)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, test, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { mkdtemp, rm, readFile } from 'fs/promises'
|
||||
import { mkdir, mkdtemp, rm, readFile, writeFile } from 'fs/promises'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@opencode-manager/shared/config/env')>()
|
||||
@@ -299,6 +300,43 @@ describe('SkillService', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('lists project skills from repo .opencode directory when OpenCode returns none', async () => {
|
||||
const { listManagedSkills } = await import('../../src/services/skills')
|
||||
const dbQueries = await import('../../src/db/queries')
|
||||
const projectPath = join(tempDir, 'project-zero')
|
||||
const skillDir = join(projectPath, '.opencode', 'skills', 'project-helper')
|
||||
const repo: Repo = {
|
||||
id: 123,
|
||||
localPath: 'Project Zero',
|
||||
fullPath: projectPath,
|
||||
sourcePath: projectPath,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
}
|
||||
|
||||
vi.mocked(dbQueries.listRepos).mockReturnValue([repo])
|
||||
await mkdir(skillDir, { recursive: true })
|
||||
await writeFile(
|
||||
join(skillDir, 'SKILL.md'),
|
||||
'---\nname: project-helper\ndescription: Helps project work\n---\nUse repo context.',
|
||||
)
|
||||
|
||||
const repoSkills = await listManagedSkills(mockDb, createMockClient([]), repo.id)
|
||||
const directorySkills = await listManagedSkills(mockDb, createMockClient([]), undefined, projectPath)
|
||||
|
||||
for (const skills of [repoSkills, directorySkills]) {
|
||||
expect(skills).toContainEqual(expect.objectContaining({
|
||||
name: 'project-helper',
|
||||
description: 'Helps project work',
|
||||
scope: 'project',
|
||||
repoId: repo.id,
|
||||
repoName: 'Project Zero',
|
||||
}))
|
||||
}
|
||||
})
|
||||
|
||||
test('preserves body content containing --- (horizontal rules)', async () => {
|
||||
const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills')
|
||||
const name = `hr-test-${Date.now()}`
|
||||
|
||||
@@ -50,7 +50,7 @@ export function RepoSkillsDialog({
|
||||
mutationFn: ({ name, scope, repoId }: { name: string; scope: SkillFileInfo['scope']; repoId?: number }) =>
|
||||
settingsApi.deleteSkill(name, scope, repoId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: skillsQueryKey })
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', 'skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
toast.success('Skill deleted successfully')
|
||||
},
|
||||
@@ -77,7 +77,7 @@ export function RepoSkillsDialog({
|
||||
}
|
||||
|
||||
const handleInstalled = () => {
|
||||
queryClient.invalidateQueries({ queryKey: skillsQueryKey })
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', 'skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
}
|
||||
|
||||
|
||||
@@ -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 />
|
||||
|
||||
@@ -1,104 +1,25 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { Plus, Trash2, ChevronDown, ChevronRight, Save, X, Download } from 'lucide-react'
|
||||
import { Plus, Download } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
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({
|
||||
@@ -172,149 +93,31 @@ 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)
|
||||
}
|
||||
|
||||
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>
|
||||
<div className="flex items-center gap-2">
|
||||
<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">
|
||||
<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>
|
||||
</div>
|
||||
|
||||
{collapsiblesOpen.managed && (
|
||||
<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">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCollapsiblesOpen(prev => ({ ...prev, config: !prev.config }))}
|
||||
className="h-auto p-0 font-medium"
|
||||
>
|
||||
{collapsiblesOpen.config ? <ChevronDown className="h-4 w-4 mr-1" /> : <ChevronRight className="h-4 w-4 mr-1" />}
|
||||
Advanced: Custom Paths & URLs
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{collapsiblesOpen.config && (
|
||||
<div className="space-y-4">
|
||||
<SkillPathEditor
|
||||
items={localPaths}
|
||||
onChange={handlePathsChange}
|
||||
onAddItem={() => {
|
||||
if (localPaths.length === 0 || localPaths[localPaths.length - 1] !== '') {
|
||||
handlePathsChange([...localPaths, ''])
|
||||
}
|
||||
}}
|
||||
onRemoveItem={(index) => {
|
||||
const updated = localPaths.filter((_, i) => i !== index)
|
||||
handlePathsChange(updated.length > 0 ? updated : [])
|
||||
}}
|
||||
label="Skill Paths"
|
||||
placeholder="e.g., .opencode/skills/"
|
||||
/>
|
||||
|
||||
<SkillPathEditor
|
||||
items={localUrls}
|
||||
onChange={handleUrlsChange}
|
||||
onAddItem={() => {
|
||||
if (localUrls.length === 0 || localUrls[localUrls.length - 1] !== '') {
|
||||
handleUrlsChange([...localUrls, ''])
|
||||
}
|
||||
}}
|
||||
onRemoveItem={(index) => {
|
||||
const updated = localUrls.filter((_, i) => i !== index)
|
||||
handleUrlsChange(updated.length > 0 ? updated : [])
|
||||
}}
|
||||
label="Skill URLs"
|
||||
placeholder="e.g., https://example.com/skills/"
|
||||
/>
|
||||
|
||||
{hasUnsavedChanges && (
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
className="flex-1"
|
||||
>
|
||||
<Save className="h-4 w-4 mr-1" />
|
||||
Save Changes
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCancel}
|
||||
className="flex-1"
|
||||
>
|
||||
<X className="h-4 w-4 mr-1" />
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<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}
|
||||
|
||||
@@ -40,6 +40,8 @@ const getScopeLabel = (skill: SkillFileInfo) => {
|
||||
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
|
||||
@@ -127,12 +129,15 @@ export function SkillLibraryList({
|
||||
<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' : ''}`}
|
||||
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">
|
||||
<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">
|
||||
<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>
|
||||
@@ -140,9 +145,9 @@ export function SkillLibraryList({
|
||||
<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()}>
|
||||
<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)}>
|
||||
<Button type="button" size="sm" onClick={() => primaryAction.onClick(skill)} className="flex-1 sm:flex-none">
|
||||
{primaryAction.label}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user