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:
Chris Scott authored and GitHub committed 2026-06-20 00:40:36 -04:00
1 parent e53b4fd32c
commit 617962f2dd
48 files changed
+1522 -293

No files matched your search

+29
View File
@@ -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)
}
+39 -10
View File
@@ -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) {
+4 -24
View File
@@ -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)
}