From f2887b610ce22bfe12a6f3d47119007185502728 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 1 May 2026 15:52:35 -0400 Subject: [PATCH] refactor: skills service and UI components with SSE improvements --- backend/src/routes/settings.ts | 6 +- backend/src/services/skills.ts | 471 ++++++------------ backend/test/routes/sse.test.ts | 48 ++ backend/test/services/skills.test.ts | 229 +++++---- frontend/src/api/opencode.ts | 8 +- .../components/repo/RepoSkillsDialog.test.tsx | 268 ++++++++++ .../src/components/repo/RepoSkillsDialog.tsx | 87 +++- .../src/components/repo/RepoSkillsList.tsx | 49 +- .../src/components/settings/SkillDialog.tsx | 94 +--- frontend/src/contexts/EventContext.test.tsx | 37 +- frontend/src/contexts/EventContext.tsx | 18 +- .../__tests__/useCommandHandler.test.tsx | 147 ++++++ .../src/hooks/__tests__/useLoadSkill.test.tsx | 293 +++++++++++ .../__tests__/useMessages.fallback.test.tsx | 91 ++++ frontend/src/hooks/useCommandHandler.ts | 24 +- frontend/src/hooks/useOpenCode.ts | 94 +++- frontend/src/hooks/useSSE.ts | 3 + frontend/src/lib/__tests__/sseManager.test.ts | 162 ++++++ frontend/src/lib/sseManager.ts | 109 +++- frontend/src/pages/SessionDetail.tsx | 31 +- .../__tests__/SessionDetail.polling.test.tsx | 94 ++++ shared/src/config/defaults.ts | 4 +- shared/src/schemas/skills.ts | 12 - 23 files changed, 1828 insertions(+), 551 deletions(-) create mode 100644 backend/test/routes/sse.test.ts create mode 100644 frontend/src/components/repo/RepoSkillsDialog.test.tsx create mode 100644 frontend/src/hooks/__tests__/useCommandHandler.test.tsx create mode 100644 frontend/src/hooks/__tests__/useLoadSkill.test.tsx create mode 100644 frontend/src/hooks/__tests__/useMessages.fallback.test.tsx create mode 100644 frontend/src/lib/__tests__/sseManager.test.ts create mode 100644 frontend/src/pages/__tests__/SessionDetail.polling.test.tsx diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 83011507..f2d5165e 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -1138,7 +1138,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic return c.json({ error: 'Invalid repoId' }, 400) } - const skills = await listManagedSkills(db, repoId) + const skills = await listManagedSkills(db, openCodeClient, repoId) return c.json(skills) } catch (error) { logger.error('Failed to list skills:', error) @@ -1160,7 +1160,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic return c.json({ error: 'repoId is required for project scope' }, 400) } - const skill = await getSkill(db, name, scope, repoId) + const skill = await getSkill(db, openCodeClient, name, scope, repoId) return c.json(skill) } catch (error) { logger.error('Failed to get skill:', error) @@ -1220,7 +1220,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic return c.json({ error: 'repoId is required for project scope' }, 400) } - const skill = await updateSkill(db, name, scope, validated, repoId) + const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId) try { await restartOpenCode(openCodeSupervisor) diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts index 6b914131..9511e955 100644 --- a/backend/src/services/skills.ts +++ b/backend/src/services/skills.ts @@ -5,9 +5,18 @@ import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest import { SKILL_NAME_REGEX } from '@opencode-manager/shared' import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { getRepoById, listRepos } from '../db/queries' +import type { Repo } from '@opencode-manager/shared/types' import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations' +import type { OpenCodeClient } from './opencode/client' import { logger } from '../utils/logger' +interface OpenCodeSkillInfo { + name: string + description: string + location: string + content: string +} + function getGlobalSkillsPath(): string { return path.join(getWorkspacePath(), '.config', 'opencode', 'skills') } @@ -16,43 +25,47 @@ function getOldGlobalSkillsPath(): string { return path.join(os.homedir(), '.config', 'opencode', 'skills') } +function getProjectSkillsPath(repo: Repo): string { + return path.join(repo.fullPath, '.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) @@ -62,133 +75,12 @@ export async function migrateGlobalSkills(): Promise { 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: { - name: string - description: string - license?: string - compatibility?: string - metadata?: Record - } - body: string -} - -function parseSkillFile(content: string): ParsedSkillFile { - const firstDelim = content.indexOf('---') - if (firstDelim === -1) { - throw new Error('Invalid SKILL.md format: missing frontmatter delimiters') - } - const afterFirst = firstDelim + 3 - const secondDelim = content.indexOf('\n---', afterFirst) - if (secondDelim === -1) { - throw new Error('Invalid SKILL.md format: missing closing frontmatter delimiter') - } - const frontmatterStr = content.substring(afterFirst, secondDelim).trim() - const afterSecond = secondDelim + 4 - const body = content.substring(afterSecond).trim() - - const frontmatter: Record = {} - const lines = frontmatterStr.split('\n') - - let currentKey: string | null = null - const metadataObj: Record = {} - - for (const line of lines) { - const trimmedLine = line.trim() - if (!trimmedLine) continue - - const kvMatch = trimmedLine.match(/^([^:]+):\s*(.*)$/) - if (kvMatch) { - const key = kvMatch[1]?.trim() - const value = kvMatch[2]?.trim() - - if (key === 'metadata') { - currentKey = 'metadata' - continue - } - - if (key && value !== undefined) { - frontmatter[key] = value - currentKey = null - } - } else if (currentKey === 'metadata' && trimmedLine) { - const metaMatch = trimmedLine.match(/^\s*([^:]+):\s*(.*)$/) - if (metaMatch) { - const metaKey = metaMatch[1]?.trim() - const metaValue = metaMatch[2]?.trim() - if (metaKey && metaValue !== undefined) { - metadataObj[metaKey] = metaValue - } - } - } - } - - if (Object.keys(metadataObj).length > 0) { - frontmatter.metadata = metadataObj - } - - return { - frontmatter: { - name: frontmatter.name as string || '', - description: frontmatter.description as string || '', - license: frontmatter.license as string | undefined, - compatibility: frontmatter.compatibility as string | undefined, - metadata: frontmatter.metadata as Record | undefined, - }, - body, - } -} - -function generateSkillFrontmatter( - name: string, - description: string, - license?: string, - compatibility?: string, - metadata?: Record -): string { - let frontmatter = `name: ${name}\ndescription: ${description}` - - if (license) { - frontmatter += `\nlicense: ${license}` - } - - if (compatibility) { - frontmatter += `\ncompatibility: ${compatibility}` - } - - if (metadata && Object.keys(metadata).length > 0) { - frontmatter += '\nmetadata:' - for (const [key, value] of Object.entries(metadata)) { - frontmatter += `\n ${key}: ${value}` - } - } - - return frontmatter -} - -function getSkillDirectoryPath(db: Database, scope: SkillScope, repoId?: number): string { - if (scope === 'global') { - return getGlobalSkillsPath() - } - - if (!repoId) { - throw new Error('repoId is required for project-scoped skills') - } - - const repo = getRepoById(db, repoId) - if (!repo) { - throw new Error(`Repository with id ${repoId} not found`) - } - - return path.join(repo.fullPath, '.opencode', 'skills') -} - function validateSkillName(name: string): void { if (!SKILL_NAME_REGEX.test(name)) { throw new Error('Invalid skill name. Must be lowercase alphanumeric with hyphens only.') @@ -197,171 +89,153 @@ function validateSkillName(name: string): void { function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string { validateSkillName(name) - const skillsDir = getSkillDirectoryPath(db, scope, repoId) - return path.join(skillsDir, name, 'SKILL.md') + if (scope === 'global') { + return path.join(getGlobalSkillsPath(), name, 'SKILL.md') + } + if (!repoId) { + throw new Error('repoId is required for project-scoped skills') + } + const repo = getRepoById(db, repoId) + if (!repo) { + throw new Error(`Repository with id ${repoId} not found`) + } + return path.join(getProjectSkillsPath(repo), name, 'SKILL.md') } -export async function listManagedSkills(db: Database, repoId?: number): Promise { - const skills: SkillFileInfo[] = [] - - const globalSkillsDir = getGlobalSkillsPath() - const globalSkillsExist = await fileExists(globalSkillsDir) - - if (globalSkillsExist) { - const entries = await listDirectory(globalSkillsDir) - 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, 'global', entry.name) - if (skillInfo) { - skills.push(skillInfo) - } - } - } +function buildSkillFileContent(name: string, description: string, body: string): string { + return `---\nname: ${name}\ndescription: ${description}\n---\n${body}` +} + +async function fetchOpenCodeSkills(openCodeClient: OpenCodeClient, directory: string): Promise { + try { + const response = await openCodeClient.forward({ + method: 'GET', + path: '/skill', + directory, + }) + if (!response.ok) { + logger.warn(`Failed to fetch skills from OpenCode (${response.status})`) + return [] + } + return await response.json() as OpenCodeSkillInfo[] + } catch (error) { + logger.warn('Error fetching skills from OpenCode:', error) + return [] + } +} + +function classifySkillLocation( + location: string, + globalPrefix: string, + repos: Repo[], +): { scope: SkillScope; repo?: Repo } | null { + if (location.startsWith(globalPrefix + path.sep)) { + return { scope: 'global' } + } + for (const repo of repos) { + const projectPrefix = getProjectSkillsPath(repo) + if (location.startsWith(projectPrefix + path.sep)) { + return { scope: 'project', repo } } } - - if (repoId) { - const repo = getRepoById(db, repoId) - if (repo) { - 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, repoId) - if (skillInfo) { - skills.push(skillInfo) - } - } - } - } - } - } - } 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 null +} + +function toSkillFileInfo( + skill: OpenCodeSkillInfo, + classification: { scope: SkillScope; repo?: Repo }, +): SkillFileInfo { + return { + name: skill.name, + description: skill.description, + body: skill.content, + scope: classification.scope, + location: skill.location, + repoId: classification.repo?.id, + repoName: classification.repo?.localPath, + } +} + +export async function listManagedSkills( + db: Database, + openCodeClient: OpenCodeClient, + repoId?: number, +): Promise { + const globalPrefix = getGlobalSkillsPath() + const allRepos = listRepos(db) + + const targetRepos = repoId + ? allRepos.filter(r => r.id === repoId) + : allRepos + + if (repoId && targetRepos.length === 0) { + throw new Error(`Repository with id ${repoId} not found`) + } + + const directories = targetRepos.length > 0 + ? targetRepos.map(r => r.fullPath) + : [getWorkspacePath()] + + const seenLocations = new Set() + const result: SkillFileInfo[] = [] + + for (const directory of directories) { + const skills = await fetchOpenCodeSkills(openCodeClient, directory) + for (const skill of skills) { + if (seenLocations.has(skill.location)) continue + const classification = classifySkillLocation(skill.location, globalPrefix, allRepos) + if (!classification) continue + seenLocations.add(skill.location) + result.push(toSkillFileInfo(skill, classification)) } } - - return skills + + return result } export async function getSkill( db: Database, + openCodeClient: OpenCodeClient, name: string, scope: SkillScope, - repoId?: number + repoId?: number, ): Promise { - const skillPath = getSkillFilePath(db, scope, name, repoId) - const exists = await fileExists(skillPath) - - if (!exists) { + validateSkillName(name) + const skills = await listManagedSkills(db, openCodeClient, repoId) + const match = skills.find(s => + s.name === name && + s.scope === scope && + (scope === 'global' || s.repoId === repoId), + ) + if (!match) { throw new Error(`Skill "${name}" not found in ${scope} scope`) } - - const skillInfo = await readSkillFile(db, scope, name, repoId) - if (!skillInfo) { - throw new Error(`Failed to read skill "${name}"`) - } - - return skillInfo -} - -async function readSkillFile( - db: Database, - scope: SkillScope, - name: string, - repoId?: number -): Promise { - try { - const skillPath = getSkillFilePath(db, scope, name, repoId) - const content = await readFileContent(skillPath) - const parsed = parseSkillFile(content) - - const repo = repoId ? getRepoById(db, repoId) : null - - return { - name: parsed.frontmatter.name, - description: parsed.frontmatter.description, - body: parsed.body, - license: parsed.frontmatter.license, - compatibility: parsed.frontmatter.compatibility, - metadata: parsed.frontmatter.metadata, - scope, - location: skillPath, - repoId: scope === 'project' ? repoId : undefined, - repoName: repo?.localPath, - } - } catch (error) { - logger.error(`Failed to read skill ${name}:`, error) - return null - } + return match } export async function createSkill( db: Database, - input: CreateSkillRequest + input: CreateSkillRequest, ): Promise { - const { name, description, body, license, compatibility, metadata, scope, repoId } = input - + const { name, description, body, scope, repoId } = input + const skillPath = getSkillFilePath(db, scope, name, repoId) const exists = await fileExists(skillPath) - + if (exists) { throw new Error(`Skill "${name}" already exists in ${scope} scope`) } - - const skillDir = path.dirname(skillPath) - await ensureDirectoryExists(skillDir) - - const frontmatter = generateSkillFrontmatter( - name, - description, - license, - compatibility, - metadata - ) - - const content = `---\n${frontmatter}\n---\n${body}` - - await writeFileContent(skillPath, content) + + await ensureDirectoryExists(path.dirname(skillPath)) + await writeFileContent(skillPath, buildSkillFileContent(name, description, body)) logger.info(`Created skill "${name}" at ${skillPath}`) - + const repo = repoId ? getRepoById(db, repoId) : null - + return { name, description, body, - license, - compatibility, - metadata, scope, location: skillPath, repoId: scope === 'project' ? repoId : undefined, @@ -371,63 +245,35 @@ export async function createSkill( export async function updateSkill( db: Database, + openCodeClient: OpenCodeClient, name: string, scope: SkillScope, input: UpdateSkillRequest, - repoId?: number + repoId?: number, ): Promise { const skillPath = getSkillFilePath(db, scope, name, repoId) const exists = await fileExists(skillPath) - + if (!exists) { throw new Error(`Skill "${name}" not found in ${scope} scope`) } - - const existingContent = await readFileContent(skillPath) - const parsed = parseSkillFile(existingContent) - - const resolveField = (field: T | null | undefined, existing: T | undefined): T | undefined => { - if (field === null) return undefined - if (field === undefined) return existing - return field - } - const updatedFrontmatter = { - name: parsed.frontmatter.name, - description: input.description ?? parsed.frontmatter.description, - license: resolveField(input.license, parsed.frontmatter.license), - compatibility: resolveField(input.compatibility, parsed.frontmatter.compatibility), - metadata: resolveField(input.metadata, parsed.frontmatter.metadata), - } - - const updatedBody = input.body ?? parsed.body - - const frontmatter = generateSkillFrontmatter( - updatedFrontmatter.name, - updatedFrontmatter.description, - updatedFrontmatter.license, - updatedFrontmatter.compatibility, - updatedFrontmatter.metadata - ) - - const content = `---\n${frontmatter}\n---\n${updatedBody}` - - await writeFileContent(skillPath, content) + const existing = await getSkill(db, openCodeClient, name, scope, repoId) + + const description = input.description ?? existing.description + const body = input.body ?? existing.body + + await writeFileContent(skillPath, buildSkillFileContent(name, description, body)) logger.info(`Updated skill "${name}" at ${skillPath}`) - - const repo = repoId ? getRepoById(db, repoId) : null - + return { - name: updatedFrontmatter.name, - description: updatedFrontmatter.description, - body: updatedBody, - license: updatedFrontmatter.license, - compatibility: updatedFrontmatter.compatibility, - metadata: updatedFrontmatter.metadata, + name, + description, + body, scope, location: skillPath, - repoId: scope === 'project' ? repoId : undefined, - repoName: repo?.localPath, + repoId: existing.repoId, + repoName: existing.repoName, } } @@ -435,16 +281,15 @@ export async function deleteSkill( db: Database, name: string, scope: SkillScope, - repoId?: number + repoId?: number, ): Promise { const skillPath = getSkillFilePath(db, scope, name, repoId) const exists = await fileExists(skillPath) - + if (!exists) { throw new Error(`Skill "${name}" not found in ${scope} scope`) } - - const skillDir = path.dirname(skillPath) - await deletePath(skillDir) - logger.info(`Deleted skill "${name}" from ${skillDir}`) + + await deletePath(path.dirname(skillPath)) + logger.info(`Deleted skill "${name}" from ${path.dirname(skillPath)}`) } diff --git a/backend/test/routes/sse.test.ts b/backend/test/routes/sse.test.ts new file mode 100644 index 00000000..dd434859 --- /dev/null +++ b/backend/test/routes/sse.test.ts @@ -0,0 +1,48 @@ +import { describe, it, expect, vi } from 'vitest' +import { DEFAULTS } from '@opencode-manager/shared/config' + +const { HEARTBEAT_INTERVAL_MS } = DEFAULTS.SSE + +describe('SSE Routes', () => { + describe('HEARTBEAT_INTERVAL_MS', () => { + it('should be 30000ms (30 seconds)', () => { + expect(HEARTBEAT_INTERVAL_MS).toBe(30000) + }) + + it('should fire heartbeats at correct interval', async () => { + vi.useFakeTimers() + + const heartbeatSpy = vi.fn() + const intervalId = setInterval(() => { + heartbeatSpy() + }, HEARTBEAT_INTERVAL_MS) + + await vi.advanceTimersByTimeAsync(0) + expect(heartbeatSpy).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(30000) + expect(heartbeatSpy).toHaveBeenCalledTimes(2) + + await vi.advanceTimersByTimeAsync(40000) + expect(heartbeatSpy).toHaveBeenCalledTimes(3) + + clearInterval(intervalId) + vi.useRealTimers() + }) + + it('should fire two heartbeats within 70 seconds', async () => { + vi.useFakeTimers() + + const heartbeatSpy = vi.fn() + const intervalId = setInterval(() => { + heartbeatSpy() + }, HEARTBEAT_INTERVAL_MS) + + await vi.advanceTimersByTimeAsync(70000) + expect(heartbeatSpy).toHaveBeenCalledTimes(3) + + clearInterval(intervalId) + vi.useRealTimers() + }) + }) +}) diff --git a/backend/test/services/skills.test.ts b/backend/test/services/skills.test.ts index 10d71222..75096c38 100644 --- a/backend/test/services/skills.test.ts +++ b/backend/test/services/skills.test.ts @@ -1,7 +1,8 @@ import { describe, expect, test, beforeEach, afterEach, vi } from 'vitest' import { join } from 'path' import { tmpdir } from 'os' -import { mkdtemp, rm } from 'fs/promises' +import { mkdtemp, rm, readFile } from 'fs/promises' +import type { OpenCodeClient } from '../../src/services/opencode/client' vi.mock('../../src/db/queries', () => ({ getRepoById: vi.fn(), @@ -17,6 +18,19 @@ vi.mock('../../src/db/queries', () => ({ deleteRepo: vi.fn(), })) +function createMockClient(skills: Array<{ name: string; description: string; location: string; content: string }>): OpenCodeClient { + return { + forward: vi.fn(async () => new Response(JSON.stringify(skills), { status: 200 })), + forwardRaw: vi.fn(), + getJson: vi.fn(), + postJson: vi.fn(), + setProviderAuth: vi.fn(), + deleteProviderAuth: vi.fn(), + startMcpAuth: vi.fn(), + authenticateMcp: vi.fn(), + } as unknown as OpenCodeClient +} + describe('SkillService', () => { let tempDir: string @@ -31,48 +45,48 @@ describe('SkillService', () => { vi.clearAllMocks() }) - const mockDb = null as unknown as any + const mockDb = null as unknown as never - test('generates correct YAML frontmatter format', async () => { + test('writes correct YAML frontmatter format', async () => { const { createSkill, deleteSkill } = await import('../../src/services/skills') const name = `test-skill-${Date.now()}` - const input = { + const result = await createSkill(mockDb, { name, description: 'A test skill', body: '## Test Body\n\nContent here', scope: 'global' as const, - license: 'MIT', - compatibility: 'opencode', - metadata: { key: 'value' }, - } + }) try { - const result = await createSkill(mockDb, input) - 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' }) + const fileContent = await readFile(result.location, 'utf-8') + expect(fileContent).toBe(`---\nname: ${name}\ndescription: A test skill\n---\n## Test Body\n\nContent here`) } finally { await deleteSkill(mockDb, name, 'global').catch(() => {}) } }) - test('parses frontmatter and body correctly', async () => { + test('reads skill via opencode API', async () => { const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills') const name = `parse-test-${Date.now()}` - const input = { + const created = await createSkill(mockDb, { name, description: 'Test description', body: '## Body\n\nSome content', scope: 'global' as const, - } + }) try { - await createSkill(mockDb, input) - const skill = await getSkill(mockDb, name, 'global') + const client = createMockClient([{ + name, + description: 'Test description', + location: created.location, + content: '## Body\n\nSome content', + }]) + + const skill = await getSkill(mockDb, client, name, 'global') expect(skill.name).toBe(name) expect(skill.description).toBe('Test description') @@ -89,15 +103,13 @@ describe('SkillService', () => { for (const baseName of validNames) { const name = `${baseName}-${Date.now()}` - const input = { - name, - description: 'Test', - body: 'Body', - scope: 'global' as const, - } - try { - await expect(createSkill(mockDb, input)).resolves.toBeDefined() + await expect(createSkill(mockDb, { + name, + description: 'Test', + body: 'Body', + scope: 'global' as const, + })).resolves.toBeDefined() createdNames.push(name) } catch { // Ignore failures, just cleanup what was created @@ -114,29 +126,25 @@ describe('SkillService', () => { const invalidNames = ['My-Skill', '--bad', 'bad-', 'has spaces', 'has_underscore', 'has.dot', 'UPPERCASE'] for (const name of invalidNames) { - const input = { + await expect(createSkill(mockDb, { name: `${name}-${Date.now()}`, description: 'Test', body: 'Body', scope: 'global' as const, - } - - await expect(createSkill(mockDb, input)).rejects.toThrow('Invalid skill name') + })).rejects.toThrow('Invalid skill name') } }) test('creates skill file at correct path', async () => { const { createSkill, deleteSkill } = await import('../../src/services/skills') const name = `new-skill-${Date.now()}` - const input = { - name, - description: 'A new skill', - body: 'Skill body content', - scope: 'global' as const, - } - try { - const result = await createSkill(mockDb, input) + const result = await createSkill(mockDb, { + name, + description: 'A new skill', + body: 'Skill body content', + scope: 'global' as const, + }) expect(result.name).toBe(name) expect(result.scope).toBe('global') @@ -149,48 +157,21 @@ describe('SkillService', () => { test('throws error on duplicate name', async () => { const { createSkill, deleteSkill } = await import('../../src/services/skills') const name = `duplicate-${Date.now()}` - const input = { - name, - description: 'First', - body: 'Body', - scope: 'global' as const, - } try { - await createSkill(mockDb, input) + await createSkill(mockDb, { + name, + description: 'First', + body: 'Body', + scope: 'global' as const, + }) - const duplicate = { + await expect(createSkill(mockDb, { 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(() => {}) - } - }) - - test('reads skill correctly', async () => { - const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills') - const name = `read-test-${Date.now()}` - const input = { - name, - description: 'Read test description', - body: 'Read test body', - scope: 'global' as const, - license: 'Apache-2.0', - } - - 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') + })).rejects.toThrow('already exists') } finally { await deleteSkill(mockDb, name, 'global').catch(() => {}) } @@ -198,34 +179,44 @@ describe('SkillService', () => { test('throws error for missing skill', async () => { const { getSkill } = await import('../../src/services/skills') - await expect(getSkill(mockDb, 'nonexistent', 'global')).rejects.toThrow('not found') + const client = createMockClient([]) + await expect(getSkill(mockDb, client, 'nonexistent', 'global')).rejects.toThrow('not found') }) - test('updates only changed fields', async () => { + test('updates only changed fields, preserving body', async () => { const { createSkill, updateSkill, deleteSkill } = await import('../../src/services/skills') const name = `update-test-${Date.now()}` - const input = { + + const created = await createSkill(mockDb, { name, description: 'Original description', body: 'Original body', scope: 'global' as const, - license: 'MIT', - } + }) try { - await createSkill(mockDb, input) + const client = createMockClient([{ + name, + description: 'Original description', + location: created.location, + content: 'Original body', + }]) const updated = await updateSkill( mockDb, + client, name, 'global', { description: 'Updated description' }, - undefined + undefined, ) expect(updated.description).toBe('Updated description') expect(updated.body).toBe('Original body') - expect(updated.license).toBe('MIT') + + const fileContent = await readFile(created.location, 'utf-8') + expect(fileContent).toContain('description: Updated description') + expect(fileContent).toContain('Original body') } finally { await deleteSkill(mockDb, name, 'global').catch(() => {}) } @@ -233,25 +224,26 @@ describe('SkillService', () => { test('throws error for missing skill on update', async () => { const { updateSkill } = await import('../../src/services/skills') + const client = createMockClient([]) await expect( - updateSkill(mockDb, 'nonexistent', 'global', { description: 'Test' }, undefined) + updateSkill(mockDb, client, 'nonexistent', 'global', { description: 'Test' }, undefined), ).rejects.toThrow('not found') }) test('deletes skill directory', async () => { const { createSkill, deleteSkill, getSkill } = await import('../../src/services/skills') const name = `delete-test-${Date.now()}` - const input = { + + await createSkill(mockDb, { name, description: 'To be deleted', body: 'Body', scope: 'global' as const, - } - - await createSkill(mockDb, input) + }) await deleteSkill(mockDb, name, 'global') - await expect(getSkill(mockDb, name, 'global')).rejects.toThrow('not found') + const client = createMockClient([]) + await expect(getSkill(mockDb, client, name, 'global')).rejects.toThrow('not found') }) test('throws error for missing skill on delete', async () => { @@ -259,32 +251,36 @@ describe('SkillService', () => { await expect(deleteSkill(mockDb, 'nonexistent', 'global')).rejects.toThrow('not found') }) - test('lists global skills', async () => { + test('lists global skills via opencode API', async () => { const { createSkill, listManagedSkills, deleteSkill } = await import('../../src/services/skills') const name1 = `list-test-1-${Date.now()}` const name2 = `list-test-2-${Date.now()}` try { - await createSkill(mockDb, { + const created1 = await createSkill(mockDb, { name: name1, description: 'Test 1', body: 'Body', scope: 'global' as const, }) - await createSkill(mockDb, { + const created2 = await createSkill(mockDb, { name: name2, description: 'Test 2', body: 'Body', scope: 'global' as const, }) - const skills = await listManagedSkills(mockDb) + const client = createMockClient([ + { name: name1, description: 'Test 1', location: created1.location, content: 'Body' }, + { name: name2, description: 'Test 2', location: created2.location, content: 'Body' }, + ]) + const skills = await listManagedSkills(mockDb, client) const createdSkills = skills.filter(s => [name1, name2].includes(s.name)) expect(createdSkills.length).toBe(2) expect(createdSkills.map(s => s.name)).toEqual( - expect.arrayContaining([name1, name2]) + expect.arrayContaining([name1, name2]), ) } finally { await deleteSkill(mockDb, name1, 'global').catch(() => {}) @@ -292,10 +288,10 @@ describe('SkillService', () => { } }) - test('should handle body content containing --- (horizontal rules)', async () => { + test('preserves body content containing --- (horizontal rules)', async () => { const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills') const name = `hr-test-${Date.now()}` - + const bodyWithHR = `This is the skill body. --- @@ -306,29 +302,50 @@ This is after a horizontal rule. Another section.` + const created = await createSkill(mockDb, { + name, + description: 'Test horizontal rules in body', + body: bodyWithHR, + scope: 'global' as const, + }) + try { - await createSkill(mockDb, { + const client = createMockClient([{ name, description: 'Test horizontal rules in body', - body: bodyWithHR, - scope: 'global' as const, - }) + location: created.location, + content: bodyWithHR, + }]) - const skill = await getSkill(mockDb, name, 'global') + const skill = await getSkill(mockDb, client, 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.') + 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(() => {}) } }) - test('lists skills from all repos when no repoId is provided', async () => { + test('returns empty list when opencode API returns nothing', async () => { const { listManagedSkills } = await import('../../src/services/skills') - - const skills = await listManagedSkills(mockDb) - + const client = createMockClient([]) + const skills = await listManagedSkills(mockDb, client) expect(Array.isArray(skills)).toBe(true) + expect(skills.length).toBe(0) + }) + + test('filters out skills outside managed directories', async () => { + const { listManagedSkills } = await import('../../src/services/skills') + const client = createMockClient([ + { + name: 'external-skill', + description: 'From .claude', + location: '/some/other/path/.claude/skills/external/SKILL.md', + content: 'body', + }, + ]) + const skills = await listManagedSkills(mockDb, client) + expect(skills.length).toBe(0) }) }) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 5b45823e..615c70d6 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -9,6 +9,7 @@ type SendPromptRequest = NonNullable['content']['application/json'] +type SendCommandResponse = paths['/session/{sessionID}/command']['post']['responses']['200']['content']['application/json'] type ShellRequest = NonNullable['content']['application/json'] type AgentListResponse = paths['/agent']['get']['responses']['200']['content']['application/json'] type PermissionListResponse = paths['/permission']['get']['responses']['200']['content']['application/json'] @@ -17,7 +18,7 @@ type SendPromptResponse = paths['/session/{sessionID}/message']['post']['respons type LspStatusResponse = paths['/lsp']['get']['responses']['200']['content']['application/json'] type LspStatus = LspStatusResponse[number] -export type { SendPromptResponse, LspStatus } +export type { SendPromptResponse, SendCommandResponse, LspStatus } export class OpenCodeClient { private baseURL: string @@ -157,12 +158,13 @@ export class OpenCodeClient { }) } - async sendCommand(sessionID: string, data: CommandRequest) { - return fetchWrapper(`${this.baseURL}/session/${sessionID}/command`, { + async sendCommand(sessionID: string, data: CommandRequest): Promise { + return fetchWrapper(`${this.baseURL}/session/${sessionID}/command`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), + timeout: 0, }) } diff --git a/frontend/src/components/repo/RepoSkillsDialog.test.tsx b/frontend/src/components/repo/RepoSkillsDialog.test.tsx new file mode 100644 index 00000000..4eaccdc0 --- /dev/null +++ b/frontend/src/components/repo/RepoSkillsDialog.test.tsx @@ -0,0 +1,268 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { ReactNode } from 'react' +import { RepoSkillsDialog } from './RepoSkillsDialog' +import type { SkillFileInfo } from '@opencode-manager/shared' + +const mocks = vi.hoisted(() => ({ + listManagedSkills: vi.fn(), + sendCommand: vi.fn(), +})) + +vi.mock('@/api/settings', () => ({ + settingsApi: { + listManagedSkills: mocks.listManagedSkills, + }, +})) + +vi.mock('@/api/opencode', () => ({ + OpenCodeClient: vi.fn(() => ({ + sendCommand: mocks.sendCommand, + })), +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + error: vi.fn(), + success: vi.fn(), + }, +})) + +describe('RepoSkillsDialog', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + const createWrapper = () => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + return ({ children }: { children: ReactNode }) => ( + {children} + ) + } + + const mockSkills: SkillFileInfo[] = [ + { + name: 'test-skill', + description: 'A test skill for testing', + body: 'Test skill content', + location: '/repo/.opencode/skills/test-skill/SKILL.md', + scope: 'project', + }, + { + name: 'global-skill', + description: 'A global skill', + body: 'Global skill content', + location: '/home/user/.config/opencode/skills/global-skill/SKILL.md', + scope: 'global', + }, + ] + + describe('tabs and skill filtering', () => { + it('shows both tabs when skills exist', async () => { + mocks.listManagedSkills.mockResolvedValue(mockSkills) + + render( + , + { wrapper: createWrapper() } + ) + + expect(screen.getByText('Project')).toBeInTheDocument() + expect(screen.getByText('Global')).toBeInTheDocument() + }) + + it('shows project skills in project tab', async () => { + mocks.listManagedSkills.mockResolvedValue(mockSkills) + + render( + , + { wrapper: createWrapper() } + ) + + await waitFor(() => { + expect(screen.getByText('Test skill')).toBeInTheDocument() + }) + }) + + it('shows global skills in global tab', async () => { + mocks.listManagedSkills.mockResolvedValue(mockSkills) + + render( + , + { wrapper: createWrapper() } + ) + + await waitFor(() => { + expect(screen.getByText('Project')).toBeInTheDocument() + }) + + const globalTab = screen.getByText('Global') + await userEvent.click(globalTab) + + expect(screen.getByText('Global skill')).toBeInTheDocument() + }) + + it('shows empty state for project tab when no project skills', async () => { + mocks.listManagedSkills.mockResolvedValue([ + { + name: 'global-skill', + description: 'A global skill', + body: 'Global skill content', + location: '/home/user/.config/opencode/skills/global-skill/SKILL.md', + scope: 'global', + }, + ]) + + render( + , + { wrapper: createWrapper() } + ) + + const projectTab = screen.getByText('Project') + await userEvent.click(projectTab) + + await waitFor(() => { + expect(screen.getByText('No local skills found')).toBeInTheDocument() + }) + }) + }) + + describe('load functionality', () => { + it('shows Load button when sessionId and opcodeUrl are provided', async () => { + mocks.listManagedSkills.mockResolvedValue(mockSkills) + mocks.sendCommand.mockResolvedValue(undefined) + + const onSkillLoaded = vi.fn() + const onOpenChange = vi.fn() + + render( + , + { wrapper: createWrapper() } + ) + + await waitFor(() => { + expect(screen.getByText('Test skill')).toBeInTheDocument() + }) + + expect(screen.getByText('Load')).toBeInTheDocument() + }) + + it('does not show Load button when sessionId is not provided', async () => { + mocks.listManagedSkills.mockResolvedValue(mockSkills) + + render( + , + { wrapper: createWrapper() } + ) + + await waitFor(() => { + expect(screen.getByText('Test skill')).toBeInTheDocument() + }) + + expect(screen.queryByText('Load')).not.toBeInTheDocument() + }) + + it('calls sendCommand and closes dialog on Load click', async () => { + mocks.listManagedSkills.mockResolvedValue(mockSkills) + mocks.sendCommand.mockReturnValue(new Promise(() => {})) + + const onSkillLoaded = vi.fn() + const onOpenChange = vi.fn() + const user = userEvent.setup() + + render( + , + { wrapper: createWrapper() } + ) + + await waitFor(() => { + expect(screen.getByText('Test skill')).toBeInTheDocument() + }) + + const loadButton = screen.getByText('Load') + await user.click(loadButton) + + expect(onOpenChange).toHaveBeenCalledWith(false) + expect(onSkillLoaded).toHaveBeenCalledWith(mockSkills[0]) + expect(mocks.sendCommand).toHaveBeenCalledWith('test-session', { + command: 'test-skill', + arguments: '', + }) + }) + + it('shows toast error on sendCommand failure', async () => { + const { showToast } = await import('@/lib/toast') + mocks.listManagedSkills.mockResolvedValue(mockSkills) + mocks.sendCommand.mockRejectedValue(new Error('Failed to load')) + + const onOpenChange = vi.fn() + const user = userEvent.setup() + + render( + , + { wrapper: createWrapper() } + ) + + await waitFor(() => { + expect(screen.getByText('Test skill')).toBeInTheDocument() + }) + + const loadButton = screen.getByText('Load') + await user.click(loadButton) + + await waitFor(() => { + expect(showToast.error).toHaveBeenCalledWith('Failed to load') + }) + + expect(onOpenChange).toHaveBeenCalledWith(false) + }) + }) +}) diff --git a/frontend/src/components/repo/RepoSkillsDialog.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx index e49143f8..113f23e6 100644 --- a/frontend/src/components/repo/RepoSkillsDialog.tsx +++ b/frontend/src/components/repo/RepoSkillsDialog.tsx @@ -1,15 +1,32 @@ -import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog' import { RepoSkillsList } from './RepoSkillsList' +import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' import { useQuery } from '@tanstack/react-query' import { settingsApi } from '@/api/settings' +import { useLoadSkill } from '@/hooks/useOpenCode' +import type { SkillFileInfo } from '@opencode-manager/shared' +import { useMemo, useState, useEffect } from 'react' -interface RepoSkillsDialogProps { +type RepoSkillsDialogBaseProps = { open: boolean onOpenChange: (open: boolean) => void repoId: number } -export function RepoSkillsDialog({ open, onOpenChange, repoId }: RepoSkillsDialogProps) { +type RepoSkillsDialogProps = RepoSkillsDialogBaseProps & ( + | { sessionId: string; opcodeUrl: string; directory: string; onSkillLoaded?: (skill: SkillFileInfo) => void } + | { sessionId?: undefined; opcodeUrl?: undefined; directory?: undefined; onSkillLoaded?: undefined } +) + +export function RepoSkillsDialog({ + open, + onOpenChange, + repoId, + sessionId, + opcodeUrl, + directory, + onSkillLoaded, +}: RepoSkillsDialogProps) { const { isLoading, data, error } = useQuery({ queryKey: ['settings', 'skills', repoId], queryFn: () => settingsApi.listManagedSkills(repoId), @@ -17,19 +34,75 @@ export function RepoSkillsDialog({ open, onOpenChange, repoId }: RepoSkillsDialo staleTime: 30000, }) + const projectSkills = useMemo( + () => data?.filter((s) => s.scope === 'project') ?? [], + [data], + ) + const globalSkills = useMemo( + () => data?.filter((s) => s.scope === 'global') ?? [], + [data], + ) + + const canLoad = !!sessionId && !!opcodeUrl + const loadSkill = useLoadSkill(opcodeUrl, sessionId, directory) + + const [activeTab, setActiveTab] = useState<'project' | 'global'>('project') + + useEffect(() => { + if (data && projectSkills.length === 0 && globalSkills.length > 0) { + setActiveTab('global') + } + }, [data, projectSkills.length, globalSkills.length]) + + const handleTabChange = (value: string) => { + setActiveTab(value as 'project' | 'global') + } + + const handleLoad = (skill: SkillFileInfo) => { + loadSkill.mutate({ skillName: skill.name }) + onSkillLoaded?.(skill) + onOpenChange(false) + } + if (!repoId) { return null } - const repoSkills = data?.filter(skill => skill.scope === 'project') - return ( - + Skills + + {canLoad ? 'Load a skill into the current session' : 'Skills available for this repository'} + - + + + Project + Global + + + + + + + + ) diff --git a/frontend/src/components/repo/RepoSkillsList.tsx b/frontend/src/components/repo/RepoSkillsList.tsx index 5b180b20..0c102a5c 100644 --- a/frontend/src/components/repo/RepoSkillsList.tsx +++ b/frontend/src/components/repo/RepoSkillsList.tsx @@ -1,13 +1,24 @@ -import { AlertCircle, Loader2 } from 'lucide-react' +import { AlertCircle, Loader2, Sparkles } from 'lucide-react' +import { Button } from '@/components/ui/button' import type { SkillFileInfo } from '@opencode-manager/shared' interface RepoSkillsListProps { isLoading: boolean data: SkillFileInfo[] | undefined error: Error | null + emptyTitle?: string + emptyHint?: string + onLoad?: (skill: SkillFileInfo) => void } -export function RepoSkillsList({ isLoading, data, error }: RepoSkillsListProps) { +export function RepoSkillsList({ + isLoading, + data, + error, + emptyTitle, + emptyHint, + onLoad, +}: RepoSkillsListProps) { const formatSkillName = (name: string): string => { const formatted = name.replace(/-/g, ' ') return formatted.charAt(0).toUpperCase() + formatted.slice(1) @@ -35,8 +46,11 @@ export function RepoSkillsList({ isLoading, data, error }: RepoSkillsListProps) if (!data || data.length === 0) { return (
-

No skills available

-

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

+

{emptyTitle || 'No skills available'}

+

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

) } @@ -47,15 +61,28 @@ export function RepoSkillsList({ isLoading, data, error }: RepoSkillsListProps) {data.map((skill) => (
-

- {formatSkillName(skill.name)} -

- {skill.description && ( -

- {skill.description} +

+

+ {formatSkillName(skill.name)}

+ {skill.description && ( +

+ {skill.description} +

+ )} +
+ {onLoad && ( + )}
))} diff --git a/frontend/src/components/settings/SkillDialog.tsx b/frontend/src/components/settings/SkillDialog.tsx index 14115b0d..fa348006 100644 --- a/frontend/src/components/settings/SkillDialog.tsx +++ b/frontend/src/components/settings/SkillDialog.tsx @@ -21,9 +21,6 @@ const skillFormSchema = z.object({ description: z.string().min(1, 'Description is required').max(1024, 'Description must be 1024 characters or less'), body: z.string().min(1, 'Skill body is required'), scope: z.enum(['global', 'project']), - license: z.string().optional(), - compatibility: z.string().optional(), - metadata: z.record(z.string(), z.string()).optional(), }) type SkillFormValues = z.infer @@ -51,9 +48,6 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil description: skill?.description || '', body: skill?.body || '', scope: skill?.scope || 'global', - license: skill?.license || '', - compatibility: skill?.compatibility || '', - metadata: skill?.metadata || {}, } } @@ -84,9 +78,6 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil repoId: editingSkill.scope === 'project' ? editingSkill.repoId : undefined, description: values.description, body: values.body, - license: values.license || undefined, - compatibility: values.compatibility || undefined, - metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined, }) } else { onSubmit({ @@ -95,9 +86,6 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil body: values.body, scope: values.scope, repoId: values.scope === 'project' ? selectedRepoId : undefined, - license: values.license || undefined, - compatibility: values.compatibility || undefined, - metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined, }) } form.reset() @@ -204,68 +192,28 @@ export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: Skil /> {scope === 'project' && ( - ( - - Repository - - - - - - )} - /> + + Repository + + + + + )} - - ( - - License (Optional) - - - - - - )} - /> - - ( - - Compatibility (Optional) - - - - - - )} - /> diff --git a/frontend/src/contexts/EventContext.test.tsx b/frontend/src/contexts/EventContext.test.tsx index 5556c6b3..c2dafae1 100644 --- a/frontend/src/contexts/EventContext.test.tsx +++ b/frontend/src/contexts/EventContext.test.tsx @@ -5,7 +5,7 @@ import type { ReactNode } from 'react' import { MemoryRouter, useLocation } from 'react-router-dom' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { PermissionRequest, QuestionRequest } from '@/api/types' -import { EventProvider, usePermissions, useQuestions } from './EventContext' +import { EventProvider, usePermissions, useQuestions, useSSEHealth } from './EventContext' const mocks = vi.hoisted(() => ({ listRepos: vi.fn(), @@ -313,4 +313,39 @@ describe('EventProvider questions', () => { expect(screen.getByTestId('current')).toHaveTextContent('none') }) }) + + it('exposes sseHealth through context', async () => { + const mockSseManager = { + getHealth: vi.fn(() => ({ isConnected: true, isHealthy: true, lastEventAt: Date.now(), isStalled: false })), + subscribeHealth: vi.fn((listener) => { + listener({ isConnected: false, isHealthy: false, lastEventAt: null, isStalled: false }) + return () => {} + }), + } + + vi.mock('@/lib/sseManager', () => ({ + sseManager: mockSseManager, + subscribeToSSE: mocks.subscribeToSSE, + addSSEDirectory: mocks.addSSEDirectory, + ensureSSEConnected: mocks.ensureSSEConnected, + })) + + const TestComponent = () => { + const { isConnected, isHealthy, isStalled } = useSSEHealth() + return ( +
+
{String(isConnected)}
+
{String(isHealthy)}
+
{String(isStalled)}
+
+ ) + } + + render(, { wrapper: createWrapper() }) + + await waitFor(() => { + expect(screen.getByTestId('connected')).toHaveTextContent('false') + expect(screen.getByTestId('healthy')).toHaveTextContent('false') + }) + }) }) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 0c2bdb74..b6c214e6 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -6,7 +6,7 @@ import { OpenCodeClient } from '@/api/opencode' import { listRepos } from '@/api/repos' import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts } from '@/api/types' import { showToast } from '@/lib/toast' -import { subscribeToSSE, addSSEDirectory, ensureSSEConnected } from '@/lib/sseManager' +import { subscribeToSSE, addSSEDirectory, ensureSSEConnected, type SSEHealthState, sseManager } from '@/lib/sseManager' import { OPENCODE_API_ENDPOINT } from '@/config' import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState' @@ -149,6 +149,7 @@ interface EventContextValue { navigateToCurrent: () => void syncForSession: (directory: string, sessionID: string) => Promise } + sseHealth: SSEHealthState getRepoIdForSession: (sessionID: string) => number | null getClient: (sessionID: string) => OpenCodeClient | null } @@ -160,6 +161,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { const navigate = useNavigate() const [sshHostKeyRequest, setSSHHostKeyRequest] = useState(null) + const [sseHealth, setSseHealth] = useState(() => sseManager.getHealth()) const respondToSSHHostKey = useCallback(async (requestId: string, approved: boolean) => { try { @@ -528,7 +530,13 @@ export function EventProvider({ children }: { children: React.ReactNode }) { } const unsubscribe = subscribeToSSE(handleSSEMessage, handleStatusChange) - return unsubscribe + + const sseHealthUnsubscribe = sseManager.subscribeHealth(setSseHealth) + + return () => { + unsubscribe() + sseHealthUnsubscribe() + } }, [addPermission, removePermission, addQuestion, removeQuestion, rememberSessionDirectory, fetchInitialPendingData, queryClient]) useEffect(() => { @@ -583,6 +591,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { navigateToCurrent: navigateToCurrentQuestion, syncForSession: syncQuestionsForSession, }, + sseHealth, getRepoIdForSession, getClient, }), [ @@ -606,6 +615,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { hasQuestionsForSession, navigateToCurrentQuestion, syncQuestionsForSession, + sseHealth, getRepoIdForSession, getClient, ]) @@ -635,3 +645,7 @@ export function usePendingAlerts(): boolean { const { permissions, questions } = useEventContext() return permissions.pendingCount + questions.pendingCount > 0 } + +export function useSSEHealth(): SSEHealthState { + return useEventContext().sseHealth +} diff --git a/frontend/src/hooks/__tests__/useCommandHandler.test.tsx b/frontend/src/hooks/__tests__/useCommandHandler.test.tsx new file mode 100644 index 00000000..20f78c53 --- /dev/null +++ b/frontend/src/hooks/__tests__/useCommandHandler.test.tsx @@ -0,0 +1,147 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { renderHook } from '@testing-library/react' +import { useCommandHandler } from '../useCommandHandler' +import { ensureSSEConnected } from '@/lib/sseManager' +import { showToast } from '@/lib/toast' + +const mocks = vi.hoisted(() => ({ + sendCommand: vi.fn(), + summarizeSession: vi.fn(), + setStatus: vi.fn(), +})) + +vi.mock('@/lib/sseManager', () => ({ + ensureSSEConnected: vi.fn().mockResolvedValue(true), +})) + +vi.mock('@/api/opencode', () => ({ + createOpenCodeClient: vi.fn().mockImplementation(() => ({ + sendCommand: mocks.sendCommand, + summarizeSession: mocks.summarizeSession, + })), +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + error: vi.fn(), + success: vi.fn(), + info: vi.fn(), + loading: vi.fn(), + }, +})) + +vi.mock('@/hooks/useOpenCode', () => ({ + useCreateSession: vi.fn(() => ({ + mutateAsync: vi.fn(), + })), +})) + +vi.mock('@/hooks/useModelSelection', () => ({ + useModelSelection: vi.fn(() => ({ + model: { providerID: 'test-provider', modelID: 'test-model' }, + modelString: 'test-provider/test-model', + })), +})) + +vi.mock('react-router-dom', () => ({ + useNavigate: vi.fn(() => vi.fn()), +})) + +vi.mock('@/stores/sessionStatusStore', () => ({ + useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })), +})) + +describe('useCommandHandler', () => { + const baseProps = { + opcodeUrl: 'http://localhost:5551', + sessionID: 'test-session-id', + directory: '/test/dir', + currentAgent: 'test-agent', + } + + beforeEach(() => { + vi.clearAllMocks() + }) + + it('themes command awaits ensureSSEConnected before sendCommand', async () => { + mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1' }, parts: [] }) + + const { result } = renderHook(() => useCommandHandler(baseProps)) + const themesCommand = { name: 'themes' as const } + + await result.current.executeCommand(themesCommand, '') + + const sseCallOrder = (ensureSSEConnected as ReturnType).mock.invocationCallOrder[0] + const sendCallOrder = mocks.sendCommand.mock.invocationCallOrder[0] + expect(sseCallOrder).toBeLessThan(sendCallOrder) + expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', { + command: 'themes', + arguments: '', + agent: 'test-agent', + model: 'test-provider/test-model', + }) + }) + + it('compact command awaits ensureSSEConnected before summarizeSession', async () => { + mocks.summarizeSession.mockResolvedValue(undefined) + + const { result } = renderHook(() => useCommandHandler(baseProps)) + const compactCommand = { name: 'compact' as const } + + await result.current.executeCommand(compactCommand, '') + + const sseCallOrder = (ensureSSEConnected as ReturnType).mock.invocationCallOrder[0] + const summarizeCallOrder = mocks.summarizeSession.mock.invocationCallOrder[0] + expect(sseCallOrder).toBeLessThan(summarizeCallOrder) + expect(mocks.summarizeSession).toHaveBeenCalledWith( + 'test-session-id', + 'test-provider', + 'test-model' + ) + }) + + it('unknown command (default) awaits ensureSSEConnected before sendCommand', async () => { + mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1' }, parts: [] }) + + const { result } = renderHook(() => useCommandHandler(baseProps)) + const unknownCommand = { name: 'myskill' as const } + + await result.current.executeCommand(unknownCommand, '') + + const sseCallOrder = (ensureSSEConnected as ReturnType).mock.invocationCallOrder[0] + const sendCallOrder = mocks.sendCommand.mock.invocationCallOrder[0] + expect(sseCallOrder).toBeLessThan(sendCallOrder) + expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', { + command: 'myskill', + arguments: '', + agent: 'test-agent', + model: 'test-provider/test-model', + }) + }) + + it('sessions command does NOT call ensureSSEConnected or sendCommand', async () => { + const onShowSessionsDialog = vi.fn() + const { result } = renderHook(() => + useCommandHandler({ ...baseProps, onShowSessionsDialog }) + ) + const sessionsCommand = { name: 'sessions' as const } + + await result.current.executeCommand(sessionsCommand, '') + + expect(ensureSSEConnected).not.toHaveBeenCalled() + expect(mocks.sendCommand).not.toHaveBeenCalled() + expect(onShowSessionsDialog).toHaveBeenCalled() + }) + + it('shows error toast when ensureSSEConnected fails', async () => { + ;(ensureSSEConnected as ReturnType).mockResolvedValueOnce(false) + + const { result } = renderHook(() => useCommandHandler(baseProps)) + const themesCommand = { name: 'themes' as const } + + await result.current.executeCommand(themesCommand, '') + + expect(showToast.error).toHaveBeenCalledWith('Unable to connect. Please try again.') + expect(mocks.sendCommand).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/hooks/__tests__/useLoadSkill.test.tsx b/frontend/src/hooks/__tests__/useLoadSkill.test.tsx new file mode 100644 index 00000000..d98f9846 --- /dev/null +++ b/frontend/src/hooks/__tests__/useLoadSkill.test.tsx @@ -0,0 +1,293 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { renderHook, waitFor } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { useLoadSkill } from '../useOpenCode' +import type { MessageWithParts } from '../../api/types' + +import { showToast } from '../../lib/toast' + +const mocks = vi.hoisted(() => ({ + sendCommand: vi.fn(), + setStatus: vi.fn(), +})) + +vi.mock('../../lib/sseManager', () => ({ + ensureSSEConnected: vi.fn().mockResolvedValue(true), + reconnectSSE: vi.fn(), +})) + +const { ensureSSEConnected } = await vi.importMock('../../lib/sseManager') + +vi.mock('../../api/opencode', () => ({ + OpenCodeClient: vi.fn().mockImplementation(() => ({ + sendCommand: mocks.sendCommand, + })), +})) + +vi.mock('../../lib/toast', () => ({ + showToast: { + error: vi.fn(), + success: vi.fn(), + info: vi.fn(), + }, +})) + +vi.mock('../../stores/sessionStatusStore', () => ({ + useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })), +})) + +const createWrapper = () => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + return ({ children }: { children: React.ReactNode }) => + {children} +} + +describe('useLoadSkill', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('calls sendCommand with correct parameters when mutate is called', async () => { + const mockResponse = { + info: { id: 'asm_1', sessionID: 'test-session-id', role: 'assistant' }, + parts: [] + } + mocks.sendCommand.mockResolvedValue(mockResponse) + + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true) + }) + + expect(mocks.sendCommand).toHaveBeenCalledTimes(1) + expect(mocks.sendCommand).toHaveBeenCalledWith('test-session-id', { + command: 'my-skill', + arguments: '', + }) + }) + + it('throws error when sessionID is undefined', async () => { + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', undefined, '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + expect(result.current.error).toBeInstanceOf(Error) + expect((result.current.error as Error).message).toBe('No active session') + }) + + it('throws error when client is not available', async () => { + const { result } = renderHook( + () => useLoadSkill(null, 'test-session-id', '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + expect(result.current.error).toBeInstanceOf(Error) + expect((result.current.error as Error).message).toBe('No OpenCode client available') + }) + + it('calls showToast.error when sendCommand fails', async () => { + const testError = new Error('Command failed') + mocks.sendCommand.mockRejectedValue(testError) + + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + expect(showToast.error).toHaveBeenCalledTimes(1) + expect(showToast.error).toHaveBeenCalledWith('Command failed') + }) + + it('calls showToast.error with default message for non-Error objects', async () => { + mocks.sendCommand.mockRejectedValue('string error') + + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + expect(showToast.error).toHaveBeenCalledTimes(1) + expect(showToast.error).toHaveBeenCalledWith('Failed to load skill') + }) + + it('adds optimistic user message with skill name on mutate', async () => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + const messagesKey = ['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir'] + queryClient.setQueryData(messagesKey, []) + + mocks.sendCommand.mockReturnValue(new Promise(() => {})) + + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: ({ children }) => {children} }, + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + const messages = queryClient.getQueryData(messagesKey) + expect(messages).toHaveLength(1) + expect(messages?.[0].info.id).toMatch(/^optimistic_user_/) + expect((messages?.[0].parts[0] as { text?: string }).text).toBe('Loading skill: my-skill') + }) + }) + + it('sets session status to busy on mutate and idle on error', async () => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + const testError = new Error('Command failed') + mocks.sendCommand.mockRejectedValue(testError) + + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: ({ children }) => {children} }, + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'busy' }) + expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'idle' }) + }) + + it('removes optimistic message from cache on error', async () => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + const messagesKey = ['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir'] + queryClient.setQueryData(messagesKey, []) + + const testError = new Error('Command failed') + mocks.sendCommand.mockRejectedValue(testError) + + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: ({ children }) => {children} }, + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + const messages = queryClient.getQueryData(messagesKey) + expect(messages).toHaveLength(0) + }) + + it('ensures SSE is connected before sending command', async () => { + mocks.sendCommand.mockResolvedValue({ info: { id: 'asm_1', sessionID: 'test-session-id', role: 'assistant' }, parts: [] }) + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true) + }) + + expect(ensureSSEConnected).toHaveBeenCalledTimes(1) + const sseCallOrder = (ensureSSEConnected as ReturnType).mock.invocationCallOrder[0] + const sendCallOrder = mocks.sendCommand.mock.invocationCallOrder[0] + expect(sseCallOrder).toBeLessThan(sendCallOrder) + }) + + it('aborts when SSE cannot connect', async () => { + ;(ensureSSEConnected as ReturnType).mockResolvedValueOnce(false) + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper: createWrapper() } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isError).toBe(true) + }) + + expect(mocks.sendCommand).not.toHaveBeenCalled() + expect(showToast.error).toHaveBeenCalledWith('Unable to connect. Please try again.') + }) + + it('replaces optimistic message with assistant response on success', async () => { + const assistant = { + info: { id: 'asm_skill_1', sessionID: 'test-session-id', role: 'assistant' }, + parts: [{ type: 'text', text: 'done' }] + } + mocks.sendCommand.mockResolvedValue(assistant) + const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + mutations: { retry: false }, + }, + }) + const wrapper = ({ children }: { children: React.ReactNode }) => + {children} + const { result } = renderHook( + () => useLoadSkill('http://localhost:5551', 'test-session-id', '/test/dir'), + { wrapper } + ) + + result.current.mutate({ skillName: 'my-skill' }) + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true) + }) + + const messages = queryClient.getQueryData(['opencode', 'messages', 'http://localhost:5551', 'test-session-id', '/test/dir']) + expect(messages?.some(m => m.info.id === 'asm_skill_1')).toBe(true) + }) +}) diff --git a/frontend/src/hooks/__tests__/useMessages.fallback.test.tsx b/frontend/src/hooks/__tests__/useMessages.fallback.test.tsx new file mode 100644 index 00000000..097e420b --- /dev/null +++ b/frontend/src/hooks/__tests__/useMessages.fallback.test.tsx @@ -0,0 +1,91 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { renderHook, waitFor } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { useMessages } from '../useOpenCode' + +const mocks = vi.hoisted(() => ({ + listMessages: vi.fn(), +})) + +vi.mock('@/api/opencode', () => ({ + OpenCodeClient: vi.fn(() => ({ + listMessages: mocks.listMessages, + })), +})) + +describe('useMessages fallback poll', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + const createQueryClient = () => new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + + const wrapper = ({ children }: { children: React.ReactNode }) => ( + + {children} + + ) + + it('should poll every 5s when fallbackPoll is enabled', async () => { + vi.useFakeTimers() + + mocks.listMessages.mockResolvedValue([]) + + renderHook( + () => useMessages('http://localhost:5003', 'session-1', '/repo', { fallbackPoll: true }), + { wrapper } + ) + + expect(mocks.listMessages).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(5000) + + await waitFor(() => { + expect(mocks.listMessages).toHaveBeenCalledTimes(2) + }) + + vi.useRealTimers() + }) + + it('should not poll when fallbackPoll is disabled', async () => { + vi.useFakeTimers() + + mocks.listMessages.mockResolvedValue([]) + + renderHook( + () => useMessages('http://localhost:5003', 'session-1', '/repo', { fallbackPoll: false }), + { wrapper } + ) + + expect(mocks.listMessages).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(15000) + + expect(mocks.listMessages).toHaveBeenCalledTimes(1) + + vi.useRealTimers() + }) + + it('should not poll by default (no opts)', async () => { + vi.useFakeTimers() + + mocks.listMessages.mockResolvedValue([]) + + renderHook( + () => useMessages('http://localhost:5003', 'session-1', '/repo'), + { wrapper } + ) + + expect(mocks.listMessages).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(15000) + + expect(mocks.listMessages).toHaveBeenCalledTimes(1) + + vi.useRealTimers() + }) +}) diff --git a/frontend/src/hooks/useCommandHandler.ts b/frontend/src/hooks/useCommandHandler.ts index 731aa2c0..e4b5000c 100644 --- a/frontend/src/hooks/useCommandHandler.ts +++ b/frontend/src/hooks/useCommandHandler.ts @@ -4,6 +4,7 @@ import { createOpenCodeClient } from '@/api/opencode' import { useCreateSession } from '@/hooks/useOpenCode' import { useModelSelection } from '@/hooks/useModelSelection' import { showToast } from '@/lib/toast' +import { ensureSSEConnected } from '@/lib/sseManager' import type { components } from '@/api/opencode-types' import { useSessionStatus } from '@/stores/sessionStatusStore' @@ -46,6 +47,15 @@ export function useCommandHandler({ try { const client = createOpenCodeClient(opcodeUrl, directory) + const ensureLive = async () => { + const ok = await ensureSSEConnected() + if (!ok) { + showToast.error('Unable to connect. Please try again.') + setSessionStatus(sessionID, { type: 'idle' }) + } + return ok + } + switch (command.name) { case 'sessions': case 'resume': @@ -57,7 +67,8 @@ export function useCommandHandler({ onShowModelsDialog?.() break - case 'themes': + case 'themes': { + if (!(await ensureLive())) break await client.sendCommand(sessionID, { command: command.name, arguments: args, @@ -65,6 +76,7 @@ export function useCommandHandler({ model: modelString || undefined }) break + } case 'help': onShowHelpDialog?.() @@ -113,6 +125,8 @@ export function useCommandHandler({ break } + if (!(await ensureLive())) break + showToast.loading('Compacting session...', { id: `compact-${sessionID}` }) setSessionStatus(sessionID, { type: 'compact' }) @@ -130,7 +144,8 @@ export function useCommandHandler({ case 'undo': case 'redo': case 'editor': - case 'init': + case 'init': { + if (!(await ensureLive())) break await client.sendCommand(sessionID, { command: command.name, arguments: args, @@ -138,14 +153,17 @@ export function useCommandHandler({ model: modelString || undefined }) break + } - default: + default: { + if (!(await ensureLive())) break await client.sendCommand(sessionID, { command: command.name, arguments: args, agent: currentAgent, model: modelString || undefined }) + } } } catch (error) { showToast.error(`Command failed: ${error instanceof Error ? error.message : 'Unknown error'}`) diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index e9a08cf1..d684cdbf 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -21,6 +21,8 @@ type SendPromptRequest = NonNullable< paths["/session/{sessionID}/message"]["post"]["requestBody"] >["content"]["application/json"]; +type SendCommandResponse = paths["/session/{sessionID}/command"]["post"]["responses"]["200"]["content"]["application/json"]; + const parseModelString = (model: string) => { const [providerID, ...rest] = model.split("/"); const modelID = rest.join("/"); @@ -61,7 +63,7 @@ export const useSession = (opcodeUrl: string | null | undefined, sessionID: stri }); }; -export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => { +export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string, opts?: { fallbackPoll?: boolean }) => { const client = useOpenCodeClient(opcodeUrl, directory); return useQuery({ @@ -76,7 +78,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str refetchOnReconnect: true, staleTime: 30000, gcTime: 10 * 60 * 1000, - + refetchInterval: opts?.fallbackPoll ? 5000 : undefined, }); }; @@ -590,6 +592,8 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s return old.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_")); }, ); + + setSessionStatus(sessionID!, { type: "idle" }); }, onSuccess: (data, variables) => { const { sessionID } = variables; @@ -631,3 +635,89 @@ export const useAgents = (opcodeUrl: string | null | undefined, directory?: stri enabled: !!client, }); }; + +export const useLoadSkill = ( + opcodeUrl: string | null | undefined, + sessionID: string | undefined, + directory?: string, +) => { + const client = useOpenCodeClient(opcodeUrl, directory); + const queryClient = useQueryClient(); + const setSessionStatus = useSessionStatus((state) => state.setStatus); + + return useMutation< + { optimisticUserID: string; response: SendCommandResponse }, + Error, + { skillName: string } + >({ + mutationFn: async ({ skillName }: { skillName: string }) => { + if (!client) throw new Error("No OpenCode client available"); + if (!sessionID) throw new Error("No active session"); + + const connected = await ensureSSEConnected(); + if (!connected) { + showToast.error("Unable to connect. Please try again."); + throw new Error("SSE connection failed"); + } + + setSessionStatus(sessionID, { type: "busy" }); + + const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`; + const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory]; + + const userMessageParts = createOptimisticUserMessageParts( + sessionID, + [{ type: "text" as const, content: `Loading skill: ${skillName}` }], + optimisticUserID, + ); + const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID); + const optimisticMessageWithParts: MessageWithParts = { + info: userMessageInfo, + parts: userMessageParts, + }; + + await queryClient.cancelQueries({ queryKey: messagesQueryKey }); + queryClient.setQueryData( + messagesQueryKey, + (old) => [...(old || []), optimisticMessageWithParts], + ); + + const response = await client.sendCommand(sessionID, { command: skillName, arguments: "" }); + return { optimisticUserID, response }; + }, + onError: (error) => { + if (sessionID) { + const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory]; + setSessionStatus(sessionID!, { type: "idle" }); + queryClient.setQueryData( + messagesQueryKey, + (old) => old?.filter((m) => !m.info.id.startsWith("optimistic_")), + ); + } + const message = error instanceof Error ? error.message : "Failed to load skill"; + showToast.error(message); + }, + onSuccess: (data) => { + const { response } = data; + const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory]; + + queryClient.setQueryData( + messagesQueryKey, + (old) => { + if (!old) return old; + + const existingIdx = old.findIndex(m => m.info.id === response.info.id); + if (existingIdx >= 0) { + const updated = [...old]; + updated[existingIdx] = { info: response.info, parts: response.parts }; + return updated; + } + + return [...old, { info: response.info, parts: response.parts }]; + }, + ); + + setSessionStatus(sessionID!, { type: "idle" }); + }, + }); +}; diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index d1fb128d..e6f2d22c 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -351,6 +351,9 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, queryClient.invalidateQueries({ queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory], }) + queryClient.invalidateQueries({ + queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, directory], + }) }, [queryClient, opcodeUrl, directory]) useEffect(() => { diff --git a/frontend/src/lib/__tests__/sseManager.test.ts b/frontend/src/lib/__tests__/sseManager.test.ts new file mode 100644 index 00000000..5c4e24fb --- /dev/null +++ b/frontend/src/lib/__tests__/sseManager.test.ts @@ -0,0 +1,162 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { sseManager, SSEHealthState } from '../sseManager' + +describe('SSEManager', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + describe('markActivity', () => { + it('should update lastEventAt when activity occurs', () => { + const health = sseManager.getHealth() + const initialTime = health.lastEventAt + + const mockEventSource = { + onopen: null as ((event: Event) => void) | null, + onerror: null as ((event: Event) => void) | null, + onmessage: null as ((event: MessageEvent) => void) | null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + close: vi.fn(), + readyState: 1, + } + + const originalEventSource = global.EventSource + global.EventSource = vi.fn(() => mockEventSource) as any + + sseManager.reconnect() + + if (mockEventSource.onopen) { + mockEventSource.onopen(new Event('open')) + } + + const healthAfter = sseManager.getHealth() + expect(healthAfter.lastEventAt).not.toBeNull() + expect(healthAfter.lastEventAt).toBeGreaterThan(initialTime || 0) + + global.EventSource = originalEventSource + }) + }) + + describe('watchdog stall', () => { + it('should trip after 90s of inactivity', async () => { + const mockEventSource = { + onopen: null as ((event: Event) => void) | null, + onerror: null as ((event: Event) => void) | null, + onmessage: null as ((event: MessageEvent) => void) | null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + close: vi.fn(), + readyState: 1, + } + + const originalEventSource = global.EventSource + global.EventSource = vi.fn(() => mockEventSource) as any + + sseManager.reconnect() + + if (mockEventSource.onopen) { + mockEventSource.onopen(new Event('open')) + } + + const initialHealth = sseManager.getHealth() + expect(initialHealth.isHealthy).toBe(true) + expect(initialHealth.isStalled).toBe(false) + + await vi.advanceTimersByTimeAsync(90000) + + expect(mockEventSource.close).toHaveBeenCalled() + + global.EventSource = originalEventSource + }) + }) + + describe('connected event', () => { + it('should reset health to healthy on connected event', () => { + const mockEventSource = { + onopen: null as ((event: Event) => void) | null, + onerror: null as ((event: Event) => void) | null, + onmessage: null as ((event: MessageEvent) => void) | null, + addEventListener: vi.fn((event: string, handler: EventListener) => { + if (event === 'connected') { + setTimeout(() => { + handler(new MessageEvent('connected', { data: JSON.stringify({ clientId: 'test' }) })) + }, 0) + } + }), + removeEventListener: vi.fn(), + close: vi.fn(), + readyState: 1, + } + + const originalEventSource = global.EventSource + global.EventSource = vi.fn(() => mockEventSource) as any + + sseManager.reconnect() + + vi.advanceTimersByTime(100) + + const health = sseManager.getHealth() + expect(health.isConnected).toBe(true) + expect(health.isHealthy).toBe(true) + expect(health.isStalled).toBe(false) + + global.EventSource = originalEventSource + }) + }) + + describe('subscribeHealth', () => { + it('should return unsubscribe function and stop receiving updates', () => { + const listener = vi.fn() + + const unsubscribe = sseManager.subscribeHealth(listener) + + expect(listener).toHaveBeenCalledTimes(1) + + unsubscribe() + + const mockEventSource = { + onopen: null as ((event: Event) => void) | null, + onerror: null as ((event: Event) => void) | null, + onmessage: null as ((event: MessageEvent) => void) | null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + close: vi.fn(), + readyState: 1, + } + + const originalEventSource = global.EventSource + global.EventSource = vi.fn(() => mockEventSource) as any + + sseManager.reconnect() + + if (mockEventSource.onopen) { + mockEventSource.onopen(new Event('open')) + } + + expect(listener).toHaveBeenCalledTimes(1) + + global.EventSource = originalEventSource + }) + }) + + describe('SSEHealthState', () => { + it('should have correct interface', () => { + const health: SSEHealthState = { + isConnected: true, + isHealthy: true, + lastEventAt: Date.now(), + isStalled: false, + } + + expect(health.isConnected).toBeDefined() + expect(health.isHealthy).toBeDefined() + expect(health.lastEventAt).toBeDefined() + expect(health.isStalled).toBeDefined() + }) + }) +}) diff --git a/frontend/src/lib/sseManager.ts b/frontend/src/lib/sseManager.ts index 9ddcee57..3b684072 100644 --- a/frontend/src/lib/sseManager.ts +++ b/frontend/src/lib/sseManager.ts @@ -9,7 +9,14 @@ interface SSESubscriber { onStatusChange?: SSEStatusHandler } -const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE +export interface SSEHealthState { + isConnected: boolean + isHealthy: boolean + lastEventAt: number | null + isStalled: boolean +} + +const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS, STALL_THRESHOLD_MS, WATCHDOG_TICK_MS } = DEFAULTS.SSE class SSEManager { private static instance: SSEManager @@ -22,6 +29,9 @@ class SSEManager { private isConnected = false private subscriberIdCounter = 0 private clientId: string | null = null + private lastEventAt: number | null = null + private healthListeners: Set<(state: SSEHealthState) => void> = new Set() + private watchdogTimer: ReturnType | null = null private constructor() {} @@ -32,6 +42,69 @@ class SSEManager { return SSEManager.instance } + private markActivity() { + this.lastEventAt = Date.now() + this.notifyHealth() + } + + private startWatchdog() { + if (this.watchdogTimer) return + this.watchdogTimer = setInterval(() => { + if (this.lastEventAt == null) return + if (Date.now() - this.lastEventAt > STALL_THRESHOLD_MS) { + this.handleStall() + } + }, WATCHDOG_TICK_MS) + } + + private stopWatchdog() { + if (this.watchdogTimer) { + clearInterval(this.watchdogTimer) + this.watchdogTimer = null + } + } + + private handleStall() { + this.eventSource?.close() + this.eventSource = null + this.lastEventAt = null + this.notifyHealth() + this.connect() + } + + private notifyHealth() { + const state: SSEHealthState = { + isConnected: this.isConnected, + isHealthy: this.isConnected && this.lastEventAt != null && Date.now() - this.lastEventAt <= STALL_THRESHOLD_MS, + lastEventAt: this.lastEventAt, + isStalled: this.isConnected && this.lastEventAt != null && Date.now() - this.lastEventAt > STALL_THRESHOLD_MS, + } + this.healthListeners.forEach(listener => { + try { + listener(state) + } catch { + // Ignore listener errors + } + }) + } + + subscribeHealth(listener: (state: SSEHealthState) => void): () => void { + this.healthListeners.add(listener) + listener(this.getHealth()) + return () => { + this.healthListeners.delete(listener) + } + } + + getHealth(): SSEHealthState { + return { + isConnected: this.isConnected, + isHealthy: this.isConnected && this.lastEventAt != null && Date.now() - this.lastEventAt <= STALL_THRESHOLD_MS, + lastEventAt: this.lastEventAt, + isStalled: this.isConnected && this.lastEventAt != null && Date.now() - this.lastEventAt > STALL_THRESHOLD_MS, + } + } + subscribe( onMessage: SSEEventHandler, onStatusChange?: SSEStatusHandler @@ -161,13 +234,37 @@ class SSEManager { this.eventSource.onopen = () => { this.isConnected = true this.reconnectDelay = RECONNECT_DELAY_MS + this.startWatchdog() + this.markActivity() this.notifyStatusChange(true) + this.notifyHealth() } this.eventSource.onerror = () => { this.isConnected = false this.clientId = null + this.stopWatchdog() + this.lastEventAt = null this.notifyStatusChange(false) + this.notifyHealth() + + if (this.eventSource) { + this.eventSource.close() + this.eventSource = null + } + + if (this.subscribers.size > 0) { + this.scheduleReconnect() + } + } + + this.eventSource.onerror = () => { + this.isConnected = false + this.clientId = null + this.stopWatchdog() + this.lastEventAt = null + this.notifyStatusChange(false) + this.notifyHealth() if (this.eventSource) { this.eventSource.close() @@ -182,6 +279,7 @@ class SSEManager { this.eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data) + this.markActivity() this.broadcast(data) } catch { // Ignore parse errors @@ -195,7 +293,10 @@ class SSEManager { this.clientId = data.clientId } this.isConnected = true + this.startWatchdog() + this.markActivity() this.notifyStatusChange(true) + this.notifyHealth() this.flushPendingDirectories() } catch { // Ignore @@ -203,7 +304,7 @@ class SSEManager { }) this.eventSource.addEventListener('heartbeat', () => { - // Heartbeat received - connection is alive + this.markActivity() }) } @@ -213,6 +314,8 @@ class SSEManager { this.reconnectTimeout = null } + this.stopWatchdog() + if (this.eventSource) { this.eventSource.close() this.eventSource = null @@ -220,6 +323,8 @@ class SSEManager { this.isConnected = false this.clientId = null + this.lastEventAt = null + this.notifyHealth() } private scheduleReconnect(): void { diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index df831abc..eb896e45 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -41,7 +41,7 @@ import { RepoLspDialog } from "@/components/repo/RepoLspDialog"; import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; import { createOpenCodeClient } from "@/api/opencode"; import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore"; -import { usePermissions, useQuestions } from "@/contexts/EventContext"; +import { usePermissions, useQuestions, useSSEHealth } from "@/contexts/EventContext"; import type { QuestionRequest } from "@/api/types"; import { QuestionPrompt } from "@/components/session/QuestionPrompt"; import { MinimizedQuestionIndicator } from "@/components/session/MinimizedQuestionIndicator"; @@ -126,7 +126,12 @@ export function SessionDetail() { const repoDirectory = isAssistantSession ? assistantMode?.directory : repo?.fullPath; const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : ''; - const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory); + const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId); + const sseHealth = useSSEHealth(); + const sessionStatus = useSessionStatusForSession(sessionId); + const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'compact' || sessionStatus.type === 'retry'; + + const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory, { fallbackPoll: !sseHealth.isHealthy && isSessionActive }); const { data: session, isLoading: sessionLoading } = useSession( opcodeUrl, sessionId, @@ -151,8 +156,6 @@ export function SessionDetail() { contentVersion: messages?.reduce((sum, m) => sum + m.parts.length, 0) ?? 0, onScrollStateChange: setShowScrollButton }); - - const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId); const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId); const updateSession = useUpdateSession(opcodeUrl, repoDirectory); const createSession = useCreateSession(opcodeUrl, repoDirectory); @@ -164,8 +167,6 @@ export function SessionDetail() { const { syncForSession: syncPermissionsForSession } = usePermissions(); const { current: currentQuestion, reply: replyToQuestion, reject: rejectQuestion, syncForSession: syncQuestionsForSession } = useQuestions(); - const sessionStatus = useSessionStatusForSession(sessionId); - const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'compact' || sessionStatus.type === 'retry'; const lastAssistantMessage = messages?.filter(m => m.info.role === 'assistant').at(-1); const lastAssistantText = getAssistantText(lastAssistantMessage); const latestPlayableAssistant = useMemo(() => getLatestPlayableAssistantMessage(messages), [messages]); @@ -225,7 +226,7 @@ export function SessionDetail() { refetchOnMount: 'always', refetchOnReconnect: true, refetchOnWindowFocus: true, - refetchInterval: isSessionActive || hasIncompleteMessages ? PENDING_ACTION_SYNC_INTERVAL_MS : false, + refetchInterval: !sseHealth.isHealthy && (isSessionActive || hasIncompleteMessages) ? PENDING_ACTION_SYNC_INTERVAL_MS : false, retry: false, }) @@ -599,11 +600,17 @@ export function SessionDetail() { directory={repoDirectory} /> - + {repoDirectory && opcodeUrl && sessionId && ( + showToast.success(`Loaded skill: ${skill.name}`)} + /> + )} ({ + syncPendingActions: vi.fn(), +})) + +describe('SessionDetail pending-actions polling', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + const createQueryClient = () => new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + + const wrapper = ({ children }: { children: React.ReactNode }) => ( + + {children} + + ) + + it('should poll pending-actions when refetchInterval is set', async () => { + vi.useFakeTimers() + + mocks.syncPendingActions.mockResolvedValue(null) + + const testQueryOptions = { + queryKey: ['opencode', 'pending-actions', 'http://localhost:5003', 'session-1', '/repo'] as const, + queryFn: async () => { + await mocks.syncPendingActions() + return null + }, + enabled: true, + refetchOnMount: 'always' as const, + refetchOnReconnect: true, + refetchOnWindowFocus: true, + refetchInterval: 30000, + retry: false, + } + + renderHook( + () => useQuery(testQueryOptions), + { wrapper } + ) + + expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(30000) + + await waitFor(() => { + expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2) + }) + + vi.useRealTimers() + }) + + it('should not poll pending-actions when refetchInterval is false', async () => { + vi.useFakeTimers() + + mocks.syncPendingActions.mockResolvedValue(null) + + const testQueryOptions = { + queryKey: ['opencode', 'pending-actions', 'http://localhost:5003', 'session-1', '/repo'] as const, + queryFn: async () => { + await mocks.syncPendingActions() + return null + }, + enabled: true, + refetchOnMount: 'always' as const, + refetchOnReconnect: true, + refetchOnWindowFocus: true, + refetchInterval: false as const, + retry: false, + } + + renderHook( + () => useQuery(testQueryOptions), + { wrapper } + ) + + expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(60000) + + expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1) + + vi.useRealTimers() + }) +}) diff --git a/shared/src/config/defaults.ts b/shared/src/config/defaults.ts index a824b969..d0a3a330 100644 --- a/shared/src/config/defaults.ts +++ b/shared/src/config/defaults.ts @@ -51,7 +51,9 @@ export const DEFAULTS = { RECONNECT_DELAY_MS: 1000, MAX_RECONNECT_DELAY_MS: 30000, IDLE_GRACE_PERIOD_MS: 5000, - HEARTBEAT_INTERVAL_MS: 60000, + HEARTBEAT_INTERVAL_MS: 30000, + STALL_THRESHOLD_MS: 90000, + WATCHDOG_TICK_MS: 15000, }, } as const diff --git a/shared/src/schemas/skills.ts b/shared/src/schemas/skills.ts index 08c9c938..20467c8c 100644 --- a/shared/src/schemas/skills.ts +++ b/shared/src/schemas/skills.ts @@ -13,9 +13,6 @@ export type SkillScope = z.infer export const SkillFrontmatterSchema = z.object({ name: SkillNameSchema, description: z.string().min(1).max(1024), - license: z.string().optional(), - compatibility: z.string().optional(), - metadata: z.record(z.string(), z.string()).optional(), }) export type SkillFrontmatter = z.infer @@ -24,9 +21,6 @@ export const CreateSkillRequestSchema = z.object({ name: SkillNameSchema, description: z.string().min(1).max(1024), body: z.string(), - license: z.string().optional(), - compatibility: z.string().optional(), - metadata: z.record(z.string(), z.string()).optional(), scope: SkillScopeSchema, repoId: z.number().optional(), }) @@ -36,9 +30,6 @@ export type CreateSkillRequest = z.infer export const UpdateSkillRequestSchema = z.object({ description: z.string().min(1).max(1024).optional(), body: z.string().optional(), - license: z.string().nullable().optional(), - compatibility: z.string().nullable().optional(), - metadata: z.record(z.string(), z.string()).nullable().optional(), }) export type UpdateSkillRequest = z.infer @@ -47,9 +38,6 @@ export interface SkillFileInfo { name: string description: string body: string - license?: string - compatibility?: string - metadata?: Record scope: SkillScope location: string repoId?: number