diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index b373b425..259db211 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -1,6 +1,6 @@ import { Hono, type Context } from 'hono' import { z } from 'zod' -import { execSync, spawnSync } from 'child_process' +import { spawnSync } from 'child_process' import { randomUUID } from 'crypto' import { existsSync } from 'fs' import { resolve, dirname } from 'path' @@ -28,7 +28,7 @@ import { logger } from '../utils/logger' import { discoverModelsCached, } from '../utils/discovery-cache' -import { opencodeServerManager, ConfigReloadError } from '../services/opencode-single-server' +import { opencodeServerManager, ConfigReloadError, resolveOpenCodeExecutable } from '../services/opencode-single-server' import { sanitizeConfigForEnforcementResult, type EnforcementRemovedSections } from '../services/opencode/enforcement-config' import { getOrCreateInternalToken, rotateInternalToken } from '../services/internal-token' import { sseAggregator } from '../services/sse-aggregator' @@ -271,45 +271,31 @@ function contentForEnforcedDefaultWrite( } function execWithTimeout( - command: string | [executable: string, ...args: string[]], + args: [executable: string, ...commandArgs: string[]], timeoutMs: number, env?: Record ): { output: string; timedOut: boolean } { - if (Array.isArray(command)) { - const result = spawnSync(command[0], command.slice(1), { - encoding: 'utf8', - timeout: timeoutMs, - killSignal: 'SIGKILL', - env: env ? { ...process.env, ...env } : undefined - }) + const result = spawnSync(args[0], args.slice(1), { + encoding: 'utf8', + timeout: timeoutMs, + killSignal: 'SIGKILL', + env: env ? { ...process.env, ...env } : undefined + }) - if (result.signal === 'SIGKILL' || result.error?.message?.includes('TIMEOUT')) { - return { output: '', timedOut: true } - } - - const output = (result.stdout || '') + (result.stderr || '') - return { output, timedOut: false } + if (result.signal === 'SIGKILL' || result.error?.message?.includes('TIMEOUT')) { + return { output: '', timedOut: true } } - try { - const output = execSync(command, { - encoding: 'utf8', - timeout: timeoutMs, - killSignal: 'SIGKILL', - env: env ? { ...process.env, ...env } : undefined - }) - return { output, timedOut: false } - } catch (error) { - if (error && typeof error === 'object' && 'status' in error && (error as { status: number }).status === null) { - return { output: '', timedOut: true } - } - if (error && typeof error === 'object' && ('stdout' in error || 'stderr' in error)) { - const stdout = (error as { stdout?: string }).stdout || '' - const stderr = (error as { stderr?: string }).stderr || '' - return { output: stdout + stderr, timedOut: false } - } - throw error + if (result.error) { + throw result.error } + + const output = (result.stdout || '') + (result.stderr || '') + if (result.status !== 0) { + throw new Error(output || `Command exited with status ${result.status}`) + } + + return { output, timedOut: false } } function spawnWithTimeout(args: string[], timeoutMs: number, env?: Record): { output: string; timedOut: boolean } { @@ -989,8 +975,9 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic try { const installMethod = getOpenCodeInstallMethod() + const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode' logger.info(`Running opencode upgrade --method ${installMethod} with 90s timeout...`) - const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade --method ${installMethod} 2>&1`, 90000) + const { output: upgradeOutput, timedOut } = execWithTimeout([openCodeExecutable, 'upgrade', '--method', installMethod], 90000) logger.info(`Upgrade output: ${upgradeOutput}`) if (timedOut) { @@ -1139,10 +1126,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic logger.info(`Installing OpenCode version: ${version}`) const versionArg = version.startsWith('v') ? version : `v${version}` const installMethod = getOpenCodeInstallMethod() + const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode' logger.info(`Running opencode upgrade ${versionArg} --method ${installMethod} with 90s timeout...`) const { output: upgradeOutput, timedOut } = execWithTimeout( - ['opencode', 'upgrade', versionArg, '--method', installMethod], + [openCodeExecutable, 'upgrade', versionArg, '--method', installMethod], 90000 ) logger.info(`Upgrade output: ${upgradeOutput}`) @@ -1155,6 +1143,10 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic const newVersion = await opencodeServerManager.fetchVersion() logger.info(`New OpenCode version: ${newVersion}`) + if (newVersion !== versionWithoutPrefix) { + throw new Error(`OpenCode version install did not result in the requested version ${versionWithoutPrefix}; detected ${newVersion ?? 'unknown'}`) + } + opencodeServerManager.clearStartupError() await restartOpenCode(openCodeSupervisor) logger.info('OpenCode server restarted after version change') diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 56b71950..66d115a1 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -264,9 +264,9 @@ async function removeChildStateMarker(): Promise { export function resolveOpenCodeExecutable(): string | null { const candidates = [ process.env.OPENCODE_BIN, + path.join(getOpenCodePluginDiscoveryHome(), '.opencode', 'bin', 'opencode'), '/usr/local/bin/opencode', '/opt/opencode/bin/opencode', - path.join(getOpenCodePluginDiscoveryHome(), '.opencode', 'bin', 'opencode'), ].filter((candidate): candidate is string => typeof candidate === 'string' && candidate.length > 0) for (const candidate of candidates) { try { diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 9cc16475..58ede50c 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { execSync, spawnSync } from 'child_process' +import { spawnSync } from 'child_process' import { Database } from 'bun:sqlite' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' import { migrate } from '../../src/db/migration-runner' @@ -32,7 +32,6 @@ vi.mock('fs', () => ({ })) vi.mock('child_process', () => ({ - execSync: vi.fn(), spawnSync: vi.fn(), spawn: vi.fn(), })) @@ -178,7 +177,6 @@ import { relinkReposFromSessionDirectories } from '../../src/services/repo' import { opencodeServerManager, ConfigReloadError } from '../../src/services/opencode-single-server' import { patchConfigWithRecovery } from '../../src/services/opencode/config-recovery' -const mockExecSync = execSync as ReturnType const mockSpawnSync = spawnSync as ReturnType const mockGetVersion = opencodeServerManager.getVersion as ReturnType const mockFetchVersion = opencodeServerManager.fetchVersion as ReturnType @@ -200,7 +198,6 @@ describe('Settings Routes - OpenCode Upgrade', () => { beforeEach(() => { vi.clearAllMocks() - mockExecSync.mockReset() mockGetVersion.mockReset() mockFetchVersion.mockReset() mockReloadConfig.mockReset() @@ -1190,7 +1187,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should upgrade OpenCode successfully and respond with success', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.1') - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1209,7 +1206,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should use a freshly fetched version and restart when the cached version is stale after upgrade', async () => { mockGetVersion.mockReturnValue('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.1') - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1228,7 +1225,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should return already up to date when version unchanged', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - mockExecSync.mockReturnValueOnce('Already up to date\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Already up to date\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1246,7 +1243,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should restart directly after a successful upgrade', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.1') - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1261,12 +1258,12 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockIsSandboxEnforced.mockReturnValue(true) mockGetVersion.mockReturnValueOnce('1.18.16') mockFetchVersion.mockResolvedValueOnce('1.19.0') - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const res = await settingsApp.fetch(new Request('http://localhost/opencode-upgrade', { method: 'POST' })) expect(res.status).toBe(200) - expect(mockExecSync).toHaveBeenCalled() + expect(mockSpawnSync).toHaveBeenCalled() expect(mockRestart).toHaveBeenCalled() }) }) @@ -1276,12 +1273,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockGetVersion.mockReturnValueOnce('1.0.0') .mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - - const timeoutError = new Error('Command timeout') - ;(timeoutError as any).status = null - mockExecSync.mockImplementationOnce(() => { - throw timeoutError - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: '', signal: 'SIGKILL', status: null, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1289,10 +1281,14 @@ describe('Settings Routes - OpenCode Upgrade', () => { const res = await settingsApp.fetch(req) const json = await res.json() as Record - expect(mockExecSync).toHaveBeenCalledWith('opencode upgrade --method curl 2>&1', expect.objectContaining({ - timeout: 90000, - killSignal: 'SIGKILL' - })) + expect(mockSpawnSync).toHaveBeenCalledWith( + 'opencode', + ['upgrade', '--method', 'curl'], + expect.objectContaining({ + timeout: 90000, + killSignal: 'SIGKILL' + }) + ) expect(mockClearStartupError).toHaveBeenCalled() expect(mockRestart).toHaveBeenCalled() expect(res.status).toBe(400) @@ -1309,9 +1305,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockGetVersion.mockReturnValueOnce('1.0.0') .mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - mockExecSync.mockImplementationOnce(() => { - throw new Error('Network error') - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: 'Network error', signal: null, status: 1, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1329,9 +1323,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockGetVersion.mockReturnValueOnce('1.0.0') .mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - mockExecSync.mockImplementationOnce(() => { - throw new Error('Upgrade failed') - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: 'Upgrade failed', signal: null, status: 1, error: undefined }) mockRestart.mockRejectedValueOnce(new Error('Restart failed')) const req = new Request('http://localhost/opencode-upgrade', { @@ -1349,7 +1341,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should use fetched version when getVersion returns null', async () => { mockGetVersion.mockReturnValueOnce(null) mockFetchVersion.mockResolvedValueOnce('1.0.1') - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1365,7 +1357,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should handle both getVersion and fetchVersion returning null', async () => { mockGetVersion.mockReturnValueOnce(null) mockFetchVersion.mockResolvedValueOnce(null) - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1383,7 +1375,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should install specific version successfully', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.5') - mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, error: undefined }) + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -1398,11 +1390,29 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(json.newVersion).toBe('1.0.5') }) + it('does not report success when the requested version was not installed', async () => { + mockGetVersion.mockReturnValue('1.0.0') + mockFetchVersion.mockResolvedValueOnce('1.0.0') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, status: 0, error: undefined }) + + const res = await settingsApp.fetch(new Request('http://localhost/opencode-install-version', { + method: 'POST', + body: JSON.stringify({ version: '1.0.5' }), + headers: { 'Content-Type': 'application/json' } + })) + const json = await res.json() as Record + + expect(res.status).toBe(400) + expect(json.success).toBe(false) + expect(json.details).toContain('did not result in the requested version 1.0.5') + expect(json.newVersion).toBe('1.0.0') + }) + it('allows installing any version while sandbox enforcement is active', async () => { mockIsSandboxEnforced.mockReturnValue(true) mockGetVersion.mockReturnValueOnce('1.18.16') mockFetchVersion.mockResolvedValueOnce('1.20.0') - mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.20.0\n', stderr: '', signal: null, error: undefined }) + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.20.0\n', stderr: '', signal: null, status: 0, error: undefined }) const res = await settingsApp.fetch(new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -1421,7 +1431,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should prepend v to version if missing', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.5') - mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, error: undefined }) + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -1440,7 +1450,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { it('should not double prepend v to version', async () => { mockGetVersion.mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.5') - mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, error: undefined }) + mockSpawnSync.mockReturnValueOnce({ stdout: 'Installed v1.0.5\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-install-version', { method: 'POST', @@ -1535,9 +1545,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockGetVersion.mockReturnValueOnce('1.0.0') .mockReturnValue('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - mockExecSync.mockImplementationOnce(() => { - throw new Error('Unexpected error') - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: 'Unexpected error', signal: null, status: 1, error: undefined }) mockRestart.mockResolvedValue(undefined) const req = new Request('http://localhost/opencode-upgrade', { @@ -1555,9 +1563,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { throw new Error('GetVersion failed') }) mockFetchVersion.mockResolvedValueOnce('1.0.0') - mockExecSync.mockImplementationOnce(() => { - throw new Error('Upgrade failed') - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: 'Upgrade failed', signal: null, status: 1, error: undefined }) mockRestart.mockResolvedValue(undefined) const req = new Request('http://localhost/opencode-upgrade', { @@ -1573,7 +1579,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { mockGetVersion.mockReturnValueOnce('1.0.0') .mockReturnValueOnce('1.0.0') mockFetchVersion.mockRejectedValueOnce(new Error('Fetch version failed')) - mockExecSync.mockReturnValueOnce('Upgrade successful\n') + mockSpawnSync.mockReturnValueOnce({ stdout: 'Upgrade successful\n', stderr: '', signal: null, status: 0, error: undefined }) const req = new Request('http://localhost/opencode-upgrade', { method: 'POST' @@ -1591,11 +1597,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { .mockReturnValueOnce('1.0.0') mockFetchVersion.mockResolvedValueOnce('1.0.0') - const timeoutError = new Error('timeout') - ;(timeoutError as any).status = null - mockExecSync.mockImplementationOnce(() => { - throw timeoutError - }) + mockSpawnSync.mockReturnValueOnce({ stdout: '', stderr: '', signal: 'SIGKILL', status: null, error: undefined }) mockRestart.mockResolvedValue(undefined) const req = new Request('http://localhost/opencode-upgrade', { diff --git a/backend/test/services/opencode-single-server.test.ts b/backend/test/services/opencode-single-server.test.ts index 0fe995c4..7a0ce82f 100644 --- a/backend/test/services/opencode-single-server.test.ts +++ b/backend/test/services/opencode-single-server.test.ts @@ -117,7 +117,7 @@ import { promises as fs, accessSync, readdirSync } from 'fs' import { execSync, spawnSync } from 'child_process' import path from 'path' import os from 'os' -import { ConfigReloadError } from '../../src/services/opencode-single-server' +import { ConfigReloadError, resolveOpenCodeExecutable } from '../../src/services/opencode-single-server' import { forceProcessAttestation, resetProcessIdentityProvider } from '../../src/services/opencode/process-identity' import { encryptSecret } from '../../src/utils/crypto' import { ENV } from '@opencode-manager/shared/config/env' @@ -771,6 +771,24 @@ describe('OpenCodeServerManager - server auth', () => { } }) + it('prefers the user-installed OpenCode executable over the bundled executable', () => { + const accessSyncMock = accessSync as ReturnType + try { + accessSyncMock.mockImplementation((candidate) => { + if (candidate === '/test/home/.opencode/bin/opencode' || candidate === '/usr/local/bin/opencode') return + throw new Error('ENOENT') + }) + + expect(resolveOpenCodeExecutable()).toBe('/test/home/.opencode/bin/opencode') + } finally { + accessSyncMock.mockImplementation(() => { + const error = new Error('ENOENT: no such file or directory') as NodeJS.ErrnoException + error.code = 'ENOENT' + throw error + }) + } + }) + it('stamps the quarantined plugin discovery home into the spawned env when enforced', async () => { sandboxRuntimeServiceMock.SandboxRuntimeService.mockImplementation(() => ({ isEnabled: () => true,