mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat: add skill installer with install/uninstall and settings UI
This commit is contained in:
1 parent
3e617c2df8
commit
50546af8cb
12 files changed
+1889
-22
No files matched your search
@@ -0,0 +1,371 @@
|
||||
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<typeof vi.fn>
|
||||
const mockInstallFromUploadedFiles = installSkillFromUploadedFiles as ReturnType<typeof vi.fn>
|
||||
const mockDeleteSkill = deleteSkill as ReturnType<typeof vi.fn>
|
||||
const mockRestart = opencodeServerManager.restart as ReturnType<typeof vi.fn>
|
||||
|
||||
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<typeof createSettingsRoutes>
|
||||
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<string, unknown>
|
||||
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)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,17 @@ import { tmpdir } from 'os'
|
||||
import { mkdtemp, rm, readFile } from 'fs/promises'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@opencode-manager/shared/config/env')>()
|
||||
return {
|
||||
...actual,
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 500,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: vi.fn(),
|
||||
listRepos: vi.fn(() => []),
|
||||
@@ -348,4 +359,382 @@ 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')
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user