From 76ca65ec5e90e87da7649d0681315b737eea9200 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:26:58 -0500 Subject: [PATCH] Isolate test state and inject the restart-pending check into config routes --- backend/src/routes/opencode-config.ts | 4 ++- backend/src/routes/settings.test.ts | 1 + backend/src/routes/settings.ts | 6 ++-- .../src/services/opencode-single-server.ts | 2 +- backend/test/routes/files.test.ts | 10 +++--- backend/test/routes/opencode-proxy.test.ts | 1 + backend/test/routes/repo-git.test.ts | 4 +-- backend/test/routes/settings.test.ts | 6 ++-- backend/test/services/git/GitService.test.ts | 10 ++++-- backend/test/services/sandbox/runtime.test.ts | 32 +++++++------------ 10 files changed, 39 insertions(+), 37 deletions(-) diff --git a/backend/src/routes/opencode-config.ts b/backend/src/routes/opencode-config.ts index cb2a68aa..05e285b1 100644 --- a/backend/src/routes/opencode-config.ts +++ b/backend/src/routes/opencode-config.ts @@ -33,6 +33,7 @@ import { logger } from '../utils/logger' interface OpenCodeConfigRoutesOptions { redactSecrets?: boolean + isRestartPending?: () => boolean } async function readMcpStatus(openCodeClient: OpenCodeClient): Promise { @@ -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) diff --git a/backend/src/routes/settings.test.ts b/backend/src/routes/settings.test.ts index 77764a77..d55fad65 100644 --- a/backend/src/routes/settings.test.ts +++ b/backend/src/routes/settings.test.ts @@ -65,6 +65,7 @@ function createSettingsDeps(): SettingsRouteDependencies { clearStartupError: () => undefined, getLastStartupError: () => null, markRestartPending: vi.fn(), + isRestartPending: () => false, restart: async () => undefined, checkHealth: async () => true, }, diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index 79bacba3..9f96caa6 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -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 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) => { diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index db3dbead..ba1467f9 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -379,7 +379,7 @@ class OpenCodeServerManager { this.db = db } - setOpenCodeClient(client: OpenCodeClient) { + setOpenCodeClient(client: OpenCodeClient | null) { this.openCodeClient = client } diff --git a/backend/test/routes/files.test.ts b/backend/test/routes/files.test.ts index 14a9a7cd..258276f6 100644 --- a/backend/test/routes/files.test.ts +++ b/backend/test/routes/files.test.ts @@ -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', diff --git a/backend/test/routes/opencode-proxy.test.ts b/backend/test/routes/opencode-proxy.test.ts index 722c41c6..b7dbfe3d 100644 --- a/backend/test/routes/opencode-proxy.test.ts +++ b/backend/test/routes/opencode-proxy.test.ts @@ -67,6 +67,7 @@ describe('opencode-proxy routes', () => { afterEach(() => { opencodeServerManager.setLifecycleInitialized(true) + opencodeServerManager.setOpenCodeClient(null) db.close() }) diff --git a/backend/test/routes/repo-git.test.ts b/backend/test/routes/repo-git.test.ts index 25a4e39b..955a363b 100644 --- a/backend/test/routes/repo-git.test.ts +++ b/backend/test/routes/repo-git.test.ts @@ -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 }) diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 5035035f..04048e19 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -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 let restart: ReturnType - let manager: SettingsRouteDependencies['openCodeManager'] + let manager: SettingsRouteDependencies['openCodeManager'] & { isRestartPending: ReturnType } let installer: ReturnType let capability: ReturnType let resourceLimitError: ReturnType @@ -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', diff --git a/backend/test/services/git/GitService.test.ts b/backend/test/services/git/GitService.test.ts index 174fa3b3..20a04eab 100644 --- a/backend/test/services/git/GitService.test.ts +++ b/backend/test/services/git/GitService.test.ts @@ -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 }) }) diff --git a/backend/test/services/sandbox/runtime.test.ts b/backend/test/services/sandbox/runtime.test.ts index fc049303..49eb8427 100644 --- a/backend/test/services/sandbox/runtime.test.ts +++ b/backend/test/services/sandbox/runtime.test.ts @@ -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 }) })