From c0f0a2226080ccf0deacef29c1f74bcc5f4eb49a Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 17 Jun 2026 22:16:42 -0400 Subject: [PATCH] feat: simplify SkillsEditor, extract SkillLibraryList --- backend/src/routes/settings.ts | 60 ++++- backend/src/services/skills.ts | 83 ++++++- backend/test/services/skills.test.ts | 40 ++- .../src/components/repo/RepoSkillsDialog.tsx | 4 +- .../settings/OpenCodeConfigManager.tsx | 22 +- .../settings/OpenCodeModelDialog.tsx | 2 + .../components/settings/SettingsDialog.tsx | 6 +- .../src/components/settings/SkillsEditor.tsx | 233 ++---------------- .../components/skills/SkillLibraryList.tsx | 19 +- 9 files changed, 205 insertions(+), 264 deletions(-) diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index cd7d7461..7c3d872b 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -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 { + 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 | undefined, next: Record | 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) diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index b429897e..998b46be 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -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 { + if (!await fileExists(root)) { + return [] + } + + let entries: Awaited> + 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, 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 diff --git a/backend/test/services/skills.test.ts b/backend/test/services/skills.test.ts index aa4bfdf7..2a2b1480 100644 --- a/backend/test/services/skills.test.ts +++ b/backend/test/services/skills.test.ts @@ -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() @@ -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()}` diff --git a/frontend/src/components/repo/RepoSkillsDialog.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx index a0ec46b8..7f07808a 100644 --- a/frontend/src/components/repo/RepoSkillsDialog.tsx +++ b/frontend/src/components/repo/RepoSkillsDialog.tsx @@ -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'] }) } diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 793934da..d9ae1046 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -874,7 +874,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
-
+
| undefined) ?? {}} onChange={(commands) => { @@ -911,7 +911,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
-
+
| undefined) ?? {}} onChange={(agents) => { @@ -941,25 +941,15 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf

Skills

- {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
-
+
{ - 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) - }} />
@@ -987,7 +977,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
-
+
updateConfigContent(selectedConfig.name, content)} @@ -1026,7 +1016,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
-
+
| undefined) ?? {}} onChange={(providers) => { diff --git a/frontend/src/components/settings/OpenCodeModelDialog.tsx b/frontend/src/components/settings/OpenCodeModelDialog.tsx index fba7d34b..2ef5a196 100644 --- a/frontend/src/components/settings/OpenCodeModelDialog.tsx +++ b/frontend/src/components/settings/OpenCodeModelDialog.tsx @@ -335,6 +335,8 @@ export function OpenCodeModelDialog({ const isEditing = !!editingModel + if (!open) return null + return ( diff --git a/frontend/src/components/settings/SettingsDialog.tsx b/frontend/src/components/settings/SettingsDialog.tsx index d7eac1ec..b67f2c16 100644 --- a/frontend/src/components/settings/SettingsDialog.tsx +++ b/frontend/src/components/settings/SettingsDialog.tsx @@ -179,7 +179,7 @@ export function SettingsDialog() {
-
+
{mobileView !== 'menu' && (
-
+
{mobileView === 'menu' && (
{menuItems.map((item) => ( @@ -235,7 +235,7 @@ export function SettingsDialog() { {mobileView === 'git' &&
} {mobileView === 'shortcuts' &&
} {mobileView === 'opencode' && ( -
+
setIsVersionDialogOpen(true)} /> diff --git a/frontend/src/components/settings/SkillsEditor.tsx b/frontend/src/components/settings/SkillsEditor.tsx index e7595efe..9f9ac519 100644 --- a/frontend/src/components/settings/SkillsEditor.tsx +++ b/frontend/src/components/settings/SkillsEditor.tsx @@ -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 ( -
- - {items.length === 0 ? ( -
-

No {label.toLowerCase()} configured. Add one to get started.

-
- ) : ( -
- {items.map((item, index) => ( -
- handleItemChange(index, e.target.value)} - placeholder={placeholder} - className="flex-1" - /> - -
- ))} -
- )} - -
- ) -} - -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(null) - const [collapsiblesOpen, setCollapsiblesOpen] = useState({ - managed: true, - config: false, - }) - const [localPaths, setLocalPaths] = useState(skills?.paths ?? []) - const [localUrls, setLocalUrls] = useState(skills?.urls ?? []) - const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false) const [deleteSkill, setDeleteSkill] = useState(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 ( -
-
- -
+
+
+
-
- {collapsiblesOpen.managed && ( - - )} - -
-
- -
- - {collapsiblesOpen.config && ( -
- { - 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/" - /> - - { - 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 && ( -
- - -
- )} -
- )} -
+ { 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({
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' : ''}`} > -
-
-

{skill.name}

- +
+
+

{skill.name}

+ + {getCompactScopeLabel(skill)} + + {getScopeLabel(skill)}
@@ -140,9 +145,9 @@ export function SkillLibraryList({

{skill.description}

)}
-
event.stopPropagation()}> +
event.stopPropagation()}> {primaryAction && ( - )}