From 24d34f28a3092d808a8767c73a2104a83a9c426b Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 17 Jun 2026 23:09:34 -0400 Subject: [PATCH] Revert "feat: add skill installer with install/uninstall and settings UI (#277)" (#278) This reverts commit 9cb2bb156b36430b3a7e3065586c71b635946d5a. --- backend/src/routes/settings.ts | 202 -------- backend/src/services/skills.ts | 440 +----------------- .../routes/settings-skills-install.test.ts | 371 --------------- backend/test/services/skills.test.ts | 429 +---------------- frontend/src/api/settings.test.ts | 95 ---- frontend/src/api/settings.ts | 39 -- frontend/src/api/types/settings.ts | 6 +- .../components/repo/RepoSkillsDialog.test.tsx | 23 +- .../src/components/repo/RepoSkillsDialog.tsx | 146 +++--- .../src/components/repo/RepoSkillsList.tsx | 81 ++++ .../settings/OpenCodeConfigManager.tsx | 22 +- .../settings/OpenCodeModelDialog.tsx | 2 - .../components/settings/SettingsDialog.tsx | 6 +- .../settings/SkillInstallDialog.tsx | 231 --------- .../components/settings/SkillsEditor.test.tsx | 184 -------- .../src/components/settings/SkillsEditor.tsx | 315 +++++++++++-- .../components/skills/SkillLibraryList.tsx | 182 -------- shared/src/schemas/skills.ts | 33 -- shared/src/types/index.ts | 9 - 19 files changed, 475 insertions(+), 2341 deletions(-) delete mode 100644 backend/test/routes/settings-skills-install.test.ts delete mode 100644 frontend/src/api/settings.test.ts create mode 100644 frontend/src/components/repo/RepoSkillsList.tsx delete mode 100644 frontend/src/components/settings/SkillInstallDialog.tsx delete mode 100644 frontend/src/components/settings/SkillsEditor.test.tsx delete mode 100644 frontend/src/components/skills/SkillLibraryList.tsx diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 7c3d872b..2a8439cc 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -18,9 +18,6 @@ import { CreateSkillRequestSchema, UpdateSkillRequestSchema, SkillScopeSchema, - InstallSkillFromGithubRequestSchema, - InstallSkillUploadRequestSchema, - InstallSkillUploadManifestEntrySchema, } from '@opencode-manager/shared' import { logger } from '../utils/logger' import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server' @@ -41,10 +38,7 @@ import { createSkill, updateSkill, deleteSkill, - installSkillFromGithubTree, - installSkillFromUploadedFiles, } from '../services/skills' -import { getRepoById } from '../db/queries' function getOpenCodeInstallMethod(): string { const homePath = process.env.HOME || '' @@ -98,37 +92,6 @@ 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, @@ -144,19 +107,6 @@ function needsOpenCodeRestart( return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field)) } -function parseOptionalRepoId(value: string | undefined): number | undefined { - if (value === undefined) return undefined - const parsed = parseInt(value, 10) - if (isNaN(parsed)) throw new Error('Invalid repoId') - return parsed -} - -function parseBooleanFormValue(value: unknown): boolean | undefined { - if (value === true || value === 'true') return true - if (value === false || value === 'false') return false - return undefined -} - function hasConfiguredPlugins(config: Record | undefined): boolean { return Array.isArray(config?.plugin) && config.plugin.length > 0 } @@ -1187,158 +1137,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic } }) - app.post('/skills/install', async (c) => { - try { - const contentType = c.req.header('content-type') || '' - - if (contentType.includes('application/json')) { - const body = await c.req.json() - const validated = InstallSkillFromGithubRequestSchema.parse(body) - - if (validated.scope === 'project' && validated.repoId === undefined) { - return c.json({ error: 'repoId is required for project scope' }, 400) - } - - const result = await installSkillFromGithubTree(db, validated) - - 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) - } - - if (contentType.includes('multipart/form-data')) { - const formData = await c.req.parseBody({ all: true }) - - const scope = formData['scope'] - const repoIdValue = formData['repoId'] - const overwriteValue = formData['overwrite'] - const fileManifestRaw = formData['fileManifest'] - - if (typeof fileManifestRaw !== 'string') { - return c.json({ error: 'fileManifest is required as a JSON string' }, 400) - } - - let manifestEntries: unknown - try { - manifestEntries = JSON.parse(fileManifestRaw) - } catch { - return c.json({ error: 'fileManifest must be valid JSON' }, 400) - } - - const manifest = InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries) - - const repoId = parseOptionalRepoId(repoIdValue as string | undefined) - const overwrite = parseBooleanFormValue(overwriteValue) - - const uploadRequest = InstallSkillUploadRequestSchema.parse({ - sourceType: 'upload', - scope, - repoId, - overwrite, - }) - - if (scope === 'project' && repoId === undefined) { - return c.json({ error: 'repoId is required for project scope' }, 400) - } - - if (manifest.length === 0) { - return c.json({ error: 'fileManifest must contain at least one entry' }, 400) - } - - const missingFields = manifest.filter((entry) => !formData[entry.fieldName]) - if (missingFields.length > 0) { - return c.json({ - error: `Missing upload file(s): ${missingFields.map((e) => e.fieldName).join(', ')}`, - }, 400) - } - - const files = await Promise.all( - manifest.map(async (entry) => { - const file = formData[entry.fieldName] - if (!file || !(file instanceof File)) { - throw new Error(`Field "${entry.fieldName}" is not a valid file`) - } - const content = Buffer.from(await file.arrayBuffer()) - return { relativePath: entry.relativePath, content } - }), - ) - - const result = await installSkillFromUploadedFiles(db, uploadRequest, files) - - 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) - } - - return c.json({ error: 'Unsupported content type. Use application/json or multipart/form-data' }, 400) - } catch (error) { - logger.error('Failed to install skill:', error) - - if (error instanceof z.ZodError) { - return c.json({ error: 'Invalid skill install data', details: error.issues }, 400) - } - - if (error instanceof Error) { - if (error.message.includes('already exists')) { - return c.json({ error: error.message }, 409) - } - if (error.message.includes('Invalid GitHub tree URL')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('Invalid skill name')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('Only one skill')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('Skill source must contain')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('Path must be relative') || error.message.includes('Path must not contain') || error.message.includes('escapes')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('no downloadable files')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('404')) { - return c.json({ error: error.message }, 404) - } - if (error.message.includes('repoId is required')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('Missing upload file')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('Invalid repoId')) { - return c.json({ error: error.message }, 400) - } - if (error.message.includes('not a valid file')) { - return c.json({ error: error.message }, 400) - } - } - - return c.json({ error: 'Failed to install skill' }, 500) - } - }) - app.get('/skills/:name', async (c) => { try { const name = c.req.param('name') diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index 998b46be..1a36a80a 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -1,10 +1,9 @@ import os from 'os' import path from 'path' -import { promises as fs } from 'fs' import type { Database } from 'bun:sqlite' -import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest, InstallSkillUploadRequest, InstallSkillFromGithubRequest, InstallSkillResponse } from '@opencode-manager/shared' -import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shared' -import { getWorkspacePath, FILE_LIMITS } from '@opencode-manager/shared/config/env' +import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest } from '@opencode-manager/shared' +import { SKILL_NAME_REGEX } from '@opencode-manager/shared' +import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { getRepoById, listRepos } from '../db/queries' import type { Repo } from '@opencode-manager/shared/types' import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations' @@ -18,343 +17,6 @@ interface OpenCodeSkillInfo { content: string } -interface SkillInstallFile { - relativePath: string - content: Buffer -} - -interface PreparedSkillFiles { - skillName: string - description: string - body: string - files: SkillInstallFile[] - filesInstalled: string[] -} - -function getSkillTargetRoot(db: Database, scope: SkillScope, repoId?: number): string { - if (scope === 'global') { - return getGlobalSkillsPath() - } - if (repoId === undefined) { - throw new Error('repoId is required for project-scoped skills') - } - const repo = getRepoById(db, repoId) - if (!repo) { - throw new Error(`Repository with id ${repoId} not found`) - } - return getProjectSkillsPath(repo) -} - -function normalizeInstallRelativePath(relativePath: string): string { - const normalized = relativePath.replace(/\\/g, '/') - if (path.isAbsolute(normalized)) { - throw new Error(`Path must be relative, got absolute path: "${relativePath}"`) - } - if (/^[A-Za-z]:\//.test(normalized)) { - throw new Error(`Path must be relative, got absolute path: "${relativePath}"`) - } - if (normalized === '' || normalized === '.') { - throw new Error('Path must not be empty') - } - const parts = normalized.split('/') - for (const part of parts) { - if (part === '..') { - throw new Error(`Path must not contain "..": "${relativePath}"`) - } - } - return normalized -} - -function parseSkillMarkdown(content: string): { name: string; description: string; body: string } { - if (!content.startsWith('---\n')) { - throw new Error('Skill markdown must start with a frontmatter block') - } - const endIndex = content.indexOf('\n---\n', 4) - if (endIndex === -1) { - throw new Error('Skill markdown must have a closing frontmatter delimiter') - } - const frontmatterBlock = content.substring(4, endIndex) - const body = content.substring(endIndex + 5) - const lines = frontmatterBlock.split('\n') - const frontmatter: Record = {} - for (const line of lines) { - const colonIndex = line.indexOf(':') - if (colonIndex === -1) continue - const key = line.substring(0, colonIndex).trim() - let value = line.substring(colonIndex + 1).trim() - if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith('"') && value.endsWith('"'))) { - value = value.substring(1, value.length - 1) - } - frontmatter[key] = value - } - const parsed = SkillFrontmatterSchema.parse({ - name: frontmatter.name, - description: frontmatter.description, - }) - return { - name: parsed.name, - description: parsed.description, - body, - } -} - -function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles { - const normalized = files.map(f => ({ - ...f, - relativePath: normalizeInstallRelativePath(f.relativePath), - })) - const skillMdFiles = normalized.filter(f => path.basename(f.relativePath) === 'SKILL.md') - if (skillMdFiles.length === 0) { - throw new Error('Skill source must contain SKILL.md') - } - if (skillMdFiles.length > 1) { - throw new Error('Only one skill can be installed at a time') - } - const skillMd = skillMdFiles[0]! - const skillDir = path.dirname(skillMd.relativePath) - const { name, description, body } = parseSkillMarkdown(skillMd.content.toString('utf-8')) - const prefix = skillDir === '.' ? '' : skillDir + '/' - const strippedFiles = normalized - .filter(f => f.relativePath === skillMd.relativePath || f.relativePath.startsWith(prefix)) - .map(f => ({ - ...f, - relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length), - })) - for (const f of strippedFiles) { - const checkPath = normalizeInstallRelativePath(f.relativePath) - if (checkPath.startsWith('..')) { - throw new Error(`File "${f.relativePath}" escapes the skill directory`) - } - } - const filesInstalled = strippedFiles.map(f => f.relativePath) - return { - skillName: name, - description, - body, - files: strippedFiles, - filesInstalled, - } -} - -async function installSkillFiles( - db: Database, - input: InstallSkillUploadRequest | InstallSkillFromGithubRequest, - files: SkillInstallFile[], -): Promise { - const prepared = prepareSingleSkillFiles(files) - const targetRoot = getSkillTargetRoot(db, input.scope, input.repoId) - const targetDir = path.join(targetRoot, prepared.skillName) - const skillPath = path.join(targetDir, 'SKILL.md') - - const targetDirExists = await fileExists(targetDir) - const targetSkillExists = await fileExists(skillPath) - const existingTarget = targetDirExists || targetSkillExists - - if (existingTarget && input.overwrite !== true) { - throw new Error(`Skill "${prepared.skillName}" already exists in ${input.scope} scope`) - } - - await fs.mkdir(targetRoot, { recursive: true }) - const stagingDir = await fs.mkdtemp(path.join(targetRoot, `.${prepared.skillName}-install-`)) - - try { - for (const file of prepared.files) { - const targetFilePath = path.resolve(stagingDir, file.relativePath) - if (!targetFilePath.startsWith(stagingDir + path.sep)) { - throw new Error(`File "${file.relativePath}" escapes the staging directory`) - } - await fs.mkdir(path.dirname(targetFilePath), { recursive: true }) - await fs.writeFile(targetFilePath, file.content) - } - - if (existingTarget && input.overwrite === true) { - await fs.rm(targetDir, { recursive: true, force: true }) - } - - await fs.rename(stagingDir, targetDir) - - const repo = input.repoId !== undefined ? getRepoById(db, input.repoId) : null - - return { - skill: { - name: prepared.skillName, - description: prepared.description, - body: prepared.body, - scope: input.scope, - location: skillPath, - repoId: input.scope === 'project' ? input.repoId : undefined, - repoName: repo?.localPath, - }, - overwritten: Boolean(existingTarget), - sourceType: input.sourceType, - filesInstalled: prepared.filesInstalled, - } - } catch (error) { - await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {}) - throw error - } -} - -export async function installSkillFromUploadedFiles( - db: Database, - input: InstallSkillUploadRequest, - files: SkillInstallFile[], -): Promise { - return installSkillFiles(db, input, files) -} - -type GithubFetchFn = (url: string | URL | Request, init?: RequestInit) => Promise - -interface GithubTreeSource { - owner: string - repo: string - ref: string - path: string -} - -interface GithubContentEntry { - name: string - path: string - type: 'file' | 'dir' - download_url?: string | null - url: string -} - -function parseGithubTreeUrl(url: string): GithubTreeSource { - let parsed: URL - try { - parsed = new URL(url) - } catch { - throw new Error('Invalid GitHub tree URL') - } - - if (parsed.protocol !== 'https:' || parsed.host !== 'github.com') { - throw new Error('Invalid GitHub tree URL: only https://github.com is supported') - } - - const segments = parsed.pathname.split('/').filter(Boolean) - if (segments.length < 4 || segments[2] !== 'tree') { - throw new Error('Invalid GitHub tree URL: must be a tree URL (github.com/owner/repo/tree/ref/path)') - } - - const owner = segments[0]! - const repo = segments[1]! - const ref = segments[3]! - const path = segments.slice(4).join('/') - - if (!path) { - throw new Error('Invalid GitHub tree URL: path is required') - } - - return { owner, repo, ref, path } -} - -async function fetchGithubJson(fetchFn: GithubFetchFn, url: string): Promise { - const response = await fetchFn(url, { - headers: { - Accept: 'application/vnd.github+json', - 'User-Agent': 'opencode-manager', - }, - }) - if (!response.ok) { - throw new Error(`GitHub request failed with status ${response.status}`) - } - return response.json() -} - -async function fetchGithubFile(fetchFn: GithubFetchFn, url: string): Promise { - const response = await fetchFn(url, { - headers: { - 'User-Agent': 'opencode-manager', - }, - }) - if (!response.ok) { - throw new Error(`GitHub request failed with status ${response.status}`) - } - return response.arrayBuffer() -} - -function githubContentsApiUrl(source: GithubTreeSource, path: string): string { - const encodedPath = path.split('/').map(encodeURIComponent).join('/') - return `https://api.github.com/repos/${source.owner}/${source.repo}/contents/${encodedPath}?ref=${encodeURIComponent(source.ref)}` -} - -async function fetchGithubSkillFiles( - source: GithubTreeSource, - fetchFn: GithubFetchFn = fetch, -): Promise { - const apiUrl = githubContentsApiUrl(source, source.path) - const data = await fetchGithubJson(fetchFn, apiUrl) - - if (!Array.isArray(data)) { - const entry = data as GithubContentEntry - if (entry.name !== 'SKILL.md') { - throw new Error('GitHub tree URL must point to a skill folder containing SKILL.md') - } - const buffer = await fetchGithubFile(fetchFn, entry.download_url!) - const content = Buffer.from(buffer) - if (content.length > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) { - throw new Error('Skill files exceed maximum upload size') - } - return [{ relativePath: 'SKILL.md', content }] - } - - const files: SkillInstallFile[] = [] - let totalBytes = 0 - const MAX_FILES = 100 - - async function walk(entries: GithubContentEntry[]) { - for (const entry of entries) { - if (files.length >= MAX_FILES) { - throw new Error(`Skill contains too many files (max ${MAX_FILES})`) - } - - if (entry.type === 'dir') { - const dirUrl = githubContentsApiUrl(source, entry.path) - const dirData = await fetchGithubJson(fetchFn, dirUrl) - if (Array.isArray(dirData)) { - await walk(dirData as GithubContentEntry[]) - } - continue - } - - if (!entry.download_url) continue - - const relativePath = entry.path.startsWith(source.path + '/') - ? entry.path.substring(source.path.length + 1) - : entry.path - - const arrayBuffer = await fetchGithubFile(fetchFn, entry.download_url) - const buffer = Buffer.from(arrayBuffer) - totalBytes += buffer.length - - if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) { - throw new Error('Skill files exceed maximum upload size') - } - - files.push({ relativePath, content: buffer }) - } - } - - await walk(data as GithubContentEntry[]) - - if (files.length === 0) { - throw new Error('GitHub tree URL contains no downloadable files') - } - - return files -} - -export async function installSkillFromGithubTree( - db: Database, - input: InstallSkillFromGithubRequest, - fetchFn: GithubFetchFn = fetch, -): Promise { - const source = parseGithubTreeUrl(input.url) - const files = await fetchGithubSkillFiles(source, fetchFn) - return installSkillFiles(db, input, files) -} - function getGlobalSkillsPath(): string { return path.join(getWorkspacePath(), '.config', 'opencode', 'skills') } @@ -427,8 +89,17 @@ function validateSkillName(name: string): void { function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string { validateSkillName(name) - const targetRoot = getSkillTargetRoot(db, scope, repoId) - return path.join(targetRoot, name, 'SKILL.md') + if (scope === 'global') { + return path.join(getGlobalSkillsPath(), name, 'SKILL.md') + } + if (!repoId) { + throw new Error('repoId is required for project-scoped skills') + } + const repo = getRepoById(db, repoId) + if (!repo) { + throw new Error(`Repository with id ${repoId} not found`) + } + return path.join(getProjectSkillsPath(repo), name, 'SKILL.md') } function buildSkillFileContent(name: string, description: string, body: string): string { @@ -462,18 +133,18 @@ function classifySkillLocation( if (location.startsWith(globalPrefix + path.sep)) { return { scope: 'global' } } - 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' } } } + for (const repo of repos) { + const projectPrefix = getProjectSkillsPath(repo) + if (location.startsWith(projectPrefix + path.sep)) { + return { scope: 'project', repo } + } + } return null } @@ -492,52 +163,6 @@ 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, @@ -556,16 +181,8 @@ export async function listManagedSkills( if (seenLocations.has(skill.location)) continue const classification = classifySkillLocation(skill.location, globalPrefix, allRepos, directory) if (!classification) continue - 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) + seenLocations.add(skill.location) + result.push(toSkillFileInfo(skill, classification)) } } else { const targetRepos = repoId @@ -586,19 +203,10 @@ export async function listManagedSkills( if (seenLocations.has(skill.location)) continue const classification = classifySkillLocation(skill.location, globalPrefix, allRepos) if (!classification) continue - addSkill(result, seenLocations, toSkillFileInfo(skill, classification)) + seenLocations.add(skill.location) + result.push(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/routes/settings-skills-install.test.ts b/backend/test/routes/settings-skills-install.test.ts deleted file mode 100644 index 1ba5ab4f..00000000 --- a/backend/test/routes/settings-skills-install.test.ts +++ /dev/null @@ -1,371 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' - -vi.mock('fs', () => ({ - existsSync: vi.fn(() => false), - promises: { - mkdir: vi.fn(), - access: vi.fn(), - readFile: vi.fn(), - writeFile: vi.fn(), - stat: vi.fn(), - chmod: vi.fn(), - unlink: vi.fn(), - rm: vi.fn(), - readdir: vi.fn(), - }, -})) - -vi.mock('child_process', () => ({ - execSync: vi.fn(), - spawnSync: vi.fn(), - spawn: vi.fn(), -})) - -vi.mock('../../src/utils/logger', () => ({ - logger: { - info: vi.fn(), - error: vi.fn(), - warn: vi.fn(), - }, -})) - -vi.mock('../../src/constants', () => ({ - DEFAULT_AGENTS_MD: '# Test Agents MD', -})) - -vi.mock('../../src/services/settings', () => ({ - SettingsService: vi.fn().mockImplementation(() => ({ - getSettings: vi.fn(), - updateSettings: vi.fn(), - saveLastKnownGoodConfig: vi.fn(), - createOpenCodeConfig: vi.fn(), - updateOpenCodeConfig: vi.fn(), - deleteOpenCodeConfig: vi.fn(), - getOpenCodeConfigByName: vi.fn(), - setDefaultOpenCodeConfig: vi.fn(), - })), -})) - -vi.mock('../../src/services/file-operations', () => ({ - writeFileContent: vi.fn(), - readFileContent: vi.fn(), - fileExists: vi.fn(), -})) - -vi.mock('../../src/services/opencode-single-server', () => { - class MockConfigReloadError extends Error { - validationIssues: Array<{ path: string; message: string }> = [] - removedFields: string[] = [] - constructor(message: string) { - super(message) - this.name = 'ConfigReloadError' - } - } - - return { - opencodeServerManager: { - getVersion: vi.fn(), - fetchVersion: vi.fn(), - reloadConfig: vi.fn(), - restart: vi.fn(), - clearStartupError: vi.fn(), - getLastStartupError: vi.fn(), - setDatabase: vi.fn(), - reinitializeBinDirectory: vi.fn(), - }, - ConfigReloadError: MockConfigReloadError, - } -}) - -vi.mock('../../src/services/skills', () => ({ - listManagedSkills: vi.fn(), - getSkill: vi.fn(), - createSkill: vi.fn(), - updateSkill: vi.fn(), - deleteSkill: vi.fn(), - installSkillFromGithubTree: vi.fn(), - installSkillFromUploadedFiles: vi.fn(), -})) - -vi.mock('@opencode-manager/shared/config/env', () => ({ - getWorkspacePath: vi.fn(() => '/tmp/test-workspace'), - getReposPath: vi.fn(() => '/tmp/test-repos'), - getOpenCodeConfigFilePath: vi.fn(() => '/tmp/test-workspace/.config/opencode.json'), - getAgentsMdPath: vi.fn(() => '/tmp/test-workspace/AGENTS.md'), - getDatabasePath: vi.fn(() => ':memory:'), - getConfigPath: vi.fn(() => '/tmp/test-workspace/config'), - ENV: { - SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' }, - AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' }, - WORKSPACE: { BASE_PATH: '/tmp/test-workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' }, - OPENCODE: { PORT: 5551, HOST: '127.0.0.1' }, - DATABASE: { PATH: ':memory:' }, - FILE_LIMITS: { - MAX_SIZE_BYTES: 1024 * 1024, - MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024, - }, - }, - FILE_LIMITS: { - MAX_SIZE_BYTES: 1024 * 1024, - MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024, - }, -})) - -import { createSettingsRoutes } from '../../src/routes/settings' -import { opencodeServerManager } from '../../src/services/opencode-single-server' -import { - installSkillFromGithubTree, - installSkillFromUploadedFiles, - deleteSkill, -} from '../../src/services/skills' - -const mockInstallFromGithubTree = installSkillFromGithubTree as ReturnType -const mockInstallFromUploadedFiles = installSkillFromUploadedFiles as ReturnType -const mockDeleteSkill = deleteSkill as ReturnType -const mockRestart = opencodeServerManager.restart as ReturnType - -const mockSuccessResponse = { - skill: { - name: 'teach', - description: 'A teaching skill', - body: '## Teach\n\nContent', - scope: 'global', - location: '/tmp/test-workspace/.config/opencode/skills/teach/SKILL.md', - }, - overwritten: false, - sourceType: 'github' as const, - filesInstalled: ['teach/SKILL.md'], -} - -describe('Settings Routes - Skill Install', () => { - let settingsApp: ReturnType - let testDb: any - - beforeEach(() => { - vi.clearAllMocks() - mockRestart.mockResolvedValue(undefined) - mockInstallFromGithubTree.mockResolvedValue(mockSuccessResponse) - mockInstallFromUploadedFiles.mockResolvedValue({ ...mockSuccessResponse, sourceType: 'upload' }) - - testDb = {} as any - settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any, createStubOpenCodeClient()) - }) - - describe('POST /skills/install', () => { - it('installs from GitHub JSON', async () => { - const res = await settingsApp.request('/skills/install', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - sourceType: 'github', - url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach', - scope: 'global', - }), - }) - - expect(res.status).toBe(200) - const body = await res.json() as Record - expect(body).toEqual(mockSuccessResponse) - expect(mockInstallFromGithubTree).toHaveBeenCalledTimes(1) - expect(mockInstallFromGithubTree).toHaveBeenCalledWith(testDb, { - sourceType: 'github', - url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach', - scope: 'global', - }) - expect(mockRestart).toHaveBeenCalledTimes(1) - }) - - it('installs from multipart upload', async () => { - const formData = new FormData() - formData.append('scope', 'global') - formData.append('sourceType', 'upload') - formData.append('fileManifest', JSON.stringify([ - { fieldName: 'file0', relativePath: 'teach/SKILL.md' }, - ])) - formData.append('file0', new File(['---\nname: teach\ndescription: A teaching skill\n---\n## Teach\n\nContent'], 'SKILL.md', { type: 'text/markdown' })) - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - body: formData, - }) - - expect(res.status).toBe(200) - const body = await res.json() as { sourceType: string } - expect(body.sourceType).toBe('upload') - expect(mockInstallFromUploadedFiles).toHaveBeenCalledTimes(1) - expect(mockInstallFromUploadedFiles).toHaveBeenCalledWith( - testDb, - { - sourceType: 'upload', - scope: 'global', - repoId: undefined, - overwrite: undefined, - }, - [ - expect.objectContaining({ - relativePath: 'teach/SKILL.md', - content: expect.any(Buffer), - }), - ], - ) - expect(mockRestart).toHaveBeenCalledTimes(1) - }) - - it('returns 409 on existing skill', async () => { - mockInstallFromGithubTree.mockRejectedValue(new Error('Skill "teach" already exists in global scope')) - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - sourceType: 'github', - url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach', - scope: 'global', - }), - }) - - expect(res.status).toBe(409) - const body = await res.json() as { error: string } - expect(body.error).toContain('already exists') - expect(mockRestart).not.toHaveBeenCalled() - }) - - it('rejects project scope without repoId', async () => { - const res = await settingsApp.request('/skills/install', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - sourceType: 'github', - url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach', - scope: 'project', - }), - }) - - expect(res.status).toBe(400) - const body = await res.json() as { error: string } - expect(body.error).toContain('repoId is required') - expect(mockInstallFromGithubTree).not.toHaveBeenCalled() - }) - - it('rejects invalid repoId in multipart upload', async () => { - const formData = new FormData() - formData.append('scope', 'global') - formData.append('sourceType', 'upload') - formData.append('repoId', 'abc') - formData.append('fileManifest', JSON.stringify([ - { fieldName: 'file0', relativePath: 'teach/SKILL.md' }, - ])) - formData.append('file0', new File(['content'], 'SKILL.md', { type: 'text/markdown' })) - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - body: formData, - }) - - expect(res.status).toBe(400) - const body = await res.json() as { error: string } - expect(body.error).toContain('Invalid repoId') - }) - - it('rejects multiple uploaded skills', async () => { - mockInstallFromUploadedFiles.mockRejectedValue(new Error('Only one skill can be installed at a time')) - - const formData = new FormData() - formData.append('scope', 'global') - formData.append('sourceType', 'upload') - formData.append('fileManifest', JSON.stringify([ - { fieldName: 'file0', relativePath: 'teach/SKILL.md' }, - { fieldName: 'file1', relativePath: 'review/SKILL.md' }, - ])) - formData.append('file0', new File(['---\nname: teach\n---\nBody'], 'SKILL.md', { type: 'text/markdown' })) - formData.append('file1', new File(['---\nname: review\n---\nBody'], 'SKILL.md', { type: 'text/markdown' })) - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - body: formData, - }) - - expect(res.status).toBe(400) - const body = await res.json() as { error: string } - expect(body.error).toContain('Only one skill') - expect(mockRestart).not.toHaveBeenCalled() - }) - - it('rejects upload with missing SKILL.md', async () => { - mockInstallFromUploadedFiles.mockRejectedValue(new Error('Skill source must contain SKILL.md')) - - const formData = new FormData() - formData.append('scope', 'global') - formData.append('sourceType', 'upload') - formData.append('fileManifest', JSON.stringify([ - { fieldName: 'file0', relativePath: 'teach/README.md' }, - ])) - formData.append('file0', new File(['# Readme'], 'README.md', { type: 'text/markdown' })) - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - body: formData, - }) - - expect(res.status).toBe(400) - const body = await res.json() as { error: string } - expect(body.error).toContain('Skill source must contain') - expect(mockRestart).not.toHaveBeenCalled() - }) - - it('rejects unsafe upload path', async () => { - mockInstallFromUploadedFiles.mockRejectedValue(new Error('Path must not contain "..": "../SKILL.md"')) - - const formData = new FormData() - formData.append('scope', 'global') - formData.append('sourceType', 'upload') - formData.append('fileManifest', JSON.stringify([ - { fieldName: 'file0', relativePath: '../SKILL.md' }, - ])) - formData.append('file0', new File(['---\nname: teach\n---\nBody'], 'SKILL.md', { type: 'text/markdown' })) - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - body: formData, - }) - - expect(res.status).toBe(400) - const body = await res.json() as { error: string } - expect(body.error).toContain('Path must not contain') - expect(mockRestart).not.toHaveBeenCalled() - }) - - it('rejects non-File manifest field in multipart upload', async () => { - const formData = new FormData() - formData.append('scope', 'global') - formData.append('sourceType', 'upload') - formData.append('fileManifest', JSON.stringify([ - { fieldName: 'file0', relativePath: 'teach/SKILL.md' }, - ])) - formData.append('file0', 'not-a-file') - - const res = await settingsApp.request('/skills/install', { - method: 'POST', - body: formData, - }) - - expect(res.status).toBe(400) - const body = await res.json() as { error: string } - expect(body.error).toContain('not a valid file') - }) - }) - - describe('DELETE /skills/:name', () => { - it('remains the deletion endpoint', async () => { - mockDeleteSkill.mockResolvedValue(undefined) - - const res = await settingsApp.request('/skills/test-skill?scope=global', { - method: 'DELETE', - }) - - expect(res.status).toBe(200) - expect(mockDeleteSkill).toHaveBeenCalledWith(testDb, 'test-skill', 'global', undefined) - }) - }) -}) diff --git a/backend/test/services/skills.test.ts b/backend/test/services/skills.test.ts index 2a2b1480..75096c38 100644 --- a/backend/test/services/skills.test.ts +++ b/backend/test/services/skills.test.ts @@ -1,20 +1,8 @@ import { describe, expect, test, beforeEach, afterEach, vi } from 'vitest' import { join } from 'path' import { tmpdir } from 'os' -import { mkdir, mkdtemp, rm, readFile, writeFile } from 'fs/promises' +import { mkdtemp, rm, readFile } 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() - return { - ...actual, - FILE_LIMITS: { - MAX_SIZE_BYTES: 1024 * 1024, - MAX_UPLOAD_SIZE_BYTES: 500, - }, - } -}) vi.mock('../../src/db/queries', () => ({ getRepoById: vi.fn(), @@ -300,43 +288,6 @@ 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()}` @@ -397,382 +348,4 @@ Another section.` const skills = await listManagedSkills(mockDb, client) expect(skills.length).toBe(0) }) - - describe('installSkillFromUploadedFiles', () => { - test('installs a single SKILL.md upload globally', async () => { - const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills') - const content = '---\nname: teach\ndescription: Teach users\nargument-hint: "topic"\n---\nBody' - const result = await installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'SKILL.md', content: Buffer.from(content) }, - ]) - - try { - expect(result.skill.name).toBe('teach') - expect(result.skill.description).toBe('Teach users') - expect(result.skill.body).toBe('Body') - expect(result.sourceType).toBe('upload') - expect(result.overwritten).toBe(false) - expect(result.filesInstalled).toEqual(['SKILL.md']) - - const fileContent = await readFile(result.skill.location, 'utf-8') - expect(fileContent).toContain('argument-hint: "topic"') - expect(fileContent).toContain('Body') - } finally { - await deleteSkill(mockDb, 'teach', 'global').catch(() => {}) - } - }) - - test('preserves bundled folder files', async () => { - const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills') - const skillMd = '---\nname: teach\ndescription: Teach users\n---\nBody' - const glossaryMd = '# GLOSSARY-FORMAT\n\nFormat guidelines' - - const result = await installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'teach/SKILL.md', content: Buffer.from(skillMd) }, - { relativePath: 'teach/GLOSSARY-FORMAT.md', content: Buffer.from(glossaryMd) }, - ]) - - try { - expect(result.filesInstalled).toContain('SKILL.md') - expect(result.filesInstalled).toContain('GLOSSARY-FORMAT.md') - - const bundledFile = join(result.skill.location.replace('/SKILL.md', ''), 'GLOSSARY-FORMAT.md') - const bundledContent = await readFile(bundledFile, 'utf-8') - expect(bundledContent).toBe(glossaryMd) - } finally { - await deleteSkill(mockDb, 'teach', 'global').catch(() => {}) - } - }) - - test('rejects multiple skills', async () => { - const { installSkillFromUploadedFiles } = await import('../../src/services/skills') - - await expect(installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'teach/SKILL.md', content: Buffer.from('---\nname: teach\ndescription: Teach\n---\nBody') }, - { relativePath: 'review/SKILL.md', content: Buffer.from('---\nname: review\ndescription: Review\n---\nBody') }, - ])).rejects.toThrow('Only one skill') - }) - - test('prompts overwrite through conflict', async () => { - const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills') - const content = '---\nname: overwrite-test\ndescription: Test\n---\nOriginal' - - const first = await installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'SKILL.md', content: Buffer.from(content) }, - ]) - expect(first.overwritten).toBe(false) - - try { - await expect(installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'SKILL.md', content: Buffer.from(content) }, - ])).rejects.toThrow('already exists') - - const newContent = '---\nname: overwrite-test\ndescription: Test\n---\nReplaced' - const second = await installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - overwrite: true, - }, [ - { relativePath: 'SKILL.md', content: Buffer.from(newContent) }, - ]) - expect(second.overwritten).toBe(true) - expect(second.skill.body).toBe('Replaced') - - const fileContent = await readFile(second.skill.location, 'utf-8') - expect(fileContent).toContain('Replaced') - } finally { - await deleteSkill(mockDb, 'overwrite-test', 'global').catch(() => {}) - } - }) - - test('deleteSkill removes bundled files from installed skill', async () => { - const { installSkillFromUploadedFiles, deleteSkill } = await import('../../src/services/skills') - - const result = await installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'teach/SKILL.md', content: Buffer.from('---\nname: teach\ndescription: Teach\n---\nBody') }, - { relativePath: 'teach/GLOSSARY-FORMAT.md', content: Buffer.from('# Glossary') }, - ]) - - const skillDir = result.skill.location.replace('/SKILL.md', '') - const bundledFile = join(skillDir, 'GLOSSARY-FORMAT.md') - - await expect(readFile(bundledFile, 'utf-8')).resolves.toBe('# Glossary') - - await deleteSkill(mockDb, 'teach', 'global') - - await expect(readFile(bundledFile, 'utf-8')).rejects.toThrow() - }) - - test('rejects Windows drive-letter absolute paths', async () => { - const { installSkillFromUploadedFiles } = await import('../../src/services/skills') - - await expect(installSkillFromUploadedFiles(mockDb, { - sourceType: 'upload', - scope: 'global', - }, [ - { relativePath: 'C:\\temp\\SKILL.md', content: Buffer.from('---\nname: teach\ndescription: Teach\n---\nBody') }, - ])).rejects.toThrow('Path must be relative') - }) - }) - - describe('installSkillFromGithubTree', () => { - test('downloads a public GitHub tree skill', async () => { - const { installSkillFromGithubTree, deleteSkill } = await import('../../src/services/skills') - - const contentsUrl = 'https://api.github.com/repos/mattpocock/skills/contents/skills/productivity/teach?ref=main' - const downloadUrl1 = 'https://raw.githubusercontent.com/mattpocock/skills/main/skills/productivity/teach/SKILL.md' - const downloadUrl2 = 'https://raw.githubusercontent.com/mattpocock/skills/main/skills/productivity/teach/GLOSSARY-FORMAT.md' - - const mockFetch = vi.fn((url: string | URL | Request) => { - const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url - if (urlStr === contentsUrl) { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'skills/productivity/teach/SKILL.md', type: 'file', download_url: downloadUrl1, url: contentsUrl }, - { name: 'GLOSSARY-FORMAT.md', path: 'skills/productivity/teach/GLOSSARY-FORMAT.md', type: 'file', download_url: downloadUrl2, url: contentsUrl.replace('teach', 'teach/GLOSSARY-FORMAT') }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === downloadUrl1) { - return Promise.resolve(new Response('---\nname: teach\ndescription: Teach users\n---\nBody content')) - } - if (urlStr === downloadUrl2) { - return Promise.resolve(new Response('# Glossary')) - } - return Promise.resolve(new Response(null, { status: 404 })) - }) - - try { - const result = await installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach', - scope: 'global', - }, mockFetch) - - expect(mockFetch).toHaveBeenCalledWith( - expect.stringContaining('/repos/mattpocock/skills/contents/skills/productivity/teach?ref=main'), - expect.objectContaining({ - headers: expect.objectContaining({ Accept: 'application/vnd.github+json' }), - }), - ) - expect(result.skill.name).toBe('teach') - expect(result.skill.description).toBe('Teach users') - expect(result.sourceType).toBe('github') - expect(result.filesInstalled).toContain('SKILL.md') - expect(result.filesInstalled).toContain('GLOSSARY-FORMAT.md') - } finally { - await deleteSkill(mockDb, 'teach', 'global').catch(() => {}) - } - }) - - test('rejects non-tree GitHub URLs', async () => { - const { installSkillFromGithubTree } = await import('../../src/services/skills') - const mockFetch = vi.fn() - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/mattpocock/skills/blob/main/skills/productivity/teach/SKILL.md', - scope: 'global', - }, mockFetch)).rejects.toThrow('Invalid GitHub tree URL') - - expect(mockFetch).not.toHaveBeenCalled() - }) - - test('rejects non-HTTPS GitHub tree URLs', async () => { - const { installSkillFromGithubTree } = await import('../../src/services/skills') - const mockFetch = vi.fn() - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'http://github.com/mattpocock/skills/tree/main/skills/productivity/teach', - scope: 'global', - }, mockFetch)).rejects.toThrow('Invalid GitHub tree URL') - - expect(mockFetch).not.toHaveBeenCalled() - }) - - test('rejects parent folder with multiple skills', async () => { - const { installSkillFromGithubTree } = await import('../../src/services/skills') - - const parentContentsUrl = 'https://api.github.com/repos/user/repo/contents/skills?ref=main' - - const mockFetch = vi.fn((url: string | URL | Request) => { - const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url - if (urlStr === parentContentsUrl) { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'teach', path: 'skills/teach', type: 'dir', download_url: null, url: parentContentsUrl + '/teach' }, - { name: 'review', path: 'skills/review', type: 'dir', download_url: null, url: parentContentsUrl + '/review' }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === 'https://api.github.com/repos/user/repo/contents/skills/teach?ref=main') { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'skills/teach/SKILL.md', type: 'file', download_url: 'https://raw.githubusercontent.com/user/repo/main/skills/teach/SKILL.md', url }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === 'https://api.github.com/repos/user/repo/contents/skills/review?ref=main') { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'skills/review/SKILL.md', type: 'file', download_url: 'https://raw.githubusercontent.com/user/repo/main/skills/review/SKILL.md', url }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === 'https://raw.githubusercontent.com/user/repo/main/skills/teach/SKILL.md') { - return Promise.resolve(new Response('---\nname: teach\ndescription: Teach\n---\nBody')) - } - if (urlStr === 'https://raw.githubusercontent.com/user/repo/main/skills/review/SKILL.md') { - return Promise.resolve(new Response('---\nname: review\ndescription: Review\n---\nBody')) - } - return Promise.resolve(new Response(null, { status: 404 })) - }) - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/skills', - scope: 'global', - }, mockFetch)).rejects.toThrow('Only one skill') - }) - - test('enforces overwrite conflicts', async () => { - const { installSkillFromGithubTree, deleteSkill } = await import('../../src/services/skills') - - const contentsUrl = 'https://api.github.com/repos/user/repo/contents/my-skill?ref=main' - const downloadUrl = 'https://raw.githubusercontent.com/user/repo/main/my-skill/SKILL.md' - - const makeMockFetch = () => vi.fn((url: string | URL | Request) => { - const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url - if (urlStr === contentsUrl) { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'my-skill/SKILL.md', type: 'file', download_url: downloadUrl, url: contentsUrl }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === downloadUrl) { - return Promise.resolve(new Response('---\nname: overwrite-test\ndescription: Test\n---\nBody')) - } - return Promise.resolve(new Response(null, { status: 404 })) - }) - - try { - const first = await installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/my-skill', - scope: 'global', - }, makeMockFetch()) - expect(first.overwritten).toBe(false) - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/my-skill', - scope: 'global', - }, makeMockFetch())).rejects.toThrow('already exists') - - const second = await installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/my-skill', - scope: 'global', - overwrite: true, - }, makeMockFetch()) - expect(second.overwritten).toBe(true) - } finally { - await deleteSkill(mockDb, 'overwrite-test', 'global').catch(() => {}) - } - }) - - test('rejects oversized single-file download exceeding size limit', async () => { - const { installSkillFromGithubTree } = await import('../../src/services/skills') - - const contentsUrl = 'https://api.github.com/repos/user/repo/contents/huge-skill?ref=main' - const downloadUrl = 'https://raw.githubusercontent.com/user/repo/main/huge-skill/SKILL.md' - const oversizedContent = '# Big\n' + 'x'.repeat(600) - - const mockFetch = vi.fn((url: string | URL | Request) => { - const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url - if (urlStr === contentsUrl) { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'huge-skill/SKILL.md', type: 'file', download_url: downloadUrl, url: contentsUrl }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === downloadUrl) { - return Promise.resolve(new Response(oversizedContent)) - } - return Promise.resolve(new Response(null, { status: 404 })) - }) - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/huge-skill', - scope: 'global', - }, mockFetch)).rejects.toThrow('Skill files exceed maximum upload size') - }) - - test('rejects single SKILL.md download failure with GitHub status', async () => { - const { installSkillFromGithubTree } = await import('../../src/services/skills') - - const contentsUrl = 'https://api.github.com/repos/user/repo/contents/failing-skill?ref=main' - const downloadUrl = 'https://raw.githubusercontent.com/user/repo/main/failing-skill/SKILL.md' - - const mockFetch = vi.fn((url: string | URL | Request) => { - const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url - if (urlStr === contentsUrl) { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'failing-skill/SKILL.md', type: 'file', download_url: downloadUrl, url: contentsUrl }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === downloadUrl) { - return Promise.resolve(new Response('Not Found', { status: 404 })) - } - return Promise.resolve(new Response(null, { status: 404 })) - }) - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/failing-skill', - scope: 'global', - }, mockFetch)).rejects.toThrow('GitHub request failed with status 404') - }) - - test('rejects bundled file download failure with GitHub status', async () => { - const { installSkillFromGithubTree } = await import('../../src/services/skills') - - const contentsUrl = 'https://api.github.com/repos/user/repo/contents/skill-with-bundle?ref=main' - const skillUrl = 'https://raw.githubusercontent.com/user/repo/main/skill-with-bundle/SKILL.md' - const bundleUrl = 'https://raw.githubusercontent.com/user/repo/main/skill-with-bundle/GLOSSARY-FORMAT.md' - - const mockFetch = vi.fn((url: string | URL | Request) => { - const urlStr = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url - if (urlStr === contentsUrl) { - return Promise.resolve(new Response(JSON.stringify([ - { name: 'SKILL.md', path: 'skill-with-bundle/SKILL.md', type: 'file', download_url: skillUrl, url: contentsUrl }, - { name: 'GLOSSARY-FORMAT.md', path: 'skill-with-bundle/GLOSSARY-FORMAT.md', type: 'file', download_url: bundleUrl, url: contentsUrl }, - ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) - } - if (urlStr === skillUrl) { - return Promise.resolve(new Response('---\nname: bundled-fail\ndescription: Test\n---\nBody')) - } - if (urlStr === bundleUrl) { - return Promise.resolve(new Response('Forbidden', { status: 403 })) - } - return Promise.resolve(new Response(null, { status: 404 })) - }) - - await expect(installSkillFromGithubTree(mockDb, { - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/skill-with-bundle', - scope: 'global', - }, mockFetch)).rejects.toThrow('GitHub request failed with status 403') - }) - }) }) diff --git a/frontend/src/api/settings.test.ts b/frontend/src/api/settings.test.ts deleted file mode 100644 index ffeb6879..00000000 --- a/frontend/src/api/settings.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { FetchError } from '@opencode-manager/shared' -import { settingsApi } from './settings' - -describe('settingsApi', () => { - const fetchMock = vi.fn() - - beforeEach(() => { - fetchMock.mockReset() - vi.stubGlobal('fetch', fetchMock) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - describe('installSkillFromGithub', () => { - it('posts JSON to skills install endpoint', async () => { - fetchMock.mockResolvedValue( - new Response(JSON.stringify({ skill: { name: 'teach' }, overwritten: false, sourceType: 'github', filesInstalled: ['SKILL.md'] }), { status: 200 }), - ) - - const result = await settingsApi.installSkillFromGithub({ - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/teach', - scope: 'global', - }) - - expect(result.skill.name).toBe('teach') - - const callUrl = fetchMock.mock.calls[0][0] - expect(callUrl).toEqual(expect.stringContaining('/api/settings/skills/install')) - - const callOptions = fetchMock.mock.calls[0][1] - expect(callOptions.method).toBe('POST') - expect(callOptions.headers['Content-Type']).toBe('application/json') - - const body = JSON.parse(callOptions.body) - expect(body.sourceType).toBe('github') - }) - - it('surfaces 409 conflict as FetchError', async () => { - fetchMock.mockResolvedValue( - new Response(JSON.stringify({ error: 'Skill "teach" already exists in global scope' }), { status: 409 }), - ) - - await expect( - settingsApi.installSkillFromGithub({ - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/teach', - scope: 'global', - }), - ).rejects.toThrow(FetchError) - - await expect( - settingsApi.installSkillFromGithub({ - sourceType: 'github', - url: 'https://github.com/user/repo/tree/main/teach', - scope: 'global', - }), - ).rejects.toMatchObject({ statusCode: 409 }) - }) - }) - - describe('installSkillFromUpload', () => { - it('posts FormData manifest and files', async () => { - fetchMock.mockResolvedValue( - new Response(JSON.stringify({ skill: { name: 'teach' }, overwritten: false, sourceType: 'upload', filesInstalled: ['teach/SKILL.md'] }), { status: 200 }), - ) - - const file = new File(['# Teach Skill'], 'SKILL.md', { type: 'text/markdown' }) - Object.defineProperty(file, 'webkitRelativePath', { value: 'teach/SKILL.md' }) - - const result = await settingsApi.installSkillFromUpload({ files: [file], scope: 'global' }) - - expect(result.sourceType).toBe('upload') - - const callUrl = fetchMock.mock.calls[0][0] - expect(callUrl).toEqual(expect.stringContaining('/api/settings/skills/install')) - - const callOptions = fetchMock.mock.calls[0][1] - expect(callOptions.method).toBe('POST') - expect(callOptions.headers?.hasOwnProperty).toBeFalsy() - - const formData = callOptions.body as FormData - expect(formData.get('sourceType')).toBe('upload') - expect(formData.get('file0')).toBe(file) - - const manifest = JSON.parse(formData.get('fileManifest') as string) - expect(manifest).toHaveLength(1) - expect(manifest[0].fieldName).toBe('file0') - expect(manifest[0].relativePath).toBe('teach/SKILL.md') - }) - }) -}) diff --git a/frontend/src/api/settings.ts b/frontend/src/api/settings.ts index 6515a31c..1a6a2f5c 100644 --- a/frontend/src/api/settings.ts +++ b/frontend/src/api/settings.ts @@ -11,8 +11,6 @@ import type { CreateSkillRequest, UpdateSkillRequest, SkillScope, - InstallSkillFromGithubRequest, - InstallSkillResponse, } from './types/settings' import { API_BASE_URL } from '@/config' import { fetchWrapper, FetchError } from './fetchWrapper' @@ -270,43 +268,6 @@ export const settingsApi = { method: 'DELETE', }) }, - - installSkillFromGithub: async (data: InstallSkillFromGithubRequest): Promise => { - return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), - }) - }, - - installSkillFromUpload: async (data: { - files: File[] - scope: SkillScope - repoId?: number - overwrite?: boolean - }): Promise => { - const formData = new FormData() - formData.append('sourceType', 'upload') - formData.append('scope', data.scope) - if (data.repoId !== undefined) formData.append('repoId', String(data.repoId)) - if (data.overwrite !== undefined) formData.append('overwrite', String(data.overwrite)) - - const fileManifest: Array<{ fieldName: string; relativePath: string }> = [] - - data.files.forEach((file, index) => { - const fieldName = `file${index}` - const relativePath = file.webkitRelativePath || file.name - fileManifest.push({ fieldName, relativePath }) - formData.append(fieldName, file) - }) - - formData.append('fileManifest', JSON.stringify(fileManifest)) - - return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, { - method: 'POST', - body: formData, - }) - }, } export interface VersionInfo { diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 72392bc5..b912b5c0 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -15,14 +15,10 @@ import { type CreateSkillRequest, type UpdateSkillRequest, type SkillScope, - type InstallSkillFromGithubRequest, - type InstallSkillUploadRequest, - type InstallSkillUploadManifestEntry, - type InstallSkillResponse, } from '@opencode-manager/shared' import type { NotificationPreferences } from '@opencode-manager/shared/types' -export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillUploadRequest, InstallSkillUploadManifestEntry, InstallSkillResponse } +export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } export interface CustomCommand { diff --git a/frontend/src/components/repo/RepoSkillsDialog.test.tsx b/frontend/src/components/repo/RepoSkillsDialog.test.tsx index fff7b5c6..c166e172 100644 --- a/frontend/src/components/repo/RepoSkillsDialog.test.tsx +++ b/frontend/src/components/repo/RepoSkillsDialog.test.tsx @@ -14,7 +14,6 @@ const mocks = vi.hoisted(() => ({ vi.mock('@/api/settings', () => ({ settingsApi: { listManagedSkills: mocks.listManagedSkills, - deleteSkill: vi.fn(), }, })) @@ -94,7 +93,7 @@ describe('RepoSkillsDialog', () => { ) await waitFor(() => { - expect(screen.getByText('test-skill')).toBeInTheDocument() + expect(screen.getByText('Test skill')).toBeInTheDocument() }) }) @@ -117,7 +116,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 () => { @@ -144,7 +143,7 @@ describe('RepoSkillsDialog', () => { await userEvent.click(projectTab) await waitFor(() => { - expect(screen.getByText('No skills found')).toBeInTheDocument() + expect(screen.getByText('No local skills found')).toBeInTheDocument() }) }) }) @@ -171,10 +170,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() }) @@ -191,10 +190,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() }) @@ -220,10 +219,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) @@ -255,10 +254,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(() => { diff --git a/frontend/src/components/repo/RepoSkillsDialog.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx index 7f07808a..06e70225 100644 --- a/frontend/src/components/repo/RepoSkillsDialog.tsx +++ b/frontend/src/components/repo/RepoSkillsDialog.tsx @@ -1,15 +1,11 @@ -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 { 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 { RepoSkillsList } from './RepoSkillsList' +import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' +import { useQuery } from '@tanstack/react-query' import { settingsApi } from '@/api/settings' import { useLoadSkill } from '@/hooks/useOpenCode' import type { SkillFileInfo } from '@opencode-manager/shared' -import { toast } from 'sonner' +import { useMemo, useState, useEffect } from 'react' type RepoSkillsDialogBaseProps = { open: boolean @@ -31,33 +27,36 @@ export function RepoSkillsDialog({ directory, onSkillLoaded, }: RepoSkillsDialogProps) { - const queryClient = useQueryClient() - const [installDialogOpen, setInstallDialogOpen] = useState(false) - const [deleteSkill, setDeleteSkill] = useState(null) - const skillsQueryKey = directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId] - const { isLoading, data, error } = useQuery({ - queryKey: skillsQueryKey, + queryKey: directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId], 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 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 [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 handleLoad = (skill: SkillFileInfo) => { loadSkill.mutate({ skillName: skill.name }) @@ -65,75 +64,46 @@ 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 ( - <> - - - -
-
- Skills - - {canLoad ? 'Search and load a skill into the current session' : 'Skills available for this repository'} - -
- -
-
-
- + + + Skills + + {canLoad ? 'Load a skill into the current session' : 'Skills available for this repository'} + + + + + Project + Global + + + -
-
-
- - - - !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} - /> - + + + + + + + ) } diff --git a/frontend/src/components/repo/RepoSkillsList.tsx b/frontend/src/components/repo/RepoSkillsList.tsx new file mode 100644 index 00000000..d0b4356b --- /dev/null +++ b/frontend/src/components/repo/RepoSkillsList.tsx @@ -0,0 +1,81 @@ +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 ( +
+ + Loading... +
+ ) + } + + if (error) { + return ( +
+ +

Failed to load skills

+

{error.message}

+
+ ) + } + + if (!data || data.length === 0) { + return ( +
+

{emptyTitle || 'No skills available'}

+

+ {emptyHint || + 'Skills will appear here when configured in the project\'s .opencode/skills/ directory'} +

+
+ ) + } + + return ( +
+
+ {data.map((skill) => ( +
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' : ''}`} + > +
+

+ {formatSkillName(skill.name)} +

+ {skill.description && ( +

+ {skill.description} +

+ )} +
+
+ ))} +
+
+ ) +} diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index d9ae1046..793934da 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,15 +941,25 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf

