mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat: directory files upload system, deferred restart model, cache invalidation consolidation, and misc improvements (#281)
* feat: show variant label on model picker and add folder upload for agents/commands
- Replace three-dot variant menu trigger with selected variant label
- Add POST /api/settings/opencode-directory-files/install endpoint
- Upload agents/commands markdown folders into .config/opencode/{agents,commands}/
- Reload OpenCode server after upload so files are picked up
* fix: revalidate branch/git caches when mobile sheet opens and on vcs.branch.updated SSE
- add shared invalidateRepoGitCaches() helper for consistent invalidation
- revalidate repo list when mobile repo quick-switch sheet opens
- revalidate current repo when mobile More drawer opens
- revalidate repo/git caches when Source Control dialog opens
- handle vcs.branch.updated SSE event with optimistic cache update
- use helper in branch create/switch mutations in useGit and BranchesTab
* style: make variant selector look more like a button with chevron and compact sizing
* refactor: consolidate settings editors, add folder upload support, and clean up unused code
* refactor: consolidate settings editors, add folder upload support, and clean up unused code
* feat: add opencode-directory-files listing service and consolidate settings editors
* fix: distinguish scroll from tap in suggestion popups on touch devices
* refactor: consolidate settings editors and add DirectoryFilesList component
* refactor: target repo status cache updates only to affected batch entries
* refactor: streamline settings, git hooks, and query invalidation logic
This commit is contained in:
1 parent
e53b4fd32c
commit
617962f2dd
48 files changed
+1522
-293
No files matched your search
@@ -91,6 +91,7 @@ export function createHealthRoutes(db: Database, openCodeSupervisor?: OpenCodeSu
|
||||
opencodeMinVersion: opencodeServerManager.getMinVersion(),
|
||||
opencodeVersionSupported: opencodeServerManager.isVersionSupported(),
|
||||
opencodeManagerVersion,
|
||||
opencodeRestartPending: opencodeServerManager.isRestartPending(),
|
||||
}
|
||||
|
||||
if (lifecycle) {
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createSettingsRoutes } from './settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
|
||||
interface TestUserPreferenceRow {
|
||||
@@ -205,9 +210,9 @@ function createTestDb(): Database {
|
||||
return db
|
||||
}
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
function createTestApp(db: Database, openCodeSupervisor?: OpenCodeSupervisor): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient()))
|
||||
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient(), openCodeSupervisor))
|
||||
return app
|
||||
}
|
||||
|
||||
@@ -291,3 +296,78 @@ describe('settings routes — serverEnvVars', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('settings routes — OpenCode directory file upload', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let originalWorkspacePath: string | undefined
|
||||
let workspacePath: string
|
||||
const restart = vi.fn(async () => undefined)
|
||||
let markRestartPendingSpy: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(async () => {
|
||||
db = createTestDb()
|
||||
restart.mockClear()
|
||||
markRestartPendingSpy = vi.spyOn(opencodeServerManager, 'markRestartPending').mockImplementation(() => undefined)
|
||||
originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
workspacePath = await mkdtemp(join(tmpdir(), 'ocm-command-upload-'))
|
||||
process.env.WORKSPACE_PATH = workspacePath
|
||||
app = createTestApp(db, { restart } as unknown as OpenCodeSupervisor)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalWorkspacePath) {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
} else {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
}
|
||||
await rm(workspacePath, { recursive: true, force: true })
|
||||
db.close()
|
||||
markRestartPendingSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('installs uploaded command markdown files into the OpenCode commands directory', async () => {
|
||||
const formData = new FormData()
|
||||
formData.append('kind', 'commands')
|
||||
formData.append('fileManifest', JSON.stringify([
|
||||
{ fieldName: 'file0', relativePath: 'commands/git/commit.md' },
|
||||
{ fieldName: 'file1', relativePath: 'commands/.DS_Store' },
|
||||
]))
|
||||
formData.append('file0', new File(['commit body'], 'commit.md', { type: 'text/markdown' }))
|
||||
|
||||
const res = await app.request('/settings/opencode-directory-files/install', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({
|
||||
kind: 'commands',
|
||||
filesInstalled: ['git/commit.md'],
|
||||
restartRequired: true,
|
||||
})
|
||||
await expect(readFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'utf8')).resolves.toBe('commit body')
|
||||
expect(restart).not.toHaveBeenCalled()
|
||||
expect(markRestartPendingSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('lists uploaded command and agent directory files', async () => {
|
||||
await mkdir(join(workspacePath, '.config/opencode/commands/git'), { recursive: true })
|
||||
await mkdir(join(workspacePath, '.config/opencode/agents/team'), { recursive: true })
|
||||
await writeFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'commit body')
|
||||
await writeFile(join(workspacePath, '.config/opencode/commands/git/.DS_Store'), 'metadata')
|
||||
await writeFile(join(workspacePath, '.config/opencode/agents/team/planner.md'), 'planner body')
|
||||
|
||||
const commandsRes = await app.request('/settings/opencode-directory-files?kind=commands')
|
||||
const agentsRes = await app.request('/settings/opencode-directory-files?kind=agents')
|
||||
|
||||
expect(commandsRes.status).toBe(200)
|
||||
expect(agentsRes.status).toBe(200)
|
||||
await expect(commandsRes.json()).resolves.toEqual([
|
||||
{ kind: 'commands', name: 'commit', relativePath: 'git/commit.md' },
|
||||
])
|
||||
await expect(agentsRes.json()).resolves.toEqual([
|
||||
{ kind: 'agents', name: 'planner', relativePath: 'team/planner.md' },
|
||||
])
|
||||
})
|
||||
})
|
||||
+185
-54
@@ -1,4 +1,4 @@
|
||||
import { Hono } from 'hono'
|
||||
import { Hono, type Context } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { execSync, spawnSync } from 'child_process'
|
||||
import { existsSync } from 'fs'
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
SkillScopeSchema,
|
||||
InstallSkillFromGithubRequestSchema,
|
||||
InstallSkillUploadRequestSchema,
|
||||
InstallSkillUploadManifestEntrySchema,
|
||||
type SkillScope,
|
||||
} from '@opencode-manager/shared'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -45,6 +44,14 @@ import {
|
||||
installSkillFromGithubTree,
|
||||
installSkillFromUploadedFiles,
|
||||
} from '../services/skills'
|
||||
import {
|
||||
installOpenCodeDirectoryFiles,
|
||||
listOpenCodeDirectoryFiles,
|
||||
getOpenCodeDirectoryFile,
|
||||
updateOpenCodeDirectoryFile,
|
||||
deleteOpenCodeDirectoryFile,
|
||||
} from '../services/opencode-directory-files'
|
||||
import { parseUploadManifest, readUploadedManifestFiles, UploadValidationError } from './upload-utils'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { githubFetch } from '../utils/github'
|
||||
|
||||
@@ -103,9 +110,9 @@ async function restartOpenCode(openCodeSupervisor?: OpenCodeSupervisor): Promise
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info(`Restarted OpenCode server after skill ${context}`)
|
||||
logger.info(`Restarted OpenCode server after ${context}`)
|
||||
} catch (restartError) {
|
||||
logger.warn(`Failed to restart OpenCode server after skill ${context}:`, restartError)
|
||||
logger.warn(`Failed to restart OpenCode server after ${context}:`, restartError)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +128,7 @@ async function dispatchSkillReload(
|
||||
return
|
||||
}
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'install')
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'skill install')
|
||||
|
||||
try {
|
||||
await openCodeClient.forward({
|
||||
@@ -141,12 +148,53 @@ async function reloadAfterSkillInstall(
|
||||
openCodeSupervisor: OpenCodeSupervisor | undefined,
|
||||
scope: SkillScope,
|
||||
repoId: number | undefined,
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
if (scope === 'project' && repoId !== undefined) {
|
||||
await dispatchSkillReload(db, openCodeClient, openCodeSupervisor, repoId)
|
||||
} else {
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'install')
|
||||
return false
|
||||
}
|
||||
|
||||
opencodeServerManager.markRestartPending()
|
||||
return true
|
||||
}
|
||||
|
||||
const OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS: ReadonlyArray<readonly [string, 400]> = [
|
||||
['No markdown', 400],
|
||||
['Path must be relative', 400],
|
||||
['Path must not contain', 400],
|
||||
['Path must reference', 400],
|
||||
['escapes', 400],
|
||||
['Missing upload file', 400],
|
||||
['not a valid file', 400],
|
||||
]
|
||||
|
||||
function matchErrorStatus<T extends number>(
|
||||
table: ReadonlyArray<readonly [string, T]>,
|
||||
error: Error,
|
||||
): T | null {
|
||||
const match = table.find(([needle]) => error.message.includes(needle))
|
||||
return match ? match[1] : null
|
||||
}
|
||||
|
||||
function handleOpenCodeDirectoryFileError(c: Context, error: unknown, operation: string) {
|
||||
logger.error(`Failed to ${operation} OpenCode directory file:`, error)
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
if ('code' in error && error.code === 'ENOENT') {
|
||||
return c.json({ error: 'File not found' }, 404)
|
||||
}
|
||||
|
||||
const status = matchErrorStatus(OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS, error)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ error: `Failed to ${operation} OpenCode directory file` }, 500)
|
||||
}
|
||||
|
||||
const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 404 | 409]> = [
|
||||
@@ -194,6 +242,10 @@ function parseBooleanFormValue(value: unknown): boolean | undefined {
|
||||
return undefined
|
||||
}
|
||||
|
||||
function getMarkdownUploadManifest(manifest: ReturnType<typeof parseUploadManifest>) {
|
||||
return manifest.filter(entry => entry.relativePath.toLowerCase().endsWith('.md'))
|
||||
}
|
||||
|
||||
function hasConfiguredPlugins(config: Record<string, unknown> | undefined): boolean {
|
||||
return Array.isArray(config?.plugin) && config.plugin.length > 0
|
||||
}
|
||||
@@ -522,9 +574,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
if (restartRequired) {
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
logger.info('OpenCode configuration requires process restart')
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
logger.info('OpenCode configuration change requires a server restart; deferring until requested')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ ...config, restartRequired: true })
|
||||
} else {
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
|
||||
if (!patchResult.success) {
|
||||
@@ -1217,6 +1269,109 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/opencode-directory-files/install', async (c) => {
|
||||
try {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
if (!contentType.includes('multipart/form-data')) {
|
||||
return c.json({ error: 'Unsupported content type. Use multipart/form-data' }, 400)
|
||||
}
|
||||
|
||||
const formData = await c.req.parseBody({ all: true })
|
||||
const kind = z.enum(['agents', 'commands']).parse(formData['kind'])
|
||||
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
const markdownManifest = getMarkdownUploadManifest(manifest)
|
||||
if (markdownManifest.length === 0) {
|
||||
return c.json({ error: `No markdown ${kind} files found` }, 400)
|
||||
}
|
||||
|
||||
const files = await readUploadedManifestFiles(formData, markdownManifest)
|
||||
|
||||
const result = await installOpenCodeDirectoryFiles(kind, files)
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ ...result, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to install OpenCode directory files:', error)
|
||||
|
||||
if (error instanceof UploadValidationError) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid upload data', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const status = matchErrorStatus(OPENCODE_DIRECTORY_UPLOAD_ERROR_STATUS, error)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json({ error: 'Failed to install OpenCode directory files' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-directory-files', async (c) => {
|
||||
try {
|
||||
const kind = z.enum(['agents', 'commands']).parse(c.req.query('kind'))
|
||||
return c.json(await listOpenCodeDirectoryFiles(kind))
|
||||
} catch (error) {
|
||||
logger.error('Failed to list OpenCode directory files:', error)
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid file kind', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
return c.json({ error: 'Failed to list OpenCode directory files' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-directory-files/content', async (c) => {
|
||||
try {
|
||||
const kind = z.enum(['agents', 'commands']).parse(c.req.query('kind'))
|
||||
const relativePath = z.string().min(1).parse(c.req.query('relativePath'))
|
||||
return c.json(await getOpenCodeDirectoryFile(kind, relativePath))
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'read')
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/opencode-directory-files', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { kind, relativePath, content } = z
|
||||
.object({
|
||||
kind: z.enum(['agents', 'commands']),
|
||||
relativePath: z.string().min(1),
|
||||
content: z.string(),
|
||||
})
|
||||
.parse(body)
|
||||
|
||||
const result = await updateOpenCodeDirectoryFile(kind, relativePath, content)
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ ...result, restartRequired: true })
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'update')
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/opencode-directory-files', async (c) => {
|
||||
try {
|
||||
const kind = z.enum(['agents', 'commands']).parse(c.req.query('kind'))
|
||||
const relativePath = z.string().min(1).parse(c.req.query('relativePath'))
|
||||
|
||||
await deleteOpenCodeDirectoryFile(kind, relativePath)
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ kind, relativePath, restartRequired: true })
|
||||
} catch (error) {
|
||||
return handleOpenCodeDirectoryFileError(c, error, 'delete')
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/skills/install', async (c) => {
|
||||
try {
|
||||
const contentType = c.req.header('content-type') || ''
|
||||
@@ -1231,9 +1386,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const result = await installSkillFromGithubTree(db, validated)
|
||||
|
||||
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId)
|
||||
const restartRequired = await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, validated.scope, validated.repoId)
|
||||
|
||||
return c.json(result)
|
||||
return c.json({ ...result, restartRequired })
|
||||
}
|
||||
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
@@ -1242,20 +1397,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const scope = formData['scope']
|
||||
const repoIdValue = formData['repoId']
|
||||
const overwriteValue = formData['overwrite']
|
||||
const fileManifestRaw = formData['fileManifest']
|
||||
|
||||
if (typeof fileManifestRaw !== 'string') {
|
||||
return c.json({ error: 'fileManifest is required as a JSON string' }, 400)
|
||||
}
|
||||
|
||||
let manifestEntries: unknown
|
||||
try {
|
||||
manifestEntries = JSON.parse(fileManifestRaw)
|
||||
} catch {
|
||||
return c.json({ error: 'fileManifest must be valid JSON' }, 400)
|
||||
}
|
||||
|
||||
const manifest = InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries)
|
||||
const manifest = parseUploadManifest(formData['fileManifest'])
|
||||
|
||||
const repoId = parseOptionalRepoId(repoIdValue as string | undefined)
|
||||
const overwrite = parseBooleanFormValue(overwriteValue)
|
||||
@@ -1275,43 +1418,31 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json({ error: 'fileManifest must contain at least one entry' }, 400)
|
||||
}
|
||||
|
||||
const missingFields = manifest.filter((entry) => !formData[entry.fieldName])
|
||||
if (missingFields.length > 0) {
|
||||
return c.json({
|
||||
error: `Missing upload file(s): ${missingFields.map((e) => e.fieldName).join(', ')}`,
|
||||
}, 400)
|
||||
}
|
||||
|
||||
const files = await Promise.all(
|
||||
manifest.map(async (entry) => {
|
||||
const file = formData[entry.fieldName]
|
||||
if (!file || !(file instanceof File)) {
|
||||
throw new Error(`Field "${entry.fieldName}" is not a valid file`)
|
||||
}
|
||||
const content = Buffer.from(await file.arrayBuffer())
|
||||
return { relativePath: entry.relativePath, content }
|
||||
}),
|
||||
)
|
||||
const files = await readUploadedManifestFiles(formData, manifest)
|
||||
|
||||
const result = await installSkillFromUploadedFiles(db, uploadRequest, files)
|
||||
|
||||
await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId)
|
||||
const restartRequired = await reloadAfterSkillInstall(db, openCodeClient, openCodeSupervisor, uploadRequest.scope, uploadRequest.repoId)
|
||||
|
||||
return c.json(result)
|
||||
return c.json({ ...result, restartRequired })
|
||||
}
|
||||
|
||||
return c.json({ error: 'Unsupported content type. Use application/json or multipart/form-data' }, 400)
|
||||
} catch (error) {
|
||||
logger.error('Failed to install skill:', error)
|
||||
|
||||
if (error instanceof UploadValidationError) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid skill install data', details: error.issues }, 400)
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const match = SKILL_INSTALL_ERROR_STATUS.find(([needle]) => error.message.includes(needle))
|
||||
if (match) {
|
||||
return c.json({ error: error.message }, match[1])
|
||||
const status = matchErrorStatus(SKILL_INSTALL_ERROR_STATUS, error)
|
||||
if (status) {
|
||||
return c.json({ error: error.message }, status)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1356,9 +1487,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const skill = await createSkill(db, validated)
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'creation')
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json(skill)
|
||||
return c.json({ ...skill, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to create skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1385,9 +1516,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
const skill = await updateSkill(db, openCodeClient, name, scope, validated, repoId)
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'update')
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json(skill)
|
||||
return c.json({ ...skill, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
@@ -1418,9 +1549,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
await deleteSkill(db, name, scope, repoId)
|
||||
|
||||
await restartOpenCodeSafe(openCodeSupervisor, 'deletion')
|
||||
opencodeServerManager.markRestartPending()
|
||||
|
||||
return c.json({ success: true })
|
||||
return c.json({ success: true, restartRequired: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete skill:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { InstallSkillUploadManifestEntrySchema, type InstallSkillUploadManifestEntry } from '@opencode-manager/shared'
|
||||
|
||||
export class UploadValidationError extends Error {}
|
||||
|
||||
type ParsedFormData = Record<string, unknown>
|
||||
|
||||
export function parseUploadManifest(fileManifestRaw: unknown): InstallSkillUploadManifestEntry[] {
|
||||
if (typeof fileManifestRaw !== 'string') {
|
||||
throw new UploadValidationError('fileManifest is required as a JSON string')
|
||||
}
|
||||
|
||||
let manifestEntries: unknown
|
||||
try {
|
||||
manifestEntries = JSON.parse(fileManifestRaw)
|
||||
} catch {
|
||||
throw new UploadValidationError('fileManifest must be valid JSON')
|
||||
}
|
||||
|
||||
return InstallSkillUploadManifestEntrySchema.array().parse(manifestEntries)
|
||||
}
|
||||
|
||||
export async function readUploadedManifestFiles(
|
||||
formData: ParsedFormData,
|
||||
manifest: InstallSkillUploadManifestEntry[],
|
||||
): Promise<{ relativePath: string; content: Buffer }[]> {
|
||||
const missingFields = manifest.filter((entry) => !formData[entry.fieldName])
|
||||
if (missingFields.length > 0) {
|
||||
throw new UploadValidationError(`Missing upload file(s): ${missingFields.map((e) => e.fieldName).join(', ')}`)
|
||||
}
|
||||
|
||||
return Promise.all(
|
||||
manifest.map(async (entry) => {
|
||||
const file = formData[entry.fieldName]
|
||||
if (!file || !(file instanceof File)) {
|
||||
throw new Error(`Field "${entry.fieldName}" is not a valid file`)
|
||||
}
|
||||
const content = Buffer.from(await file.arrayBuffer())
|
||||
return { relativePath: entry.relativePath, content }
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -89,6 +89,35 @@ export async function getFileStats(filePath: string): Promise<{ size: number; la
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeUploadRelativePath(
|
||||
relativePath: string,
|
||||
options?: { collapseEmptySegments?: boolean },
|
||||
): string {
|
||||
const normalized = relativePath.replace(/\\/g, '/')
|
||||
if (path.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) {
|
||||
throw new Error(`Path must be relative, got absolute path: "${relativePath}"`)
|
||||
}
|
||||
if (normalized === '' || normalized === '.') {
|
||||
throw new Error('Path must not be empty')
|
||||
}
|
||||
const rawParts = normalized.split('/')
|
||||
const parts = options?.collapseEmptySegments ? rawParts.filter(Boolean) : rawParts
|
||||
for (const part of parts) {
|
||||
if (part === '..') {
|
||||
throw new Error(`Path must not contain "..": "${relativePath}"`)
|
||||
}
|
||||
}
|
||||
return options?.collapseEmptySegments ? parts.join('/') : normalized
|
||||
}
|
||||
|
||||
export function resolveWithinDirectory(rootDir: string, relativePath: string, escapeLabel: string): string {
|
||||
const resolved = path.resolve(rootDir, relativePath)
|
||||
if (!resolved.startsWith(rootDir + path.sep)) {
|
||||
throw new Error(`File "${relativePath}" escapes the ${escapeLabel}`)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
export async function listDirectory(dirPath: string): Promise<Array<{
|
||||
name: string
|
||||
path: string
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
|
||||
|
||||
export type OpenCodeDirectoryFileKind = 'agents' | 'commands'
|
||||
|
||||
interface UploadedOpenCodeFile {
|
||||
relativePath: string
|
||||
content: Buffer
|
||||
}
|
||||
|
||||
export interface InstallOpenCodeDirectoryFilesResult {
|
||||
kind: OpenCodeDirectoryFileKind
|
||||
filesInstalled: string[]
|
||||
}
|
||||
|
||||
export interface OpenCodeDirectoryFileInfo {
|
||||
kind: OpenCodeDirectoryFileKind
|
||||
name: string
|
||||
relativePath: string
|
||||
}
|
||||
|
||||
function getOpenCodeDirectoryRoot(kind: OpenCodeDirectoryFileKind): string {
|
||||
return path.join(getWorkspacePath(), '.config', 'opencode', kind)
|
||||
}
|
||||
|
||||
function getNameFromRelativePath(relativePath: string): string {
|
||||
return relativePath.replace(/\.md$/i, '').split('/').pop() ?? relativePath
|
||||
}
|
||||
|
||||
async function listMarkdownFiles(rootDir: string, currentDir = rootDir): Promise<string[]> {
|
||||
let entries
|
||||
try {
|
||||
entries = await fs.readdir(currentDir, { withFileTypes: true })
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return []
|
||||
throw error
|
||||
}
|
||||
|
||||
const files = await Promise.all(entries.map(async entry => {
|
||||
const absolutePath = path.join(currentDir, entry.name)
|
||||
if (entry.isDirectory()) return listMarkdownFiles(rootDir, absolutePath)
|
||||
if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) return []
|
||||
|
||||
return [path.relative(rootDir, absolutePath).replace(/\\/g, '/')]
|
||||
}))
|
||||
|
||||
return files.flat().sort((a, b) => a.localeCompare(b))
|
||||
}
|
||||
|
||||
function getTargetRelativePath(relativePath: string, kind: OpenCodeDirectoryFileKind): string | null {
|
||||
const normalized = normalizeUploadRelativePath(relativePath, { collapseEmptySegments: true })
|
||||
if (!normalized.toLowerCase().endsWith('.md')) return null
|
||||
|
||||
const parts = normalized.split('/')
|
||||
const kindIndex = parts.findIndex(part => part === kind)
|
||||
const targetParts = kindIndex >= 0 ? parts.slice(kindIndex + 1) : parts.slice(1)
|
||||
const fallbackParts = parts.length === 1 ? parts : targetParts
|
||||
const targetRelativePath = fallbackParts.join('/')
|
||||
|
||||
return targetRelativePath || null
|
||||
}
|
||||
|
||||
export async function installOpenCodeDirectoryFiles(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
files: UploadedOpenCodeFile[],
|
||||
): Promise<InstallOpenCodeDirectoryFilesResult> {
|
||||
const targetRoot = getOpenCodeDirectoryRoot(kind)
|
||||
const preparedFiles = files.flatMap(file => {
|
||||
const relativePath = getTargetRelativePath(file.relativePath, kind)
|
||||
return relativePath ? [{ relativePath, content: file.content }] : []
|
||||
})
|
||||
|
||||
if (preparedFiles.length === 0) {
|
||||
throw new Error(`No markdown ${kind} files found`)
|
||||
}
|
||||
|
||||
const targets = preparedFiles.map(file => ({
|
||||
relativePath: file.relativePath,
|
||||
content: file.content,
|
||||
targetFilePath: resolveWithinDirectory(targetRoot, file.relativePath, `${kind} directory`),
|
||||
}))
|
||||
|
||||
await fs.mkdir(targetRoot, { recursive: true })
|
||||
|
||||
await Promise.all(
|
||||
targets.map(async target => {
|
||||
await fs.mkdir(path.dirname(target.targetFilePath), { recursive: true })
|
||||
await fs.writeFile(target.targetFilePath, target.content)
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
kind,
|
||||
filesInstalled: preparedFiles.map(file => file.relativePath),
|
||||
}
|
||||
}
|
||||
|
||||
export async function listOpenCodeDirectoryFiles(kind: OpenCodeDirectoryFileKind): Promise<OpenCodeDirectoryFileInfo[]> {
|
||||
const rootDir = getOpenCodeDirectoryRoot(kind)
|
||||
const files = await listMarkdownFiles(rootDir)
|
||||
|
||||
return files.map(relativePath => ({
|
||||
kind,
|
||||
name: getNameFromRelativePath(relativePath),
|
||||
relativePath,
|
||||
}))
|
||||
}
|
||||
|
||||
function resolveDirectoryFilePath(kind: OpenCodeDirectoryFileKind, relativePath: string): string {
|
||||
const normalized = normalizeUploadRelativePath(relativePath, { collapseEmptySegments: true })
|
||||
if (!normalized.toLowerCase().endsWith('.md')) {
|
||||
throw new Error(`Path must reference a markdown file: "${relativePath}"`)
|
||||
}
|
||||
return resolveWithinDirectory(getOpenCodeDirectoryRoot(kind), normalized, `${kind} directory`)
|
||||
}
|
||||
|
||||
export async function getOpenCodeDirectoryFile(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
relativePath: string,
|
||||
): Promise<OpenCodeDirectoryFileInfo & { content: string }> {
|
||||
const filePath = resolveDirectoryFilePath(kind, relativePath)
|
||||
const content = await fs.readFile(filePath, 'utf8')
|
||||
|
||||
return {
|
||||
kind,
|
||||
name: getNameFromRelativePath(relativePath),
|
||||
relativePath,
|
||||
content,
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateOpenCodeDirectoryFile(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
relativePath: string,
|
||||
content: string,
|
||||
): Promise<OpenCodeDirectoryFileInfo> {
|
||||
const filePath = resolveDirectoryFilePath(kind, relativePath)
|
||||
await fs.access(filePath)
|
||||
await fs.writeFile(filePath, content, 'utf8')
|
||||
|
||||
return {
|
||||
kind,
|
||||
name: getNameFromRelativePath(relativePath),
|
||||
relativePath,
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOpenCodeDirectoryFile(
|
||||
kind: OpenCodeDirectoryFileKind,
|
||||
relativePath: string,
|
||||
): Promise<void> {
|
||||
const filePath = resolveDirectoryFilePath(kind, relativePath)
|
||||
await fs.unlink(filePath)
|
||||
}
|
||||
@@ -30,6 +30,8 @@ const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
const HEALTH_CHECK_TIMEOUT_MS = 3000
|
||||
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
|
||||
const PROCESS_EXIT_GRACE_MS = 2000
|
||||
const PROCESS_EXIT_POLL_MS = 50
|
||||
const DEPRECATED_PLUGIN_PACKAGES = ['opencode-openai-codex-auth', 'opencode-copilot-auth']
|
||||
|
||||
type StartupValidationIssue = {
|
||||
@@ -106,6 +108,7 @@ class OpenCodeServerManager {
|
||||
private db: Database | null = null
|
||||
private version: string | null = null
|
||||
private lastStartupError: string | null = null
|
||||
private restartPending: boolean = false
|
||||
private opInProgress: boolean = false
|
||||
private openCodeClient: OpenCodeClient | null = null
|
||||
|
||||
@@ -405,6 +408,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
this.isHealthy = true
|
||||
this.restartPending = false
|
||||
logger.info('OpenCode server is healthy')
|
||||
|
||||
await this.fetchVersion()
|
||||
@@ -441,16 +445,18 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
const exited = await this.waitForProcessExit(this.serverPid, PROCESS_EXIT_GRACE_MS)
|
||||
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${this.serverPid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
|
||||
if (!exited) {
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${this.serverPid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,7 +623,6 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
logger.info('Restarting OpenCode server (full process restart)')
|
||||
await this.stop(true)
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
await this.start(false, true)
|
||||
} finally {
|
||||
this.releaseOp(acquired)
|
||||
@@ -698,6 +703,14 @@ class OpenCodeServerManager {
|
||||
this.lastStartupError = null
|
||||
}
|
||||
|
||||
isRestartPending(): boolean {
|
||||
return this.restartPending
|
||||
}
|
||||
|
||||
markRestartPending(): void {
|
||||
this.restartPending = true
|
||||
}
|
||||
|
||||
async reinitializeBinDirectory(): Promise<void> {
|
||||
logger.info('Reinitializing OpenCode bin directory')
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
@@ -733,6 +746,22 @@ class OpenCodeServerManager {
|
||||
return null
|
||||
}
|
||||
|
||||
private async waitForProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
await new Promise(r => setTimeout(r, PROCESS_EXIT_POLL_MS))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private async waitForHealth(timeoutMs: number): Promise<boolean> {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { SKILL_NAME_REGEX, SkillFrontmatterSchema } from '@opencode-manager/shar
|
||||
import { getWorkspacePath, FILE_LIMITS } 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 { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory, normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { githubFetchJson, githubFetchBinary, type GithubFetchFn } from '../utils/github'
|
||||
@@ -46,23 +46,6 @@ function getSkillTargetRoot(db: Database, scope: SkillScope, repoId?: number): s
|
||||
return getProjectSkillsPath(repo)
|
||||
}
|
||||
|
||||
function normalizeInstallRelativePath(relativePath: string): string {
|
||||
const normalized = relativePath.replace(/\\/g, '/')
|
||||
if (path.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) {
|
||||
throw new Error(`Path must be relative, got absolute path: "${relativePath}"`)
|
||||
}
|
||||
if (normalized === '' || normalized === '.') {
|
||||
throw new Error('Path must not be empty')
|
||||
}
|
||||
const parts = normalized.split('/')
|
||||
for (const part of parts) {
|
||||
if (part === '..') {
|
||||
throw new Error(`Path must not contain "..": "${relativePath}"`)
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function parseSkillMarkdown(content: string): { name: string; description: string; body: string } {
|
||||
if (!content.startsWith('---\n')) {
|
||||
throw new Error('Skill markdown must start with a frontmatter block')
|
||||
@@ -99,7 +82,7 @@ function parseSkillMarkdown(content: string): { name: string; description: strin
|
||||
function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles {
|
||||
const normalized = files.map(f => ({
|
||||
...f,
|
||||
relativePath: normalizeInstallRelativePath(f.relativePath),
|
||||
relativePath: normalizeUploadRelativePath(f.relativePath),
|
||||
}))
|
||||
const skillMdFiles = normalized.filter(f => path.basename(f.relativePath) === 'SKILL.md')
|
||||
if (skillMdFiles.length === 0) {
|
||||
@@ -119,7 +102,7 @@ function prepareSingleSkillFiles(files: SkillInstallFile[]): PreparedSkillFiles
|
||||
relativePath: skillDir === '.' ? f.relativePath : f.relativePath.substring(prefix.length),
|
||||
}))
|
||||
for (const f of strippedFiles) {
|
||||
const checkPath = normalizeInstallRelativePath(f.relativePath)
|
||||
const checkPath = normalizeUploadRelativePath(f.relativePath)
|
||||
if (checkPath.startsWith('..')) {
|
||||
throw new Error(`File "${f.relativePath}" escapes the skill directory`)
|
||||
}
|
||||
@@ -157,10 +140,7 @@ async function installSkillFiles(
|
||||
|
||||
try {
|
||||
for (const file of prepared.files) {
|
||||
const targetFilePath = path.resolve(stagingDir, file.relativePath)
|
||||
if (!targetFilePath.startsWith(stagingDir + path.sep)) {
|
||||
throw new Error(`File "${file.relativePath}" escapes the staging directory`)
|
||||
}
|
||||
const targetFilePath = resolveWithinDirectory(stagingDir, file.relativePath, 'staging directory')
|
||||
await fs.mkdir(path.dirname(targetFilePath), { recursive: true })
|
||||
await fs.writeFile(targetFilePath, file.content)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
getVersion: vi.fn(() => '1.0.0'),
|
||||
getMinVersion: vi.fn(() => '1.0.137'),
|
||||
isVersionSupported: vi.fn(() => true),
|
||||
isRestartPending: vi.fn(() => false),
|
||||
},
|
||||
}))
|
||||
|
||||
|
||||
@@ -71,6 +71,8 @@ vi.mock('../../src/services/opencode-single-server', () => {
|
||||
restart: vi.fn(),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(),
|
||||
markRestartPending: vi.fn(),
|
||||
isRestartPending: vi.fn(),
|
||||
setDatabase: vi.fn(),
|
||||
reinitializeBinDirectory: vi.fn(),
|
||||
},
|
||||
@@ -124,6 +126,7 @@ const mockInstallFromGithubTree = installSkillFromGithubTree as ReturnType<typeo
|
||||
const mockInstallFromUploadedFiles = installSkillFromUploadedFiles as ReturnType<typeof vi.fn>
|
||||
const mockDeleteSkill = deleteSkill as ReturnType<typeof vi.fn>
|
||||
const mockRestart = opencodeServerManager.restart as ReturnType<typeof vi.fn>
|
||||
const mockMarkRestartPending = opencodeServerManager.markRestartPending as ReturnType<typeof vi.fn>
|
||||
|
||||
const mockSuccessResponse = {
|
||||
skill: {
|
||||
@@ -166,14 +169,15 @@ describe('Settings Routes - Skill Install', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as Record<string, unknown>
|
||||
expect(body).toEqual(mockSuccessResponse)
|
||||
expect(body).toEqual({ ...mockSuccessResponse, restartRequired: true })
|
||||
expect(mockInstallFromGithubTree).toHaveBeenCalledTimes(1)
|
||||
expect(mockInstallFromGithubTree).toHaveBeenCalledWith(testDb, {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/mattpocock/skills/tree/main/skills/productivity/teach',
|
||||
scope: 'global',
|
||||
})
|
||||
expect(mockRestart).toHaveBeenCalledTimes(1)
|
||||
expect(mockMarkRestartPending).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('installs from multipart upload', async () => {
|
||||
@@ -209,7 +213,8 @@ describe('Settings Routes - Skill Install', () => {
|
||||
}),
|
||||
],
|
||||
)
|
||||
expect(mockRestart).toHaveBeenCalledTimes(1)
|
||||
expect(mockMarkRestartPending).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestart).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 409 on existing skill', async () => {
|
||||
|
||||
@@ -104,6 +104,8 @@ vi.mock('../../src/services/opencode-single-server', async (importOriginal) => {
|
||||
restart: vi.fn(),
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(),
|
||||
markRestartPending: vi.fn(),
|
||||
isRestartPending: vi.fn(),
|
||||
setDatabase: vi.fn(),
|
||||
reinitializeBinDirectory: vi.fn(),
|
||||
},
|
||||
|
||||
@@ -13,12 +13,26 @@ import type {
|
||||
SkillScope,
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillResponse,
|
||||
OpenCodeDirectoryFileInfo,
|
||||
} from './types/settings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
|
||||
const DEFAULT_USER_ID = 'default'
|
||||
|
||||
function appendFilesWithManifest(formData: FormData, files: File[]): void {
|
||||
const fileManifest: Array<{ fieldName: string; relativePath: string }> = []
|
||||
|
||||
files.forEach((file, index) => {
|
||||
const fieldName = `file${index}`
|
||||
const relativePath = file.webkitRelativePath || file.name
|
||||
fileManifest.push({ fieldName, relativePath })
|
||||
formData.append(fieldName, file)
|
||||
})
|
||||
|
||||
formData.append('fileManifest', JSON.stringify(fileManifest))
|
||||
}
|
||||
|
||||
export const settingsApi = {
|
||||
getSettings: async (userId = DEFAULT_USER_ID): Promise<SettingsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, {
|
||||
@@ -291,22 +305,65 @@ export const settingsApi = {
|
||||
if (data.repoId !== undefined) formData.append('repoId', String(data.repoId))
|
||||
if (data.overwrite !== undefined) formData.append('overwrite', String(data.overwrite))
|
||||
|
||||
const fileManifest: Array<{ fieldName: string; relativePath: string }> = []
|
||||
|
||||
data.files.forEach((file, index) => {
|
||||
const fieldName = `file${index}`
|
||||
const relativePath = file.webkitRelativePath || file.name
|
||||
fileManifest.push({ fieldName, relativePath })
|
||||
formData.append(fieldName, file)
|
||||
})
|
||||
|
||||
formData.append('fileManifest', JSON.stringify(fileManifest))
|
||||
appendFilesWithManifest(formData, data.files)
|
||||
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
},
|
||||
|
||||
installOpenCodeDirectoryFiles: async (data: {
|
||||
kind: 'agents' | 'commands'
|
||||
files: File[]
|
||||
}): Promise<{ kind: 'agents' | 'commands'; filesInstalled: string[] }> => {
|
||||
const formData = new FormData()
|
||||
formData.append('kind', data.kind)
|
||||
|
||||
appendFilesWithManifest(formData, data.files)
|
||||
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files/install`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
},
|
||||
|
||||
listOpenCodeDirectoryFiles: async (kind: 'agents' | 'commands'): Promise<OpenCodeDirectoryFileInfo[]> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, {
|
||||
params: { kind },
|
||||
})
|
||||
},
|
||||
|
||||
getOpenCodeDirectoryFile: async (
|
||||
kind: 'agents' | 'commands',
|
||||
relativePath: string,
|
||||
): Promise<OpenCodeDirectoryFileInfo & { content: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files/content`, {
|
||||
params: { kind, relativePath },
|
||||
})
|
||||
},
|
||||
|
||||
updateOpenCodeDirectoryFile: async (data: {
|
||||
kind: 'agents' | 'commands'
|
||||
relativePath: string
|
||||
content: string
|
||||
}): Promise<OpenCodeDirectoryFileInfo> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
},
|
||||
|
||||
deleteOpenCodeDirectoryFile: async (
|
||||
kind: 'agents' | 'commands',
|
||||
relativePath: string,
|
||||
): Promise<{ kind: 'agents' | 'commands'; relativePath: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, {
|
||||
method: 'DELETE',
|
||||
params: { kind, relativePath },
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export interface VersionInfo {
|
||||
|
||||
@@ -210,6 +210,14 @@ export interface SSELspUpdatedEvent {
|
||||
properties: Record<string, never>
|
||||
}
|
||||
|
||||
export interface SSEVcsBranchUpdatedEvent {
|
||||
type: 'vcs.branch.updated'
|
||||
directory?: string
|
||||
properties: {
|
||||
branch?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESSHHostKeyRequestEvent {
|
||||
type: 'ssh.host-key-request'
|
||||
properties: SSHHostKeyRequest
|
||||
@@ -237,6 +245,7 @@ export type SSEEvent =
|
||||
| SSEInstallationUpdatedEvent
|
||||
| SSEInstallationUpdateAvailableEvent
|
||||
| SSELspUpdatedEvent
|
||||
| SSEVcsBranchUpdatedEvent
|
||||
| SSESSHHostKeyRequestEvent
|
||||
|
||||
export type ContentPart =
|
||||
|
||||
@@ -92,6 +92,7 @@ export interface OpenCodeConfig {
|
||||
message: string
|
||||
}>
|
||||
removedFields?: string[]
|
||||
restartRequired?: boolean
|
||||
isValid: boolean
|
||||
isDefault: boolean
|
||||
createdAt: number
|
||||
@@ -137,3 +138,9 @@ export interface SyncOpenCodeImportResponse extends OpenCodeImportStatus {
|
||||
errors: Array<{ path: string; error: string }>
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenCodeDirectoryFileInfo {
|
||||
kind: 'agents' | 'commands'
|
||||
name: string
|
||||
relativePath: string
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Command } from 'lucide-react'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
|
||||
|
||||
type CommandType = components['schemas']['Command']
|
||||
|
||||
@@ -22,6 +23,7 @@ export function CommandSuggestions({
|
||||
selectedIndex = 0
|
||||
}: CommandSuggestionsProps) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const touchTapSelect = useTouchTapSelect(onSelect)
|
||||
|
||||
const filteredCommands = commands.filter(command =>
|
||||
command.name.toLowerCase().includes(query.toLowerCase())
|
||||
@@ -66,11 +68,10 @@ export function CommandSuggestions({
|
||||
<button
|
||||
key={command.name}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onTouchEnd={(e) => {
|
||||
e.preventDefault()
|
||||
onSelect(command)
|
||||
}}
|
||||
onClick={() => onSelect(command)}
|
||||
onTouchStart={touchTapSelect.onTouchStart}
|
||||
onTouchMove={touchTapSelect.onTouchMove}
|
||||
onTouchEnd={(e) => touchTapSelect.onTouchEnd(e, command)}
|
||||
onClick={() => touchTapSelect.onClick(command)}
|
||||
className={`w-full px-3 py-2 text-left transition-colors flex items-center gap-2 ${
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Bot, FileText } from 'lucide-react'
|
||||
import { useTouchTapSelect } from '@/hooks/useTouchTapSelect'
|
||||
|
||||
export interface MentionItem {
|
||||
type: 'file' | 'agent'
|
||||
@@ -24,6 +25,7 @@ export function MentionSuggestions({
|
||||
selectedIndex = 0
|
||||
}: MentionSuggestionsProps) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const touchTapSelect = useTouchTapSelect(onSelect)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
@@ -64,11 +66,10 @@ export function MentionSuggestions({
|
||||
<button
|
||||
key={`${item.type}-${item.value}`}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onTouchEnd={(e) => {
|
||||
e.preventDefault()
|
||||
onSelect(item)
|
||||
}}
|
||||
onClick={() => onSelect(item)}
|
||||
onTouchStart={touchTapSelect.onTouchStart}
|
||||
onTouchMove={touchTapSelect.onTouchMove}
|
||||
onTouchEnd={(e) => touchTapSelect.onTouchEnd(e, item)}
|
||||
onClick={() => touchTapSelect.onClick(item)}
|
||||
className={`w-full px-3 py-2 text-left transition-colors flex items-start gap-2 ${
|
||||
idx === selectedIndex
|
||||
? 'bg-primary text-primary-foreground'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Check, ChevronLeft, ChevronRight, Clock, MoreVertical, Search, Star, Trash2, X } from 'lucide-react'
|
||||
import { Check, ChevronDown, ChevronLeft, ChevronRight, Clock, Search, Star, Trash2, X } from 'lucide-react'
|
||||
import { useModelSelection } from '@/hooks/useModelSelection'
|
||||
import { useVariants } from '@/hooks/useVariants'
|
||||
import { formatModelName, formatProviderName, getProviders } from '@/api/providers'
|
||||
@@ -535,6 +535,8 @@ export function ModelQuickSelect({
|
||||
)
|
||||
}
|
||||
|
||||
const selectedVariantLabel = currentVariant ? currentVariant : 'Default'
|
||||
|
||||
const handleMoreModelsBack = () => {
|
||||
if (selectedProviderId) {
|
||||
setSelectedProviderId(null)
|
||||
@@ -608,10 +610,11 @@ export function ModelQuickSelect({
|
||||
<button
|
||||
type="button"
|
||||
disabled={!model && !hasVariants}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full text-white/70 hover:bg-white/10 disabled:opacity-30"
|
||||
aria-label="Model actions"
|
||||
className="flex h-9 w-24 items-center justify-center gap-1 rounded-md border border-white/10 bg-white/5 px-1.5 text-sm font-medium capitalize text-white/70 hover:bg-white/10 disabled:opacity-30"
|
||||
aria-label={`Current variant: ${selectedVariantLabel}`}
|
||||
>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
<span className="truncate">{selectedVariantLabel}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-white/40" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="z-[350] min-w-56">
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { useUIState } from '@/stores/uiStateStore'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getRepo } from '@/api/repos'
|
||||
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
|
||||
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
|
||||
@@ -51,12 +52,14 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
}
|
||||
}, [isOpen, bind])
|
||||
|
||||
const { data: repo } = useQuery({
|
||||
const { data: repo, refetch: refetchRepo } = useQuery({
|
||||
queryKey: ['repo', repoId],
|
||||
queryFn: () => repoId ? getRepo(repoId) : null,
|
||||
enabled: !!repoId,
|
||||
})
|
||||
|
||||
useRefreshOnOpen(isOpen && repoId != null, () => { void refetchRepo() })
|
||||
|
||||
const currentBranch = repo?.currentBranch || repo?.branch
|
||||
const repoDisplayName = isAssistantRoute || isAssistantSession
|
||||
? 'Assistant'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from '@/components/ui/bottom-sheet'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -30,12 +31,14 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
return match ? Number(match[1]) : null
|
||||
}, [location.pathname])
|
||||
|
||||
const { data: repos, isLoading } = useQuery({
|
||||
const { data: repos, isLoading, refetch } = useQuery({
|
||||
queryKey: ['repos'],
|
||||
queryFn: listRepos,
|
||||
enabled: isOpen,
|
||||
})
|
||||
|
||||
useRefreshOnOpen(isOpen, () => { void refetch() })
|
||||
|
||||
const regularRepos = useMemo(
|
||||
() => repos?.filter((r) => r.id !== ASSISTANT_REPO_ID) ?? null,
|
||||
[repos],
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateRepoListCaches } from '@/lib/queryInvalidation'
|
||||
import { getRepoBaseDirectoryName, getRepoDirectoryNameError, getRepoNameFromUrl, normalizeRepoUrlForCompare, sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils'
|
||||
import type { DiscoverReposResponse } from '@opencode-manager/shared/types'
|
||||
import type { Repo } from '@/api/types'
|
||||
@@ -82,8 +83,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
|
||||
return { mode: 'single', repo }
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
invalidateRepoListCaches(queryClient)
|
||||
setRepoUrl('')
|
||||
setLocalPath('')
|
||||
setFolderPath('')
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
|
||||
import { createRepo, listBranches } from '@/api/repos'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
interface CreateWorktreeDialogProps {
|
||||
open: boolean
|
||||
@@ -66,8 +67,7 @@ export function CreateWorktreeDialog({
|
||||
baseBranch: payload.base,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
invalidateRepoGitCaches(queryClient, repoId)
|
||||
showToast.success('Worktree created')
|
||||
onCreated?.()
|
||||
onOpenChange(false)
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type RepoSortMode,
|
||||
} from "./repo-list-state"
|
||||
import { RepoListControls } from "./RepoListControls"
|
||||
import { invalidateRepoListCaches } from "@/lib/queryInvalidation"
|
||||
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils"
|
||||
|
||||
function formatActivityLabel(timestamp: number): string {
|
||||
@@ -229,8 +230,7 @@ export function RepoList() {
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: deleteRepo,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["repos"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["reposGitStatus"] })
|
||||
invalidateRepoListCaches(queryClient)
|
||||
setDeleteDialogOpen(false)
|
||||
setRepoToDelete(null)
|
||||
},
|
||||
@@ -241,8 +241,7 @@ export function RepoList() {
|
||||
await Promise.all(repoIds.map((id) => deleteRepo(id)))
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["repos"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["reposGitStatus"] })
|
||||
invalidateRepoListCaches(queryClient)
|
||||
setDeleteDialogOpen(false)
|
||||
setSelectedRepos(new Set())
|
||||
setSelectionMode(false)
|
||||
@@ -270,8 +269,7 @@ export function RepoList() {
|
||||
queryClient.setQueryData(["repos"], context?.previousRepos)
|
||||
},
|
||||
onSettled: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["repos"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["reposGitStatus"] })
|
||||
invalidateRepoListCaches(queryClient)
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { AgentsEditor } from './AgentsEditor'
|
||||
|
||||
vi.mock('./AgentDialog', () => ({
|
||||
@@ -8,6 +9,13 @@ vi.mock('./AgentDialog', () => ({
|
||||
open ? <div data-testid="agent-dialog">{editingAgent ? 'Edit Agent' : 'Create Agent'}</div> : null,
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const mockAgents = {
|
||||
'code-reviewer': {
|
||||
description: 'Reviews code changes',
|
||||
@@ -27,7 +35,7 @@ describe('AgentsEditor', () => {
|
||||
|
||||
it('renders empty state when no agents configured', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={{}} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('No agents configured')).toBeInTheDocument()
|
||||
expect(screen.getByText('Add your first agent to get started.')).toBeInTheDocument()
|
||||
@@ -35,16 +43,33 @@ describe('AgentsEditor', () => {
|
||||
|
||||
it('renders agent names', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('code-reviewer')).toBeInTheDocument()
|
||||
expect(screen.getByText('helper')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders uploaded directory agent files', () => {
|
||||
const onChange = vi.fn()
|
||||
render(
|
||||
<AgentsEditor
|
||||
agents={{}}
|
||||
directoryAgents={[{ kind: 'agents', name: 'planner', relativePath: 'team/planner.md' }]}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
expect(screen.getByText('planner')).toBeInTheDocument()
|
||||
expect(screen.getByText('Uploaded file: team/planner.md')).toBeInTheDocument()
|
||||
expect(screen.getByText('File')).toBeInTheDocument()
|
||||
expect(screen.queryByText('No agents configured')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens AgentDialog when clicking Edit on a row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
const editButtons = screen.getAllByText('Edit')
|
||||
await user.click(editButtons[0])
|
||||
@@ -56,7 +81,7 @@ describe('AgentsEditor', () => {
|
||||
it('opens AgentDialog when clicking row body', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('code-reviewer'))
|
||||
|
||||
@@ -66,7 +91,7 @@ describe('AgentsEditor', () => {
|
||||
it('opens AgentDialog and displays Create Agent text when clicking Add Agent button', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={{}} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('Add Agent'))
|
||||
|
||||
@@ -77,7 +102,7 @@ describe('AgentsEditor', () => {
|
||||
it('calls onChange with agent removed when Delete is clicked from overflow menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for code-reviewer'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
@@ -88,7 +113,7 @@ describe('AgentsEditor', () => {
|
||||
|
||||
it('renders mode and disabled badges for agents', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />)
|
||||
render(<AgentsEditor agents={mockAgents} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('subagent')).toBeInTheDocument()
|
||||
expect(screen.getByText('Disabled')).toBeInTheDocument()
|
||||
|
||||
@@ -5,6 +5,9 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { SettingsList, SettingsListRow } from '@/components/ui/settings-list'
|
||||
import { AgentDialog } from './AgentDialog'
|
||||
import { UploadFolderButton } from './UploadFolderButton'
|
||||
import { DirectoryFilesList } from './DirectoryFilesList'
|
||||
import type { OpenCodeDirectoryFileInfo } from '@/api/types/settings'
|
||||
|
||||
interface Agent {
|
||||
prompt?: string
|
||||
@@ -26,12 +29,14 @@ interface Agent {
|
||||
|
||||
interface AgentsEditorProps {
|
||||
agents: Record<string, Agent>
|
||||
directoryAgents?: OpenCodeDirectoryFileInfo[]
|
||||
onChange: (agents: Record<string, Agent>) => void
|
||||
}
|
||||
|
||||
export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
|
||||
export function AgentsEditor({ agents, directoryAgents = [], onChange }: AgentsEditorProps) {
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [editingAgent, setEditingAgent] = useState<{ name: string; agent: Agent } | null>(null)
|
||||
const hasAgents = Object.keys(agents).length > 0 || directoryAgents.length > 0
|
||||
|
||||
const handleAgentSubmit = (name: string, agent: Agent) => {
|
||||
if (editingAgent) {
|
||||
@@ -62,7 +67,8 @@ export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-end">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<UploadFolderButton kind="agents" />
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
@@ -79,7 +85,7 @@ export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
|
||||
</div>
|
||||
|
||||
<SettingsList
|
||||
isEmpty={Object.keys(agents).length === 0}
|
||||
isEmpty={!hasAgents}
|
||||
emptyTitle="No agents configured"
|
||||
emptyHint="Add your first agent to get started."
|
||||
maxHeightClassName="max-h-[calc(100dvh-300px)] sm:max-h-[420px]"
|
||||
@@ -101,6 +107,7 @@ export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
|
||||
actionsLabel={`Actions for ${name}`}
|
||||
/>
|
||||
))}
|
||||
<DirectoryFilesList kind="agents" files={directoryAgents} />
|
||||
</SettingsList>
|
||||
|
||||
<AgentDialog
|
||||
|
||||
@@ -1,13 +1,40 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { CommandsEditor } from './CommandsEditor'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
installOpenCodeDirectoryFiles: vi.fn(),
|
||||
toastError: vi.fn(),
|
||||
toastSuccess: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('./CommandDialog', () => ({
|
||||
CommandDialog: ({ open, editingCommand }: { open: boolean; editingCommand?: { name: string } | null }) =>
|
||||
open ? <div data-testid="command-dialog">{editingCommand ? 'Edit Command' : 'Create Command'}</div> : null,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
installOpenCodeDirectoryFiles: mocks.installOpenCodeDirectoryFiles,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
error: mocks.toastError,
|
||||
success: mocks.toastSuccess,
|
||||
},
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const mockCommands = {
|
||||
'review': {
|
||||
template: 'Review this code',
|
||||
@@ -23,11 +50,12 @@ const mockCommands = {
|
||||
describe('CommandsEditor', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.installOpenCodeDirectoryFiles.mockResolvedValue({ kind: 'commands', filesInstalled: ['git/commit.md'] })
|
||||
})
|
||||
|
||||
it('renders empty state when no commands configured', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={{}} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('No commands configured')).toBeInTheDocument()
|
||||
expect(screen.getByText('Add your first command to get started.')).toBeInTheDocument()
|
||||
@@ -35,16 +63,33 @@ describe('CommandsEditor', () => {
|
||||
|
||||
it('renders command names with leading slash', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('/review')).toBeInTheDocument()
|
||||
expect(screen.getByText('/build')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders uploaded directory command files', () => {
|
||||
const onChange = vi.fn()
|
||||
render(
|
||||
<CommandsEditor
|
||||
commands={{}}
|
||||
directoryCommands={[{ kind: 'commands', name: 'deploy', relativePath: 'project/deploy.md' }]}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
expect(screen.getByText('/deploy')).toBeInTheDocument()
|
||||
expect(screen.getByText('Uploaded file: project/deploy.md')).toBeInTheDocument()
|
||||
expect(screen.getByText('File')).toBeInTheDocument()
|
||||
expect(screen.queryByText('No commands configured')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens CommandDialog when clicking Edit on a row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
const editButtons = screen.getAllByText('Edit')
|
||||
await user.click(editButtons[0])
|
||||
@@ -56,7 +101,7 @@ describe('CommandsEditor', () => {
|
||||
it('opens CommandDialog when clicking row body', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('/review'))
|
||||
|
||||
@@ -66,7 +111,7 @@ describe('CommandsEditor', () => {
|
||||
it('opens CommandDialog and displays Create Command text when clicking Add Command button', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={{}} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByText('Add Command'))
|
||||
|
||||
@@ -77,7 +122,7 @@ describe('CommandsEditor', () => {
|
||||
it('calls onChange with command removed when Delete is clicked from overflow menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
await user.click(screen.getByLabelText('Actions for /review'))
|
||||
await user.click(screen.getByText('Delete'))
|
||||
@@ -88,8 +133,40 @@ describe('CommandsEditor', () => {
|
||||
|
||||
it('renders agent badge when command has agent', () => {
|
||||
const onChange = vi.fn()
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />)
|
||||
render(<CommandsEditor commands={mockCommands} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
|
||||
expect(screen.getByText('code-reviewer')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uploads only markdown files from a selected commands folder', async () => {
|
||||
const onChange = vi.fn()
|
||||
const markdownFile = new File(['commit body'], 'commit.md', { type: 'text/markdown' })
|
||||
const systemFile = new File(['metadata'], '.DS_Store')
|
||||
Object.defineProperty(markdownFile, 'webkitRelativePath', { value: 'commands/git/commit.md' })
|
||||
Object.defineProperty(systemFile, 'webkitRelativePath', { value: 'commands/.DS_Store' })
|
||||
|
||||
const { container } = render(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
const input = container.querySelector('input[type="file"]') as HTMLInputElement
|
||||
|
||||
fireEvent.change(input, { target: { files: [markdownFile, systemFile] } })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.installOpenCodeDirectoryFiles).toHaveBeenCalledWith({ kind: 'commands', files: [markdownFile] })
|
||||
})
|
||||
expect(mocks.toastSuccess).toHaveBeenCalledWith('Uploaded 1 command file')
|
||||
})
|
||||
|
||||
it('shows an error when a selected commands folder has no markdown files', async () => {
|
||||
const onChange = vi.fn()
|
||||
const systemFile = new File(['metadata'], '.DS_Store')
|
||||
Object.defineProperty(systemFile, 'webkitRelativePath', { value: 'commands/.DS_Store' })
|
||||
|
||||
const { container } = render(<CommandsEditor commands={{}} onChange={onChange} />, { wrapper: createWrapper() })
|
||||
const input = container.querySelector('input[type="file"]') as HTMLInputElement
|
||||
|
||||
fireEvent.change(input, { target: { files: [systemFile] } })
|
||||
|
||||
expect(mocks.installOpenCodeDirectoryFiles).not.toHaveBeenCalled()
|
||||
expect(mocks.toastError).toHaveBeenCalledWith('No markdown commands files found')
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,9 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { SettingsList, SettingsListRow } from '@/components/ui/settings-list'
|
||||
import { CommandDialog } from './CommandDialog'
|
||||
import { UploadFolderButton } from './UploadFolderButton'
|
||||
import { DirectoryFilesList } from './DirectoryFilesList'
|
||||
import type { OpenCodeDirectoryFileInfo } from '@/api/types/settings'
|
||||
|
||||
interface Command {
|
||||
template: string
|
||||
@@ -17,12 +20,14 @@ interface Command {
|
||||
|
||||
interface CommandsEditorProps {
|
||||
commands: Record<string, Command>
|
||||
directoryCommands?: OpenCodeDirectoryFileInfo[]
|
||||
onChange: (commands: Record<string, Command>) => void
|
||||
}
|
||||
|
||||
export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
|
||||
export function CommandsEditor({ commands, directoryCommands = [], onChange }: CommandsEditorProps) {
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
|
||||
const [editingCommand, setEditingCommand] = useState<{ name: string; command: Command } | null>(null)
|
||||
const hasCommands = Object.keys(commands).length > 0 || directoryCommands.length > 0
|
||||
|
||||
const handleCommandSubmit = (name: string, command: Command) => {
|
||||
if (editingCommand) {
|
||||
@@ -53,7 +58,8 @@ export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-end">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<UploadFolderButton kind="commands" />
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
@@ -70,7 +76,7 @@ export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
|
||||
</div>
|
||||
|
||||
<SettingsList
|
||||
isEmpty={Object.keys(commands).length === 0}
|
||||
isEmpty={!hasCommands}
|
||||
emptyTitle="No commands configured"
|
||||
emptyHint="Add your first command to get started."
|
||||
maxHeightClassName="max-h-[calc(100dvh-300px)] sm:max-h-[420px]"
|
||||
@@ -89,6 +95,7 @@ export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
|
||||
actionsLabel={`Actions for /${name}`}
|
||||
/>
|
||||
))}
|
||||
<DirectoryFilesList kind="commands" files={directoryCommands} titlePrefix="/" />
|
||||
</SettingsList>
|
||||
|
||||
<CommandDialog
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { SettingsListRow } from '@/components/ui/settings-list'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import type { OpenCodeDirectoryFileInfo } from '@/api/types/settings'
|
||||
|
||||
interface DirectoryFilesListProps {
|
||||
kind: 'agents' | 'commands'
|
||||
files: OpenCodeDirectoryFileInfo[]
|
||||
titlePrefix?: string
|
||||
}
|
||||
|
||||
export function DirectoryFilesList({ kind, files, titlePrefix = '' }: DirectoryFilesListProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [editingFile, setEditingFile] = useState<OpenCodeDirectoryFileInfo | null>(null)
|
||||
const [deletingFile, setDeletingFile] = useState<OpenCodeDirectoryFileInfo | null>(null)
|
||||
const [content, setContent] = useState('')
|
||||
|
||||
const { isFetching: isLoadingContent } = useQuery({
|
||||
queryKey: ['opencode-directory-file', kind, editingFile?.relativePath],
|
||||
queryFn: async () => {
|
||||
const result = await settingsApi.getOpenCodeDirectoryFile(kind, editingFile!.relativePath)
|
||||
setContent(result.content)
|
||||
return result
|
||||
},
|
||||
enabled: !!editingFile,
|
||||
staleTime: 0,
|
||||
gcTime: 0,
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
settingsApi.updateOpenCodeDirectoryFile({
|
||||
kind,
|
||||
relativePath: editingFile!.relativePath,
|
||||
content,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
toast.success('File saved')
|
||||
setEditingFile(null)
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to save file')
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: () => settingsApi.deleteOpenCodeDirectoryFile(kind, deletingFile!.relativePath),
|
||||
onSuccess: () => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
toast.success('File deleted')
|
||||
setDeletingFile(null)
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete file')
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
{files.map((file) => (
|
||||
<SettingsListRow
|
||||
key={`file:${file.relativePath}`}
|
||||
title={`${titlePrefix}${file.name}`}
|
||||
description={`Uploaded file: ${file.relativePath}`}
|
||||
badges={<Badge variant="secondary" className="shrink-0">File</Badge>}
|
||||
onClick={() => setEditingFile(file)}
|
||||
primaryAction={{ label: 'Edit', onClick: () => setEditingFile(file) }}
|
||||
actions={[{ label: 'Delete', destructive: true, onClick: () => setDeletingFile(file) }]}
|
||||
actionsLabel={`Actions for ${file.name}`}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Dialog open={!!editingFile} onOpenChange={(open) => !open && setEditingFile(null)}>
|
||||
<DialogContent mobileFullscreen className="sm:max-w-2xl sm:max-h-[85vh] gap-0 flex flex-col p-0 md:p-6 pb-safe">
|
||||
<DialogHeader className="p-4 sm:p-6 border-b">
|
||||
<DialogTitle className="truncate">{editingFile?.relativePath}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-2 sm:p-4">
|
||||
<Textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
disabled={isLoadingContent}
|
||||
rows={18}
|
||||
className="font-mono md:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end pb-4 p-3">
|
||||
<Button variant="outline" onClick={() => setEditingFile(null)} className="flex-1 sm:flex-none">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => updateMutation.mutate()}
|
||||
disabled={isLoadingContent || updateMutation.isPending}
|
||||
className="flex-1 sm:flex-none"
|
||||
>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!deletingFile}
|
||||
onOpenChange={(open) => !open && setDeletingFile(null)}
|
||||
onConfirm={() => deleteMutation.mutate()}
|
||||
onCancel={() => setDeletingFile(null)}
|
||||
title="Delete File"
|
||||
description="Are you sure you want to delete this uploaded file?"
|
||||
itemName={deletingFile?.relativePath}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest'
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeConfigManager } from './OpenCodeConfigManager'
|
||||
@@ -11,16 +11,20 @@ const {
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetOpenCodeImportStatus,
|
||||
mockListManagedSkills,
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfigs: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetOpenCodeImportStatus: vi.fn(),
|
||||
mockListManagedSkills: vi.fn(),
|
||||
mockListOpenCodeDirectoryFiles: vi.fn(),
|
||||
healthState: { data: { opencode: 'healthy', opencodeRestartPending: false } as Record<string, unknown> },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: () => ({ data: { opencode: 'healthy' } }),
|
||||
useServerHealth: () => healthState,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
@@ -34,6 +38,7 @@ vi.mock('@/api/settings', () => ({
|
||||
restartOpenCodeServer: mockRestartOpenCodeServer,
|
||||
getOpenCodeImportStatus: mockGetOpenCodeImportStatus,
|
||||
listManagedSkills: mockListManagedSkills,
|
||||
listOpenCodeDirectoryFiles: mockListOpenCodeDirectoryFiles,
|
||||
syncOpenCodeImport: vi.fn(),
|
||||
upgradeOpenCode: vi.fn(),
|
||||
},
|
||||
@@ -70,18 +75,45 @@ describe('OpenCodeConfigManager', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
|
||||
mockGetOpenCodeConfigs.mockResolvedValue({ configs: [defaultConfig] })
|
||||
mockGetOpenCodeImportStatus.mockResolvedValue({})
|
||||
mockListManagedSkills.mockResolvedValue([])
|
||||
mockListOpenCodeDirectoryFiles.mockImplementation((kind: 'agents' | 'commands') => {
|
||||
if (kind === 'commands') return Promise.resolve([])
|
||||
return Promise.resolve([])
|
||||
})
|
||||
mockUpdateOpenCodeConfig.mockResolvedValue(defaultConfig)
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
})
|
||||
|
||||
it('optimistic delete + restart prompt', async () => {
|
||||
let resolveUpdate: (config: OpenCodeConfig) => void = () => {}
|
||||
mockUpdateOpenCodeConfig.mockImplementationOnce(() => new Promise<OpenCodeConfig>((resolve) => {
|
||||
resolveUpdate = resolve
|
||||
}))
|
||||
it('shows uploaded command and agent directory files in settings', async () => {
|
||||
mockListOpenCodeDirectoryFiles.mockImplementation((kind: 'agents' | 'commands') => {
|
||||
if (kind === 'commands') return Promise.resolve([{ kind, name: 'deploy', relativePath: 'project/deploy.md' }])
|
||||
return Promise.resolve([{ kind, name: 'planner', relativePath: 'team/planner.md' }])
|
||||
})
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
|
||||
await screen.findByText('Commands')
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getAllByText('1 configured').length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Commands/i }))
|
||||
expect(await screen.findByText('/deploy')).toBeInTheDocument()
|
||||
expect(screen.getByText('Uploaded file: project/deploy.md')).toBeInTheDocument()
|
||||
|
||||
const agentsButton = screen.getAllByRole('button', { name: /Agents/i }).find(button => button.textContent?.startsWith('Agents'))
|
||||
expect(agentsButton).toBeDefined()
|
||||
await user.click(agentsButton!)
|
||||
expect(await screen.findByText('planner')).toBeInTheDocument()
|
||||
expect(screen.getByText('Uploaded file: team/planner.md')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('optimistic delete saves without eager restart modal', async () => {
|
||||
mockUpdateOpenCodeConfig.mockResolvedValueOnce({ ...defaultConfig, restartRequired: true })
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
@@ -98,17 +130,19 @@ describe('OpenCodeConfigManager', () => {
|
||||
expect(configName).toBe('default')
|
||||
expect(payload.content.provider.openai.models).not.toHaveProperty('gpt-4o')
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('deferred restart banner triggers server restart', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeConfigManager hideHealthStatus />)
|
||||
|
||||
const restartNowButton = await screen.findByRole('button', { name: /restart now/i })
|
||||
await user.click(restartNowButton)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
expect(screen.getByRole('button', { name: /saving/i })).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
resolveUpdate(defaultConfig)
|
||||
})
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /restart now/i })).not.toBeDisabled()
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /restart now/i }))
|
||||
|
||||
expect(mockRestartOpenCodeServer).toHaveBeenCalledTimes(1)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ArrowUpCircle, History, ChevronDown } from 'lucide-react'
|
||||
import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ArrowUpCircle, History, ChevronDown, AlertTriangle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@@ -58,6 +58,8 @@ interface OpenCodeConfigManagerProps {
|
||||
hideHealthStatus?: boolean
|
||||
}
|
||||
|
||||
const EXPANDED_SECTION_CONTENT_CLASS = 'p-2 sm:p-4'
|
||||
|
||||
export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConfigManagerProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: health } = useServerHealth()
|
||||
@@ -100,11 +102,23 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
staleTime: 30 * 1000,
|
||||
})
|
||||
|
||||
const { data: directoryCommands = [] } = useQuery({
|
||||
queryKey: ['opencode-directory-files', 'commands'],
|
||||
queryFn: () => settingsApi.listOpenCodeDirectoryFiles('commands'),
|
||||
staleTime: 30 * 1000,
|
||||
})
|
||||
|
||||
const { data: directoryAgents = [] } = useQuery({
|
||||
queryKey: ['opencode-directory-files', 'agents'],
|
||||
queryFn: () => settingsApi.listOpenCodeDirectoryFiles('agents'),
|
||||
staleTime: 30 * 1000,
|
||||
})
|
||||
|
||||
const scrollToSection = (ref: React.RefObject<HTMLButtonElement | null>) => {
|
||||
if (ref.current) {
|
||||
ref.current.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
block: 'nearest',
|
||||
inline: 'nearest'
|
||||
})
|
||||
}
|
||||
@@ -238,7 +252,6 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
const previousConfig = configs.find(c => c.name === configName)
|
||||
const previousContent = previousConfig?.content
|
||||
const previousSelectedConfig = selectedConfig
|
||||
const shouldPromptRestart = Boolean(previousConfig?.isDefault)
|
||||
const now = Date.now()
|
||||
|
||||
setConfigs(prev => prev.map(config =>
|
||||
@@ -247,15 +260,14 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
if (selectedConfig && selectedConfig.name === configName) {
|
||||
setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: now })
|
||||
}
|
||||
if (shouldPromptRestart) {
|
||||
setIsRestartPromptOpen(true)
|
||||
}
|
||||
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const result = await settingsApi.updateOpenCodeConfig(configName, { content: newContent })
|
||||
if (result.removedFields && result.removedFields.length > 0) {
|
||||
showToast.info(`Configuration updated after removing invalid fields: ${result.removedFields.join(', ')}`)
|
||||
} else if (result.restartRequired) {
|
||||
showToast.success('Configuration saved. Restart the server to apply changes.')
|
||||
} else {
|
||||
showToast.success('Configuration updated')
|
||||
}
|
||||
@@ -267,9 +279,6 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
if (previousSelectedConfig && previousSelectedConfig.name === configName) {
|
||||
setSelectedConfig(previousSelectedConfig)
|
||||
}
|
||||
if (shouldPromptRestart) {
|
||||
setIsRestartPromptOpen(false)
|
||||
}
|
||||
console.error('Failed to update config:', error)
|
||||
showToast.error(getApiErrorMessage(error, 'Failed to update config'))
|
||||
} finally {
|
||||
@@ -413,7 +422,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
const activeConfig = configs.find((c) => c.name === activeConfigName) ?? null
|
||||
|
||||
return (
|
||||
<div className="space-y-6 overflow-y-auto">
|
||||
<div className="space-y-6 min-w-0">
|
||||
{!hideHealthStatus && health && (
|
||||
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
|
||||
<CardContent className="p-3">
|
||||
@@ -500,6 +509,30 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{health?.opencodeRestartPending && (
|
||||
<div className="flex flex-col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-500" />
|
||||
<p className="text-sm">
|
||||
Configuration changes are saved but require a server restart to take effect.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setIsRestartPromptOpen(true)}
|
||||
disabled={restartServerMutation.isPending}
|
||||
className="shrink-0"
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 mr-1" />
|
||||
)}
|
||||
Restart Now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
@@ -745,10 +778,10 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
if (!editingConfig) return
|
||||
showToast.loading('Saving configuration...', { id: 'edit-config' })
|
||||
try {
|
||||
await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent })
|
||||
const result = await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent })
|
||||
await fetchConfigs()
|
||||
const successMsg = editingConfig.isDefault
|
||||
? 'Configuration saved and server reloaded'
|
||||
const successMsg = result.restartRequired
|
||||
? 'Configuration saved. Restart the server to apply changes.'
|
||||
: 'Configuration saved'
|
||||
showToast.success(successMsg, { id: 'edit-config' })
|
||||
invalidateConfigCaches(queryClient)
|
||||
@@ -817,7 +850,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 pb-20 min-w-0">
|
||||
<div className="flex flex-col gap-4 pb-4 min-w-0">
|
||||
{selectedConfig ? (
|
||||
<>
|
||||
{!selectedConfig.isValid && selectedConfig.validationIssues && selectedConfig.validationIssues.length > 0 && (
|
||||
@@ -856,15 +889,16 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Commands</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}).length} configured
|
||||
{Object.keys((selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}).length + directoryCommands.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.commands ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.commands ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<CommandsEditor
|
||||
commands={(selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}}
|
||||
directoryCommands={directoryCommands}
|
||||
onChange={(commands) => {
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
@@ -893,15 +927,16 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<h4 className="text-sm font-medium truncate">Agents</h4>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{Object.keys((selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}).length} configured
|
||||
{Object.keys((selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}).length + directoryAgents.length} configured
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.agents ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.agents ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<AgentsEditor
|
||||
agents={(selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}}
|
||||
directoryAgents={directoryAgents}
|
||||
onChange={(agents) => {
|
||||
const updatedContent = {
|
||||
...selectedConfig.content,
|
||||
@@ -935,7 +970,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.skills ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.skills ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<SkillsEditor
|
||||
managedSkills={managedSkills}
|
||||
/>
|
||||
@@ -965,7 +1000,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.mcp ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.mcp ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<McpManager
|
||||
config={selectedConfig}
|
||||
onUpdate={(content) => updateConfigContent(selectedConfig.name, content)}
|
||||
@@ -1004,7 +1039,7 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.models ? 'rotate-90' : ''}`} />
|
||||
</button>
|
||||
<div className={`${expandedSections.models ? 'block' : 'hidden'} border-t border-border`}>
|
||||
<div className="p-2 sm:max-h-[50vh] sm:overflow-y-auto sm:p-4">
|
||||
<div className={EXPANDED_SECTION_CONTENT_CLASS}>
|
||||
<OpenCodeModelsEditor
|
||||
providers={(selectedConfig.content?.provider as Record<string, ConfigProvider> | undefined) ?? {}}
|
||||
onChange={(providers) => {
|
||||
@@ -1045,7 +1080,6 @@ export function OpenCodeConfigManager({ hideHealthStatus = false }: OpenCodeConf
|
||||
<RestartServerDialog
|
||||
open={isRestartPromptOpen}
|
||||
onOpenChange={setIsRestartPromptOpen}
|
||||
isSaving={isUpdating && !restartServerMutation.isPending}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setIsRestartPromptOpen(false)}
|
||||
onConfirm={async () => {
|
||||
|
||||
@@ -52,14 +52,6 @@ describe('RestartServerDialog', () => {
|
||||
expect(screen.getByText('Restarting...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disables confirm button and shows Saving... when isSaving is true', () => {
|
||||
render(<RestartServerDialog {...baseProps} isSaving={true} />)
|
||||
|
||||
const confirmButton = screen.getByRole('button', { name: /saving/i })
|
||||
expect(confirmButton).toBeDisabled()
|
||||
expect(screen.getByText('Saving...')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disables Later button when isRestarting is true', () => {
|
||||
render(<RestartServerDialog {...baseProps} isRestarting={true} />)
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ interface RestartServerDialogProps {
|
||||
onOpenChange: (open: boolean) => void
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
isSaving?: boolean
|
||||
isRestarting?: boolean
|
||||
}
|
||||
|
||||
@@ -16,10 +15,9 @@ export function RestartServerDialog({
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
isSaving = false,
|
||||
isRestarting = false,
|
||||
}: RestartServerDialogProps) {
|
||||
const isConfirmDisabled = isSaving || isRestarting
|
||||
const isConfirmDisabled = isRestarting
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -35,12 +33,7 @@ export function RestartServerDialog({
|
||||
Later
|
||||
</Button>
|
||||
<Button onClick={onConfirm} disabled={isConfirmDisabled}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : isRestarting ? (
|
||||
{isRestarting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
|
||||
Restarting...
|
||||
|
||||
@@ -153,7 +153,7 @@ export function SettingsDialog() {
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
<div className="px-6 pb-6">
|
||||
<TabsContent key="account" value="account" className="mt-0"><AccountSettings /></TabsContent>
|
||||
<TabsContent key="general" value="general" className="mt-0"><GeneralSettings /></TabsContent>
|
||||
@@ -205,7 +205,7 @@ export function SettingsDialog() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-3 pb-20">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-3 pb-[calc(env(safe-area-inset-bottom)+1rem)]">
|
||||
{mobileView === 'menu' && (
|
||||
<div className="space-y-3">
|
||||
{menuItems.map((item) => (
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { Upload, FileUp, FolderUp, ChevronDown } from 'lucide-react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
const KIND_NOUN: Record<'agents' | 'commands', string> = {
|
||||
agents: 'agent',
|
||||
commands: 'command',
|
||||
}
|
||||
|
||||
const DIRECTORY_INPUT_PROPS = {
|
||||
webkitdirectory: '',
|
||||
directory: '',
|
||||
mozdirectory: '',
|
||||
} as React.InputHTMLAttributes<HTMLInputElement>
|
||||
|
||||
function isMarkdownFile(file: File): boolean {
|
||||
return (file.webkitRelativePath || file.name).toLowerCase().endsWith('.md')
|
||||
}
|
||||
|
||||
interface UploadFolderButtonProps {
|
||||
kind: 'agents' | 'commands'
|
||||
}
|
||||
|
||||
export function UploadFolderButton({ kind }: UploadFolderButtonProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
const noun = KIND_NOUN[kind]
|
||||
|
||||
const openPicker = (inputRef: React.RefObject<HTMLInputElement | null>) => {
|
||||
requestAnimationFrame(() => inputRef.current?.click())
|
||||
}
|
||||
|
||||
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFiles = Array.from(event.target.files ?? [])
|
||||
event.target.value = ''
|
||||
if (selectedFiles.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const files = selectedFiles.filter(isMarkdownFile)
|
||||
if (files.length === 0) {
|
||||
toast.error(`No markdown ${kind} files found`)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
setIsUploading(true)
|
||||
const result = await settingsApi.installOpenCodeDirectoryFiles({ kind, files })
|
||||
invalidateConfigCaches(queryClient)
|
||||
toast.success(`Uploaded ${result.filesInstalled.length} ${noun} file${result.filesInstalled.length === 1 ? '' : 's'}`)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : `Failed to upload ${kind}`)
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="sm" variant="outline" disabled={isUploading}>
|
||||
<Upload className="h-4 w-4 mr-1" />
|
||||
{isUploading ? 'Uploading...' : 'Upload'}
|
||||
<ChevronDown className="h-4 w-4 ml-1" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onSelect={() => openPicker(fileInputRef)}>
|
||||
<FileUp className="h-4 w-4 mr-2" />
|
||||
Upload File
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => openPicker(folderInputRef)}>
|
||||
<FolderUp className="h-4 w-4 mr-2" />
|
||||
Upload Folder
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".md,text/markdown"
|
||||
className="sr-only"
|
||||
multiple
|
||||
disabled={isUploading}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<input
|
||||
ref={folderInputRef}
|
||||
type="file"
|
||||
accept=".md,text/markdown"
|
||||
className="sr-only"
|
||||
multiple
|
||||
disabled={isUploading}
|
||||
{...DIRECTORY_INPUT_PROPS}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { listBranches, switchBranch, GitAuthError, getRepo } from '@/api/repos'
|
||||
import { useGitStatus } from '@/api/git'
|
||||
import { fetchGitStatus, useGitStatus } from '@/api/git'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Loader2, GitBranch, GitBranchPlus, Check, Plus, AlertCircle, ArrowUp, ArrowDown, Globe } from 'lucide-react'
|
||||
@@ -10,6 +10,7 @@ import { showToast } from '@/lib/toast'
|
||||
import { useGit } from '@/hooks/useGit'
|
||||
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
|
||||
import { CreateWorktreeDialog } from '@/components/repo/CreateWorktreeDialog'
|
||||
import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
interface BranchesTabProps {
|
||||
repoId: number
|
||||
@@ -41,12 +42,15 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
|
||||
const isRepoWorktree = repo?.isWorktree ?? false
|
||||
|
||||
const switchBranchMutation = useMutation({
|
||||
mutationFn: (branch: string) => switchBranch(repoId, branch),
|
||||
onSuccess: (updatedRepo) => {
|
||||
mutationFn: async (branch: string) => {
|
||||
const updatedRepo = await switchBranch(repoId, branch)
|
||||
const status = await fetchGitStatus(repoId)
|
||||
return { updatedRepo, status }
|
||||
},
|
||||
onSuccess: ({ updatedRepo, status }) => {
|
||||
queryClient.setQueryData(['repo', repoId], updatedRepo)
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] })
|
||||
setRepoGitStatusCaches(queryClient, repoId, status)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false })
|
||||
refetch()
|
||||
showToast.success(`Switched to branch: ${updatedRepo.currentBranch}`)
|
||||
},
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { useGitStatus, getApiErrorMessage } from '@/api/git'
|
||||
import { getRepo } from '@/api/repos'
|
||||
|
||||
import { useGit } from '@/hooks/useGit'
|
||||
import { ChangesTab } from './ChangesTab'
|
||||
@@ -26,6 +28,8 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
|
||||
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
|
||||
|
||||
interface SourceControlPanelProps {
|
||||
repoId: number
|
||||
@@ -51,8 +55,17 @@ export function SourceControlPanel({
|
||||
const [selectedCommit, setSelectedCommit] = useState<string | undefined>()
|
||||
const [selectedCommitFile, setSelectedCommitFile] = useState<string | undefined>()
|
||||
const [gitError, setGitError] = useState<{ summary: string; detail?: string } | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
const { data: status } = useGitStatus(repoId)
|
||||
const { data: repo } = useQuery({
|
||||
queryKey: ['repo', repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
enabled: isOpen,
|
||||
})
|
||||
const isMobile = useMobile()
|
||||
const displayBranch = repo?.currentBranch || repo?.branch || currentBranch
|
||||
|
||||
useRefreshOnOpen(isOpen, () => { invalidateRepoGitCaches(queryClient, repoId) })
|
||||
|
||||
const handleGitError = (error: unknown) => {
|
||||
if (error instanceof FetchError) {
|
||||
@@ -100,7 +113,7 @@ export function SourceControlPanel({
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="w-4 h-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{currentBranch}</span>
|
||||
<span className="text-sm font-medium">{displayBranch}</span>
|
||||
</div>
|
||||
{status && (status.ahead > 0 || status.behind > 0) && (
|
||||
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
@@ -220,7 +233,7 @@ export function SourceControlPanel({
|
||||
<CommitsTab repoId={repoId} onSelectCommit={handleSelectCommit} />
|
||||
)}
|
||||
{activeTab === 'branches' && currentView === 'default' && (
|
||||
<BranchesTab repoId={repoId} currentBranch={currentBranch} />
|
||||
<BranchesTab repoId={repoId} currentBranch={displayBranch} />
|
||||
)}
|
||||
|
||||
{currentView === 'commit-detail' && selectedCommit && (
|
||||
|
||||
@@ -13,6 +13,7 @@ describe('SettingsList', () => {
|
||||
expect(screen.getByText('Nothing here')).toBeInTheDocument()
|
||||
expect(screen.getByText('Try adding something')).toBeInTheDocument()
|
||||
expect(screen.queryByText('child')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Nothing here').parentElement).toHaveClass('max-h-40')
|
||||
})
|
||||
|
||||
it('renders loadingLabel when isLoading', () => {
|
||||
|
||||
@@ -77,7 +77,7 @@ export function SettingsList({
|
||||
|
||||
if (isEmpty) {
|
||||
return (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card/50 p-6 text-center text-muted-foreground">
|
||||
<div className="h-auto max-h-40 min-h-24 rounded-lg border border-dashed border-border bg-card/50 p-6 text-center text-muted-foreground">
|
||||
<p className="text-sm font-medium text-foreground">{emptyTitle}</p>
|
||||
<p className="text-xs mt-1">{emptyHint}</p>
|
||||
</div>
|
||||
|
||||
@@ -4,11 +4,12 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useQueryClient, useQuery } from '@tanstack/react-query'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts } from '@/api/types'
|
||||
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts, Repo } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
import { invalidateRepoGitCachesDebounced } from '@/lib/queryInvalidation'
|
||||
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
type QuestionsBySession = Record<string, QuestionRequest[]>
|
||||
@@ -29,6 +30,18 @@ function sortById<T extends SessionScopedItem>(items: T[]): T[] {
|
||||
return [...items].sort((a, b) => a.id.localeCompare(b.id))
|
||||
}
|
||||
|
||||
function normalizeDirectory(directory?: string | null) {
|
||||
return directory?.replace(/\/+$/, '') ?? null
|
||||
}
|
||||
|
||||
function repoMatchesDirectory(repo: Repo, directory?: string | null) {
|
||||
const normalizedDirectory = normalizeDirectory(directory)
|
||||
if (!normalizedDirectory) return false
|
||||
|
||||
return [repo.fullPath, repo.localPath, repo.sourcePath]
|
||||
.some((path) => normalizeDirectory(path) === normalizedDirectory)
|
||||
}
|
||||
|
||||
function reconcileBySessionForDirectory<T extends SessionScopedItem>(
|
||||
prev: Record<string, T[]>,
|
||||
directory: string,
|
||||
@@ -265,7 +278,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
if (!repos) return null
|
||||
const directory = findSessionDirectory(sessionID)
|
||||
if (!directory) return null
|
||||
const repo = repos.find(r => r.fullPath === directory)
|
||||
const repo = repos.find(r => repoMatchesDirectory(r, directory))
|
||||
return repo?.id ?? null
|
||||
}, [repos, findSessionDirectory])
|
||||
|
||||
@@ -503,6 +516,22 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
queryKey: ['opencode', 'lsp']
|
||||
})
|
||||
break
|
||||
case 'vcs.branch.updated': {
|
||||
const repo = reposRef.current?.find((candidate) => repoMatchesDirectory(candidate, event.directory))
|
||||
if (!repo) break
|
||||
|
||||
const branch = event.properties.branch
|
||||
if (branch) {
|
||||
const updatedRepo = { ...repo, currentBranch: branch, branch }
|
||||
queryClient.setQueryData(['repo', repo.id], updatedRepo)
|
||||
queryClient.setQueryData<Repo[]>(['repos'], (current) =>
|
||||
current?.map((candidate) => candidate.id === repo.id ? updatedRepo : candidate)
|
||||
)
|
||||
}
|
||||
|
||||
invalidateRepoGitCachesDebounced(queryClient, repo.id)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useCommands } from './useCommands'
|
||||
import { createOpenCodeClient } from '../api/opencode'
|
||||
|
||||
@@ -7,13 +8,24 @@ vi.mock('../api/opencode', () => ({
|
||||
createOpenCodeClient: vi.fn(),
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('useCommands', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns commands in alphabetical order when there is no query', () => {
|
||||
const { result } = renderHook(() => useCommands(null))
|
||||
const { result } = renderHook(() => useCommands(null), { wrapper: createWrapper() })
|
||||
|
||||
expect(result.current.filterCommands('').map(command => command.name).slice(0, 5)).toEqual([
|
||||
'clear',
|
||||
@@ -25,7 +37,7 @@ describe('useCommands', () => {
|
||||
})
|
||||
|
||||
it('prioritizes exact and prefix matches before other matches', () => {
|
||||
const { result } = renderHook(() => useCommands(null))
|
||||
const { result } = renderHook(() => useCommands(null), { wrapper: createWrapper() })
|
||||
|
||||
expect(result.current.filterCommands('co').map(command => command.name)).toEqual([
|
||||
'compact',
|
||||
@@ -45,7 +57,7 @@ describe('useCommands', () => {
|
||||
]),
|
||||
} as unknown as ReturnType<typeof createOpenCodeClient>)
|
||||
|
||||
const { result } = renderHook(() => useCommands('http://localhost:5551'))
|
||||
const { result } = renderHook(() => useCommands('http://localhost:5551'), { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.filterCommands('').map(command => command.name).slice(0, 3)).toEqual([
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createOpenCodeClient } from '@/api/opencode'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
|
||||
@@ -163,36 +163,23 @@ const BUILTIN_COMMANDS: CommandType[] = [
|
||||
}
|
||||
]
|
||||
|
||||
const SORTED_BUILTIN_COMMANDS = sortCommandsByName(BUILTIN_COMMANDS)
|
||||
|
||||
export function useCommands(opcodeUrl: string | null) {
|
||||
const [commands, setCommands] = useState<CommandType[]>(sortCommandsByName(BUILTIN_COMMANDS))
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!opcodeUrl) return
|
||||
|
||||
const fetchCommands = async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient(opcodeUrl)
|
||||
const commandList = await client.listCommands()
|
||||
const allCommands = [...BUILTIN_COMMANDS, ...commandList]
|
||||
const uniqueCommands = allCommands.filter((command, index, self) =>
|
||||
index === self.findIndex((c) => c.name === command.name)
|
||||
)
|
||||
setCommands(sortCommandsByName(uniqueCommands))
|
||||
} catch {
|
||||
setError('Failed to load commands')
|
||||
setCommands(sortCommandsByName(BUILTIN_COMMANDS))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
fetchCommands()
|
||||
}, [opcodeUrl])
|
||||
const { data: commands, isLoading: loading, error } = useQuery({
|
||||
queryKey: ['opencode', 'commands', opcodeUrl],
|
||||
queryFn: async () => {
|
||||
const client = createOpenCodeClient(opcodeUrl!)
|
||||
const commandList = await client.listCommands()
|
||||
const allCommands = [...BUILTIN_COMMANDS, ...commandList]
|
||||
const uniqueCommands = allCommands.filter((command, index, self) =>
|
||||
index === self.findIndex((c) => c.name === command.name)
|
||||
)
|
||||
return sortCommandsByName(uniqueCommands)
|
||||
},
|
||||
enabled: !!opcodeUrl,
|
||||
initialData: SORTED_BUILTIN_COMMANDS,
|
||||
})
|
||||
|
||||
const filterCommands = (query: string) => {
|
||||
if (!query.trim()) return commands
|
||||
@@ -210,7 +197,7 @@ export function useCommands(opcodeUrl: string | null) {
|
||||
return {
|
||||
commands,
|
||||
loading,
|
||||
error,
|
||||
error: error ? 'Failed to load commands' : null,
|
||||
filterCommands
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useGit } from './useGit'
|
||||
import * as gitApi from '../api/git'
|
||||
import * as toast from '../lib/toast'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { GitStatusResponse } from '../types/git'
|
||||
|
||||
vi.mock('../api/git', () => ({
|
||||
gitFetch: vi.fn(),
|
||||
@@ -14,6 +15,7 @@ vi.mock('../api/git', () => ({
|
||||
gitUnstageFiles: vi.fn(),
|
||||
gitDiscardFiles: vi.fn(),
|
||||
gitReset: vi.fn(),
|
||||
fetchGitStatus: vi.fn(),
|
||||
fetchGitLog: vi.fn(),
|
||||
fetchGitDiff: vi.fn(),
|
||||
createBranch: vi.fn(),
|
||||
@@ -34,6 +36,15 @@ vi.mock('../lib/toast', () => ({
|
||||
|
||||
const mockInvalidateQueries = vi.fn()
|
||||
const mockSetQueryData = vi.fn()
|
||||
const mockSetQueriesData = vi.fn()
|
||||
|
||||
const mockGitStatus: GitStatusResponse = {
|
||||
branch: 'main',
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
files: [],
|
||||
hasChanges: false,
|
||||
}
|
||||
|
||||
vi.mock('@tanstack/react-query', async () => {
|
||||
const actual = await vi.importActual('@tanstack/react-query')
|
||||
@@ -42,6 +53,7 @@ vi.mock('@tanstack/react-query', async () => {
|
||||
useQueryClient: vi.fn(() => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
setQueryData: mockSetQueryData,
|
||||
setQueriesData: mockSetQueriesData,
|
||||
}))
|
||||
}
|
||||
})
|
||||
@@ -62,8 +74,40 @@ describe('useGit', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockInvalidateQueries.mockClear()
|
||||
vi.mocked(gitApi.gitFetch).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitPull).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitPush).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitCommit).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitStageFiles).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitUnstageFiles).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitDiscardFiles).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.gitReset).mockResolvedValue(mockGitStatus)
|
||||
vi.mocked(gitApi.fetchGitStatus).mockResolvedValue(mockGitStatus)
|
||||
})
|
||||
|
||||
const expectTargetedStatusCacheUpdate = () => {
|
||||
expect(mockSetQueryData).toHaveBeenCalledWith(['gitStatus', 1], mockGitStatus)
|
||||
expect(mockSetQueriesData).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
queryKey: ['reposGitStatus'],
|
||||
predicate: expect.any(Function),
|
||||
}),
|
||||
expect.any(Function),
|
||||
)
|
||||
|
||||
const [filters, updater] = mockSetQueriesData.mock.calls[0]
|
||||
expect(filters.predicate({ queryKey: ['reposGitStatus', [1, 2]] })).toBe(true)
|
||||
expect(filters.predicate({ queryKey: ['reposGitStatus', [2, 3]] })).toBe(false)
|
||||
expect(filters.predicate({ queryKey: ['other', [1]] })).toBe(false)
|
||||
|
||||
const otherStatus = { ...mockGitStatus, branch: 'dev' }
|
||||
const oldData = new Map<number, GitStatusResponse>([[1, otherStatus], [2, otherStatus]])
|
||||
const updated = updater(oldData)
|
||||
expect(updated).not.toBe(oldData)
|
||||
expect(updated.get(1)).toBe(mockGitStatus)
|
||||
expect(updated.get(2)).toBe(otherStatus)
|
||||
}
|
||||
|
||||
it('returns all mutations', () => {
|
||||
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
|
||||
|
||||
@@ -86,7 +130,9 @@ describe('useGit', () => {
|
||||
})
|
||||
|
||||
expect(gitApi.gitFetch).toHaveBeenCalledWith(1)
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
@@ -113,7 +159,9 @@ describe('useGit', () => {
|
||||
})
|
||||
|
||||
expect(gitApi.gitPull).toHaveBeenCalledWith(1)
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
@@ -136,10 +184,12 @@ describe('useGit', () => {
|
||||
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
result.current.push.mutateAsync()
|
||||
result.current.push.mutateAsync(undefined)
|
||||
})
|
||||
|
||||
expect(gitApi.gitPush).toHaveBeenCalledWith(1, false)
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
@@ -150,7 +200,7 @@ describe('useGit', () => {
|
||||
const { result } = renderHook(() => useGit(1), { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
result.current.push.mutateAsync().catch(() => {})
|
||||
result.current.push.mutateAsync(undefined).catch(() => {})
|
||||
})
|
||||
|
||||
expect(toast.showToast.error).toHaveBeenCalledWith('Push failed')
|
||||
@@ -166,7 +216,9 @@ describe('useGit', () => {
|
||||
})
|
||||
|
||||
expect(gitApi.gitCommit).toHaveBeenCalledWith(1, 'test commit', undefined)
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
@@ -193,7 +245,9 @@ describe('useGit', () => {
|
||||
})
|
||||
|
||||
expect(gitApi.gitStageFiles).toHaveBeenCalledWith(1, ['file.txt'])
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
@@ -220,7 +274,9 @@ describe('useGit', () => {
|
||||
})
|
||||
|
||||
expect(gitApi.gitUnstageFiles).toHaveBeenCalledWith(1, ['file.txt'])
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expectTargetedStatusCacheUpdate()
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['reposGitStatus'] })
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['gitStatus', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['fileDiff', 1] })
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['gitLog', 1] })
|
||||
})
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage } from '@/api/git'
|
||||
import { gitFetch, gitPull, gitPush, gitCommit, gitStageFiles, gitUnstageFiles, gitDiscardFiles, fetchGitLog, fetchGitDiff, gitReset, getApiErrorMessage, fetchGitStatus } from '@/api/git'
|
||||
import { createBranch, switchBranch } from '@/api/repos'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
export function useGit(repoId: number | undefined, onError?: (error: unknown) => void) {
|
||||
const queryClient = useQueryClient()
|
||||
@@ -14,19 +15,14 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
}
|
||||
}
|
||||
|
||||
const invalidateCache = (additionalKeys: string[] = []) => {
|
||||
if (!repoId) return
|
||||
const keys = ['gitStatus', 'fileDiff', 'gitLog', ...additionalKeys]
|
||||
keys.forEach(key => queryClient.invalidateQueries({ queryKey: [key, repoId] }))
|
||||
}
|
||||
|
||||
const fetch = useMutation({
|
||||
mutationFn: () => {
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitFetch(repoId)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Fetch completed')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -37,8 +33,9 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitPull(repoId)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Pull completed')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -50,9 +47,8 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
return gitPush(repoId, options?.setUpstream ?? false)
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData(['gitStatus', repoId], data)
|
||||
const keysToInvalidate = ['fileDiff', 'gitLog', 'repo', 'branches']
|
||||
keysToInvalidate.forEach(key => queryClient.invalidateQueries({ queryKey: [key, repoId] }))
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Push completed')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -63,8 +59,9 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitCommit(repoId, message, stagedPaths)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Commit created')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -75,8 +72,9 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitStageFiles(repoId, paths)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Files staged')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -87,8 +85,9 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitUnstageFiles(repoId, paths)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Files unstaged')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -99,8 +98,9 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitDiscardFiles(repoId, paths, staged)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
},
|
||||
onError: handleError,
|
||||
})
|
||||
@@ -122,24 +122,28 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
})
|
||||
|
||||
const createBranchMutation = useMutation({
|
||||
mutationFn: (branchName: string) => {
|
||||
mutationFn: async (branchName: string) => {
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return createBranch(repoId, branchName)
|
||||
await createBranch(repoId, branchName)
|
||||
return fetchGitStatus(repoId)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache(['branches'])
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false })
|
||||
showToast.success('Branch created')
|
||||
},
|
||||
onError: handleError,
|
||||
})
|
||||
|
||||
const switchBranchMutation = useMutation({
|
||||
mutationFn: (branchName: string) => {
|
||||
mutationFn: async (branchName: string) => {
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return switchBranch(repoId, branchName)
|
||||
await switchBranch(repoId, branchName)
|
||||
return fetchGitStatus(repoId)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache(['branches'])
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false })
|
||||
showToast.success('Switched to branch')
|
||||
},
|
||||
onError: handleError,
|
||||
@@ -150,8 +154,9 @@ export function useGit(repoId: number | undefined, onError?: (error: unknown) =>
|
||||
if (!repoId) throw new Error('No repo ID')
|
||||
return gitReset(repoId, commitHash)
|
||||
},
|
||||
onSuccess: () => {
|
||||
invalidateCache()
|
||||
onSuccess: (data) => {
|
||||
if (repoId) setRepoGitStatusCaches(queryClient, repoId, data)
|
||||
invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false, invalidateRepoMeta: false })
|
||||
showToast.success('Reset to commit')
|
||||
},
|
||||
onError: handleError,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
export function useRefreshOnOpen(isOpen: boolean, refresh: () => void) {
|
||||
const refreshRef = useRef(refresh)
|
||||
refreshRef.current = refresh
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
refreshRef.current()
|
||||
}, [isOpen])
|
||||
}
|
||||
@@ -22,6 +22,7 @@ interface HealthResponse {
|
||||
opencodeMinVersion: string
|
||||
opencodeVersionSupported: boolean
|
||||
opencodeManagerVersion: string | null
|
||||
opencodeRestartPending?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useCallback, useRef, type TouchEvent } from 'react'
|
||||
|
||||
const TOUCH_TAP_MOVE_THRESHOLD = 8
|
||||
const TOUCH_CLICK_SUPPRESS_MS = 400
|
||||
|
||||
export function useTouchTapSelect<T>(onSelect: (item: T) => void) {
|
||||
const touchStartRef = useRef<{ x: number, y: number } | null>(null)
|
||||
const hasTouchMovedRef = useRef(false)
|
||||
const suppressClickRef = useRef(false)
|
||||
|
||||
const suppressNextClick = useCallback(() => {
|
||||
suppressClickRef.current = true
|
||||
setTimeout(() => {
|
||||
suppressClickRef.current = false
|
||||
}, TOUCH_CLICK_SUPPRESS_MS)
|
||||
}, [])
|
||||
|
||||
const onTouchStart = useCallback((event: TouchEvent<HTMLElement>) => {
|
||||
const touch = event.touches[0]
|
||||
if (!touch) return
|
||||
|
||||
touchStartRef.current = { x: touch.clientX, y: touch.clientY }
|
||||
hasTouchMovedRef.current = false
|
||||
}, [])
|
||||
|
||||
const onTouchMove = useCallback((event: TouchEvent<HTMLElement>) => {
|
||||
const start = touchStartRef.current
|
||||
const touch = event.touches[0]
|
||||
if (!start || !touch) return
|
||||
|
||||
const deltaX = Math.abs(touch.clientX - start.x)
|
||||
const deltaY = Math.abs(touch.clientY - start.y)
|
||||
if (deltaX > TOUCH_TAP_MOVE_THRESHOLD || deltaY > TOUCH_TAP_MOVE_THRESHOLD) {
|
||||
hasTouchMovedRef.current = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const onTouchEnd = useCallback((event: TouchEvent<HTMLElement>, item: T) => {
|
||||
const hasTouchMoved = hasTouchMovedRef.current
|
||||
|
||||
touchStartRef.current = null
|
||||
hasTouchMovedRef.current = false
|
||||
|
||||
if (hasTouchMoved) {
|
||||
suppressNextClick()
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
suppressNextClick()
|
||||
onSelect(item)
|
||||
}, [onSelect, suppressNextClick])
|
||||
|
||||
const onClick = useCallback((item: T) => {
|
||||
if (suppressClickRef.current) {
|
||||
suppressClickRef.current = false
|
||||
return
|
||||
}
|
||||
|
||||
onSelect(item)
|
||||
}, [onSelect])
|
||||
|
||||
return {
|
||||
onTouchStart,
|
||||
onTouchMove,
|
||||
onTouchEnd,
|
||||
onClick,
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
const isTextInputFocused = () => {
|
||||
const el = document.activeElement
|
||||
if (!el) return false
|
||||
const tag = el.tagName
|
||||
return tag === 'TEXTAREA' || tag === 'INPUT' || (el as HTMLElement).isContentEditable
|
||||
}
|
||||
|
||||
export function useVisualViewport() {
|
||||
const [keyboardHeight, setKeyboardHeight] = useState(0)
|
||||
|
||||
@@ -8,6 +15,10 @@ export function useVisualViewport() {
|
||||
if (!viewport) return
|
||||
|
||||
const update = () => {
|
||||
if (!isTextInputFocused()) {
|
||||
setKeyboardHeight(0)
|
||||
return
|
||||
}
|
||||
const layoutHeight = window.innerHeight
|
||||
const visualHeight = viewport.height + viewport.offsetTop
|
||||
const offset = Math.max(0, layoutHeight - visualHeight)
|
||||
@@ -16,11 +27,17 @@ export function useVisualViewport() {
|
||||
|
||||
viewport.addEventListener('resize', update)
|
||||
viewport.addEventListener('scroll', update)
|
||||
window.addEventListener('focusout', update)
|
||||
window.addEventListener('pageshow', update)
|
||||
document.addEventListener('visibilitychange', update)
|
||||
update()
|
||||
|
||||
return () => {
|
||||
viewport.removeEventListener('resize', update)
|
||||
viewport.removeEventListener('scroll', update)
|
||||
window.removeEventListener('focusout', update)
|
||||
window.removeEventListener('pageshow', update)
|
||||
document.removeEventListener('visibilitychange', update)
|
||||
}
|
||||
}, [])
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import type { GitStatusResponse } from '@/types/git'
|
||||
|
||||
export function messagesQueryKey(
|
||||
opcodeUrl: string | null | undefined,
|
||||
@@ -20,11 +21,13 @@ export function invalidateProviderCaches(queryClient: QueryClient) {
|
||||
export function invalidateConfigCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'config'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'commands'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-directory-files'] })
|
||||
invalidateProviderCaches(queryClient)
|
||||
}
|
||||
|
||||
@@ -32,6 +35,7 @@ export function invalidateSkillCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['settings', 'skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
}
|
||||
|
||||
export function invalidateSettingsCaches(queryClient: QueryClient, userId = 'default') {
|
||||
@@ -39,6 +43,83 @@ export function invalidateSettingsCaches(queryClient: QueryClient, userId = 'def
|
||||
invalidateConfigCaches(queryClient)
|
||||
}
|
||||
|
||||
export function invalidateRepoListCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['reposGitStatus'] })
|
||||
}
|
||||
|
||||
interface RepoGitInvalidationOptions {
|
||||
invalidateStatus?: boolean
|
||||
invalidateRepoMeta?: boolean
|
||||
}
|
||||
|
||||
export function invalidateRepoGitCaches(
|
||||
queryClient: QueryClient,
|
||||
repoId?: number | null,
|
||||
options: RepoGitInvalidationOptions = {},
|
||||
) {
|
||||
if (!repoId) {
|
||||
invalidateRepoListCaches(queryClient)
|
||||
queryClient.invalidateQueries({ queryKey: ['repo'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['branches'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['gitStatus'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['gitLog'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['fileDiff'] })
|
||||
return
|
||||
}
|
||||
|
||||
if (options.invalidateRepoMeta ?? true) {
|
||||
queryClient.invalidateQueries({ queryKey: ['repos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['repo', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['branches', repoId] })
|
||||
}
|
||||
if (options.invalidateStatus ?? true) {
|
||||
queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['gitLog', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['fileDiff', repoId] })
|
||||
}
|
||||
|
||||
function reposGitStatusQueryIncludesRepo(queryKey: readonly unknown[], repoId: number) {
|
||||
const repoIds = queryKey[1]
|
||||
return queryKey[0] === 'reposGitStatus' && Array.isArray(repoIds) && repoIds.includes(repoId)
|
||||
}
|
||||
|
||||
export function setRepoGitStatusCaches(queryClient: QueryClient, repoId: number, data: GitStatusResponse) {
|
||||
queryClient.setQueryData(['gitStatus', repoId], data)
|
||||
queryClient.setQueriesData<Map<number, GitStatusResponse>>(
|
||||
{
|
||||
queryKey: ['reposGitStatus'],
|
||||
predicate: (query) => reposGitStatusQueryIncludesRepo(query.queryKey, repoId),
|
||||
},
|
||||
(oldData) => {
|
||||
if (!oldData) return oldData
|
||||
const updated = new Map(oldData)
|
||||
updated.set(repoId, data)
|
||||
return updated
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const repoGitInvalidationTimers = new WeakMap<QueryClient, Map<number, ReturnType<typeof setTimeout>>>()
|
||||
|
||||
export function invalidateRepoGitCachesDebounced(queryClient: QueryClient, repoId: number, delayMs = 200) {
|
||||
const existingTimers = repoGitInvalidationTimers.get(queryClient)
|
||||
const timers = existingTimers ?? new Map<number, ReturnType<typeof setTimeout>>()
|
||||
if (!existingTimers) {
|
||||
repoGitInvalidationTimers.set(queryClient, timers)
|
||||
}
|
||||
const existing = timers.get(repoId)
|
||||
if (existing) clearTimeout(existing)
|
||||
timers.set(
|
||||
repoId,
|
||||
setTimeout(() => {
|
||||
timers.delete(repoId)
|
||||
invalidateRepoGitCaches(queryClient, repoId)
|
||||
}, delayMs),
|
||||
)
|
||||
}
|
||||
|
||||
export function invalidateSessionCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (query) =>
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"predev": "bash scripts/setup-dev.sh",
|
||||
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
|
||||
"dev:backend": "NODE_ENV=development bun --watch-path backend/src --watch backend/src/index.ts",
|
||||
"dev:backend": "NODE_ENV=development bun --watch backend/src/index.ts",
|
||||
"dev:frontend": "pnpm --filter frontend dev",
|
||||
"start": "concurrently \"pnpm:start:backend\" \"pnpm:start:frontend\"",
|
||||
"start:backend": "bun run backend/dist/index.js",
|
||||
|
||||
Reference in new issue
Block a user