fix(settings): harden config directory replace and consolidate upload plumbing

Validate the config before any filesystem work and persist the default row
only after the directory swap succeeds; reject oversize uploads before
buffering and stream parts to staging; re-ensure AGENTS.md after a replace.
Consolidate the upload contract in shared, unify the default-config upsert,
single-own the browser directory-upload and restart state, and drop dead code.
This commit is contained in:
Chris Scott committed 2026-08-25 10:11:46 -04:00
1 parent b1bccb3dd5
commit 39d2b98370
36 files changed
+1098 -510

No files matched your search

@@ -131,14 +131,16 @@ import { SettingsService } from '../../src/services/settings'
import { opencodeServerManager } from '../../src/services/opencode-single-server'
import { restartOpenCode } from '../../src/services/opencode-restart'
import { replaceOpenCodeConfigDirectory } from '../../src/services/opencode-config-directory'
import { writeFileContent, fileExists } from '../../src/services/file-operations'
const mockReplace = replaceOpenCodeConfigDirectory as ReturnType<typeof vi.fn>
const mockRestartOpenCode = restartOpenCode as ReturnType<typeof vi.fn>
const mockMarkRestartPending = opencodeServerManager.markRestartPending as ReturnType<typeof vi.fn>
const mockClearStartupError = opencodeServerManager.clearStartupError as ReturnType<typeof vi.fn>
const mockWriteFileContent = writeFileContent as ReturnType<typeof vi.fn>
const mockFileExists = fileExists as ReturnType<typeof vi.fn>
const mockReplaceResult = {
configDirectory: '/tmp/test-workspace/config',
configSourceFilename: 'opencode.json',
filesInstalled: ['opencode.json', 'agents/team/lead.md'],
skippedPaths: ['node_modules/package/dist/index.js'],
@@ -164,6 +166,7 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
vi.clearAllMocks()
mockReplace.mockResolvedValue(mockReplaceResult)
mockRestartOpenCode.mockResolvedValue({ resumedSessionIDs: [] })
mockFileExists.mockResolvedValue(false)
testDb = {} as any
settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any, createStubOpenCodeClient())
@@ -183,7 +186,7 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
}
describe('POST /opencode-config-directory/replace', () => {
it('replaces the config directory and marks a restart required', async () => {
it('replaces the config directory, re-ensures AGENTS.md, and restarts the server', async () => {
const res = await settingsApp.request('/opencode-config-directory/replace?userId=custom', {
method: 'POST',
body: buildFormData(),
@@ -191,18 +194,21 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
expect(res.status).toBe(200)
const body = await res.json() as Record<string, unknown>
expect(body).toEqual({ ...mockReplaceResult, restartRequired: true })
expect(body).toEqual(mockReplaceResult)
expect('restartRequired' in body).toBe(false)
expect('configDirectory' in body).toBe(false)
expect(mockReplace).toHaveBeenCalledTimes(1)
expect(mockReplace).toHaveBeenCalledWith(
testDb,
[
expect.objectContaining({ relativePath: 'opencode.json', content: expect.any(Buffer) }),
expect.objectContaining({ relativePath: 'agents/team/lead.md', content: expect.any(Buffer) }),
expect.objectContaining({ relativePath: 'opencode.json', file: expect.any(File) }),
expect.objectContaining({ relativePath: 'agents/team/lead.md', file: expect.any(File) }),
],
'custom',
)
expect(mockSaveLastKnownGoodConfig).toHaveBeenCalledWith('custom')
expect(mockWriteFileContent).toHaveBeenCalledWith('/tmp/test-workspace/AGENTS.md', '# Test Agents MD')
expect(mockMarkRestartPending).toHaveBeenCalledTimes(1)
expect(mockClearStartupError).toHaveBeenCalledTimes(1)
expect(mockRestartOpenCode).toHaveBeenCalledTimes(1)
@@ -263,6 +269,25 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
expect(body.error).toBe('Uploaded config directory contains too many files (max 5000)')
})
it('rejects an over-count manifest with 400 before reading any file content', async () => {
const manifest = Array.from({ length: 5001 }, (_, index) => ({
fieldName: `file${index}`,
relativePath: `dir/file${index}.md`,
}))
const formData = new FormData()
formData.append('fileManifest', JSON.stringify(manifest))
const res = await settingsApp.request('/opencode-config-directory/replace', {
method: 'POST',
body: formData,
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toBe('Uploaded config directory contains too many files (max 5000)')
expect(mockReplace).not.toHaveBeenCalled()
})
it('reports invalid config content as a ZodError 400 with issue details', async () => {
mockReplace.mockRejectedValue(createZodError())
@@ -325,7 +350,20 @@ describe('Settings Routes - OpenCode Config Directory Replace', () => {
expect(mockReplace).not.toHaveBeenCalled()
})
it('leaves restartRequired false when the replace itself fails', async () => {
it('maps a "." manifest relative path to 400 instead of 500', async () => {
mockReplace.mockRejectedValue(new Error('Path must not be empty'))
const res = await settingsApp.request('/opencode-config-directory/replace', {
method: 'POST',
body: buildFormData(),
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toBe('Path must not be empty')
})
it('returns 500 when the replace itself fails without restarting', async () => {
mockReplace.mockRejectedValue(new Error('unexpected failure'))
const res = await settingsApp.request('/opencode-config-directory/replace', {
@@ -1,6 +1,7 @@
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest'
import { join } from 'path'
import { tmpdir } from 'os'
import { promises as fs } from 'fs'
import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'fs/promises'
import type { Database } from 'bun:sqlite'
import { z } from 'zod'
@@ -16,10 +17,13 @@ vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
}
})
const mockValidateOpenCodeConfigContent = vi.fn()
const mockUpsertDefaultOpenCodeConfig = vi.fn()
const mockBunWrite = vi.fn()
vi.mock('../../src/services/settings', () => ({
SettingsService: vi.fn(() => ({
validateOpenCodeConfigContent: mockValidateOpenCodeConfigContent,
upsertDefaultOpenCodeConfig: mockUpsertDefaultOpenCodeConfig,
})),
}))
@@ -28,13 +32,13 @@ import { SettingsService } from '../../src/services/settings'
interface TestUploadFile {
relativePath: string
content: Buffer
file: File
}
function payload(files: Array<[string, string]>): TestUploadFile[] {
return files.map(([relativePath, content]) => ({
relativePath,
content: Buffer.from(content),
file: new File([content], relativePath.split('/').pop() ?? relativePath),
}))
}
@@ -66,12 +70,18 @@ describe('replaceOpenCodeConfigDirectory', () => {
configDir = join(tempDir, '.config', 'opencode')
vi.spyOn(await import('@opencode-manager/shared/config/env'), 'getConfigPath').mockReturnValue(configDir)
mockDb = { query: vi.fn() } as unknown as Database
mockValidateOpenCodeConfigContent.mockReturnValue({})
mockUpsertDefaultOpenCodeConfig.mockReturnValue({ name: 'default', isDefault: true })
mockBunWrite.mockImplementation(async (targetPath: string, file: File) => {
await writeFile(targetPath, Buffer.from(await file.arrayBuffer()))
})
vi.stubGlobal('Bun', { write: mockBunWrite })
})
afterEach(async () => {
await rm(tempDir, { recursive: true, force: true })
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
it('replaces the directory with the uploaded tree, normalizing the config and restoring executables', async () => {
@@ -97,8 +107,8 @@ describe('replaceOpenCodeConfigDirectory', () => {
]))
expect(SettingsService).toHaveBeenCalledWith(mockDb)
expect(mockValidateOpenCodeConfigContent).toHaveBeenCalledWith(jsonc)
expect(mockUpsertDefaultOpenCodeConfig).toHaveBeenCalledWith(jsonc, 'default')
expect(result.configDirectory).toBe(configDir)
expect(result.configSourceFilename).toBe('opencode.jsonc')
expect(result.filesInstalled).toEqual([
'opencode.json',
@@ -111,7 +121,7 @@ describe('replaceOpenCodeConfigDirectory', () => {
'vendor/x.js',
'postgres-mcp-manager.sh',
])
expect(result.executablesRestored).toEqual(['skills/quo-api/scripts/quo-spec.sh', 'postgres-mcp-manager.sh'])
expect(result.executablesRestored).toEqual(['postgres-mcp-manager.sh', 'skills/quo-api/scripts/quo-spec.sh'])
expect(result.skippedPaths).toEqual([])
expect(result.preservedEntries).toEqual([])
@@ -172,6 +182,21 @@ describe('replaceOpenCodeConfigDirectory', () => {
await expect(readFile(join(configDir, '.DS_Store'), 'utf8')).rejects.toThrow()
})
it('computes the common upload root from kept paths, ignoring excluded siblings', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
const result = await replaceOpenCodeConfigDirectory(mockDb, payload([
['my-config/opencode.json', '{"theme":"dark"}'],
['my-config/AGENTS.md', '# Project'],
['other/node_modules/installed.js', 'x'],
]))
expect(result.filesInstalled).toEqual(['opencode.json', 'AGENTS.md'])
expect(result.skippedPaths).toEqual(['other/node_modules/installed.js'])
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"dark"}')
expect(await readFile(join(configDir, 'AGENTS.md'), 'utf8')).toBe('# Project')
await expect(readFile(join(configDir, 'other', 'node_modules', 'installed.js'), 'utf8')).rejects.toThrow()
})
it('rejects a payload with no root config file, leaving the old directory untouched', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
await mkdir(join(configDir, 'agents'), { recursive: true })
@@ -192,7 +217,7 @@ describe('replaceOpenCodeConfigDirectory', () => {
it('rejects when the config fails validation before touching disk', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
mockUpsertDefaultOpenCodeConfig.mockImplementationOnce(() => {
mockValidateOpenCodeConfigContent.mockImplementationOnce(() => {
throw createConfigZodError()
})
await mkdir(join(configDir, 'agents'), { recursive: true })
@@ -205,13 +230,64 @@ describe('replaceOpenCodeConfigDirectory', () => {
])).catch((caught) => caught)
expect(error).toBeInstanceOf(z.ZodError)
expect(mockUpsertDefaultOpenCodeConfig).toHaveBeenCalledWith('{"theme": 42}', 'default')
expect(mockValidateOpenCodeConfigContent).toHaveBeenCalledWith('{"theme": 42}')
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"old"}')
expect(await readFile(join(configDir, 'agents', 'existing.md'), 'utf8')).toBe('keep me')
const parentEntries = await listParentEntries(join(tempDir, '.config'))
expect(parentEntries.filter((name) => name.startsWith('.opencode-config-staging-') || name.startsWith('.opencode-config-backup-'))).toEqual([])
})
it('does not persist to the database when the filesystem phase fails', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
await mkdir(join(configDir, 'agents'), { recursive: true })
await writeFile(join(configDir, 'agents', 'existing.md'), 'keep me')
await writeFile(join(configDir, 'opencode.json'), '{"theme":"old"}')
mockBunWrite.mockImplementationOnce(() => {
throw new Error('ENOSPC: no space left on device')
})
const error = await replaceOpenCodeConfigDirectory(mockDb, payload([
['opencode.json', '{"theme":"new"}'],
['agents/planner.md', '# Planner'],
])).catch((caught) => caught)
expect(error).toBeInstanceOf(Error)
expect((error as Error).message).toContain('ENOSPC')
expect(mockValidateOpenCodeConfigContent).toHaveBeenCalledWith('{"theme":"new"}')
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"old"}')
expect(await readFile(join(configDir, 'agents', 'existing.md'), 'utf8')).toBe('keep me')
const parentEntries = await listParentEntries(join(tempDir, '.config'))
expect(parentEntries.filter((name) => name.startsWith('.opencode-config-staging-') || name.startsWith('.opencode-config-backup-'))).toEqual([])
})
it('reports success when a post-swap node_modules preservation step fails', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
await mkdir(join(configDir, 'node_modules', 'dep'), { recursive: true })
await writeFile(join(configDir, 'node_modules', 'dep', 'index.js'), 'module.exports = 1')
const realRename = fs.rename.bind(fs)
vi.spyOn(fs, 'rename').mockImplementation(async (oldPath, newPath) => {
if (String(newPath).includes('node_modules')) {
throw new Error('EACCES: permission denied')
}
return realRename(oldPath, newPath)
})
const result = await replaceOpenCodeConfigDirectory(mockDb, payload([
['opencode.json', '{"theme":"dark"}'],
]))
expect(result.filesInstalled).toEqual(['opencode.json'])
expect(result.preservedEntries).toEqual([])
expect(mockUpsertDefaultOpenCodeConfig).toHaveBeenCalledWith('{"theme":"dark"}', 'default')
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"dark"}')
await expect(readFile(join(configDir, 'node_modules', 'dep', 'index.js'), 'utf8')).rejects.toThrow()
const parentEntries = await listParentEntries(join(tempDir, '.config'))
expect(parentEntries.filter((name) => name.startsWith('.opencode-config-staging-') || name.startsWith('.opencode-config-backup-'))).toEqual([])
})
it('rejects a path containing .. before any disk mutation', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
await mkdir(configDir, { recursive: true })
@@ -226,6 +302,20 @@ describe('replaceOpenCodeConfigDirectory', () => {
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
})
it('rejects a "." manifest relative path before any disk mutation', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
await mkdir(configDir, { recursive: true })
await writeFile(join(configDir, 'opencode.json'), '{"theme":"old"}')
await expect(replaceOpenCodeConfigDirectory(mockDb, payload([
['opencode.json', '{"theme":"new"}'],
['.', 'x'],
]))).rejects.toThrow('Path must not be empty')
expect(await readFile(join(configDir, 'opencode.json'), 'utf8')).toBe('{"theme":"old"}')
expect(mockUpsertDefaultOpenCodeConfig).not.toHaveBeenCalled()
})
it('rejects payloads exceeding the upload size limit', async () => {
const { replaceOpenCodeConfigDirectory } = await import('../../src/services/opencode-config-directory')
await mkdir(configDir, { recursive: true })
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { ensureDirectoryExists, writeFileContent } from '../../src/services/file-operations'
import { OpenCodeSupervisor } from '../../src/services/opencode-supervisor'
import { DEFAULT_SEED_OPENCODE_CONFIG } from '../../src/services/settings'
vi.mock('../../src/utils/logger', () => ({
logger: {
@@ -18,6 +19,7 @@ vi.mock('../../src/services/file-operations', () => ({
vi.mock('@opencode-manager/shared/config/env', () => ({
getWorkspacePath: vi.fn(() => '/tmp/opencode-workspace'),
getOpenCodeConfigFilePath: vi.fn(() => '/tmp/opencode-workspace/.config/opencode.json'),
getConfigPath: vi.fn(() => '/tmp/opencode-workspace/.config/opencode'),
ENV: {
OPENCODE: {
HEALTH_POLL_MS: 200,
@@ -48,6 +50,7 @@ interface FakeSettingsService {
getDefaultOpenCodeConfig: ReturnType<typeof vi.fn>
updateOpenCodeConfig: ReturnType<typeof vi.fn>
createOpenCodeConfig: ReturnType<typeof vi.fn>
upsertDefaultOpenCodeConfig: ReturnType<typeof vi.fn>
}
describe('OpenCodeSupervisor', () => {
@@ -85,6 +88,12 @@ describe('OpenCodeSupervisor', () => {
isDefault: true,
})),
createOpenCodeConfig: vi.fn(),
upsertDefaultOpenCodeConfig: vi.fn(() => ({
name: 'default',
content: { $schema: 'https://opencode.ai/config.json' },
rawContent: DEFAULT_SEED_OPENCODE_CONFIG,
isDefault: true,
})),
})
it('recovers a startup failure through rollback and keeps watching', async () => {
@@ -171,4 +180,32 @@ describe('OpenCodeSupervisor', () => {
expect(manager.checkHealth).not.toHaveBeenCalled()
})
it('seeds the default config via upsert when recovery reaches seed_default_config', async () => {
const manager = createManager()
const settings = createSettings()
const supervisor = new OpenCodeSupervisor(manager as unknown as never, settings as unknown as never, {
failureThreshold: 1,
userId: 'default',
})
manager.start.mockRejectedValueOnce(new Error('startup failed'))
manager.checkHealth
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const status = await supervisor.start()
expect(status.healthy).toBe(true)
expect(settings.upsertDefaultOpenCodeConfig).toHaveBeenCalledWith(DEFAULT_SEED_OPENCODE_CONFIG, 'default')
expect(writeFileContent).toHaveBeenCalledWith(
'/tmp/opencode-workspace/.config/opencode.json',
DEFAULT_SEED_OPENCODE_CONFIG,
)
expect(manager.restart).toHaveBeenCalledTimes(4)
await supervisor.stop()
})
})
@@ -7,7 +7,7 @@ vi.mock('bun:sqlite', () => ({
})),
}))
import { SettingsService } from '../../src/services/settings'
import { SettingsService, DEFAULT_SEED_OPENCODE_CONFIG } from '../../src/services/settings'
describe('SettingsService - upsertDefaultOpenCodeConfig', () => {
let settingsService: SettingsService
@@ -54,4 +54,21 @@ describe('SettingsService - upsertDefaultOpenCodeConfig', () => {
expect(mockUpdateOpenCodeConfig).not.toHaveBeenCalled()
expect(result.isDefault).toBe(true)
})
it('seeds a default config row marked isDefault when no config exists (index seed path)', () => {
expect(JSON.parse(DEFAULT_SEED_OPENCODE_CONFIG)).toEqual({ $schema: 'https://opencode.ai/config.json' })
mockGetOpenCodeConfigByName.mockReturnValue(null)
mockCreateOpenCodeConfig.mockReturnValue({ name: 'default', isDefault: true })
const result = settingsService.upsertDefaultOpenCodeConfig(DEFAULT_SEED_OPENCODE_CONFIG)
expect(mockCreateOpenCodeConfig).toHaveBeenCalledWith({
name: 'default',
content: DEFAULT_SEED_OPENCODE_CONFIG,
isDefault: true,
}, 'default')
expect(result.name).toBe('default')
expect(result.isDefault).toBe(true)
})
})