mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Isolate test state and inject the restart-pending check into config routes
This commit is contained in:
1 parent
26fd21250a
commit
76ca65ec5e
10 files changed
+39
-37
No files matched your search
@@ -33,6 +33,7 @@ import { logger } from '../utils/logger'
|
||||
|
||||
interface OpenCodeConfigRoutesOptions {
|
||||
redactSecrets?: boolean
|
||||
isRestartPending?: () => boolean
|
||||
}
|
||||
|
||||
async function readMcpStatus(openCodeClient: OpenCodeClient): Promise<McpStatusMap> {
|
||||
@@ -70,6 +71,7 @@ export function createOpenCodeConfigRoutes(
|
||||
options: OpenCodeConfigRoutesOptions = {},
|
||||
) {
|
||||
const app = new Hono()
|
||||
const isRestartPending = options.isRestartPending ?? (() => opencodeServerManager.isRestartPending())
|
||||
|
||||
app.get('/', async (c) => {
|
||||
try {
|
||||
@@ -173,7 +175,7 @@ export function createOpenCodeConfigRoutes(
|
||||
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
|
||||
}
|
||||
|
||||
if (opencodeServerManager.isRestartPending() && patchNamesOpenCodeConfigEntities(parsed.data.patch)) {
|
||||
if (isRestartPending() && patchNamesOpenCodeConfigEntities(parsed.data.patch)) {
|
||||
return c.json({
|
||||
error: 'OpenCode has not loaded the saved configuration yet. Restart OpenCode before editing entries.',
|
||||
}, 409)
|
||||
|
||||
@@ -65,6 +65,7 @@ function createSettingsDeps(): SettingsRouteDependencies {
|
||||
clearStartupError: () => undefined,
|
||||
getLastStartupError: () => null,
|
||||
markRestartPending: vi.fn(),
|
||||
isRestartPending: () => false,
|
||||
restart: async () => undefined,
|
||||
checkHealth: async () => true,
|
||||
},
|
||||
|
||||
@@ -74,7 +74,7 @@ import {
|
||||
export interface SettingsRouteDependencies {
|
||||
openCodeManager: Pick<
|
||||
typeof opencodeServerManager,
|
||||
'getVersion' | 'fetchVersion' | 'clearStartupError' | 'getLastStartupError' | 'markRestartPending' | 'restart' | 'checkHealth'
|
||||
'getVersion' | 'fetchVersion' | 'clearStartupError' | 'getLastStartupError' | 'markRestartPending' | 'isRestartPending' | 'restart' | 'checkHealth'
|
||||
>
|
||||
installOpenCodeVersion: (version: string) => Promise<string>
|
||||
detectSandboxCapability: () => SandboxCapability
|
||||
@@ -528,7 +528,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
})
|
||||
|
||||
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient))
|
||||
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient, {
|
||||
isRestartPending: () => deps.openCodeManager.isRestartPending(),
|
||||
}))
|
||||
app.route('/remote-access-headers', createRemoteAccessHeaderRoutes(new RemoteAccessHeadersService(db)))
|
||||
|
||||
app.post('/opencode-restart', async (c) => {
|
||||
|
||||
@@ -379,7 +379,7 @@ class OpenCodeServerManager {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
setOpenCodeClient(client: OpenCodeClient) {
|
||||
setOpenCodeClient(client: OpenCodeClient | null) {
|
||||
this.openCodeClient = client
|
||||
}
|
||||
|
||||
|
||||
@@ -252,7 +252,7 @@ describe('file routes', () => {
|
||||
})
|
||||
|
||||
it('returns 404 when the path does not exist', async () => {
|
||||
files.getFile.mockReturnValue(Promise.reject({ message: 'File or directory not found', statusCode: 404 }))
|
||||
files.getFile.mockRejectedValue({ message: 'File or directory not found', statusCode: 404 })
|
||||
|
||||
const response = await app.request('/api/files/test-repo/nonexistent.txt')
|
||||
const body = await readJson(response, ErrorResponseSchema)
|
||||
@@ -264,7 +264,7 @@ describe('file routes', () => {
|
||||
it.each(['test-repo/../etc/passwd', 'test-repo/..%2Fetc'])(
|
||||
'returns the service path traversal rejection for %s',
|
||||
async (requestPath) => {
|
||||
files.getFile.mockReturnValue(Promise.reject({ message: 'Path traversal detected', statusCode: 403 }))
|
||||
files.getFile.mockRejectedValue({ message: 'Path traversal detected', statusCode: 403 })
|
||||
|
||||
const response = await app.request(`/api/files/${requestPath}`)
|
||||
const body = await readJson(response, ErrorResponseSchema)
|
||||
@@ -426,7 +426,7 @@ describe('file routes', () => {
|
||||
})
|
||||
|
||||
it('maps a deletion failure to its status code', async () => {
|
||||
files.deleteFileOrFolder.mockReturnValue(Promise.reject({ message: 'File not found', statusCode: 404 }))
|
||||
files.deleteFileOrFolder.mockRejectedValue({ message: 'File not found', statusCode: 404 })
|
||||
|
||||
const response = await app.request('/api/files/test-repo/nonexistent.ts', { method: 'DELETE' })
|
||||
const body = await readJson(response, ErrorResponseSchema)
|
||||
@@ -457,7 +457,7 @@ describe('file routes', () => {
|
||||
})
|
||||
|
||||
it('maps a patch failure to its status code', async () => {
|
||||
files.applyFilePatches.mockReturnValue(Promise.reject({ message: 'Invalid patch', statusCode: 404 }))
|
||||
files.applyFilePatches.mockRejectedValue({ message: 'Invalid patch', statusCode: 404 })
|
||||
const requestBody: FilePatchRequest = {
|
||||
patches: [{ type: 'replace', startLine: 999 }],
|
||||
}
|
||||
@@ -496,7 +496,7 @@ describe('file routes', () => {
|
||||
})
|
||||
|
||||
it('maps a rename failure to its status code', async () => {
|
||||
files.renameOrMoveFile.mockReturnValue(Promise.reject({ message: 'File not found', statusCode: 404 }))
|
||||
files.renameOrMoveFile.mockRejectedValue({ message: 'File not found', statusCode: 404 })
|
||||
|
||||
const response = await app.request('/api/files/test-repo/nonexistent.ts', {
|
||||
method: 'PATCH',
|
||||
|
||||
@@ -67,6 +67,7 @@ describe('opencode-proxy routes', () => {
|
||||
|
||||
afterEach(() => {
|
||||
opencodeServerManager.setLifecycleInitialized(true)
|
||||
opencodeServerManager.setOpenCodeClient(null)
|
||||
db.close()
|
||||
})
|
||||
|
||||
|
||||
@@ -224,7 +224,7 @@ describe('repo git routes', () => {
|
||||
expect(body.status).toEqual({ ahead: 0, behind: 0 })
|
||||
})
|
||||
|
||||
it('returns 500 when the checkout is not a git repository', async () => {
|
||||
it('returns 400 NOT_A_REPO when the checkout is not a git repository', async () => {
|
||||
const plainPath = path.join(workspace.path, 'repos', 'plain-branches')
|
||||
mkdirSync(plainPath, { recursive: true })
|
||||
const plain = seedRepo(db, { localPath: 'plain-branches', sourcePath: plainPath })
|
||||
@@ -270,7 +270,7 @@ describe('repo git routes', () => {
|
||||
expect(body.files).toEqual([])
|
||||
})
|
||||
|
||||
it('returns 500 when the checkout is not a git repository', async () => {
|
||||
it('returns 400 NOT_A_REPO when the checkout is not a git repository', async () => {
|
||||
const plainPath = path.join(workspace.path, 'repos', 'plain-discard')
|
||||
mkdirSync(plainPath, { recursive: true })
|
||||
const plain = seedRepo(db, { localPath: 'plain-discard', sourcePath: plainPath })
|
||||
|
||||
@@ -15,7 +15,6 @@ import { GitAuthService } from '../../src/services/git-auth'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
import { clearOpenCodeVersionCache } from '../../src/services/opencode-installer'
|
||||
import { forceProcessAttestation } from '../../src/services/opencode/process-identity'
|
||||
import { opencodeServerManager } from '../../src/services/opencode-single-server'
|
||||
import { sseAggregator } from '../../src/services/sse-aggregator'
|
||||
import { createStubOpenCodeClient, type OpenCodeApiOverrides } from '../helpers/stub-opencode-client'
|
||||
import { createTestDatabase } from '../helpers/test-database'
|
||||
@@ -130,7 +129,7 @@ describe('Settings routes', () => {
|
||||
let db: Database
|
||||
let reload: ReturnType<typeof vi.fn>
|
||||
let restart: ReturnType<typeof vi.fn>
|
||||
let manager: SettingsRouteDependencies['openCodeManager']
|
||||
let manager: SettingsRouteDependencies['openCodeManager'] & { isRestartPending: ReturnType<typeof vi.fn> }
|
||||
let installer: ReturnType<typeof vi.fn>
|
||||
let capability: ReturnType<typeof vi.fn>
|
||||
let resourceLimitError: ReturnType<typeof vi.fn>
|
||||
@@ -185,6 +184,7 @@ describe('Settings routes', () => {
|
||||
clearStartupError: vi.fn(),
|
||||
getLastStartupError: vi.fn(() => null),
|
||||
markRestartPending: vi.fn(),
|
||||
isRestartPending: vi.fn(() => false),
|
||||
restart: vi.fn(async () => undefined),
|
||||
checkHealth: vi.fn(async () => true),
|
||||
}
|
||||
@@ -401,7 +401,7 @@ describe('Settings routes', () => {
|
||||
it('reloads a patch that names no entities while a restart is pending, and blocks entity patches', async () => {
|
||||
await writeConfig('opencode.json', '{"theme":"light"}')
|
||||
settingsApp = createApp()
|
||||
opencodeServerManager.markRestartPending()
|
||||
manager.isRestartPending.mockReturnValue(true)
|
||||
|
||||
const entityRes = await settingsApp.request('/opencode-config', {
|
||||
method: 'PATCH',
|
||||
|
||||
@@ -6,13 +6,16 @@ import type { Database } from 'bun:sqlite'
|
||||
import { createRepo } from '../../../src/db/queries'
|
||||
import { createGitService, type GitService } from '../../../src/services/git/GitService'
|
||||
import type { Repo } from '../../../src/types/repo'
|
||||
import { applyTestEnv } from '../../helpers/test-env'
|
||||
import { createTestDatabase } from '../../helpers/test-database'
|
||||
import { cloneOrigin, createCommittedRepo, createGitAuthService, createOrigin, git, uniqueName } from '../../helpers/git-fixtures'
|
||||
|
||||
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'git-service-'))
|
||||
process.env.WORKSPACE_PATH = workspaceRoot
|
||||
process.env.GIT_CONFIG_NOSYSTEM = '1'
|
||||
process.env.GIT_CONFIG_GLOBAL = '/dev/null'
|
||||
const restoreEnv = applyTestEnv({
|
||||
WORKSPACE_PATH: workspaceRoot,
|
||||
GIT_CONFIG_NOSYSTEM: '1',
|
||||
GIT_CONFIG_GLOBAL: '/dev/null',
|
||||
})
|
||||
|
||||
const reposPath = path.join(workspaceRoot, 'repos')
|
||||
|
||||
@@ -37,6 +40,7 @@ describe('GitService', () => {
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
restoreEnv()
|
||||
rmSync(workspaceRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
|
||||
@@ -36,21 +36,20 @@ import { expectLoggedMessage, resetTestLogs, testLogEntries } from '../../helper
|
||||
import { FAKE_MSB_SCRIPT, FAKE_MSB_STATE_ENV } from '../../helpers/fake-msb'
|
||||
import { createTestDatabase } from '../../helpers/test-database'
|
||||
import { git } from '../../helpers/git-fixtures'
|
||||
import { applyTestEnv } from '../../helpers/test-env'
|
||||
|
||||
const originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
const originalGitConfigGlobal = process.env.GIT_CONFIG_GLOBAL
|
||||
const originalGitConfigSystem = process.env.GIT_CONFIG_SYSTEM
|
||||
const originalGitConfigNoSystem = process.env.GIT_CONFIG_NOSYSTEM
|
||||
const suiteBinDir = mkdtempSync(path.join(realpathSync(tmpdir()), 'ocm-runtime-bin-'))
|
||||
writeFileSync(path.join(suiteBinDir, 'msb'), FAKE_MSB_SCRIPT, { mode: 0o755 })
|
||||
process.env.PATH = `${suiteBinDir}${path.delimiter}${process.env.PATH ?? ''}`
|
||||
process.env.GIT_CONFIG_GLOBAL = '/dev/null'
|
||||
process.env.GIT_CONFIG_SYSTEM = '/dev/null'
|
||||
process.env.GIT_CONFIG_NOSYSTEM = '1'
|
||||
overrideSandboxExecutableTrustValidator(() => true)
|
||||
const suiteWorkspaceParent = mkdtempSync(path.join(realpathSync(tmpdir()), 'ocm-runtime-test-'))
|
||||
process.env.WORKSPACE_PATH = suiteWorkspaceParent
|
||||
process.env[FAKE_MSB_STATE_ENV] = path.join(suiteWorkspaceParent, 'fake-msb')
|
||||
const restoreTestEnv = applyTestEnv({
|
||||
PATH: `${suiteBinDir}${path.delimiter}${process.env.PATH ?? ''}`,
|
||||
GIT_CONFIG_GLOBAL: '/dev/null',
|
||||
GIT_CONFIG_SYSTEM: '/dev/null',
|
||||
GIT_CONFIG_NOSYSTEM: '1',
|
||||
WORKSPACE_PATH: suiteWorkspaceParent,
|
||||
[FAKE_MSB_STATE_ENV]: path.join(suiteWorkspaceParent, 'fake-msb'),
|
||||
})
|
||||
overrideSandboxExecutableTrustValidator(() => true)
|
||||
|
||||
const reposRoot = getReposPath()
|
||||
const worktreesRoot = getScheduleWorktreesPath()
|
||||
@@ -479,15 +478,8 @@ describe('SandboxRuntimeService', () => {
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
if (originalWorkspacePath === undefined) delete process.env.WORKSPACE_PATH
|
||||
else process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
if (originalGitConfigGlobal === undefined) delete process.env.GIT_CONFIG_GLOBAL
|
||||
else process.env.GIT_CONFIG_GLOBAL = originalGitConfigGlobal
|
||||
if (originalGitConfigSystem === undefined) delete process.env.GIT_CONFIG_SYSTEM
|
||||
else process.env.GIT_CONFIG_SYSTEM = originalGitConfigSystem
|
||||
if (originalGitConfigNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM
|
||||
else process.env.GIT_CONFIG_NOSYSTEM = originalGitConfigNoSystem
|
||||
delete process.env[FAKE_MSB_STATE_ENV]
|
||||
restoreTestEnv()
|
||||
overrideSandboxExecutableTrustValidator(null)
|
||||
rmSync(suiteWorkspaceParent, { recursive: true, force: true })
|
||||
rmSync(suiteBinDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user