Update skills UI components for managed skills (#165)

* ralph: ralph-repo-level-skills-dialog-skillseditor-fix completed after 4 iterations

* Remove parent session notification and child session tracking from Ralph loops

Sending promptAsync to parent sessions on loop completion could resume
work in previously inactive sessions. Removed parentSessionId from
RalphState, child session tracking maps, and all related event handling.
Watchdog stall detection still works via the session status API.

* Migrate global skills to workspace path

* Add skill injection to scheduled job prompts

* Refactor schedules UI with MultiSelect and tab menu

* Update skills UI components for managed skills
This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-22 14:52:32 -04:00
1 parent 4bd0940ab9
commit c3cba72b51
22 files changed
+981 -337

No files matched your search

+3
View File
@@ -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}`)
+64 -1
View File
@@ -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<string[]> {
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_content name="${skill.name}">`,
`# Skill: ${skill.name}`,
'',
skill.content.trim(),
'</skill_content>',
].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<string> {
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,
}),
)
+85 -4
View File
@@ -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<void> {
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<SkillFileInfo[]> {
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
+229
View File
@@ -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('<skill_content name="git-release">')
expect(parsed.parts[0].text).toContain('<skill_content name="code-review">')
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('<skill_content name="git-release">')
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', () => {
+128 -71
View File
@@ -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)
})
})
@@ -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 (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0 shrink-0">
<DialogTitle>Skills</DialogTitle>
</DialogHeader>
<RepoSkillsList isLoading={isLoading} data={repoSkills} error={error} />
</DialogContent>
</Dialog>
)
}
@@ -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 (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-4 h-4 animate-spin text-blue-600 dark:text-blue-400" />
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
</div>
)
}
if (error) {
return (
<div className="text-center py-6 text-muted-foreground">
<AlertCircle className="w-10 h-10 mx-auto mb-3 opacity-50 text-red-500" />
<p className="text-sm">Failed to load skills</p>
<p className="text-xs mt-1">{error.message}</p>
</div>
)
}
if (!data || data.length === 0) {
return (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No skills available</p>
<p className="text-xs mt-1">Skills will appear here when configured in the project's .opencode/skills/ directory</p>
</div>
)
}
return (
<div className="flex-1 overflow-y-auto min-h-0 px-2 sm:px-4 py-2">
<div className="space-y-2">
{data.map((skill) => (
<div
key={skill.name}
className="p-2 rounded-lg border border-border bg-card"
>
<p className="text-sm font-medium truncate">
{formatSkillName(skill.name)}
</p>
{skill.description && (
<p className="text-xs text-muted-foreground truncate mt-0.5">
{skill.description}
</p>
)}
</div>
))}
</div>
</div>
)
}
@@ -12,7 +12,7 @@ interface JobsTabProps {
export function JobsTab({ jobs, selectedJobId, onSelectJob }: JobsTabProps) {
return (
<div className="h-full overflow-y-auto space-y-2 py-2">
<div className="h-full overflow-y-auto space-y-2 pt-2">
{jobs.map((job) => (
<button
key={job.id}
@@ -1,5 +1,5 @@
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
import { useEffect, useState } from 'react'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
@@ -111,11 +111,8 @@ export function RunHistoryTab({
onCancelRun,
cancelRunPending,
}: RunHistoryTabProps) {
const [expandedRunId, setExpandedRunId] = useState<number | null>(selectedRunId)
const [expandedRunId, setExpandedRunId] = useState<number | null>(null)
useEffect(() => {
setExpandedRunId(selectedRunId)
}, [selectedRunId])
function getRunStatusIcon(status: ScheduleRun['status']) {
if (status === 'completed') return <CheckCircle2 className="h-3.5 w-3.5 text-green-400" />
@@ -193,7 +190,7 @@ export function RunHistoryTab({
<p className="mt-0.5 truncate text-xs text-red-400/80">{run.errorText}</p>
)}
</div>
<ChevronDown className={`h-4 w-4 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${expandedRunId === run.id ? 'rotate-180' : ''}`} />
<ChevronDown className={`h-6 w-6 flex-shrink-0 text-muted-foreground transition-transform duration-200 self-start ${expandedRunId === run.id ? 'rotate-180' : ''}`} />
</button>
{expandedRunId === run.id && (
<div className="border-t border-border/60 flex flex-col" style={{ maxHeight: 'calc(100vh - 200px)' }}>
@@ -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
<p className="text-sm text-muted-foreground">No skills discovered. Configure skill paths in Settings to make skills available here.</p>
</div>
) : (
<div className="flex flex-wrap gap-2">
{skills.map((skill) => (
<button
key={skill.name}
type="button"
onClick={() => {
setSkillSlugs(prev =>
prev.includes(skill.name)
? prev.filter(s => s !== skill.name)
: [...prev, skill.name]
)
}}
className={cn(
'inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
skillSlugs.includes(skill.name)
? 'border-primary bg-primary/10 text-primary'
: 'border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground'
)}
>
{skillSlugs.includes(skill.name) && <Check className="h-3 w-3" />}
{skill.name}
</button>
))}
</div>
)}
{skillSlugs.length > 0 && (
<div className="text-xs text-muted-foreground">
{skillSlugs.length} skill{skillSlugs.length !== 1 ? 's' : ''} selected
</div>
<MultiSelect
value={skillSlugs}
onChange={setSkillSlugs}
options={skills.map(s => ({ value: s.name, label: s.name, description: s.description }))}
placeholder="Search and select skills..."
/>
)}
<div className="space-y-2">
@@ -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 (
<div className={cn('flex border-t border-border bg-card/80 backdrop-blur-sm pb-1', className)}>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-0.5 pt-2.5 pb-2 pb-safe text-xs font-medium transition-colors',
activeTab === 'jobs'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => onTabChange('jobs')}
>
<CalendarClock className="h-4 w-4" />
<span>Jobs</span>
</button>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-0.5 pt-2.5 pb-2 pb-safe text-xs font-medium transition-colors',
activeTab === 'detail'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => onTabChange('detail')}
>
<Info className="h-4 w-4" />
<span>Detail</span>
</button>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-0.5 pt-1.5 py-2 pb-safe text-xs font-medium transition-colors',
activeTab === 'runs'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => onTabChange('runs')}
>
<History className="h-4 w-4" />
<span>Run History</span>
</button>
</div>
)
}
@@ -3,3 +3,4 @@ export { JobDetailTab } from './JobDetailTab'
export { RunHistoryTab } from './RunHistoryTab'
export { ScheduleJobDialog } from './ScheduleJobDialog'
export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
export { ScheduleTabMenu } from './ScheduleTabMenu'
@@ -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<HTMLButtonElement>(null)
const mcpRef = useRef<HTMLButtonElement>(null)
const { data: managedSkills = [] } = useQuery({
queryKey: ['managed-skills'],
queryFn: () => settingsApi.listManagedSkills(),
staleTime: 5 * 60 * 1000,
})
const scrollToSection = (ref: React.RefObject<HTMLButtonElement | null>) => {
if (ref.current) {
ref.current.scrollIntoView({
@@ -563,7 +569,7 @@ export function OpenCodeConfigManager() {
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0 mb-6">
<button
ref={agentsMdRef}
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agentsMd ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
onClick={() => {
const isExpanding = !expandedSections.agentsMd
setExpandedSections(prev => ({ ...prev, agentsMd: isExpanding }))
@@ -620,7 +626,7 @@ export function OpenCodeConfigManager() {
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
<button
ref={commandsRef}
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.commands ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
onClick={() => {
const isExpanding = !expandedSections.commands
setExpandedSections(prev => ({ ...prev, commands: isExpanding }))
@@ -657,7 +663,7 @@ export function OpenCodeConfigManager() {
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
<button
ref={agentsRef}
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.agents ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
onClick={() => {
const isExpanding = !expandedSections.agents
setExpandedSections(prev => ({ ...prev, agents: isExpanding }))
@@ -694,7 +700,7 @@ export function OpenCodeConfigManager() {
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
<button
ref={skillsRef}
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.skills ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
onClick={() => {
const isExpanding = !expandedSections.skills
setExpandedSections(prev => ({ ...prev, skills: isExpanding }))
@@ -706,33 +712,34 @@ export function OpenCodeConfigManager() {
<div className="flex items-center gap-3 min-w-0">
<h4 className="text-sm font-medium truncate">Skills</h4>
<span className="text-xs text-muted-foreground">
{(selectedConfig.content?.skills?.paths?.length ?? 0) + (selectedConfig.content?.skills?.urls?.length ?? 0)} configured
{managedSkills.length + (selectedConfig.content?.skills?.paths?.length ?? 0) + (selectedConfig.content?.skills?.urls?.length ?? 0)} configured
</span>
</div>
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
</button>
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<SkillsEditor
skills={selectedConfig.content?.skills}
onChange={(skills) => {
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)
}}
/>
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<SkillsEditor
skills={selectedConfig.content?.skills}
managedSkills={managedSkills}
onChange={(skills) => {
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)
}}
/>
</div>
</div>
</div>
</div>
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
<button
ref={mcpRef}
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.mcp ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
onClick={() => {
const isExpanding = !expandedSections.mcp
setExpandedSections(prev => ({ ...prev, mcp: isExpanding }))
@@ -115,7 +115,7 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6">
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
<DialogHeader className="p-4 sm:p-6 border-b flex flex-row items-center justify-between space-y-0">
<DialogTitle>{editingSkill ? 'Edit Skill' : 'Create Skill'}</DialogTitle>
</DialogHeader>
@@ -270,7 +270,7 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil
</Form>
</div>
<DialogFooter className="p-3 sm:p-4 border-t gap-2 pb-4">
<DialogFooter className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end pb-4 p-3">
<Button variant="outline" onClick={() => handleOpenChange(false)} className="flex-1 sm:flex-none">
Cancel
</Button>
@@ -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<SkillFileInfo | null>(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 ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : managedSkills.length === 0 ? (
{managedSkills.length === 0 ? (
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-2 mb-2">
+220
View File
@@ -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<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const triggerRef = useRef<HTMLDivElement>(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 (
<div ref={containerRef} className={cn('relative', className)}>
<div
ref={triggerRef}
role="combobox"
aria-expanded={isOpen}
aria-haspopup="listbox"
aria-activedescendant={isOpen ? `option-${highlightedIndex}` : undefined}
tabIndex={disabled ? -1 : 0}
onClick={handleOpen}
onKeyDown={handleTriggerKeyDown}
className={cn(
'flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-3 py-1.5 text-sm shadow-sm transition-colors cursor-pointer',
'focus-within:outline-none focus-within:ring-1 focus-within:ring-ring',
disabled && 'cursor-not-allowed opacity-50',
value.length === 0 && 'pr-8'
)}
>
{value.length === 0 && (
<span className="text-muted-foreground text-sm">{placeholder}</span>
)}
{value.map(v => {
const option = options.find(o => o.value === v)
return (
<span
key={v}
className="inline-flex items-center gap-1 rounded-full border border-border bg-muted px-2 py-0.5 text-xs font-medium"
>
{option?.label ?? v}
<button
type="button"
onClick={(e) => handleRemove(v, e)}
disabled={disabled}
className="text-muted-foreground hover:text-foreground disabled:pointer-events-none"
aria-label={`Remove ${option?.label ?? v}`}
>
<X className="h-3 w-3" />
</button>
</span>
)
})}
<ChevronDown className={cn(
'ml-auto h-4 w-4 shrink-0 text-muted-foreground transition-transform',
isOpen && 'rotate-180'
)} />
</div>
{isOpen && (
<div className="absolute z-[150] mt-1 w-full bg-popover border border-border rounded-md shadow-lg">
<div className="p-2 border-b border-border">
<input
ref={inputRef}
type="text"
value={search}
onChange={e => 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'
)}
/>
</div>
<div className="max-h-52 overflow-y-auto" role="listbox">
{filteredOptions.length === 0 ? (
<div className="px-3 py-4 text-center text-sm text-muted-foreground">No skills found</div>
) : (
filteredOptions.map((option, index) => {
const isSelected = value.includes(option.value)
const isHighlighted = index === highlightedIndex
return (
<button
key={option.value}
id={`option-${index}`}
type="button"
role="option"
aria-selected={isSelected}
onClick={() => handleToggle(option.value)}
className={cn(
'flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors hover:bg-muted',
isSelected && 'bg-primary/5',
isHighlighted && 'bg-accent'
)}
>
<div className={cn(
'flex h-4 w-4 shrink-0 items-center justify-center rounded border',
isSelected ? 'border-primary bg-primary text-primary-foreground' : 'border-border'
)}>
{isSelected && <Check className="h-3 w-3" />}
</div>
<div className="min-w-0 flex-1">
<div className="font-medium truncate">{option.label}</div>
{option.description && (
<div className="text-xs text-muted-foreground truncate">{option.description}</div>
)}
</div>
</button>
)
})
)}
</div>
</div>
)}
</div>
)
}
+21 -1
View File
@@ -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<HTMLDivElement>(null);
@@ -146,6 +148,15 @@ export function RepoDetail() {
<Plug className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">MCP</span>
</Button>
<Button
variant="outline"
onClick={() => setSkillsDialogOpen(true)}
size="sm"
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<Sparkles className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Skills</span>
</Button>
<Button
variant="outline"
onClick={() => setSourceControlOpen(true)}
@@ -205,6 +216,9 @@ export function RepoDetail() {
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
<Plug className="w-4 h-4 mr-2" /> MCP
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setSkillsDialogOpen(true)}>
<Sparkles className="w-4 h-4 mr-2" /> Skills
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
</DropdownMenuItem>
@@ -251,6 +265,12 @@ export function RepoDetail() {
directory={repoDirectory}
/>
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
/>
<SourceControlPanel
repoId={repoId}
isOpen={sourceControlOpen}
+3 -44
View File
@@ -14,8 +14,7 @@ import {
useRunRepoSchedule,
useUpdateRepoSchedule,
} from '@/hooks/useSchedules'
import { ScheduleJobDialog } from '@/components/schedules/ScheduleJobDialog'
import { JobsTab, JobDetailTab, RunHistoryTab } from '@/components/schedules'
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
@@ -23,7 +22,7 @@ import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { getRepoDisplayName, cn } from '@/lib/utils'
import { CalendarClock, History, Info, Loader2, Plus } from 'lucide-react'
import { CalendarClock, Loader2, Plus } from 'lucide-react'
export function Schedules() {
const { id } = useParams<{ id: string }>()
@@ -270,47 +269,7 @@ export function Schedules() {
</div>
{hasJobs && (
<div className="flex border-t border-border bg-card/80 backdrop-blur-sm pb-[env(safe-area-inset-bottom)]">
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
activeTab === 'jobs'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => setActiveTab('jobs')}
>
<CalendarClock className="h-5 w-5" />
<span>Jobs</span>
</button>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
activeTab === 'detail'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => setActiveTab('detail')}
>
<Info className="h-5 w-5" />
<span>Detail</span>
</button>
<button
type="button"
className={cn(
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
activeTab === 'runs'
? 'bg-primary/10 text-primary'
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
)}
onClick={() => setActiveTab('runs')}
>
<History className="h-5 w-5" />
<span>Run History</span>
</button>
</div>
<ScheduleTabMenu activeTab={activeTab} onTabChange={setActiveTab} />
)}
<ScheduleJobDialog
+21 -1
View File
@@ -5,7 +5,7 @@ import { getRepo } from "@/api/repos";
import { MessageThread } from "@/components/message/MessageThread";
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
import { X, FolderOpen, Plug, Settings, CornerUpLeft, GitCommitHorizontal, Brain, ShieldOff, Code } from "lucide-react";
import { X, FolderOpen, Plug, Settings, CornerUpLeft, GitCommitHorizontal, Brain, ShieldOff, Code, Sparkles } from "lucide-react";
import { ModelSelectDialog } from "@/components/model/ModelSelectDialog";
import { Header } from "@/components/ui/header";
import { SessionList } from "@/components/session/SessionList";
@@ -37,6 +37,7 @@ import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
import { LspStatusButton } from "@/components/repo/LspStatusButton";
import { RepoLspDialog } from "@/components/repo/RepoLspDialog";
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
import { createOpenCodeClient } from "@/api/opencode";
import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore";
import { useQuestions } from "@/contexts/EventContext";
@@ -66,6 +67,7 @@ export function SessionDetail() {
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
const [lspDialogOpen, setLspDialogOpen] = useState(false);
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
const [skillsDialogOpen, setSkillsDialogOpen] = useState(false);
const [sourceControlOpen, setSourceControlOpen] = useState(false);
const [resetPermissionsOpen, setResetPermissionsOpen] = useState(false);
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
@@ -386,6 +388,15 @@ export function SessionDetail() {
directory={repoDirectory}
onClick={() => setLspDialogOpen(true)}
/>
<Button
variant="outline"
size="sm"
onClick={() => setSkillsDialogOpen(true)}
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
>
<Sparkles className="w-4 h-4 sm:mr-2" />
<span className="hidden sm:inline">Skills</span>
</Button>
<Button
variant="outline"
size="sm"
@@ -441,6 +452,9 @@ export function SessionDetail() {
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
<Plug className="w-4 h-4 mr-2" /> MCP
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setSkillsDialogOpen(true)}>
<Sparkles className="w-4 h-4 mr-2" /> Skills
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLspDialogOpen(true)}>
<Code className="w-4 h-4 mr-2" /> LSP
</DropdownMenuItem>
@@ -576,6 +590,12 @@ export function SessionDetail() {
directory={repoDirectory}
/>
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
/>
<RepoMcpDialog
open={mcpDialogOpen}
onOpenChange={setMcpDialogOpen}
+2 -128
View File
@@ -28,7 +28,6 @@ export function createRalphEventHandler(
const lastActivityTime = new Map<string, number>()
const stallWatchdogs = new Map<string, NodeJS.Timeout>()
const consecutiveStalls = new Map<string, number>()
const childSessions = new Map<string, Set<string>>()
async function commitAndCleanupWorktree(state: RalphState): Promise<{ committed: boolean; cleaned: boolean }> {
if (state.inPlace) {
logger.log(`Ralph: in-place mode, skipping commit and cleanup`)
@@ -81,19 +80,6 @@ export function createRalphEventHandler(
return { committed, cleaned }
}
function findRalphParent(childSessionId: string): string | undefined {
for (const [ralphId, children] of childSessions.entries()) {
if (children.has(childSessionId)) {
return ralphId
}
}
return undefined
}
function recordActivity(sessionId: string): void {
lastActivityTime.set(sessionId, Date.now())
}
function stopWatchdog(sessionId: string): void {
const interval = stallWatchdogs.get(sessionId)
if (interval) {
@@ -102,7 +88,6 @@ export function createRalphEventHandler(
}
lastActivityTime.delete(sessionId)
consecutiveStalls.delete(sessionId)
childSessions.delete(sessionId)
}
function startWatchdog(sessionId: string): void {
@@ -129,11 +114,8 @@ export function createRalphEventHandler(
const statusResult = await v2Client.session.status()
const statuses = (statusResult.data ?? {}) as Record<string, { type: string }>
const sessionIds = [sessionId, ...(childSessions.get(sessionId) ?? [])]
const hasActiveWork = sessionIds.some(id => {
const status = statuses[id]?.type
return status === 'busy' || status === 'retry' || status === 'compact'
})
const status = statuses[sessionId]?.type
const hasActiveWork = status === 'busy' || status === 'retry' || status === 'compact'
if (hasActiveWork) {
lastActivityTime.set(sessionId, Date.now())
@@ -182,19 +164,6 @@ export function createRalphEventHandler(
}
async function terminateLoop(sessionId: string, state: RalphState, reason: string): Promise<void> {
const children = childSessions.get(sessionId)
if (children) {
await Promise.all(
Array.from(children).map(async (childId) => {
try {
await v2Client.session.abort({ sessionID: childId })
} catch {
// Child session may already be idle
}
})
)
}
stopWatchdog(sessionId)
const retryTimeout = retryTimeouts.get(sessionId)
@@ -222,49 +191,6 @@ export function createRalphEventHandler(
if (reason === 'completed') {
commitResult = await commitAndCleanupWorktree(state)
}
if (state.parentSessionId) {
try {
let notificationText: string
if (state.inPlace) {
if (reason === 'completed') {
notificationText = [
`Ralph loop "${state.worktreeName}" completed (in-place).`,
'',
`Iteration: ${state.iteration}`,
`Changes are in the current directory on branch: ${state.worktreeBranch}`,
].join('\n')
} else {
notificationText = `Ralph loop "${state.worktreeName}" terminated (in-place).\n\nReason: ${reason}\nIteration: ${state.iteration}\nDirectory: ${state.worktreeDir}\nBranch: ${state.worktreeBranch}`
}
} else if (reason === 'completed' && commitResult) {
const parts = [`Ralph loop "${state.worktreeName}" completed.`, '', `Iteration: ${state.iteration}`]
if (commitResult.committed) {
parts.push(`Changes committed on branch: ${state.worktreeBranch}`)
}
if (commitResult.cleaned) {
parts.push(`Worktree removed. Use \`git merge ${state.worktreeBranch}\` or \`git checkout ${state.worktreeBranch}\` to access the changes.`)
} else {
parts.push(`Worktree: ${state.worktreeDir}`)
}
notificationText = parts.join('\n')
} else {
notificationText = `Ralph loop "${state.worktreeName}" terminated.\n\nReason: ${reason}\nIteration: ${state.iteration}\nWorktree: ${state.worktreeDir}\nBranch: ${state.worktreeBranch}`
}
await client.session.promptAsync({
path: { id: state.parentSessionId },
body: {
parts: [{
type: 'text' as const,
text: notificationText,
}],
},
})
} catch (err) {
logger.error(`Ralph: failed to notify parent session`, err)
}
}
}
async function handlePromptError(sessionId: string, state: RalphState, context: string, err: unknown, retryFn?: () => Promise<void>): Promise<void> {
@@ -580,35 +506,6 @@ export function createRalphEventHandler(
return
}
if (event.type === 'session.created' || event.type === 'session.updated') {
const info = event.properties?.info as { id?: string; parentID?: string } | undefined
if (info?.id && info?.parentID) {
const parentState = ralphService.getActiveState(info.parentID)
if (parentState?.active) {
let children = childSessions.get(info.parentID)
if (!children) {
children = new Set()
childSessions.set(info.parentID, children)
}
children.add(info.id)
recordActivity(info.parentID)
}
}
}
if (event.type === 'session.status') {
const eventSessionId = event.properties?.sessionID as string
if (eventSessionId) {
if (ralphService.getActiveState(eventSessionId)?.active) {
recordActivity(eventSessionId)
}
const parentId = findRalphParent(eventSessionId)
if (parentId) {
recordActivity(parentId)
}
}
}
if (event.type === 'session.error') {
const errorProps = event.properties as { sessionID?: string; error?: { name?: string } }
const eventSessionId = errorProps?.sessionID
@@ -622,21 +519,6 @@ export function createRalphEventHandler(
logger.log(`Ralph: session ${eventSessionId} aborted, terminating loop`)
await terminateLoop(eventSessionId, state, 'user_aborted')
}
const parentId = findRalphParent(eventSessionId)
if (parentId) {
const parentState = ralphService.getActiveState(parentId)
if (parentState?.active) {
logger.log(`Ralph: child session abort detected, terminating parent loop ${parentId}`)
await terminateLoop(parentId, parentState, 'user_aborted')
}
}
const childLoops = ralphService.findByParentSessionId(eventSessionId)
for (const childLoop of childLoops) {
logger.log(`Ralph: launcher session ${eventSessionId} aborted, terminating child loop ${childLoop.sessionId}`)
await terminateLoop(childLoop.sessionId, childLoop, 'user_aborted')
}
return
}
@@ -648,13 +530,6 @@ export function createRalphEventHandler(
const state = ralphService.getActiveState(sessionId)
if (!state || !state.active) return
const parentId = findRalphParent(sessionId)
if (parentId) {
recordActivity(parentId)
}
recordActivity(sessionId)
try {
// Re-check state right before calling phase handler as extra safety
const freshState = ralphService.getActiveState(sessionId)
@@ -689,7 +564,6 @@ export function createRalphEventHandler(
}
lastActivityTime.clear()
consecutiveStalls.clear()
childSessions.clear()
logger.log('Ralph: cleared all retry timeouts')
}
-4
View File
@@ -408,7 +408,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
audit: boolean
agent?: string
model?: { providerID: string; modelID: string }
parentSessionId?: string
inPlace?: boolean
onLoopStarted?: (sessionId: string) => void
}
@@ -506,7 +505,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
audit: options.audit,
errorCount: 0,
auditCount: 0,
parentSessionId: options.parentSessionId,
inPlace: options.inPlace,
}
@@ -873,7 +871,6 @@ Do NOT output text without also making this tool call.
agent: 'code',
model: ralphModel,
inPlace: args.inPlace,
parentSessionId: context.sessionID,
onLoopStarted: (id) => ralphHandler.startWatchdog(id),
})
},
@@ -1045,7 +1042,6 @@ Do NOT output text without also making this tool call.
audit: stoppedState.audit,
errorCount: 0,
auditCount: 0,
parentSessionId: stoppedState.parentSessionId,
inPlace: stoppedState.inPlace,
}
-7
View File
@@ -25,7 +25,6 @@ export interface RalphState {
auditCount: number
terminationReason?: string
completedAt?: string
parentSessionId?: string
inPlace?: boolean
}
@@ -40,7 +39,6 @@ export interface RalphService {
listActive(): RalphState[]
listRecent(): RalphState[]
findByWorktreeName(name: string): RalphState | null
findByParentSessionId(parentId: string): RalphState[]
getStallTimeoutMs(): number
getMinAudits(): number
terminateAll(): void
@@ -143,10 +141,6 @@ export function createRalphService(
return active.find((s) => s.worktreeName === name) ?? null
}
function findByParentSessionId(parentId: string): RalphState[] {
return listActive().filter((s) => s.parentSessionId === parentId)
}
function getStallTimeoutMs(): number {
return ralphConfig?.stallTimeoutMs ?? STALL_TIMEOUT_MS
}
@@ -180,7 +174,6 @@ export function createRalphService(
listActive,
listRecent,
findByWorktreeName,
findByParentSessionId,
getStallTimeoutMs,
getMinAudits,
terminateAll,