mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(lsp): Fixes LSP initialization timeout (#152)
* fix(lsp): Fixes pyright LSP initialization timeout * test(lsp): Add unit tests for bin directory initialization - Add reinitializeBinDirectory() public method for testing - Add 7 comprehensive test cases - Cover success scenarios, error handling, and edge cases - Achieve 100% code and branch coverage * Refactor OpenCode server for testability and fix bin directory tests --------- Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
1 parent
20fc31bb9b
commit
62343366f6
5 files changed
+310
-17
No files matched your search
@@ -1,4 +1,7 @@
|
||||
NODE_ENV=test
|
||||
PORT=3001
|
||||
DATABASE_PATH=:memory:
|
||||
AUTH_SECRET=test-secret-for-encryption
|
||||
AUTH_SECRET=test-secret-for-encryption
|
||||
WORKSPACE_PATH=/test/workspace
|
||||
OPENCODE_SERVER_PORT=5551
|
||||
OPENCODE_HOST=127.0.0.1
|
||||
@@ -1,5 +1,6 @@
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import { logger } from '../utils/logger'
|
||||
import { createGitEnv, createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
@@ -21,11 +22,14 @@ import { compareVersions } from '../utils/version-utils'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
||||
const OPENCODE_SERVER_DIRECTORY = getWorkspacePath()
|
||||
const OPENCODE_CONFIG_PATH = getOpenCodeConfigFilePath()
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
|
||||
// Helper getters to ensure values are computed at runtime (not module load time)
|
||||
// This allows proper mocking in tests
|
||||
const getOpenCodeServerDirectory = () => getWorkspacePath()
|
||||
const getOpenCodeConfigPath = () => getOpenCodeConfigFilePath()
|
||||
|
||||
class OpenCodeServerManager {
|
||||
private static instance: OpenCodeServerManager
|
||||
private serverProcess: ReturnType<typeof spawn> | null = null
|
||||
@@ -48,6 +52,14 @@ class OpenCodeServerManager {
|
||||
return OpenCodeServerManager.instance
|
||||
}
|
||||
|
||||
/**
|
||||
* Test-only method to reset the singleton instance.
|
||||
* Should only be used in test setup/teardown.
|
||||
*/
|
||||
static resetInstance(): void {
|
||||
OpenCodeServerManager.instance = null as unknown as OpenCodeServerManager
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.isHealthy) {
|
||||
logger.info('OpenCode server already running and healthy')
|
||||
@@ -109,8 +121,10 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`OpenCode server working directory: ${OPENCODE_SERVER_DIRECTORY}`)
|
||||
logger.info(`OpenCode XDG_CONFIG_HOME: ${path.join(OPENCODE_SERVER_DIRECTORY, '.config')}`)
|
||||
const openCodeServerDirectory = getOpenCodeServerDirectory()
|
||||
const openCodeConfigPath = getOpenCodeConfigPath()
|
||||
logger.info(`OpenCode server working directory: ${openCodeServerDirectory}`)
|
||||
logger.info(`OpenCode XDG_CONFIG_HOME: ${path.join(openCodeServerDirectory, '.config')}`)
|
||||
logger.info(`OpenCode will use ?directory= parameter for session isolation`)
|
||||
|
||||
const gitEnv = createGitEnv(gitCredentials)
|
||||
@@ -160,13 +174,15 @@ class OpenCodeServerManager {
|
||||
|
||||
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
|
||||
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
this.serverProcess = spawn(
|
||||
'opencode',
|
||||
['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', OPENCODE_SERVER_HOST],
|
||||
{
|
||||
cwd: OPENCODE_SERVER_DIRECTORY,
|
||||
cwd: openCodeServerDirectory,
|
||||
detached: !isDevelopment,
|
||||
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
@@ -174,9 +190,9 @@ class OpenCodeServerManager {
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'),
|
||||
XDG_CONFIG_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.config'),
|
||||
OPENCODE_CONFIG: OPENCODE_CONFIG_PATH,
|
||||
XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
|
||||
XDG_CONFIG_HOME: path.join(openCodeServerDirectory, '.config'),
|
||||
OPENCODE_CONFIG: openCodeConfigPath,
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -261,6 +277,46 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeOpencodeBinDirectory(): Promise<void> {
|
||||
const binDir = path.join(
|
||||
getOpenCodeServerDirectory(),
|
||||
'.opencode',
|
||||
'state',
|
||||
'opencode',
|
||||
'bin'
|
||||
)
|
||||
|
||||
const packageJsonPath = path.join(binDir, 'package.json')
|
||||
|
||||
try {
|
||||
await fs.mkdir(binDir, { recursive: true })
|
||||
|
||||
const packageJsonExists = await fs.access(packageJsonPath)
|
||||
.then(() => true)
|
||||
.catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return false
|
||||
throw error
|
||||
})
|
||||
|
||||
if (!packageJsonExists) {
|
||||
try {
|
||||
execSync('bun init -y', {
|
||||
cwd: binDir,
|
||||
stdio: 'inherit',
|
||||
timeout: 30000
|
||||
})
|
||||
logger.info('OpenCode bin directory initialized successfully')
|
||||
} catch (error) {
|
||||
logger.error('bun init failed:', error)
|
||||
throw new Error(`bun init failed: ${error}`)
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize OpenCode bin directory:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async restart(): Promise<void> {
|
||||
logger.info('Restarting OpenCode server (full process restart)')
|
||||
await this.stop()
|
||||
@@ -328,6 +384,11 @@ class OpenCodeServerManager {
|
||||
this.lastStartupError = null
|
||||
}
|
||||
|
||||
async reinitializeBinDirectory(): Promise<void> {
|
||||
logger.info('Reinitializing OpenCode bin directory')
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/doc`, {
|
||||
@@ -375,3 +436,4 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
export const opencodeServerManager = OpenCodeServerManager.getInstance()
|
||||
export { OpenCodeServerManager }
|
||||
@@ -0,0 +1,212 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getWorkspacePath: vi.fn(() => '/test/workspace'),
|
||||
getOpenCodeConfigFilePath: vi.fn(() => '/test/workspace/.config/opencode.json'),
|
||||
getReposPath: vi.fn(() => '/test/workspace/repos'),
|
||||
getAgentsMdPath: vi.fn(() => '/test/workspace/AGENTS.md'),
|
||||
getDatabasePath: vi.fn(() => ':memory:'),
|
||||
getConfigPath: vi.fn(() => '/test/workspace/config'),
|
||||
ENV: {
|
||||
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
|
||||
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' },
|
||||
WORKSPACE: { BASE_PATH: '/test/workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' },
|
||||
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
|
||||
DATABASE: { PATH: ':memory:' },
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
|
||||
},
|
||||
},
|
||||
FILE_LIMITS: {
|
||||
MAX_SIZE_BYTES: 1024 * 1024,
|
||||
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
promises: {
|
||||
mkdir: vi.fn(),
|
||||
access: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
chmod: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rm: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
execSync: vi.fn(),
|
||||
}))
|
||||
|
||||
import { promises as fs } from 'fs'
|
||||
import { execSync } from 'child_process'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mkdirMock = fs.mkdir as any
|
||||
const accessMock = fs.access as any
|
||||
const execSyncMock = execSync as any
|
||||
|
||||
// Reset singleton before any tests run to clear any polluted state from previous test files
|
||||
beforeAll(async () => {
|
||||
const { OpenCodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
OpenCodeServerManager.resetInstance()
|
||||
})
|
||||
|
||||
describe('OpenCodeServerManager - reinitializeBinDirectory', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.WORKSPACE_PATH = '/test/workspace'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
delete process.env.WORKSPACE_PATH
|
||||
})
|
||||
|
||||
describe('Success Cases', () => {
|
||||
it('should create directory and initialize when package.json does not exist', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
const enoentError = new Error('File not found') as NodeJS.ErrnoException
|
||||
enoentError.code = 'ENOENT'
|
||||
accessMock.mockRejectedValue(enoentError)
|
||||
execSyncMock.mockReturnValue(Buffer.from('Success'))
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(mkdirMock).toHaveBeenCalledWith(
|
||||
'/test/workspace/.opencode/state/opencode/bin',
|
||||
{ recursive: true }
|
||||
)
|
||||
expect(execSyncMock).toHaveBeenCalledWith(
|
||||
'bun init -y',
|
||||
expect.objectContaining({
|
||||
cwd: '/test/workspace/.opencode/state/opencode/bin',
|
||||
stdio: 'inherit',
|
||||
timeout: 30000
|
||||
})
|
||||
)
|
||||
expect(logger.info).toHaveBeenCalledWith('Reinitializing OpenCode bin directory')
|
||||
expect(logger.info).toHaveBeenCalledWith('OpenCode bin directory initialized successfully')
|
||||
})
|
||||
|
||||
it('should skip initialization when package.json already exists', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
accessMock.mockResolvedValue(undefined)
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(mkdirMock).toHaveBeenCalledWith(
|
||||
'/test/workspace/.opencode/state/opencode/bin',
|
||||
{ recursive: true }
|
||||
)
|
||||
expect(execSyncMock).not.toHaveBeenCalled()
|
||||
expect(logger.info).toHaveBeenCalledWith('Reinitializing OpenCode bin directory')
|
||||
})
|
||||
|
||||
it('should log reinitialization message', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
accessMock.mockResolvedValue(undefined)
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(logger.info).toHaveBeenCalledWith('Reinitializing OpenCode bin directory')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should handle bun init failure gracefully', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
const enoentError = new Error('Not found') as NodeJS.ErrnoException
|
||||
enoentError.code = 'ENOENT'
|
||||
accessMock.mockRejectedValue(enoentError)
|
||||
execSyncMock.mockImplementation(() => {
|
||||
throw new Error('bun init failed')
|
||||
})
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith('bun init failed:', expect.any(Error))
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
'Failed to initialize OpenCode bin directory:',
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle directory creation failure gracefully', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
mkdirMock.mockRejectedValue(new Error('Permission denied'))
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
'Failed to initialize OpenCode bin directory:',
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle fs.access throwing non-ENOENT error gracefully', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
mkdirMock.mockResolvedValue(undefined)
|
||||
accessMock.mockRejectedValue(new Error('Permission denied'))
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(execSyncMock).not.toHaveBeenCalled()
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
'Failed to initialize OpenCode bin directory:',
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle timeout during bun init', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { logger } = await import('../../src/utils/logger')
|
||||
|
||||
mkdirMock.mockResolvedValue(undefined)
|
||||
const enoentError = new Error('Not found') as NodeJS.ErrnoException
|
||||
enoentError.code = 'ENOENT'
|
||||
accessMock.mockRejectedValue(enoentError)
|
||||
execSyncMock.mockImplementation(() => {
|
||||
const error = new Error('Command timed out')
|
||||
error.name = 'ETIMEDOUT'
|
||||
throw error
|
||||
})
|
||||
|
||||
await opencodeServerManager.reinitializeBinDirectory()
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith('bun init failed:', expect.any(Error))
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
'Failed to initialize OpenCode bin directory:',
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
+15
-6
@@ -1,12 +1,21 @@
|
||||
import { beforeAll, afterAll, vi } from 'vitest'
|
||||
import { beforeAll, afterAll } from 'vitest'
|
||||
|
||||
const originalEnv: Record<string, string | undefined> = {}
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubEnv('NODE_ENV', 'test')
|
||||
vi.stubEnv('PORT', '3001')
|
||||
vi.stubEnv('DATABASE_PATH', ':memory:')
|
||||
vi.stubEnv('AUTH_SECRET', 'test-secret-for-encryption')
|
||||
originalEnv.NODE_ENV = process.env.NODE_ENV
|
||||
originalEnv.PORT = process.env.PORT
|
||||
originalEnv.DATABASE_PATH = process.env.DATABASE_PATH
|
||||
originalEnv.AUTH_SECRET = process.env.AUTH_SECRET
|
||||
originalEnv.WORKSPACE_PATH = process.env.WORKSPACE_PATH
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
vi.unstubAllEnvs()
|
||||
for (const [key, value] of Object.entries(originalEnv)) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key]
|
||||
} else {
|
||||
process.env[key] = value
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -4,6 +4,13 @@ export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
setupFiles: ['./test/setup.ts']
|
||||
}
|
||||
setupFiles: ['./test/setup.ts'],
|
||||
env: {
|
||||
NODE_ENV: 'test',
|
||||
PORT: '3001',
|
||||
DATABASE_PATH: ':memory:',
|
||||
AUTH_SECRET: 'test-secret-for-encryption',
|
||||
WORKSPACE_PATH: '/test/workspace',
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in new issue
Block a user