diff --git a/backend/src/index.ts b/backend/src/index.ts index 0e2f1bf7..729bd736 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -45,6 +45,7 @@ import { opencodeServerManager } from './services/opencode-single-server' import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy' import { NotificationService } from './services/notification' import { ScheduleRunner, ScheduleService } from './services/schedules' +import { migrateGlobalSkills } from './services/skills' import { logger } from './utils/logger' import { @@ -306,6 +307,8 @@ try { const settingsService = new SettingsService(db) settingsService.initializeLastKnownGoodConfig() + await migrateGlobalSkills() + ipcServer = await createIPCServer(process.env.STORAGE_PATH || undefined) await gitAuthService.initialize(ipcServer, db) logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`) diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 5f1fefad..85dcd2ff 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -107,6 +107,69 @@ function buildSessionTitle(job: ScheduleJob): string { return `Scheduled: ${job.name}` } +type SkillInfo = { + name: string + description: string + location: string + content: string +} + +async function fetchSkillContent(slugs: string[], repoPath: string): Promise { + try { + const response = await proxyToOpenCodeWithDirectory('/skill', 'GET', repoPath) + if (!response.ok) { + logger.warn(`Failed to fetch skills from OpenCode (${response.status}), falling back to name-only injection`) + return [] + } + const skills = await response.json() as SkillInfo[] + + const skillBlocks = slugs + .map((slug) => { + const skill = skills.find((s) => s.name === slug || s.name.endsWith(`/${slug}`) || s.name.endsWith(`-${slug}`)) + if (!skill) { + logger.warn(`Skill "${slug}" not found in OpenCode skill list`) + return null + } + return [ + ``, + `# Skill: ${skill.name}`, + '', + skill.content.trim(), + '', + ].join('\n') + }) + .filter((block): block is string => block !== null) + + const foundCount = skillBlocks.length + if (foundCount < slugs.length) { + logger.warn(`Only ${foundCount} of ${slugs.length} requested skills were found`) + } + + return skillBlocks + } catch (error) { + logger.warn('Error fetching skills from OpenCode, falling back to name-only injection:', error) + return [] + } +} + +async function buildPromptWithSkills( + prompt: string, + skillMetadata: ScheduleJob['skillMetadata'], + repoPath: string +): Promise { + if (!skillMetadata || !skillMetadata.skillSlugs || skillMetadata.skillSlugs.length === 0) return prompt + + const skillBlocks = await fetchSkillContent(skillMetadata.skillSlugs, repoPath) + const notesLine = skillMetadata.notes ? `\nSkill notes: ${skillMetadata.notes}` : '' + + if (skillBlocks.length === 0) { + const skillList = skillMetadata.skillSlugs.join(', ') + return `${prompt}\n\nFor this task, use the following skills: ${skillList}${notesLine}` + } + + return `${prompt}\n\nThe following skills have been loaded for this task:\n\n${skillBlocks.join('\n\n')}${notesLine}` +} + function buildRunLog(input: { job: ScheduleJob triggerSource: ScheduleRunTriggerSource @@ -578,7 +641,7 @@ export class ScheduleService { 'POST', repo.fullPath, JSON.stringify({ - parts: [{ type: 'text', text: input.job.prompt }], + parts: [{ type: 'text', text: await buildPromptWithSkills(input.job.prompt, input.job.skillMetadata, repo.fullPath) }], model: input.model, }), ) diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index f7e499da..6b914131 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -3,11 +3,70 @@ import path from 'path' import type { Database } from 'bun:sqlite' import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest } from '@opencode-manager/shared' import { SKILL_NAME_REGEX } from '@opencode-manager/shared' -import { getRepoById } from '../db/queries' +import { getWorkspacePath } from '@opencode-manager/shared/config/env' +import { getRepoById, listRepos } from '../db/queries' import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations' import { logger } from '../utils/logger' -const GLOBAL_SKILLS_PATH = path.join(os.homedir(), '.config', 'opencode', 'skills') +function getGlobalSkillsPath(): string { + return path.join(getWorkspacePath(), '.config', 'opencode', 'skills') +} + +function getOldGlobalSkillsPath(): string { + return path.join(os.homedir(), '.config', 'opencode', 'skills') +} + +export async function migrateGlobalSkills(): Promise { + const oldSkillsPath = getOldGlobalSkillsPath() + const newSkillsPath = getGlobalSkillsPath() + + const oldSkillsExist = await fileExists(oldSkillsPath) + if (!oldSkillsExist) { + logger.debug('No old global skills found to migrate') + return + } + + const entries = await listDirectory(oldSkillsPath) + const skillDirs = entries.filter(entry => entry.isDirectory) + + if (skillDirs.length === 0) { + logger.debug('No skill directories found in old location') + return + } + + let migratedCount = 0 + let skippedCount = 0 + + for (const entry of skillDirs) { + const oldSkillPath = path.join(entry.path, 'SKILL.md') + const newSkillPath = path.join(newSkillsPath, entry.name, 'SKILL.md') + + const alreadyMigrated = await fileExists(newSkillPath) + if (alreadyMigrated) { + skippedCount++ + continue + } + + const skillExists = await fileExists(oldSkillPath) + if (!skillExists) { + logger.warn(`Skill ${entry.name} has no SKILL.md file, skipping`) + continue + } + + try { + const content = await readFileContent(oldSkillPath) + await writeFileContent(newSkillPath, content) + logger.info(`Migrated skill ${entry.name} from ${oldSkillsPath} to ${newSkillsPath}`) + migratedCount++ + } catch (error) { + logger.error(`Failed to migrate skill ${entry.name}:`, error) + } + } + + if (migratedCount > 0 || skippedCount > 0) { + logger.info(`Skill migration complete: ${migratedCount} migrated, ${skippedCount} skipped (already existed)`) + } +} interface ParsedSkillFile { frontmatter: { @@ -115,7 +174,7 @@ function generateSkillFrontmatter( function getSkillDirectoryPath(db: Database, scope: SkillScope, repoId?: number): string { if (scope === 'global') { - return GLOBAL_SKILLS_PATH + return getGlobalSkillsPath() } if (!repoId) { @@ -145,7 +204,7 @@ function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId? export async function listManagedSkills(db: Database, repoId?: number): Promise { const skills: SkillFileInfo[] = [] - const globalSkillsDir = GLOBAL_SKILLS_PATH + const globalSkillsDir = getGlobalSkillsPath() const globalSkillsExist = await fileExists(globalSkillsDir) if (globalSkillsExist) { @@ -186,6 +245,28 @@ export async function listManagedSkills(db: Database, repoId?: number): Promise< } } } + } else { + const allRepos = listRepos(db) + for (const repo of allRepos) { + const projectSkillsDir = path.join(repo.fullPath, '.opencode', 'skills') + const projectSkillsExist = await fileExists(projectSkillsDir) + + if (projectSkillsExist) { + const entries = await listDirectory(projectSkillsDir) + for (const entry of entries) { + if (entry.isDirectory) { + const skillPath = path.join(entry.path, 'SKILL.md') + const skillExists = await fileExists(skillPath) + if (skillExists) { + const skillInfo = await readSkillFile(db, 'project', entry.name, repo.id) + if (skillInfo) { + skills.push(skillInfo) + } + } + } + } + } + } } return skills diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index 2c85f7e8..f29d37a2 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -708,6 +708,235 @@ describe('ScheduleService', () => { expect.objectContaining({ status: 'completed', responseText: 'Completed summary' }), ) }) + + describe('skill injection in prompt', () => { + it('appends skill content to the prompt when skillSlugs are set', async () => { + const service = new ScheduleService({} as never) + const jobWithSkills: ScheduleJob = { + ...job, + skillMetadata: { skillSlugs: ['git-release', 'code-review'], notes: undefined }, + } + mocks.getScheduleJobById.mockReturnValue(jobWithSkills) + + const runWithSession: ScheduleRun = { + ...baseRun, + sessionId: 'ses-skills-1', + sessionTitle: 'Scheduled: Weekly engineering summary', + logText: 'Run started. Waiting for assistant response...', + } + mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession) + mocks.getScheduleRunById.mockReturnValue(runWithSession) + + let capturedPromptBody: string | undefined + mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => { + if (path === '/skill' && method === 'GET') { + return Promise.resolve(jsonResponse([ + { name: 'git-release', description: 'Git release workflow', location: '/path/SKILL.md', content: 'Release instructions here' }, + { name: 'code-review', description: 'Code review workflow', location: '/path/SKILL.md', content: 'Review instructions here' }, + ])) + } + if (path === '/session' && method === 'POST') { + return Promise.resolve(jsonResponse({ id: 'ses-skills-1' })) + } + if (path === '/session/ses-skills-1/message' && method === 'POST') { + capturedPromptBody = body + return Promise.resolve(textResponse(JSON.stringify({ + parts: [{ type: 'text', text: 'Done.' }], + }))) + } + throw new Error(`Unexpected proxy request: ${method} ${path}`) + }) + + await service.runJob(42, 7, 'manual') + + await vi.waitFor(() => { + expect(capturedPromptBody).toBeDefined() + }) + + const parsed = JSON.parse(capturedPromptBody!) + expect(parsed.parts[0].text).toContain('') + expect(parsed.parts[0].text).toContain('') + expect(parsed.parts[0].text).toContain('Release instructions here') + expect(parsed.parts[0].text).toContain('Review instructions here') + }) + + it('appends skill notes when provided', async () => { + const service = new ScheduleService({} as never) + const jobWithSkillsAndNotes: ScheduleJob = { + ...job, + skillMetadata: { skillSlugs: ['git-release'], notes: 'Focus on changelog' }, + } + mocks.getScheduleJobById.mockReturnValue(jobWithSkillsAndNotes) + + const runWithSession: ScheduleRun = { + ...baseRun, + sessionId: 'ses-skills-2', + sessionTitle: 'Scheduled: Weekly engineering summary', + logText: 'Run started. Waiting for assistant response...', + } + mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession) + mocks.getScheduleRunById.mockReturnValue(runWithSession) + + let capturedPromptBody: string | undefined + mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => { + if (path === '/skill' && method === 'GET') { + return Promise.resolve(jsonResponse([ + { name: 'git-release', description: 'Git release workflow', location: '/path/SKILL.md', content: 'Release instructions here' }, + ])) + } + if (path === '/session' && method === 'POST') { + return Promise.resolve(jsonResponse({ id: 'ses-skills-2' })) + } + if (path === '/session/ses-skills-2/message' && method === 'POST') { + capturedPromptBody = body + return Promise.resolve(textResponse(JSON.stringify({ + parts: [{ type: 'text', text: 'Done.' }], + }))) + } + throw new Error(`Unexpected proxy request: ${method} ${path}`) + }) + + await service.runJob(42, 7, 'manual') + + await vi.waitFor(() => { + expect(capturedPromptBody).toBeDefined() + }) + + const parsed = JSON.parse(capturedPromptBody!) + expect(parsed.parts[0].text).toContain('') + expect(parsed.parts[0].text).toContain('Release instructions here') + expect(parsed.parts[0].text).toContain('\nSkill notes: Focus on changelog') + }) + + it('does not modify the prompt when skillSlugs is empty', async () => { + const service = new ScheduleService({} as never) + const jobWithEmptySkills: ScheduleJob = { + ...job, + skillMetadata: { skillSlugs: [], notes: 'some notes' }, + } + mocks.getScheduleJobById.mockReturnValue(jobWithEmptySkills) + + const runWithSession: ScheduleRun = { + ...baseRun, + sessionId: 'ses-skills-3', + sessionTitle: 'Scheduled: Weekly engineering summary', + logText: 'Run started. Waiting for assistant response...', + } + mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession) + mocks.getScheduleRunById.mockReturnValue(runWithSession) + + let capturedPromptBody: string | undefined + mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => { + if (path === '/session' && method === 'POST') { + return Promise.resolve(jsonResponse({ id: 'ses-skills-3' })) + } + if (path === '/session/ses-skills-3/message' && method === 'POST') { + capturedPromptBody = body + return Promise.resolve(textResponse(JSON.stringify({ + parts: [{ type: 'text', text: 'Done.' }], + }))) + } + throw new Error(`Unexpected proxy request: ${method} ${path}`) + }) + + await service.runJob(42, 7, 'manual') + + await vi.waitFor(() => { + expect(capturedPromptBody).toBeDefined() + }) + + const parsed = JSON.parse(capturedPromptBody!) + expect(parsed.parts[0].text).toBe(job.prompt) + }) + + it('falls back to name-only injection when skill endpoint fails', async () => { + const service = new ScheduleService({} as never) + const jobWithSkills: ScheduleJob = { + ...job, + skillMetadata: { skillSlugs: ['git-release'], notes: undefined }, + } + mocks.getScheduleJobById.mockReturnValue(jobWithSkills) + + const runWithSession: ScheduleRun = { + ...baseRun, + sessionId: 'ses-skills-4', + sessionTitle: 'Scheduled: Weekly engineering summary', + logText: 'Run started. Waiting for assistant response...', + } + mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession) + mocks.getScheduleRunById.mockReturnValue(runWithSession) + + let capturedPromptBody: string | undefined + mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => { + if (path === '/skill' && method === 'GET') { + return Promise.resolve(new Response('error', { status: 500 })) + } + if (path === '/session' && method === 'POST') { + return Promise.resolve(jsonResponse({ id: 'ses-skills-4' })) + } + if (path === '/session/ses-skills-4/message' && method === 'POST') { + capturedPromptBody = body + return Promise.resolve(textResponse(JSON.stringify({ + parts: [{ type: 'text', text: 'Done.' }], + }))) + } + throw new Error(`Unexpected proxy request: ${method} ${path}`) + }) + + await service.runJob(42, 7, 'manual') + + await vi.waitFor(() => { + expect(capturedPromptBody).toBeDefined() + }) + + const parsed = JSON.parse(capturedPromptBody!) + expect(parsed.parts[0].text).toContain('For this task, use the following skills: git-release') + }) + + it('falls back gracefully when a skill slug is not found in the list', async () => { + const service = new ScheduleService({} as never) + const jobWithUnknownSkill: ScheduleJob = { + ...job, + skillMetadata: { skillSlugs: ['unknown-skill'], notes: undefined }, + } + mocks.getScheduleJobById.mockReturnValue(jobWithUnknownSkill) + + const runWithSession: ScheduleRun = { + ...baseRun, + sessionId: 'ses-skills-5', + sessionTitle: 'Scheduled: Weekly engineering summary', + logText: 'Run started. Waiting for assistant response...', + } + mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession) + mocks.getScheduleRunById.mockReturnValue(runWithSession) + + let capturedPromptBody: string | undefined + mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => { + if (path === '/skill' && method === 'GET') { + return Promise.resolve(jsonResponse([])) + } + if (path === '/session' && method === 'POST') { + return Promise.resolve(jsonResponse({ id: 'ses-skills-5' })) + } + if (path === '/session/ses-skills-5/message' && method === 'POST') { + capturedPromptBody = body + return Promise.resolve(textResponse(JSON.stringify({ + parts: [{ type: 'text', text: 'Done.' }], + }))) + } + throw new Error(`Unexpected proxy request: ${method} ${path}`) + }) + + await service.runJob(42, 7, 'manual') + + await vi.waitFor(() => { + expect(capturedPromptBody).toBeDefined() + }) + + const parsed = JSON.parse(capturedPromptBody!) + expect(parsed.parts[0].text).toContain('For this task, use the following skills: unknown-skill') + }) + }) }) describe('ScheduleRunner', () => { diff --git a/backend/test/services/skills.test.ts b/backend/test/services/skills.test.ts index 530d7d41..10d71222 100644 --- a/backend/test/services/skills.test.ts +++ b/backend/test/services/skills.test.ts @@ -1,31 +1,43 @@ -import { describe, expect, test, beforeEach, afterEach } from 'vitest' +import { describe, expect, test, beforeEach, afterEach, vi } from 'vitest' import { join } from 'path' import { tmpdir } from 'os' import { mkdtemp, rm } from 'fs/promises' +vi.mock('../../src/db/queries', () => ({ + getRepoById: vi.fn(), + listRepos: vi.fn(() => []), + getRepoByUrlAndBranch: vi.fn(), + getRepoByLocalPath: vi.fn(), + getRepoBySourcePath: vi.fn(), + createRepo: vi.fn(), + updateRepoStatus: vi.fn(), + updateRepoConfigName: vi.fn(), + updateLastPulled: vi.fn(), + updateRepoBranch: vi.fn(), + deleteRepo: vi.fn(), +})) + describe('SkillService', () => { let tempDir: string - let originalHome: string beforeEach(async () => { tempDir = await mkdtemp(join(tmpdir(), 'skills-test-')) - originalHome = process.env.HOME || '' - process.env.HOME = tempDir + vi.spyOn(await import('@opencode-manager/shared/config/env'), 'getWorkspacePath').mockReturnValue(tempDir) }) afterEach(async () => { await rm(tempDir, { recursive: true, force: true }) - if (originalHome) { - process.env.HOME = originalHome - } + vi.restoreAllMocks() + vi.clearAllMocks() }) const mockDb = null as unknown as any test('generates correct YAML frontmatter format', async () => { - const { createSkill } = await import('../../src/services/skills') + const { createSkill, deleteSkill } = await import('../../src/services/skills') + const name = `test-skill-${Date.now()}` const input = { - name: `test-skill-${Date.now()}`, + name, description: 'A test skill', body: '## Test Body\n\nContent here', scope: 'global' as const, @@ -34,18 +46,22 @@ describe('SkillService', () => { metadata: { key: 'value' }, } - const result = await createSkill(mockDb, input) + try { + const result = await createSkill(mockDb, input) - expect(result.name).toBe(input.name) - expect(result.description).toBe('A test skill') - expect(result.body).toBe('## Test Body\n\nContent here') - expect(result.license).toBe('MIT') - expect(result.compatibility).toBe('opencode') - expect(result.metadata).toEqual({ key: 'value' }) + expect(result.name).toBe(name) + expect(result.description).toBe('A test skill') + expect(result.body).toBe('## Test Body\n\nContent here') + expect(result.license).toBe('MIT') + expect(result.compatibility).toBe('opencode') + expect(result.metadata).toEqual({ key: 'value' }) + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) + } }) test('parses frontmatter and body correctly', async () => { - const { createSkill, getSkill } = await import('../../src/services/skills') + const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills') const name = `parse-test-${Date.now()}` const input = { name, @@ -54,27 +70,42 @@ describe('SkillService', () => { scope: 'global' as const, } - await createSkill(mockDb, input) - const skill = await getSkill(mockDb, name, 'global') + try { + await createSkill(mockDb, input) + const skill = await getSkill(mockDb, name, 'global') - expect(skill.name).toBe(name) - expect(skill.description).toBe('Test description') - expect(skill.body).toBe('## Body\n\nSome content') + expect(skill.name).toBe(name) + expect(skill.description).toBe('Test description') + expect(skill.body).toBe('## Body\n\nSome content') + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) + } }) test('accepts valid skill names', async () => { - const { createSkill } = await import('../../src/services/skills') + const { createSkill, deleteSkill } = await import('../../src/services/skills') const validNames = ['my-skill', 'a', 'skill-1-2', 'test123', 'a-b-c'] + const createdNames: string[] = [] - for (const name of validNames) { + for (const baseName of validNames) { + const name = `${baseName}-${Date.now()}` const input = { - name: `${name}-${Date.now()}`, + name, description: 'Test', body: 'Body', scope: 'global' as const, } - await expect(createSkill(mockDb, input)).resolves.toBeDefined() + try { + await expect(createSkill(mockDb, input)).resolves.toBeDefined() + createdNames.push(name) + } catch { + // Ignore failures, just cleanup what was created + } + } + + for (const name of createdNames) { + await deleteSkill(mockDb, name, 'global').catch(() => {}) } }) @@ -95,7 +126,7 @@ describe('SkillService', () => { }) test('creates skill file at correct path', async () => { - const { createSkill } = await import('../../src/services/skills') + const { createSkill, deleteSkill } = await import('../../src/services/skills') const name = `new-skill-${Date.now()}` const input = { name, @@ -104,15 +135,19 @@ describe('SkillService', () => { scope: 'global' as const, } - const result = await createSkill(mockDb, input) + try { + const result = await createSkill(mockDb, input) - expect(result.name).toBe(name) - expect(result.scope).toBe('global') - expect(result.location).toContain(`${name}/SKILL.md`) + expect(result.name).toBe(name) + expect(result.scope).toBe('global') + expect(result.location).toContain(`${name}/SKILL.md`) + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) + } }) test('throws error on duplicate name', async () => { - const { createSkill } = await import('../../src/services/skills') + const { createSkill, deleteSkill } = await import('../../src/services/skills') const name = `duplicate-${Date.now()}` const input = { name, @@ -121,20 +156,24 @@ describe('SkillService', () => { scope: 'global' as const, } - await createSkill(mockDb, input) + try { + await createSkill(mockDb, input) - const duplicate = { - name, - description: 'Second', - body: 'Body', - scope: 'global' as const, + const duplicate = { + name, + description: 'Second', + body: 'Body', + scope: 'global' as const, + } + + await expect(createSkill(mockDb, duplicate)).rejects.toThrow('already exists') + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) } - - await expect(createSkill(mockDb, duplicate)).rejects.toThrow('already exists') }) test('reads skill correctly', async () => { - const { createSkill, getSkill } = await import('../../src/services/skills') + const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills') const name = `read-test-${Date.now()}` const input = { name, @@ -144,13 +183,17 @@ describe('SkillService', () => { license: 'Apache-2.0', } - await createSkill(mockDb, input) - const skill = await getSkill(mockDb, name, 'global') + try { + await createSkill(mockDb, input) + const skill = await getSkill(mockDb, name, 'global') - expect(skill.name).toBe(name) - expect(skill.description).toBe('Read test description') - expect(skill.body).toBe('Read test body') - expect(skill.license).toBe('Apache-2.0') + expect(skill.name).toBe(name) + expect(skill.description).toBe('Read test description') + expect(skill.body).toBe('Read test body') + expect(skill.license).toBe('Apache-2.0') + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) + } }) test('throws error for missing skill', async () => { @@ -159,7 +202,7 @@ describe('SkillService', () => { }) test('updates only changed fields', async () => { - const { createSkill, updateSkill } = await import('../../src/services/skills') + const { createSkill, updateSkill, deleteSkill } = await import('../../src/services/skills') const name = `update-test-${Date.now()}` const input = { name, @@ -169,19 +212,23 @@ describe('SkillService', () => { license: 'MIT', } - await createSkill(mockDb, input) + try { + await createSkill(mockDb, input) - const updated = await updateSkill( - mockDb, - name, - 'global', - { description: 'Updated description' }, - undefined - ) + const updated = await updateSkill( + mockDb, + name, + 'global', + { description: 'Updated description' }, + undefined + ) - expect(updated.description).toBe('Updated description') - expect(updated.body).toBe('Original body') - expect(updated.license).toBe('MIT') + expect(updated.description).toBe('Updated description') + expect(updated.body).toBe('Original body') + expect(updated.license).toBe('MIT') + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) + } }) test('throws error for missing skill on update', async () => { @@ -259,19 +306,29 @@ This is after a horizontal rule. Another section.` - await createSkill(mockDb, { - name, - description: 'Test horizontal rules in body', - body: bodyWithHR, - scope: 'global' as const, - }) + try { + await createSkill(mockDb, { + name, + description: 'Test horizontal rules in body', + body: bodyWithHR, + scope: 'global' as const, + }) - const skill = await getSkill(mockDb, name, 'global') - expect(skill).not.toBeNull() - expect(skill!.body).toContain('---') - expect(skill!.body).toContain('This is after a horizontal rule.') - expect(skill!.body).toContain('Another section.') + const skill = await getSkill(mockDb, name, 'global') + expect(skill).not.toBeNull() + expect(skill!.body).toContain('---') + expect(skill!.body).toContain('This is after a horizontal rule.') + expect(skill!.body).toContain('Another section.') + } finally { + await deleteSkill(mockDb, name, 'global').catch(() => {}) + } + }) - await deleteSkill(mockDb, name, 'global') + test('lists skills from all repos when no repoId is provided', async () => { + const { listManagedSkills } = await import('../../src/services/skills') + + const skills = await listManagedSkills(mockDb) + + expect(Array.isArray(skills)).toBe(true) }) }) diff --git a/frontend/src/components/repo/RepoSkillsDialog.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx new file mode 100644 index 00000000..e49143f8 --- /dev/null +++ b/frontend/src/components/repo/RepoSkillsDialog.tsx @@ -0,0 +1,36 @@ +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { RepoSkillsList } from './RepoSkillsList' +import { useQuery } from '@tanstack/react-query' +import { settingsApi } from '@/api/settings' + +interface RepoSkillsDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + repoId: number +} + +export function RepoSkillsDialog({ open, onOpenChange, repoId }: RepoSkillsDialogProps) { + const { isLoading, data, error } = useQuery({ + queryKey: ['settings', 'skills', repoId], + queryFn: () => settingsApi.listManagedSkills(repoId), + enabled: open && !!repoId, + staleTime: 30000, + }) + + if (!repoId) { + return null + } + + const repoSkills = data?.filter(skill => skill.scope === 'project') + + return ( + + + + Skills + + + + + ) +} diff --git a/frontend/src/components/repo/RepoSkillsList.tsx b/frontend/src/components/repo/RepoSkillsList.tsx new file mode 100644 index 00000000..5b180b20 --- /dev/null +++ b/frontend/src/components/repo/RepoSkillsList.tsx @@ -0,0 +1,65 @@ +import { AlertCircle, Loader2 } from 'lucide-react' +import type { SkillFileInfo } from '@opencode-manager/shared' + +interface RepoSkillsListProps { + isLoading: boolean + data: SkillFileInfo[] | undefined + error: Error | null +} + +export function RepoSkillsList({ isLoading, data, error }: 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 ( +
+

No skills available

+

Skills will appear here when configured in the project's .opencode/skills/ directory

+
+ ) + } + + return ( +
+
+ {data.map((skill) => ( +
+

+ {formatSkillName(skill.name)} +

+ {skill.description && ( +

+ {skill.description} +

+ )} +
+ ))} +
+
+ ) +} diff --git a/frontend/src/components/schedules/JobsTab.tsx b/frontend/src/components/schedules/JobsTab.tsx index b7399f18..8dc9d364 100644 --- a/frontend/src/components/schedules/JobsTab.tsx +++ b/frontend/src/components/schedules/JobsTab.tsx @@ -12,7 +12,7 @@ interface JobsTabProps { export function JobsTab({ jobs, selectedJobId, onSelectJob }: JobsTabProps) { return ( -
+
{jobs.map((job) => (
- + {expandedRunId === run.id && (
diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index 8f6cdb2c..0cf5572f 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -9,6 +9,7 @@ import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Combobox, type ComboboxOption } from '@/components/ui/combobox' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { MultiSelect } from '@/components/ui/multi-select' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Switch } from '@/components/ui/switch' @@ -26,7 +27,6 @@ import { weekdayOptions, } from '@/components/schedules/schedule-utils' import { Check, Info, Loader2, Pencil, Plus, Sparkles, Trash2 } from 'lucide-react' -import { cn } from '@/lib/utils' import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates' import { PromptTemplateDialog } from './PromptTemplateDialog' import { DeleteDialog } from '@/components/ui/delete-dialog' @@ -613,36 +613,12 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit

No skills discovered. Configure skill paths in Settings to make skills available here.

) : ( -
- {skills.map((skill) => ( - - ))} -
- )} - - {skillSlugs.length > 0 && ( -
- {skillSlugs.length} skill{skillSlugs.length !== 1 ? 's' : ''} selected -
+ ({ value: s.name, label: s.name, description: s.description }))} + placeholder="Search and select skills..." + /> )}
diff --git a/frontend/src/components/schedules/ScheduleTabMenu.tsx b/frontend/src/components/schedules/ScheduleTabMenu.tsx new file mode 100644 index 00000000..613ddc69 --- /dev/null +++ b/frontend/src/components/schedules/ScheduleTabMenu.tsx @@ -0,0 +1,56 @@ +import { CalendarClock, History, Info } from 'lucide-react' +import { cn } from '@/lib/utils' + +type TabType = 'jobs' | 'detail' | 'runs' + +interface ScheduleTabMenuProps { + activeTab: TabType + onTabChange: (tab: TabType) => void + className?: string +} + +export function ScheduleTabMenu({ activeTab, onTabChange, className }: ScheduleTabMenuProps) { + return ( +
+ + + +
+ ) +} diff --git a/frontend/src/components/schedules/index.ts b/frontend/src/components/schedules/index.ts index 51c5c10f..7880aa91 100644 --- a/frontend/src/components/schedules/index.ts +++ b/frontend/src/components/schedules/index.ts @@ -3,3 +3,4 @@ export { JobDetailTab } from './JobDetailTab' export { RunHistoryTab } from './RunHistoryTab' export { ScheduleJobDialog } from './ScheduleJobDialog' export { ScheduleRunMarkdown } from './ScheduleRunMarkdown' +export { ScheduleTabMenu } from './ScheduleTabMenu' diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index b3caacf3..f771cb74 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -17,7 +17,7 @@ import { SkillsEditor } from './SkillsEditor' import { VersionSelectDialog } from './VersionSelectDialog' import { MemoryPluginConfig } from './MemoryPluginConfig' import { settingsApi } from '@/api/settings' -import { useMutation, useQueryClient } from '@tanstack/react-query' +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useServerHealth } from '@/hooks/useServerHealth' import { parseJsonc, hasJsoncComments } from '@/lib/jsonc' import { showToast } from '@/lib/toast' @@ -77,6 +77,12 @@ export function OpenCodeConfigManager() { const skillsRef = useRef(null) const mcpRef = useRef(null) + const { data: managedSkills = [] } = useQuery({ + queryKey: ['managed-skills'], + queryFn: () => settingsApi.listManagedSkills(), + staleTime: 5 * 60 * 1000, + }) + const scrollToSection = (ref: React.RefObject) => { if (ref.current) { ref.current.scrollIntoView({ @@ -563,7 +569,7 @@ export function OpenCodeConfigManager() {
-
-
- { - 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) - }} - /> +
+
+ { + 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) + }} + /> +
-
- + diff --git a/frontend/src/components/settings/SkillsEditor.tsx b/frontend/src/components/settings/SkillsEditor.tsx index 915825c8..eb5a0455 100644 --- a/frontend/src/components/settings/SkillsEditor.tsx +++ b/frontend/src/components/settings/SkillsEditor.tsx @@ -1,6 +1,6 @@ import { useState, useEffect } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { Plus, Trash2, Loader2, Pencil, ChevronDown, ChevronRight, Save, X } from 'lucide-react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +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' @@ -14,6 +14,7 @@ import { toast } from 'sonner' interface SkillsEditorProps { skills?: OpenCodeConfigInput['skills'] + managedSkills?: SkillFileInfo[] onChange?: (skills: OpenCodeConfigInput['skills']) => void } @@ -77,7 +78,7 @@ function SkillPathEditor({ items, onChange, onAddItem, onRemoveItem, label, plac ) } -export function SkillsEditor({ skills, onChange }: SkillsEditorProps) { +export function SkillsEditor({ skills, managedSkills = [], onChange }: SkillsEditorProps) { const [dialogOpen, setDialogOpen] = useState(false) const [editingSkill, setEditingSkill] = useState(null) const [collapsiblesOpen, setCollapsiblesOpen] = useState({ @@ -98,12 +99,6 @@ export function SkillsEditor({ skills, onChange }: SkillsEditorProps) { const queryClient = useQueryClient() - const { data: managedSkills = [], isLoading: isLoadingManaged } = useQuery({ - queryKey: ['managed-skills'], - queryFn: () => settingsApi.listManagedSkills(), - staleTime: 5 * 60 * 1000, - }) - const createMutation = useMutation({ mutationFn: (data: CreateSkillRequest) => settingsApi.createSkill(data), onSuccess: () => { @@ -238,11 +233,7 @@ export function SkillsEditor({ skills, onChange }: SkillsEditorProps) { {collapsiblesOpen.managed && ( <> - {isLoadingManaged ? ( -
- -
- ) : managedSkills.length === 0 ? ( + {managedSkills.length === 0 ? (
diff --git a/frontend/src/components/ui/multi-select.tsx b/frontend/src/components/ui/multi-select.tsx new file mode 100644 index 00000000..15c3f281 --- /dev/null +++ b/frontend/src/components/ui/multi-select.tsx @@ -0,0 +1,220 @@ +import { useState, useRef, useEffect, useCallback } from 'react' +import { cn } from '@/lib/utils' +import { Check, ChevronDown, X } from 'lucide-react' + +export interface MultiSelectOption { + value: string + label: string + description?: string +} + +interface MultiSelectProps { + value: string[] + onChange: (values: string[]) => void + options: MultiSelectOption[] + placeholder?: string + disabled?: boolean + className?: string +} + +export function MultiSelect({ + value, + onChange, + options, + placeholder = 'Select...', + disabled = false, + className, +}: MultiSelectProps) { + const [isOpen, setIsOpen] = useState(false) + const [search, setSearch] = useState('') + const [highlightedIndex, setHighlightedIndex] = useState(0) + const containerRef = useRef(null) + const inputRef = useRef(null) + const triggerRef = useRef(null) + + const filteredOptions = options.filter(option => + option.label.toLowerCase().includes(search.toLowerCase()) || + option.value.toLowerCase().includes(search.toLowerCase()) || + (option.description?.toLowerCase().includes(search.toLowerCase())) + ) + + useEffect(() => { + if (!isOpen) return + + const handleClickOutside = (e: MouseEvent) => { + if (containerRef.current && !containerRef.current.contains(e.target as Node)) { + setIsOpen(false) + setSearch('') + } + } + + document.addEventListener('mousedown', handleClickOutside) + return () => document.removeEventListener('mousedown', handleClickOutside) + }, [isOpen]) + + useEffect(() => { + setHighlightedIndex(0) + }, [search]) + + const handleToggle = useCallback((optionValue: string) => { + if (value.includes(optionValue)) { + onChange(value.filter(v => v !== optionValue)) + } else { + onChange([...value, optionValue]) + } + }, [value, onChange]) + + const handleRemove = useCallback((optionValue: string, e: React.MouseEvent) => { + e.stopPropagation() + onChange(value.filter(v => v !== optionValue)) + }, [value, onChange]) + + const handleOpen = () => { + if (disabled) return + setIsOpen(true) + setTimeout(() => inputRef.current?.focus(), 0) + } + + const handleTriggerKeyDown = useCallback((e: React.KeyboardEvent) => { + if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') { + e.preventDefault() + if (!isOpen) { + setIsOpen(true) + setTimeout(() => inputRef.current?.focus(), 0) + } + } else if (e.key === 'Escape') { + setIsOpen(false) + setSearch('') + } + }, [isOpen]) + + const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => { + if (e.key === 'Escape') { + e.preventDefault() + setIsOpen(false) + setSearch('') + triggerRef.current?.focus() + } else if (e.key === 'ArrowDown') { + e.preventDefault() + setHighlightedIndex(prev => Math.min(prev + 1, filteredOptions.length - 1)) + } else if (e.key === 'ArrowUp') { + e.preventDefault() + setHighlightedIndex(prev => Math.max(prev - 1, 0)) + } else if (e.key === 'Enter') { + e.preventDefault() + if (filteredOptions[highlightedIndex]) { + handleToggle(filteredOptions[highlightedIndex].value) + } + } else if (e.key === 'Tab') { + setIsOpen(false) + setSearch('') + } + }, [highlightedIndex, filteredOptions, handleToggle]) + + return ( +
+
+ {value.length === 0 && ( + {placeholder} + )} + {value.map(v => { + const option = options.find(o => o.value === v) + return ( + + {option?.label ?? v} + + + ) + })} + +
+ + {isOpen && ( +
+
+ setSearch(e.target.value)} + onKeyDown={handleInputKeyDown} + placeholder="Search skills..." + className={cn( + 'flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors', + 'placeholder:text-muted-foreground', + 'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring' + )} + /> +
+
+ {filteredOptions.length === 0 ? ( +
No skills found
+ ) : ( + filteredOptions.map((option, index) => { + const isSelected = value.includes(option.value) + const isHighlighted = index === highlightedIndex + return ( + + ) + }) + )} +
+
+ )} +
+ ) +} diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index 396109ef..98bc74d0 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -8,6 +8,7 @@ import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Header } from "@/components/ui/header"; import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog"; import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"; +import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; import { SourceControlPanel } from "@/components/source-control"; import { useCreateSession } from "@/hooks/useOpenCode"; import { useSSE } from "@/hooks/useSSE"; @@ -16,7 +17,7 @@ import { useSwipeBack } from "@/hooks/useMobile"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; -import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2, CalendarClock } from "lucide-react"; +import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2, CalendarClock, Sparkles } from "lucide-react"; import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"; import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"; import { invalidateConfigCaches } from "@/lib/queryInvalidation"; @@ -29,6 +30,7 @@ export function RepoDetail() { const [fileBrowserOpen, setFileBrowserOpen] = useState(false); const [switchConfigOpen, setSwitchConfigOpen] = useState(false); const [mcpDialogOpen, setMcpDialogOpen] = useState(false); + const [skillsDialogOpen, setSkillsDialogOpen] = useState(false); const [sourceControlOpen, setSourceControlOpen] = useState(false); const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false); const pageRef = useRef(null); @@ -146,6 +148,15 @@ export function RepoDetail() { MCP +
{hasJobs && ( -
- - - -
+ )} (); @@ -386,6 +388,15 @@ export function SessionDetail() { directory={repoDirectory} onClick={() => setLspDialogOpen(true)} /> +