Skills

- {managedSkills.length} configured + {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
-
+
{ + 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) + }} />
@@ -977,7 +987,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
-
+
updateConfigContent(selectedConfig.name, content)} @@ -1016,7 +1026,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 2ef5a196..fba7d34b 100644 --- a/frontend/src/components/settings/OpenCodeModelDialog.tsx +++ b/frontend/src/components/settings/OpenCodeModelDialog.tsx @@ -335,8 +335,6 @@ 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 b67f2c16..d7eac1ec 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/SkillInstallDialog.tsx b/frontend/src/components/settings/SkillInstallDialog.tsx deleted file mode 100644 index 984e67ba..00000000 --- a/frontend/src/components/settings/SkillInstallDialog.tsx +++ /dev/null @@ -1,231 +0,0 @@ -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('global') - const [selectedRepoId, setSelectedRepoId] = useState(undefined) - const [files, setFiles] = useState([]) - const [overwrite, setOverwrite] = useState(false) - - useEffect(() => { - setOverwrite(false) - }, [url, files, sourceType, scope, selectedRepoId]) - - const { data: repos = [] } = useQuery({ - 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) => { - 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 ( -

- {files.length} file{files.length > 1 ? 's' : ''} selected (first: {relPath}) -

- ) - } - - return ( - - - - Install Skill - - -
-
- setSourceType(v as 'github' | 'upload')}> - - GitHub URL - Upload - - - -
- - setUrl(e.target.value)} - placeholder="Paste a GitHub skill URL" - /> -
-
- - -
- - -
-
- - } - onChange={handleFileChange} - /> -
- {selectedFileSummary()} -
-
- -
- - -
- - {scope === 'project' && ( -
- - -
- )} - - {overwrite && ( - - - A skill with this name already exists. Install again to overwrite the managed skill directory. - - - )} -
-
- - - - - -
-
- ) -} diff --git a/frontend/src/components/settings/SkillsEditor.test.tsx b/frontend/src/components/settings/SkillsEditor.test.tsx deleted file mode 100644 index 6eb47552..00000000 --- a/frontend/src/components/settings/SkillsEditor.test.tsx +++ /dev/null @@ -1,184 +0,0 @@ -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 }) => ( - {children} - ) -} - -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(, { 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(, { 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(, { 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(, { 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(, { - 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() - }) - }) -}) diff --git a/frontend/src/components/settings/SkillsEditor.tsx b/frontend/src/components/settings/SkillsEditor.tsx index 9f9ac519..eb5a0455 100644 --- a/frontend/src/components/settings/SkillsEditor.tsx +++ b/frontend/src/components/settings/SkillsEditor.tsx @@ -1,25 +1,102 @@ -import { useState } from 'react' +import { useState, useEffect } from 'react' import { useMutation, useQueryClient } from '@tanstack/react-query' -import { Plus, Download } from 'lucide-react' +import { Plus, Trash2, Pencil, ChevronDown, ChevronRight, Save, X } 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 { SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared' +import type { OpenCodeConfigInput, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared' import { toast } from 'sonner' interface SkillsEditorProps { + skills?: OpenCodeConfigInput['skills'] managedSkills?: SkillFileInfo[] + onChange?: (skills: OpenCodeConfigInput['skills']) => void } -export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { +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) { 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({ @@ -93,37 +170,204 @@ export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { } } + 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 Global + } + return ( + + Project{skill.repoName ? `: ${skill.repoName}` : ''} + + ) + } + return ( -
-
-
- - -
+
+
+ +
- + {collapsiblesOpen.managed && ( + <> + {managedSkills.length === 0 ? ( + + +
+

No skills created

+
+

+ Create your first skill to get started. +

+
+
+ ) : ( +
+
+ {managedSkills.map((skill) => ( + + +
+ {skill.name} +
+ {getScopeBadge(skill)} + + +
+
+
+ + {skill.description && ( +

{skill.description}

+ )} + {skill.body && ( +
+ {skill.body} +
+ )} +
+
+ ))} +
+
+ )} + + )} - queryClient.invalidateQueries({ queryKey: ['managed-skills'] })} - /> +
+
+ +
+ + {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 && ( +
+ + +
+ )} +
+ )} +
setDeleteSkill(null)} title="Delete Skill" - description="Delete this managed skill directory and bundled files? This action cannot be undone." + description="Are you sure you want to delete this skill? This action cannot be undone." itemName={deleteSkill?.name} isDeleting={deleteMutation.isPending} />
) } + diff --git a/frontend/src/components/skills/SkillLibraryList.tsx b/frontend/src/components/skills/SkillLibraryList.tsx deleted file mode 100644 index 44403323..00000000 --- a/frontend/src/components/skills/SkillLibraryList.tsx +++ /dev/null @@ -1,182 +0,0 @@ -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('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 ( -
-
-
- - setSearch(event.target.value)} - placeholder="Search skills..." - className="pl-9" - /> -
-
- - - -
-
- - {isLoading ? ( -
- - Loading... -
- ) : error ? ( -
- -

Failed to load skills

-

{error.message}

-
- ) : filteredSkills.length === 0 ? ( -
-

{emptyTitle || 'No skills available'}

-

{emptyHint || 'Create or install a skill to get started.'}

-
- ) : ( -
-
- {filteredSkills.map((skill) => ( -
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' : ''}`} - > -
-
-

{skill.name}

- - {getCompactScopeLabel(skill)} - - - {getScopeLabel(skill)} - -
- {skill.description && ( -

{skill.description}

- )} -
-
event.stopPropagation()}> - {primaryAction && ( - - )} - {rowActions.length > 0 && ( - - - - - - {rowActions.map((action) => ( - action.onClick(skill)} - className={action.destructive ? 'text-destructive focus:text-destructive' : undefined} - > - {action.label} - - ))} - - - )} -
-
- ))} -
-
- )} -
- ) -} diff --git a/shared/src/schemas/skills.ts b/shared/src/schemas/skills.ts index 9c3ac42d..20467c8c 100644 --- a/shared/src/schemas/skills.ts +++ b/shared/src/schemas/skills.ts @@ -43,36 +43,3 @@ export interface SkillFileInfo { repoId?: number repoName?: string } - -export const SkillInstallSourceSchema = z.enum(['github', 'upload']) -export type SkillInstallSource = z.infer - -export const InstallSkillFromGithubRequestSchema = z.object({ - sourceType: z.literal('github'), - url: z.string().url(), - scope: SkillScopeSchema, - repoId: z.number().optional(), - overwrite: z.boolean().optional(), -}) -export type InstallSkillFromGithubRequest = z.infer - -export const InstallSkillUploadManifestEntrySchema = z.object({ - fieldName: z.string().min(1), - relativePath: z.string().min(1), -}) -export type InstallSkillUploadManifestEntry = z.infer - -export const InstallSkillUploadRequestSchema = z.object({ - sourceType: z.literal('upload'), - scope: SkillScopeSchema, - repoId: z.number().optional(), - overwrite: z.boolean().optional(), -}) -export type InstallSkillUploadRequest = z.infer - -export interface InstallSkillResponse { - skill: SkillFileInfo - overwritten: boolean - sourceType: 'github' | 'upload' - filesInstalled: string[] -} diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 7fc5d5c5..836c2e65 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -127,11 +127,6 @@ export type { CreateSkillRequest, UpdateSkillRequest, SkillFileInfo, - SkillInstallSource, - InstallSkillFromGithubRequest, - InstallSkillUploadRequest, - InstallSkillUploadManifestEntry, - InstallSkillResponse, } from '../schemas/skills' export { SKILL_NAME_REGEX, @@ -140,8 +135,4 @@ export { SkillFrontmatterSchema, CreateSkillRequestSchema, UpdateSkillRequestSchema, - SkillInstallSourceSchema, - InstallSkillFromGithubRequestSchema, - InstallSkillUploadRequestSchema, - InstallSkillUploadManifestEntrySchema, } from '../schemas/skills'