From 1c87d33a5fe17d3fcf939cb92e6aa9786ba5d7be Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 17 Jun 2026 23:04:22 -0400 Subject: [PATCH] feat: refactor skill installer components and add github utility --- backend/src/routes/health.ts | 9 +- backend/src/routes/settings.ts | 182 +++++++----------- backend/src/services/skills.ts | 157 ++++++--------- backend/src/utils/git-auth.ts | 17 +- backend/src/utils/github.ts | 45 +++++ backend/test/services/skills.test.ts | 22 +-- frontend/src/api/types/settings.ts | 4 +- .../src/components/repo/RepoSkillsDialog.tsx | 36 +--- .../settings/SkillInstallDialog.tsx | 20 +- .../src/components/settings/SkillsEditor.tsx | 41 +--- .../components/skills/SkillLibraryList.tsx | 18 +- frontend/src/hooks/useDeleteSkill.ts | 36 ++++ frontend/src/lib/queryInvalidation.ts | 6 + shared/src/schemas/skills.ts | 3 - shared/src/types/index.ts | 2 - 15 files changed, 268 insertions(+), 330 deletions(-) create mode 100644 backend/src/utils/github.ts create mode 100644 frontend/src/hooks/useDeleteSkill.ts diff --git a/backend/src/routes/health.ts b/backend/src/routes/health.ts index 78f8caa1..5efa6aa3 100644 --- a/backend/src/routes/health.ts +++ b/backend/src/routes/health.ts @@ -4,6 +4,7 @@ import { readFile } from 'fs/promises' import { opencodeServerManager } from '../services/opencode-single-server' import type { OpenCodeSupervisor } from '../services/opencode-supervisor' import { compareVersions } from '../utils/version-utils' +import { githubFetch } from '../utils/github' const GITHUB_REPO_OWNER = 'chriswritescode-dev' const GITHUB_REPO_NAME = 'opencode-manager' @@ -24,14 +25,8 @@ async function fetchLatestRelease(): Promise { } try { - const response = await fetch( + const response = await githubFetch( `https://api.github.com/repos/${GITHUB_REPO_OWNER}/${GITHUB_REPO_NAME}/releases/latest`, - { - headers: { - 'Accept': 'application/vnd.github+json', - 'User-Agent': 'OpenCode-Manager' - } - } ) if (!response.ok) { diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 7c3d872b..61aca94e 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -21,6 +21,7 @@ import { InstallSkillFromGithubRequestSchema, InstallSkillUploadRequestSchema, InstallSkillUploadManifestEntrySchema, + type SkillScope, } from '@opencode-manager/shared' import { logger } from '../utils/logger' import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server' @@ -45,6 +46,7 @@ import { installSkillFromUploadedFiles, } from '../services/skills' import { getRepoById } from '../db/queries' +import { githubFetch } from '../utils/github' function getOpenCodeInstallMethod(): string { const homePath = process.env.HOME || '' @@ -98,6 +100,15 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise await opencodeServerManager.restart() } +async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise { + try { + await restartOpenCode(openCodeSupervisor) + logger.info(`Restarted OpenCode server after skill ${context}`) + } catch (restartError) { + logger.warn(`Failed to restart OpenCode server after skill ${context}:`, restartError) + } +} + async function dispatchSkillReload( db: Database, openCodeClient: OpenCodeClient, @@ -110,12 +121,7 @@ async function dispatchSkillReload( 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) - } + await restartOpenCodeSafe(openCodeSupervisor, 'install') try { await openCodeClient.forward({ @@ -129,6 +135,37 @@ async function dispatchSkillReload( } } +async function reloadAfterSkillInstall( + db: Database, + openCodeClient: OpenCodeClient, + openCodeSupervisor: OpenCodeSupervisor | undefined, + scope: SkillScope, + repoId: number | undefined, +): Promise { + if (scope === 'project' && repoId !== undefined) { + await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, repoId) + } else { + await restartOpenCodeSafe(openCodeSupervisor, 'install') + } +} + +const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray = [ + ['already exists', 409], + ['404', 404], + ['Invalid GitHub tree URL', 400], + ['Invalid skill name', 400], + ['Only one skill', 400], + ['Skill source must contain', 400], + ['Path must be relative', 400], + ['Path must not contain', 400], + ['escapes', 400], + ['no downloadable files', 400], + ['repoId is required', 400], + ['Missing upload file', 400], + ['Invalid repoId', 400], + ['not a valid file', 400], +] + function didConfigFieldChange( previous: Record | undefined, next: Record | undefined, @@ -905,11 +942,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic try { logger.info('Fetching available OpenCode versions from GitHub') - const response = await fetch('https://api.github.com/repos/sst/opencode/releases?per_page=20', { - headers: { - 'Accept': 'application/vnd.github.v3+json', - 'User-Agent': 'opencode-manager' - } + const response = await githubFetch('https://api.github.com/repos/sst/opencode/releases?per_page=20', { + accept: 'application/vnd.github.v3+json', }) if (!response.ok) { @@ -1172,11 +1206,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic app.get('/skills', async (c) => { try { - const repoIdParam = c.req.query('repoId') - const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined - if (repoId !== undefined && isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } + const repoId = parseOptionalRepoId(c.req.query('repoId')) const directory = c.req.query('directory') const skills = await listManagedSkills(db, openCodeClient, repoId, directory) @@ -1201,16 +1231,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic 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) - } - } + await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId) return c.json(result) } @@ -1274,16 +1295,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic 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) - } - } + await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId) return c.json(result) } @@ -1297,41 +1309,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic } 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) + const match = SKILL_INSTALL_ERROR_STATUS.find(([needle]) => error.message.includes(needle)) + if (match) { + return c.json({ error: error.message }, match[1]) } } @@ -1343,11 +1323,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic try { const name = c.req.param('name') const scope = SkillScopeSchema.parse(c.req.query('scope')) - const repoIdParam = c.req.query('repoId') - const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined - if (repoId !== undefined && isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } + const repoId = parseOptionalRepoId(c.req.query('repoId')) if (scope === 'project' && !repoId) { return c.json({ error: 'repoId is required for project scope' }, 400) @@ -1360,6 +1336,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic if (error instanceof z.ZodError) { return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400) } + if (error instanceof Error && error.message.includes('Invalid repoId')) { + return c.json({ error: error.message }, 400) + } if (error instanceof Error && error.message.includes('not found')) { return c.json({ error: error.message }, 404) } @@ -1376,14 +1355,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const validated = CreateSkillRequestSchema.parse(body) const skill = await createSkill(db, validated) - - try { - await restartOpenCode(openCodeSupervisor) - logger.info('Restarted OpenCode server after skill creation') - } catch (restartError) { - logger.warn('Failed to restart OpenCode server after skill creation:', restartError) - } - + + await restartOpenCodeSafe(openCodeSupervisor, 'creation') + return c.json(skill) } catch (error) { logger.error('Failed to create skill:', error) @@ -1401,11 +1375,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic try { const name = c.req.param('name') const scope = SkillScopeSchema.parse(c.req.query('scope')) - const repoIdParam = c.req.query('repoId') - const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined - if (repoId !== undefined && isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } + const repoId = parseOptionalRepoId(c.req.query('repoId')) const body = await c.req.json() const validated = UpdateSkillRequestSchema.parse(body) @@ -1414,20 +1384,18 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic } const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId) - - try { - await restartOpenCode(openCodeSupervisor) - logger.info('Restarted OpenCode server after skill update') - } catch (restartError) { - logger.warn('Failed to restart OpenCode server after skill update:', restartError) - } - + + await restartOpenCodeSafe(openCodeSupervisor, 'update') + return c.json(skill) } catch (error) { logger.error('Failed to update skill:', error) if (error instanceof z.ZodError) { return c.json({ error: 'Invalid request data', details: error.issues }, 400) } + if (error instanceof Error && error.message.includes('Invalid repoId')) { + return c.json({ error: error.message }, 400) + } if (error instanceof Error && error.message.includes('not found')) { return c.json({ error: error.message }, 404) } @@ -1442,31 +1410,25 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic try { const name = c.req.param('name') const scope = SkillScopeSchema.parse(c.req.query('scope')) - const repoIdParam = c.req.query('repoId') - const repoId = repoIdParam ? parseInt(repoIdParam, 10) : undefined - if (repoId !== undefined && isNaN(repoId)) { - return c.json({ error: 'Invalid repoId' }, 400) - } + const repoId = parseOptionalRepoId(c.req.query('repoId')) if (scope === 'project' && !repoId) { return c.json({ error: 'repoId is required for project scope' }, 400) } await deleteSkill(db, name, scope, repoId) - - try { - await restartOpenCode(openCodeSupervisor) - logger.info('Restarted OpenCode server after skill deletion') - } catch (restartError) { - logger.warn('Failed to restart OpenCode server after skill deletion:', restartError) - } - + + await restartOpenCodeSafe(openCodeSupervisor, 'deletion') + return c.json({ success: true }) } catch (error) { logger.error('Failed to delete skill:', error) if (error instanceof z.ZodError) { return c.json({ error: 'Invalid scope parameter. Must be "global" or "project"' }, 400) } + if (error instanceof Error && error.message.includes('Invalid repoId')) { + return c.json({ error: error.message }, 400) + } if (error instanceof Error && error.message.includes('not found')) { return c.json({ error: error.message }, 404) } diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index 998b46be..25a5f499 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -10,6 +10,7 @@ import type { Repo } from '@opencode-manager/shared/types' import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations' import type { OpenCodeClient } from './opencode/client' import { logger } from '../utils/logger' +import { githubFetchJson, githubFetchBinary, type GithubFetchFn } from '../utils/github' interface OpenCodeSkillInfo { name: string @@ -47,10 +48,7 @@ function getSkillTargetRoot(db: Database, scope: SkillScope, repoId?: number): s 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)) { + if (path.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) { throw new Error(`Path must be relative, got absolute path: "${relativePath}"`) } if (normalized === '' || normalized === '.') { @@ -203,8 +201,6 @@ export async function installSkillFromUploadedFiles( return installSkillFiles(db, input, files) } -type GithubFetchFn = (url: string | URL | Request, init?: RequestInit) => Promise - interface GithubTreeSource { owner: string repo: string @@ -217,7 +213,6 @@ interface GithubContentEntry { path: string type: 'file' | 'dir' download_url?: string | null - url: string } function parseGithubTreeUrl(url: string): GithubTreeSource { @@ -249,31 +244,6 @@ function parseGithubTreeUrl(url: string): GithubTreeSource { 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)}` @@ -284,14 +254,14 @@ async function fetchGithubSkillFiles( fetchFn: GithubFetchFn = fetch, ): Promise { const apiUrl = githubContentsApiUrl(source, source.path) - const data = await fetchGithubJson(fetchFn, apiUrl) + const data = await githubFetchJson(apiUrl, {}, fetchFn) 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 buffer = await githubFetchBinary(entry.download_url!, {}, fetchFn) const content = Buffer.from(buffer) if (content.length > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) { throw new Error('Skill files exceed maximum upload size') @@ -299,45 +269,41 @@ async function fetchGithubSkillFiles( 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})`) - } + async function collectFileEntries(entries: GithubContentEntry[]): Promise { + const fileEntries = entries.filter((entry) => entry.type === 'file' && entry.download_url) + const dirEntries = entries.filter((entry) => entry.type === 'dir') + const nested = await Promise.all( + dirEntries.map(async (dir) => { + const dirData = await githubFetchJson(githubContentsApiUrl(source, dir.path), {}, fetchFn) + return Array.isArray(dirData) ? collectFileEntries(dirData as GithubContentEntry[]) : [] + }), + ) + return [...fileEntries, ...nested.flat()] + } - 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 - } + const collected = await collectFileEntries(data as GithubContentEntry[]) - if (!entry.download_url) continue + if (collected.length > MAX_FILES) { + throw new Error(`Skill contains too many files (max ${MAX_FILES})`) + } + const files = await Promise.all( + collected.map(async (entry) => { const relativePath = entry.path.startsWith(source.path + '/') ? entry.path.substring(source.path.length + 1) : entry.path + const arrayBuffer = await githubFetchBinary(entry.download_url!, {}, fetchFn) + return { relativePath, content: Buffer.from(arrayBuffer) } + }), + ) - 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 }) - } + const totalBytes = files.reduce((sum, file) => sum + file.content.length, 0) + if (totalBytes > FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES) { + throw new Error('Skill files exceed maximum upload size') } - await walk(data as GithubContentEntry[]) - if (files.length === 0) { throw new Error('GitHub tree URL contains no downloadable files') } @@ -505,31 +471,33 @@ async function scanSkillRoot(root: string, scope: SkillScope, repo?: Repo): Prom return [] } - const skills: SkillFileInfo[] = [] - for (const entry of entries) { - if (!entry.isDirectory) continue + const scanned = await Promise.all( + entries + .filter((entry) => entry.isDirectory) + .map(async (entry): Promise => { + const skillPath = path.join(entry.path, 'SKILL.md') + if (!await fileExists(skillPath)) return null - const skillPath = path.join(entry.path, 'SKILL.md') - if (!await fileExists(skillPath)) continue + try { + const content = await readFileContent(skillPath) + const parsed = parseSkillMarkdown(content) + return { + 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 null + } + }), + ) - 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 + return scanned.filter((skill): skill is SkillFileInfo => skill !== null) } function addSkill(result: SkillFileInfo[], seenLocations: Set, skill: SkillFileInfo): void { @@ -560,10 +528,10 @@ export async function listManagedSkills( } const repo = allRepos.find(r => r.fullPath === directory) - const fallbackSkills = [ - ...await scanSkillRoot(globalPrefix, 'global'), - ...await scanSkillRoot(path.join(directory, '.opencode', 'skills'), 'project', repo), - ] + const fallbackSkills = (await Promise.all([ + scanSkillRoot(globalPrefix, 'global'), + scanSkillRoot(path.join(directory, '.opencode', 'skills'), 'project', repo), + ])).flat() for (const skill of fallbackSkills) { addSkill(result, seenLocations, skill) } @@ -590,12 +558,11 @@ export async function listManagedSkills( } } - const fallbackSkills = [ - ...await scanSkillRoot(globalPrefix, 'global'), - ...(await Promise.all( - targetRepos.map(repo => scanSkillRoot(getProjectSkillsPath(repo), 'project', repo)), - )).flat(), - ] + const [globalFallback, repoFallbacks] = await Promise.all([ + scanSkillRoot(globalPrefix, 'global'), + Promise.all(targetRepos.map(repo => scanSkillRoot(getProjectSkillsPath(repo), 'project', repo))), + ]) + const fallbackSkills = [...globalFallback, ...repoFallbacks.flat()] for (const skill of fallbackSkills) { addSkill(result, seenLocations, skill) } diff --git a/backend/src/utils/git-auth.ts b/backend/src/utils/git-auth.ts index d2132428..e39b3720 100644 --- a/backend/src/utils/git-auth.ts +++ b/backend/src/utils/git-auth.ts @@ -1,4 +1,5 @@ import type { GitCredential } from '@opencode-manager/shared' +import { githubFetch } from './github' export function isGitHubHttpsUrl(repoUrl: string): boolean { const url = normalizeGitCredentialUrl(repoUrl) @@ -202,20 +203,8 @@ export function createGitIdentityEnv(identity: GitIdentity): Record { try { const [userResponse, emailsResponse] = await Promise.all([ - fetch('https://api.github.com/user', { - headers: { - 'Authorization': `Bearer ${token}`, - 'Accept': 'application/vnd.github+json', - 'X-GitHub-Api-Version': '2022-11-28' - } - }), - fetch('https://api.github.com/user/emails', { - headers: { - 'Authorization': `Bearer ${token}`, - 'Accept': 'application/vnd.github+json', - 'X-GitHub-Api-Version': '2022-11-28' - } - }) + githubFetch('https://api.github.com/user', { token, apiVersion: '2022-11-28' }), + githubFetch('https://api.github.com/user/emails', { token, apiVersion: '2022-11-28' }), ]) if (!userResponse.ok) return null diff --git a/backend/src/utils/github.ts b/backend/src/utils/github.ts new file mode 100644 index 00000000..d69928e3 --- /dev/null +++ b/backend/src/utils/github.ts @@ -0,0 +1,45 @@ +export type GithubFetchFn = (url: string | URL | Request, init?: RequestInit) => Promise + +interface GithubRequestOptions { + token?: string + apiVersion?: string + accept?: string +} + +export function githubFetch( + url: string, + options: GithubRequestOptions = {}, + fetchFn: GithubFetchFn = fetch, +): Promise { + const headers: Record = { + Accept: options.accept ?? 'application/vnd.github+json', + 'User-Agent': 'opencode-manager', + } + if (options.token) headers.Authorization = `Bearer ${options.token}` + if (options.apiVersion) headers['X-GitHub-Api-Version'] = options.apiVersion + return fetchFn(url, { headers }) +} + +export async function githubFetchJson( + url: string, + options: GithubRequestOptions = {}, + fetchFn: GithubFetchFn = fetch, +): Promise { + const response = await githubFetch(url, options, fetchFn) + if (!response.ok) { + throw new Error(`GitHub request failed with status ${response.status}`) + } + return response.json() as Promise +} + +export async function githubFetchBinary( + url: string, + options: GithubRequestOptions = {}, + fetchFn: GithubFetchFn = fetch, +): Promise { + const response = await githubFetch(url, options, fetchFn) + if (!response.ok) { + throw new Error(`GitHub request failed with status ${response.status}`) + } + return response.arrayBuffer() +} diff --git a/backend/test/services/skills.test.ts b/backend/test/services/skills.test.ts index 2a2b1480..356f0a08 100644 --- a/backend/test/services/skills.test.ts +++ b/backend/test/services/skills.test.ts @@ -545,8 +545,8 @@ Another section.` 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') }, + { name: 'SKILL.md', path: 'skills/productivity/teach/SKILL.md', type: 'file', download_url: downloadUrl1 }, + { name: 'GLOSSARY-FORMAT.md', path: 'skills/productivity/teach/GLOSSARY-FORMAT.md', type: 'file', download_url: downloadUrl2 }, ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) } if (urlStr === downloadUrl1) { @@ -616,18 +616,18 @@ Another section.` 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' }, + { name: 'teach', path: 'skills/teach', type: 'dir', download_url: null }, + { name: 'review', path: 'skills/review', type: 'dir', download_url: null }, ]), { 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 }, + { name: 'SKILL.md', path: 'skills/teach/SKILL.md', type: 'file', download_url: 'https://raw.githubusercontent.com/user/repo/main/skills/teach/SKILL.md' }, ]), { 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 }, + { name: 'SKILL.md', path: 'skills/review/SKILL.md', type: 'file', download_url: 'https://raw.githubusercontent.com/user/repo/main/skills/review/SKILL.md' }, ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) } if (urlStr === 'https://raw.githubusercontent.com/user/repo/main/skills/teach/SKILL.md') { @@ -656,7 +656,7 @@ Another section.` 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 }, + { name: 'SKILL.md', path: 'my-skill/SKILL.md', type: 'file', download_url: downloadUrl }, ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) } if (urlStr === downloadUrl) { @@ -702,7 +702,7 @@ Another section.` 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 }, + { name: 'SKILL.md', path: 'huge-skill/SKILL.md', type: 'file', download_url: downloadUrl }, ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) } if (urlStr === downloadUrl) { @@ -728,7 +728,7 @@ Another section.` 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 }, + { name: 'SKILL.md', path: 'failing-skill/SKILL.md', type: 'file', download_url: downloadUrl }, ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) } if (urlStr === downloadUrl) { @@ -755,8 +755,8 @@ Another section.` 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 }, + { name: 'SKILL.md', path: 'skill-with-bundle/SKILL.md', type: 'file', download_url: skillUrl }, + { name: 'GLOSSARY-FORMAT.md', path: 'skill-with-bundle/GLOSSARY-FORMAT.md', type: 'file', download_url: bundleUrl }, ]), { status: 200, headers: { 'Content-Type': 'application/json' } })) } if (urlStr === skillUrl) { diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 72392bc5..6c7da6c8 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -16,13 +16,11 @@ import { 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, InstallSkillFromGithubRequest, InstallSkillResponse } 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.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx index 7f07808a..06d5a61b 100644 --- a/frontend/src/components/repo/RepoSkillsDialog.tsx +++ b/frontend/src/components/repo/RepoSkillsDialog.tsx @@ -1,5 +1,5 @@ import { useState } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { 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' @@ -8,8 +8,9 @@ import { SkillLibraryList } from '@/components/skills/SkillLibraryList' import { SkillInstallDialog } from '@/components/settings/SkillInstallDialog' import { settingsApi } from '@/api/settings' import { useLoadSkill } from '@/hooks/useOpenCode' +import { useDeleteSkill } from '@/hooks/useDeleteSkill' +import { invalidateSkillCaches } from '@/lib/queryInvalidation' import type { SkillFileInfo } from '@opencode-manager/shared' -import { toast } from 'sonner' type RepoSkillsDialogBaseProps = { open: boolean @@ -33,7 +34,7 @@ export function RepoSkillsDialog({ }: RepoSkillsDialogProps) { const queryClient = useQueryClient() const [installDialogOpen, setInstallDialogOpen] = useState(false) - const [deleteSkill, setDeleteSkill] = useState(null) + const { deleteSkill, setDeleteSkill, confirmDelete, isDeleting } = useDeleteSkill() const skillsQueryKey = directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId] const { isLoading, data, error } = useQuery({ @@ -46,39 +47,14 @@ export function RepoSkillsDialog({ 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 handleLoad = (skill: SkillFileInfo) => { loadSkill.mutate({ skillName: skill.name }) onSkillLoaded?.(skill) 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'] }) + invalidateSkillCaches(queryClient) } if (!repoId && !sessionId) { @@ -132,7 +108,7 @@ export function RepoSkillsDialog({ title="Delete Skill" description="Delete this managed skill directory and bundled files? This action cannot be undone." itemName={deleteSkill?.name} - isDeleting={deleteMutation.isPending} + isDeleting={isDeleting} /> ) diff --git a/frontend/src/components/settings/SkillInstallDialog.tsx b/frontend/src/components/settings/SkillInstallDialog.tsx index 984e67ba..76abea83 100644 --- a/frontend/src/components/settings/SkillInstallDialog.tsx +++ b/frontend/src/components/settings/SkillInstallDialog.tsx @@ -32,6 +32,14 @@ export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillIns setOverwrite(false) }, [url, files, sourceType, scope, selectedRepoId]) + const resetForm = () => { + setUrl('') + setScope('global') + setSelectedRepoId(undefined) + setFiles([]) + setOverwrite(false) + } + const { data: repos = [] } = useQuery({ queryKey: ['repos'], queryFn: listRepos, @@ -59,11 +67,7 @@ export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillIns }, onSuccess: () => { toast.success('Skill installed successfully') - setUrl('') - setScope('global') - setSelectedRepoId(undefined) - setFiles([]) - setOverwrite(false) + resetForm() onInstalled() onOpenChange(false) }, @@ -94,11 +98,7 @@ export function SkillInstallDialog({ open, onOpenChange, onInstalled }: SkillIns const handleOpenChange = (isOpen: boolean) => { if (!isOpen) { - setUrl('') - setScope('global') - setSelectedRepoId(undefined) - setFiles([]) - setOverwrite(false) + resetForm() } onOpenChange(isOpen) } diff --git a/frontend/src/components/settings/SkillsEditor.tsx b/frontend/src/components/settings/SkillsEditor.tsx index 9f9ac519..7df490e1 100644 --- a/frontend/src/components/settings/SkillsEditor.tsx +++ b/frontend/src/components/settings/SkillsEditor.tsx @@ -7,6 +7,8 @@ import { SkillInstallDialog } from './SkillInstallDialog' import { DeleteDialog } from '@/components/ui/delete-dialog' import { SkillLibraryList } from '@/components/skills/SkillLibraryList' import { settingsApi } from '@/api/settings' +import { useDeleteSkill } from '@/hooks/useDeleteSkill' +import { invalidateSkillCaches } from '@/lib/queryInvalidation' import type { SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared' import { toast } from 'sonner' @@ -18,14 +20,14 @@ export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { const [dialogOpen, setDialogOpen] = useState(false) const [installDialogOpen, setInstallDialogOpen] = useState(false) const [editingSkill, setEditingSkill] = useState(null) - const [deleteSkill, setDeleteSkill] = useState(null) + const { deleteSkill, setDeleteSkill, confirmDelete, isDeleting } = useDeleteSkill() const queryClient = useQueryClient() const createMutation = useMutation({ mutationFn: (data: CreateSkillRequest) => settingsApi.createSkill(data), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['managed-skills'] }) + invalidateSkillCaches(queryClient) toast.success('Skill created successfully') setDialogOpen(false) }, @@ -38,7 +40,7 @@ export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { mutationFn: ({ name, scope, repoId, ...data }: UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number }) => settingsApi.updateSkill(name, scope, data, repoId), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['managed-skills'] }) + invalidateSkillCaches(queryClient) toast.success('Skill updated successfully') setDialogOpen(false) setEditingSkill(null) @@ -48,38 +50,11 @@ export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { }, }) - const deleteMutation = useMutation({ - mutationFn: ({ name, scope, repoId }: { name: string; scope: SkillScope; repoId?: number }) => - settingsApi.deleteSkill(name, scope, repoId), - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['managed-skills'] }) - toast.success('Skill deleted successfully') - }, - onError: (error) => { - toast.error(error instanceof Error ? error.message : 'Failed to delete skill') - }, - }) - const handleEdit = (skill: SkillFileInfo) => { setEditingSkill(skill) setDialogOpen(true) } - const handleDelete = (skill: SkillFileInfo) => { - setDeleteSkill(skill) - } - - const confirmDelete = () => { - if (!deleteSkill) return - deleteMutation.mutate({ - name: deleteSkill.name, - scope: deleteSkill.scope, - repoId: deleteSkill.scope === 'project' ? deleteSkill.repoId : undefined, - }, { - onSettled: () => setDeleteSkill(null), - }) - } - const handleCreate = () => { setEditingSkill(null) setDialogOpen(true) @@ -113,7 +88,7 @@ export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { data={managedSkills} error={null} primaryAction={{ label: 'Edit', onClick: handleEdit }} - rowActions={[{ label: 'Delete', onClick: handleDelete, destructive: true }]} + rowActions={[{ label: 'Delete', onClick: setDeleteSkill, destructive: true }]} emptyTitle="No skills created" emptyHint="Create or install your first skill to get started." maxHeightClassName="max-h-[calc(100dvh-300px)] sm:max-h-[420px]" @@ -122,7 +97,7 @@ export function SkillsEditor({ managedSkills = [] }: SkillsEditorProps) { queryClient.invalidateQueries({ queryKey: ['managed-skills'] })} + onInstalled={() => invalidateSkillCaches(queryClient)} /> ) diff --git a/frontend/src/components/skills/SkillLibraryList.tsx b/frontend/src/components/skills/SkillLibraryList.tsx index 44403323..fd569b40 100644 --- a/frontend/src/components/skills/SkillLibraryList.tsx +++ b/frontend/src/components/skills/SkillLibraryList.tsx @@ -91,18 +91,12 @@ export function SkillLibraryList({ />
- - - + {(['all', 'project', 'global'] as const).map((key) => ( + + ))}
diff --git a/frontend/src/hooks/useDeleteSkill.ts b/frontend/src/hooks/useDeleteSkill.ts new file mode 100644 index 00000000..1c349aa7 --- /dev/null +++ b/frontend/src/hooks/useDeleteSkill.ts @@ -0,0 +1,36 @@ +import { useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { settingsApi } from '@/api/settings' +import { invalidateSkillCaches } from '@/lib/queryInvalidation' +import type { SkillFileInfo } from '@opencode-manager/shared' + +export function useDeleteSkill() { + const queryClient = useQueryClient() + const [deleteSkill, setDeleteSkill] = useState(null) + + const deleteMutation = useMutation({ + mutationFn: ({ name, scope, repoId }: { name: string; scope: SkillFileInfo['scope']; repoId?: number }) => + settingsApi.deleteSkill(name, scope, repoId), + onSuccess: () => { + invalidateSkillCaches(queryClient) + toast.success('Skill deleted successfully') + }, + onError: (error) => { + toast.error(error instanceof Error ? error.message : 'Failed to delete skill') + }, + }) + + const confirmDelete = () => { + if (!deleteSkill) return + deleteMutation.mutate({ + name: deleteSkill.name, + scope: deleteSkill.scope, + repoId: deleteSkill.scope === 'project' ? deleteSkill.repoId : undefined, + }, { + onSettled: () => setDeleteSkill(null), + }) + } + + return { deleteSkill, setDeleteSkill, confirmDelete, isDeleting: deleteMutation.isPending } +} diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index 7ae0cd8b..3e097d12 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -28,6 +28,12 @@ export function invalidateConfigCaches(queryClient: QueryClient) { invalidateProviderCaches(queryClient) } +export function invalidateSkillCaches(queryClient: QueryClient) { + queryClient.invalidateQueries({ queryKey: ['settings', 'skills'] }) + queryClient.invalidateQueries({ queryKey: ['managed-skills'] }) + queryClient.invalidateQueries({ queryKey: ['opencode-skills'] }) +} + export function invalidateSettingsCaches(queryClient: QueryClient, userId = 'default') { queryClient.invalidateQueries({ queryKey: ['settings', userId] }) invalidateConfigCaches(queryClient) diff --git a/shared/src/schemas/skills.ts b/shared/src/schemas/skills.ts index 9c3ac42d..4a5d6b3f 100644 --- a/shared/src/schemas/skills.ts +++ b/shared/src/schemas/skills.ts @@ -44,9 +44,6 @@ export interface SkillFileInfo { 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(), diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 7fc5d5c5..4d87df20 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -127,7 +127,6 @@ export type { CreateSkillRequest, UpdateSkillRequest, SkillFileInfo, - SkillInstallSource, InstallSkillFromGithubRequest, InstallSkillUploadRequest, InstallSkillUploadManifestEntry, @@ -140,7 +139,6 @@ export { SkillFrontmatterSchema, CreateSkillRequestSchema, UpdateSkillRequestSchema, - SkillInstallSourceSchema, InstallSkillFromGithubRequestSchema, InstallSkillUploadRequestSchema, InstallSkillUploadManifestEntrySchema,