Bump version to 0.8.21 (#99)

* Add timeout handling and recovery for OpenCode upgrade/install operations

- Extract DEFAULT_AGENTS_MD to constants file
- Add 90s timeout for opencode upgrade/install commands
- Implement server recovery when upgrade/install fails
- Update frontend error handling for recovery status
- Add settings route tests

* Add centralized query cache invalidation utility

* Bump version to 0.8.21
This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-30 22:39:24 -05:00
1 parent 3661f0a271
commit a02f7a2e98
14 files changed
+1100 -126

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
export const DEFAULT_AGENTS_MD = `# OpenCode Manager - Global Agent Instructions
## Critical System Constraints
- **DO NOT** use ports 5003 or 5551 - these are reserved for OpenCode Manager
- **DO NOT** kill or stop processes on ports 5003 or 5551
- **DO NOT** modify files in the \`.config/opencode\` directory unless explicitly requested
## Dev Server Ports
When starting dev servers, use the pre-allocated ports 5100-5103:
- Port 5100: Primary dev server (frontend)
- Port 5101: Secondary dev server (API/backend)
- Port 5102: Additional service
- Port 5103: Additional service
Always bind to \`0.0.0.0\` to allow external access from the Docker host.
## Package Management
### Node.js Packages
Prefer **pnpm** or **bun** over npm for installing dependencies to save disk space:
- Use \`pnpm install\` instead of \`npm install\`
- Use \`bun install\` as an alternative
- Both are pre-installed in the container
### Python Packages
Always create a virtual environment in the repository directory before installing packages:
1. Create virtual environment in repo:
\`cd \`<repo_path>\`
\`uv venv .venv\`
2. Activate the virtual environment:
\`source .venv/bin/activate\` # or \`uv pip sync\` for project-based workflows
3. Install packages into activated environment:
\`uv pip install \`<package>\`
\`uv pip install -r requirements.txt\`
4. Run Python commands:
\`python script.py\` # Uses activated .venv
Alternative: Use \`uv run python script.py\` to skip explicit activation
**Important:**
- Always create .venv in the repository directory (not workspace root)
- Activate the environment before running pip operations
- uv is pre-installed in the container and provides faster package installation
- .venv directories created in repos will persist but can be removed safely
## General Guidelines
- This file is merged with any AGENTS.md files in individual repositories
- Repository-specific instructions take precedence for their respective codebases
`
+2 -57
View File
@@ -60,66 +60,11 @@ const db = initializeDatabase(DB_PATH)
const auth = createAuth(db)
const requireAuth = createAuthMiddleware(auth)
import { DEFAULT_AGENTS_MD } from './constants'
let ipcServer: IPCServer | undefined
const gitAuthService = new GitAuthService()
export const DEFAULT_AGENTS_MD = `# OpenCode Manager - Global Agent Instructions
## Critical System Constraints
- **DO NOT** use ports 5003 or 5551 - these are reserved for OpenCode Manager
- **DO NOT** kill or stop processes on ports 5003 or 5551
- **DO NOT** modify files in the \`.config/opencode\` directory unless explicitly requested
## Dev Server Ports
When starting dev servers, use the pre-allocated ports 5100-5103:
- Port 5100: Primary dev server (frontend)
- Port 5101: Secondary dev server (API/backend)
- Port 5102: Additional service
- Port 5103: Additional service
Always bind to \`0.0.0.0\` to allow external access from the Docker host.
## Package Management
### Node.js Packages
Prefer **pnpm** or **bun** over npm for installing dependencies to save disk space:
- Use \`pnpm install\` instead of \`npm install\`
- Use \`bun install\` as an alternative
- Both are pre-installed in the container
### Python Packages
Always create a virtual environment in the repository directory before installing packages:
1. Create virtual environment in repo:
\`cd \`<repo_path>\`
\`uv venv .venv\`
2. Activate the virtual environment:
\`source .venv/bin/activate\` # or \`uv pip sync\` for project-based workflows
3. Install packages into activated environment:
\`uv pip install \`<package>\`
\`uv pip install -r requirements.txt\`
4. Run Python commands:
\`python script.py\` # Uses activated .venv
Alternative: Use \`uv run python script.py\` to skip explicit activation
**Important:**
- Always create .venv in the repository directory (not workspace root)
- Activate the environment before running pip operations
- uv is pre-installed in the container and provides faster package installation
- .venv directories created in repos will persist but can be removed safely
## General Guidelines
- This file is merged with any AGENTS.md files in individual repositories
- Repository-specific instructions take precedence for their respective codebases
`
async function ensureDefaultConfigExists(): Promise<void> {
const settingsService = new SettingsService(db)
const workspaceConfigPath = getOpenCodeConfigFilePath()
+126 -32
View File
@@ -12,7 +12,7 @@ import {
} from '../types/settings'
import { logger } from '../utils/logger'
import { opencodeServerManager } from '../services/opencode-single-server'
import { DEFAULT_AGENTS_MD } from '../index'
import { DEFAULT_AGENTS_MD } from '../constants'
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(s => Number(s))
@@ -27,6 +27,22 @@ function compareVersions(v1: string, v2: string): number {
return 0
}
function execWithTimeout(command: string, timeoutMs: number): { output: string; timedOut: boolean } {
try {
const output = execSync(command, {
encoding: 'utf8',
timeout: timeoutMs,
killSignal: 'SIGKILL'
})
return { output, timedOut: false }
} catch (error) {
if (error && typeof error === 'object' && 'status' in error && (error as { status: number }).status === null) {
return { output: '', timedOut: true }
}
throw error
}
}
const UpdateSettingsSchema = z.object({
preferences: UserPreferencesSchema.partial(),
})
@@ -376,20 +392,20 @@ export function createSettingsRoutes(db: Database) {
})
app.post('/opencode-upgrade', async (c) => {
const oldVersion = opencodeServerManager.getVersion()
logger.info(`Current OpenCode version: ${oldVersion}`)
try {
logger.info('OpenCode upgrade requested')
const oldVersion = opencodeServerManager.getVersion()
logger.info(`Current OpenCode version: ${oldVersion}`)
logger.info('Running opencode upgrade...')
const upgradeOutput = execSync('opencode upgrade 2>&1', { encoding: 'utf8' })
logger.info('Running opencode upgrade with 90s timeout...')
const { output: upgradeOutput, timedOut } = execWithTimeout('opencode upgrade 2>&1', 90000)
logger.info(`Upgrade output: ${upgradeOutput}`)
await new Promise(r => setTimeout(r, 2000))
if (timedOut) {
logger.warn('OpenCode upgrade timed out after 90 seconds')
throw new Error('Upgrade command timed out after 90 seconds')
}
const newVersion = opencodeServerManager.getVersion() || await opencodeServerManager.fetchVersion()
logger.info(`New OpenCode version: ${newVersion}`)
const upgraded = oldVersion && newVersion && compareVersions(newVersion, oldVersion) > 0
@@ -419,16 +435,58 @@ export function createSettingsRoutes(db: Database) {
success: true,
message: 'OpenCode is already up to date',
oldVersion,
newVersion: oldVersion,
newVersion,
upgraded: false
})
}
} catch (error) {
logger.error('Failed to upgrade OpenCode:', error)
return c.json({
error: 'Failed to upgrade OpenCode',
details: error instanceof Error ? error.message : 'Unknown error'
}, 500)
logger.warn('Attempting to recover OpenCode server...')
let recovered = false
let recoveryMessage = ''
opencodeServerManager.clearStartupError()
try {
await opencodeServerManager.restart()
logger.warn('OpenCode server restarted after upgrade failure')
recovered = true
recoveryMessage = 'Server recovered'
} catch (recoveryError) {
logger.error('Failed to recover OpenCode server:', recoveryError)
recovered = false
recoveryMessage = recoveryError instanceof Error ? recoveryError.message : 'Unknown error'
}
let currentVersion: string | null | undefined = oldVersion
try {
currentVersion = opencodeServerManager.getVersion() || oldVersion
} catch (versionError) {
logger.error('Failed to get version after recovery:', versionError)
currentVersion = oldVersion
}
return c.json(
recovered ? {
success: false,
error: 'Upgrade failed but server recovered',
details: error instanceof Error ? error.message : 'Unknown error',
oldVersion,
newVersion: currentVersion,
upgraded: false,
recovered: true,
recoveryMessage
} : {
error: 'Failed to upgrade OpenCode and could not recover',
details: error instanceof Error ? error.message : 'Unknown error',
oldVersion,
newVersion: currentVersion,
upgraded: false,
recovered: false,
recoveryMessage
},
recovered ? 400 : 500
)
}
})
@@ -479,30 +537,32 @@ export function createSettingsRoutes(db: Database) {
})
app.post('/opencode-install-version', async (c) => {
const oldVersion = opencodeServerManager.getVersion()
logger.info(`Current OpenCode version: ${oldVersion}`)
try {
const body = await c.req.json()
const { version } = z.object({ version: z.string().min(1) }).parse(body)
logger.info(`Installing OpenCode version: ${version}`)
const oldVersion = opencodeServerManager.getVersion()
logger.info(`Current OpenCode version: ${oldVersion}`)
const versionArg = version.startsWith('v') ? version : `v${version}`
logger.info(`Running opencode upgrade ${versionArg}...`)
const upgradeOutput = execSync(`opencode upgrade ${versionArg} 2>&1`, { encoding: 'utf8' })
logger.info(`Running opencode upgrade ${versionArg} with 90s timeout...`)
const { output: upgradeOutput, timedOut } = execWithTimeout(`opencode upgrade ${versionArg} 2>&1`, 90000)
logger.info(`Upgrade output: ${upgradeOutput}`)
await new Promise(r => setTimeout(r, 2000))
if (timedOut) {
logger.warn('OpenCode version install timed out after 90 seconds')
throw new Error('Version install command timed out after 90 seconds')
}
const newVersion = await opencodeServerManager.fetchVersion()
logger.info(`New OpenCode version: ${newVersion}`)
opencodeServerManager.clearStartupError()
await opencodeServerManager.restart()
logger.info('OpenCode server restarted after version change')
return c.json({
success: true,
message: `OpenCode ${oldVersion ? `changed from v${oldVersion} to` : 'installed as'} v${newVersion}`,
@@ -511,10 +571,44 @@ export function createSettingsRoutes(db: Database) {
})
} catch (error) {
logger.error('Failed to install OpenCode version:', error)
return c.json({
error: 'Failed to install OpenCode version',
details: error instanceof Error ? error.message : 'Unknown error'
}, 500)
logger.warn('Attempting to recover OpenCode server...')
let recovered = false
let recoveryMessage = ''
opencodeServerManager.clearStartupError()
try {
await opencodeServerManager.restart()
logger.warn('OpenCode server restarted after install failure')
recovered = true
recoveryMessage = 'Server recovered'
} catch (recoveryError) {
logger.error('Failed to recover OpenCode server:', recoveryError)
recovered = false
recoveryMessage = recoveryError instanceof Error ? recoveryError.message : 'Unknown error'
}
const currentVersion = opencodeServerManager.getVersion() || oldVersion
return c.json(
recovered ? {
success: false,
error: 'Version install failed but server recovered',
details: error instanceof Error ? error.message : 'Unknown error',
oldVersion,
newVersion: currentVersion,
recovered: true,
recoveryMessage
} : {
error: 'Failed to install OpenCode version and could not recover',
details: error instanceof Error ? error.message : 'Unknown error',
oldVersion,
newVersion: currentVersion,
recovered: false,
recoveryMessage
},
recovered ? 400 : 500
)
}
})
+460
View File
@@ -0,0 +1,460 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { execSync } from 'child_process'
vi.mock('child_process', () => ({
execSync: vi.fn(),
}))
vi.mock('../../src/services/opencode-single-server', () => ({
opencodeServerManager: {
getVersion: vi.fn(),
fetchVersion: vi.fn(),
reloadConfig: vi.fn(),
restart: vi.fn(),
clearStartupError: vi.fn(),
},
}))
vi.mock('../../src/utils/logger', () => ({
logger: {
info: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}))
vi.mock('../../src/constants', () => ({
DEFAULT_AGENTS_MD: '# Test Agents MD',
}))
vi.mock('../../src/services/settings', () => ({
SettingsService: vi.fn().mockImplementation(() => ({
getSettings: vi.fn(),
updateSettings: vi.fn(),
})),
}))
vi.mock('../../src/services/file-operations', () => ({
writeFileContent: vi.fn(),
readFileContent: vi.fn(),
fileExists: vi.fn(),
}))
vi.mock('../../src/services/proxy', () => ({
patchOpenCodeConfig: vi.fn(),
proxyToOpenCodeWithDirectory: vi.fn(),
}))
vi.mock('@opencode-manager/shared/config/env', () => ({
getOpenCodeConfigFilePath: vi.fn(() => '/test/config.json'),
getAgentsMdPath: vi.fn(() => '/test/AGENTS.md'),
getWorkspacePath: vi.fn(() => '/test/workspace'),
getReposPath: vi.fn(() => '/test/repos'),
getDatabasePath: vi.fn(() => '/test/db.sqlite'),
ENV: {
SERVER: { PORT: 5003, HOST: '0.0.0.0' },
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173' },
WORKSPACE: { BASE_PATH: '/test/workspace' },
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
},
FILE_LIMITS: {
MAX_SIZE_BYTES: 1024 * 1024,
MAX_UPLOAD_SIZE_BYTES: 10 * 1024 * 1024,
},
}))
import { opencodeServerManager } from '../../src/services/opencode-single-server'
import { createSettingsRoutes } from '../../src/routes/settings'
const mockExecSync = execSync as ReturnType<typeof vi.fn>
const mockGetVersion = opencodeServerManager.getVersion as ReturnType<typeof vi.fn>
const mockFetchVersion = opencodeServerManager.fetchVersion as ReturnType<typeof vi.fn>
const mockReloadConfig = opencodeServerManager.reloadConfig as ReturnType<typeof vi.fn>
const mockRestart = opencodeServerManager.restart as ReturnType<typeof vi.fn>
const mockClearStartupError = opencodeServerManager.clearStartupError as ReturnType<typeof vi.fn>
describe('Settings Routes - OpenCode Upgrade', () => {
let settingsApp: ReturnType<typeof createSettingsRoutes>
let testDb: any
beforeEach(() => {
vi.clearAllMocks()
mockExecSync.mockReset()
mockGetVersion.mockReset()
mockFetchVersion.mockReset()
mockReloadConfig.mockReset()
mockRestart.mockReset()
mockClearStartupError.mockReset()
testDb = {} as any
settingsApp = createSettingsRoutes(testDb)
mockReloadConfig.mockResolvedValue(undefined)
mockRestart.mockResolvedValue(undefined)
mockClearStartupError.mockReturnValue(undefined)
})
describe('POST /opencode-upgrade', () => {
describe('successful upgrade scenarios', () => {
it('should upgrade OpenCode successfully and respond with success', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.1')
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.success).toBe(true)
expect(json.upgraded).toBe(true)
expect(json.oldVersion).toBe('1.0.0')
expect(json.newVersion).toBe('1.0.1')
})
it('should return already up to date when version unchanged', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.0')
mockExecSync.mockReturnValueOnce('Already up to date\n')
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.success).toBe(true)
expect(json.upgraded).toBe(false)
expect(json.message).toContain('already up to date')
})
it('should try reloadConfig first then restart on success', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.1')
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
mockReloadConfig.mockResolvedValueOnce(undefined)
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
await settingsApp.fetch(req)
expect(mockReloadConfig).toHaveBeenCalled()
expect(mockRestart).not.toHaveBeenCalled()
})
it('should fall back to restart if reloadConfig fails', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.1')
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
mockReloadConfig.mockRejectedValueOnce(new Error('Reload failed'))
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
await settingsApp.fetch(req)
expect(mockReloadConfig).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
})
})
describe('timeout and recovery scenarios', () => {
it('should timeout after 90 seconds and attempt server recovery', async () => {
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
})
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(mockExecSync).toHaveBeenCalledWith('opencode upgrade 2>&1', expect.objectContaining({
timeout: 90000,
killSignal: 'SIGKILL'
}))
expect(mockClearStartupError).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
expect(res.status).toBe(400)
expect(json).toMatchObject({
upgraded: false,
recovered: true,
oldVersion: '1.0.0',
newVersion: '1.0.0'
})
expect(json.error).toContain('recovered')
})
it('should attempt recovery when upgrade command throws non-timeout error', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.0')
mockExecSync.mockImplementationOnce(() => {
throw new Error('Network error')
})
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(mockClearStartupError).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
expect(res.status).toBe(400)
expect(json.recovered).toBe(true)
})
it('should return 500 when recovery fails', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.0')
mockExecSync.mockImplementationOnce(() => {
throw new Error('Upgrade failed')
})
mockRestart.mockRejectedValueOnce(new Error('Restart failed'))
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(500)
expect(json.recovered).toBe(false)
})
})
describe('version handling', () => {
it('should use fetched version when getVersion returns null', async () => {
mockGetVersion.mockReturnValueOnce(null)
.mockReturnValueOnce(null)
mockFetchVersion.mockResolvedValueOnce('1.0.1')
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(mockFetchVersion).toHaveBeenCalled()
expect(json.oldVersion).toBe(null)
expect(json.newVersion).toBe('1.0.1')
})
it('should handle both getVersion and fetchVersion returning null', async () => {
mockGetVersion.mockReturnValueOnce(null)
.mockReturnValueOnce(null)
mockFetchVersion.mockResolvedValueOnce(null)
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(json.upgraded).toBe(false)
})
})
})
describe('POST /opencode-install-version', () => {
describe('successful installation', () => {
it('should install specific version successfully', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.5')
mockExecSync.mockReturnValueOnce('Installed v1.0.5\n')
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.0.5' }),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.success).toBe(true)
expect(json.newVersion).toBe('1.0.5')
})
it('should prepend v to version if missing', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.5')
mockExecSync.mockReturnValueOnce('Installed v1.0.5\n')
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.0.5' }),
headers: { 'Content-Type': 'application/json' }
})
await settingsApp.fetch(req)
expect(mockExecSync).toHaveBeenCalledWith(
'opencode upgrade v1.0.5 2>&1',
expect.any(Object)
)
})
it('should not double prepend v to version', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.5')
mockExecSync.mockReturnValueOnce('Installed v1.0.5\n')
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: 'v1.0.5' }),
headers: { 'Content-Type': 'application/json' }
})
await settingsApp.fetch(req)
expect(mockExecSync).toHaveBeenCalledWith(
'opencode upgrade v1.0.5 2>&1',
expect.any(Object)
)
})
})
describe('timeout and recovery', () => {
it('should timeout and recover on version install', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.0')
mockExecSync.mockImplementationOnce(() => {
throw new Error('timeout')
})
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '1.0.5' }),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(mockExecSync).toHaveBeenCalledWith(
'opencode upgrade v1.0.5 2>&1',
expect.objectContaining({ timeout: 90000 })
)
expect(mockRestart).toHaveBeenCalled()
expect(res.status).toBe(400)
expect(json.recovered).toBe(true)
})
})
describe('validation', () => {
it('should reject empty version', async () => {
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({ version: '' }),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(400)
})
it('should reject missing version', async () => {
const req = new Request('http://localhost/opencode-install-version', {
method: 'POST',
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json' }
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(400)
})
})
})
describe('error scenarios - server stability', () => {
it('should not crash when upgrade command throws unexpected error', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValue('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.0')
mockExecSync.mockImplementationOnce(() => {
throw new Error('Unexpected error')
})
mockRestart.mockResolvedValue(undefined)
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(400)
await expect(res.json()).resolves.toBeDefined()
})
it('should not crash when getVersion throws error during failure recovery', async () => {
mockGetVersion.mockImplementationOnce(() => '1.0.0')
.mockImplementationOnce(() => {
throw new Error('GetVersion failed')
})
mockFetchVersion.mockResolvedValueOnce('1.0.0')
mockExecSync.mockImplementationOnce(() => {
throw new Error('Upgrade failed')
})
mockRestart.mockResolvedValue(undefined)
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(400)
await expect(res.json()).resolves.toBeDefined()
})
it('should handle fetchVersion throwing error during normal upgrade', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.1')
mockExecSync.mockReturnValueOnce('Upgrade successful\n')
mockReloadConfig.mockResolvedValue(undefined)
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
expect(res.status).toBe(200)
await expect(res.json()).resolves.toBeDefined()
})
it('should not leave server in broken state when upgrade times out', async () => {
mockGetVersion.mockReturnValueOnce('1.0.0')
.mockReturnValueOnce('1.0.0')
mockFetchVersion.mockResolvedValueOnce('1.0.0')
const timeoutError = new Error('timeout')
;(timeoutError as any).status = null
mockExecSync.mockImplementationOnce(() => {
throw timeoutError
})
mockRestart.mockResolvedValue(undefined)
const req = new Request('http://localhost/opencode-upgrade', {
method: 'POST'
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(mockClearStartupError).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
expect(json.recovered).toBe(true)
})
})
})
+356
View File
@@ -0,0 +1,356 @@
# Backend Routes Code Review
## Duplicate Code
- **Repeated error handling pattern for Zod validation** - Multiple route files
- Evidence: Identical Zod error handling pattern repeated across 10+ files:
```typescript
// In oauth.ts:47-51
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
// In providers.ts:47-50 (identical)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
```
- Files: `oauth.ts:47-51`, `providers.ts:47-50`, `sse.ts:67-70`, `sse.ts:80-83`, `settings.ts:120-123`, `settings.ts:172-177`, `settings.ts:219-222`, `tts.ts:418-420`
- Issue: Code duplication makes maintenance harder and can lead to inconsistent responses
- Suggestion: Create a reusable middleware or utility function: `handleZodError(error: ZodError) => Response`
- **Duplicate discovery cache logic in TTS and STT routes** - `backend/src/routes/tts.ts:120-151`, `backend/src/routes/stt.ts:36-67`
- Evidence: Nearly identical cache reading/writing functions
```typescript
// Both files have identical getCachedDiscovery() and cacheDiscovery() functions
async function getCachedDiscovery(cacheKey: string): Promise<string[] | null> {
// Same implementation in both files
}
```
- Issue: Same logic duplicated across both files, violates DRY principle
- Suggestion: Extract to shared utility in `backend/src/services/cache.ts` with configurable directory and TTL
- **Duplicate fetch logic for models/voices** - `backend/src/routes/tts.ts:152-240` vs `backend/src/routes/stt.ts:69-117`
- Evidence: Both implement nearly identical endpoint probing logic for OpenAI-compatible APIs
- Issue: Business logic duplicated instead of being reusable
- Suggestion: Create shared `OpenAIAPIService` class with methods to detect available endpoints
## Broken/Suspect Logic
- **Integer parsing without validation** - `backend/src/routes/repos.ts:113`, `backend/src/routes/repo-git.ts:28`
- Evidence: `parseInt(c.req.param('id'))` without checking result validity
```typescript
const id = parseInt(c.req.param('id'))
const repo = db.getRepoById(database, id)
// If 'abc' passed, id becomes NaN, silently fails
```
- Issue: NaN passed to database queries returns no results instead of 400 error, making debugging difficult
- Suggestion: Validate parsed ID: `const id = parseInt(c.req.param('id')); if (isNaN(id)) return c.json({ error: 'Invalid ID' }, 400)`
- **Incorrect error status code casting in repo creation** - `backend/src/routes/repos.ts:67`
- Evidence: Unsafe type cast without validation
```typescript
return c.json({ error: getErrorMessage(error) }, getStatusCode(error) as ContentfulStatusCode)
```
- Issue: `getStatusCode()` could return invalid status codes that Hono doesn't accept, causing runtime errors
- Suggestion: Validate status code is valid (200-599 range) before casting, default to 500
- **SSE route never completes** - `backend/src/routes/sse.ts:61`
- Evidence: Promise that never resolves
```typescript
await new Promise(() => {})
```
- Issue: While intentional for keeping connection open, this is an anti-pattern without timeout handling or cleanup verification
- Suggestion: Document specifically why this pattern is used and consider adding timeout/heartbeat verification
## Unused Code
- **Unused parameter in createAuthRoutes** - `backend/src/routes/auth.ts:8`
- Evidence: `_db` parameter prefixed with underscore to indicate it's unused
```typescript
export function createAuthRoutes(auth: AuthInstance, _db: Database) {
```
- Issue: Dead parameter suggests either incomplete implementation or refactoring artifact
- Suggestion: Remove unused parameter or implement functionality that uses it
- **Unused exported utility functions in TTS routes** - `backend/src/routes/tts.ts:303`
- Evidence: Functions exported but never used elsewhere in codebase
```typescript
export { generateCacheKey, ensureCacheDir, getCachedAudio, cacheAudio, getCacheSize, cleanupOldestFiles }
```
- Verification: Checked all backend/src imports, these functions are not imported by any other module
- Issue: Code bloat, exports suggest API surface that doesn't exist
- Suggestion: Remove unnecessary exports; keep functions internal unless explicitly needed by consumers
## Missing Error Handling
- **Missing error handling in index.ts initialization** - `backend/src/index.ts:255-257`
- Evidence: Catch block catches error but doesn't prevent server from starting
```typescript
} catch (error) {
logger.error('Failed to initialize workspace:', error)
}
// Server continues to start even if initialization failed
serve({ ... })
```
- Issue: Server starts in degraded state without proper error propagation, leading to silent failures
- Suggestion: Exit or return error status if critical initialization fails
- **Unhandled promise rejection in SSE route** - `backend/src/routes/sse.ts:61`
- Evidence: Promise that never resolves
```typescript
await new Promise(() => {})
```
- Issue: While intentional for SSE, errors in the stream handler before this point aren't caught; also memory leak risk if cleanup fails
- Suggestion: Add error boundary around SSE setup logic and ensure cleanup is called properly
- **SQLite operations not wrapped in transactions where needed** - `backend/src/routes/repos.ts:23-69`, `backend/src/routes/repos.ts:160-202`
- Evidence: Multiple database operations without transaction boundary for complex multi-step operations
- Issue: If any step fails, partial state changes remain in database, leading to data inconsistency
- Suggestion: Wrap multi-step operations in database transactions (BEGIN/COMMIT/ROLLBACK)
## Inconsistent Patterns
- **Inconsistent error response formats** - Across all route files
- Evidence: Multiple error response formats used:
```typescript
// Format 1: Simple error message (repos.ts)
return c.json({ error: 'Repo not found' }, 404)
// Format 2: Error with details (oauth.ts)
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
// Format 3: Nested error structure (tts.ts)
return c.json({ error: 'TTS API request failed', details: errorDetails }, 500)
// Format 4: Error field in response object (title.ts)
return c.json({ error: 'Failed to fetch config' }, 500)
```
- Issue: Frontend must handle multiple response formats, increasing complexity and potential for bugs
- Suggestion: Standardize on single error response format with `{ error: string, details?: any, statusCode?: number }`
- **Inconsistent route parameter extraction** - Across route files
- Evidence: Mixed parameter handling patterns:
```typescript
// Pattern 1: Direct param access (repos.ts:113)
const id = parseInt(c.req.param('id'))
// Pattern 2: Direct param access without parseInt (oauth.ts:20)
const providerId = c.req.param('id')
// Pattern 3: DecodeURIComponent (settings.ts:562)
const commandName = decodeURIComponent(c.req.param('name'))
// Pattern 4: Query param vs param (multiple files)
const userId = c.req.query('userId') || 'default'
```
- Issue: Inconsistent parameter extraction leads to bugs (e.g., URL encoding issues, type mismatches)
- Suggestion: Create helper functions for common parameter patterns: `getNumberParam(c, name)`, `getStringParam(c, name)`, `getUserId(c)`
- **Mixed async/await and .then() patterns** - `backend/src/index.ts:289-298`
- Evidence: In production route, uses top-level await pattern then .then() chained approach
```typescript
const html = await fs.readFile(indexPath, 'utf-8')
return c.html(html)
// vs elsewhere: consistent async/await usage
```
- Issue: Inconsistent patterns make code harder to read and reason about
- Suggestion: Use async/await consistently throughout codebase (per AGENTS.md guidelines)
- **Inconsistent database query patterns** - `backend/src/routes/repos.ts` vs `backend/src/routes/repo-git.ts`
- Evidence: Some routes use prepared statements directly, others use query helper functions
- Issue: Inconsistent database access patterns lead to maintenance issues and potential SQL injection risks
- Suggestion: Standardize on using query helper functions from `db/queries.ts` module
## Hardcoded Values
- **Hardcoded cache TTL values** - `backend/src/routes/tts.ts:13-14`, `backend/src/routes/stt.ts:23`
- Evidence: Magic numbers for cache expiration
```typescript
const CACHE_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours
const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour
```
- Issue: Cache durations hardcoded instead of configurable, making tuning difficult per deployment
- Suggestion: Move to environment variables or config file with sensible defaults
- **Hardcoded cache size limits** - `backend/src/routes/tts.ts:15-16`
- Evidence: Cache size limit as magic number
```typescript
const MAX_CACHE_SIZE_MB = 200
const MAX_CACHE_SIZE_BYTES = MAX_CACHE_SIZE_MB * 1024 * 1024
```
- Issue: Cache size not configurable per deployment requirements
- Suggestion: Make configurable via environment variable or settings
- **Hardcoded port references** - `backend/src/routes/oauth.ts:13`, `backend/src/routes/title.ts:11`
- Evidence: OpenCode server port hardcoded in multiple places
```typescript
// oauth.ts:13
const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
// title.ts:11
const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}`
```
- Issue: Inconsistent port construction (one uses ENV.OPENCODE.HOST, other uses 127.0.0.1)
- Suggestion: Create shared utility function `getOpenCodeServerUrl()` to ensure consistency
- **Hardcoded content length limits** - `backend/src/routes/tts.ts:19`, `backend/src/routes/title.ts:7`
- Evidence: Arbitrary limits as magic numbers in schemas
```typescript
// tts.ts:19
z.string().min(1).max(4096)
// title.ts:7
z.string().min(1).max(5000)
```
- Issue: Limits not documented or configurable, may not suit all use cases
- Suggestion: Move to constants module with documentation of rationale
## Security Issues
- **Missing input validation on multiple endpoints** - `backend/src/routes/repos.ts:23-69`, `backend/src/routes/repo-git.ts:166-190`, `backend/src/routes/repo-git.ts:214-238`
- Evidence: Routes accept JSON payloads without Zod schema validation
```typescript
app.post('/', async (c) => {
try {
const body = await c.req.json()
const { repoUrl, localPath, branch, openCodeConfigName, useWorktree, provider } = body
// No validation on body structure or types
```
- Issue: Missing input validation allows malformed requests to reach business logic, potentially causing runtime errors or data corruption
- Suggestion: Add Zod schemas for all request bodies, similar to how `settings.ts` and `tts.ts` handle validation
- **Path injection vulnerability in routes with user-provided paths** - `backend/src/routes/files.ts:102-117`, `backend/src/routes/files.ts:119-130`
- Evidence: User paths extracted from URL without sanitization
```typescript
const path = c.req.path.replace(/^\/api\/files\//, '') || ''
const body = await c.req.parseBody()
const file = body.file as File
const relativePath = body.relativePath as string | undefined
const result = await fileService.uploadFile(path, file, relativePath)
```
- Issue: Malicious paths like `../../etc/passwd` could access files outside workspace
- Suggestion: Validate paths resolve within workspace directory using path.isAbsolute() and path.normalize() checks
- **No rate limiting on sensitive operations** - `backend/src/routes/providers.ts:33-53`, `backend/src/routes/oauth.ts:18-53`
- Evidence: API credential operations and OAuth flows have no rate limiting middleware
- Issue: Brute force attacks on credential endpoints could exhaust API quotas or enable credential stuffing
- Suggestion: Implement rate limiting middleware on credential and OAuth endpoints
## API Design Issues
- **Inconsistent HTTP status code usage** - Across multiple routes
- Evidence: Mixed status codes for similar situations:
```typescript
// Missing resources: 404 (repos.ts:117)
return c.json({ error: 'Repo not found' }, 404)
// Missing resources: 400 (providers.ts:73)
return c.json({ success: false, error: 'Client not found' }, 404)
// Missing configs: 404 (settings.ts:277)
return c.json({ error: 'No default config found' }, 404)
// Same as above: but 400 elsewhere
```
- Issue: Inconsistent status codes make API harder to use correctly
- Suggestion: Follow REST principles strictly: 200/201 for success, 400 for bad request, 404 for not found, 409 for conflicts, 500 for server errors
- **Missing Content-Type headers on some endpoints** - `backend/src/routes/sse.ts:18-21`
- Evidence: SSE sets headers but many other endpoints don't explicitly set Content-Type
```typescript
// SSE properly sets headers
c.header('Content-Type', 'text/event-stream')
c.header('Cache-Control', 'no-cache, no-store, no-transform')
// Many other endpoints rely on Hono default behavior
return c.json(data) // May not be explicit
```
- Issue: Implicit Content-Type can lead to browser/client interpretation bugs
- Suggestion: Always explicitly set Content-Type and Cache-Control headers
- **Inconsistent pagination patterns** - `backend/src/routes/repo-git.ts:275`, `backend/src/routes/settings.ts:459`
- Evidence: Pagination implemented inconsistently across endpoints
```typescript
// repo-git.ts:275 - uses limit query param
const limit = parseInt(c.req.query('limit') || '10', 10)
const commits = await gitLogService.getLog(id, database, limit)
// settings.ts:459 - no pagination for potentially large lists
const versions = releases.filter(r => !r.prerelease).map(...)
```
- Issue: Some endpoints support pagination, others don't, leading to performance issues with large datasets
- Suggestion: Implement consistent pagination pattern with limit/offset query params and total count metadata
- **Query parameter type validation missing** - Multiple route files
- Evidence: Query parameters used without validation
```typescript
// repo-git.ts:85-87
const filePath = c.req.query('path')
if (!filePath) {
return c.json({ error: 'path query parameter is required' }, 400)
}
// No validation on(filePath) or path sanitization
// sse.ts:14-15
const directoriesParam = c.req.query('directories')
const directories = directoriesParam ? directoriesParam.split(',').filter(Boolean) : []
// No validation that directories are valid paths
```
- Issue: Malformed query parameters can cause runtime errors or unexpected behavior
- Suggestion: Validate all query parameters with schemas, similar to request body validation
## Summary
**Files Reviewed**: 13 files (1 index.ts + 12 route modules)
**Issues Found**: 24 total
- Security Issues: 3
- Missing Error Handling: 3
- Duplicate Code: 3
- Broken/Suspect Logic: 3
- Inconsistent Patterns: 4
- Hardcoded Values: 4
- API Design Issues: 4
- Unused Code: 2
**Critical Issues (Immediate Action Required)**:
1. **Missing input validation on multiple endpoints** - potential runtime errors, data corruption, and security risks
2. **Path injection vulnerability in file routes** - could allow unauthorized file access (../../ traversal)
3. **Missing error handling in index.ts initialization** - server starts in degraded state without alerting
4. **Integer parsing without validation** - NaN values passed to DB queries instead of proper 400 errors
**High Priority Issues**:
1. Duplicate code patterns (Zod error handling, cache logic, API discovery) - maintenance burden and inconsistency
2. Inconsistent error response formats - makes frontend integration error-prone
3. Hardcoded values (cache TTLs, sizes, ports) - reduces flexibility and deployment tuning
4. Inconsistent HTTP status codes - violates REST principles and confuses API consumers
5. Type assertions without runtime validation - potential runtime errors from mismatched shapes
**Overall Assessment**:
The backend routes layer demonstrates good structure with proper separation of concerns. Route files are well-organized with clear responsibilities. However, there are significant inconsistencies in validation, error handling, and API design patterns that could lead to bugs, security vulnerabilities, and maintenance issues.
**Strengths**:
- Good separation of routes into logical modules
- Proper use of Zod for input validation where implemented
- Comprehensive error logging throughout
- Clean route organization with nested route groups
- Authentication middleware properly applied to protected routes
**Areas for Improvement**:
- Implement comprehensive input validation on ALL endpoints (not just some)
- Create reusable middleware for common patterns (error handling, parameter extraction)
- Standardize error response formats and HTTP status codes across all routes
- Move hardcoded values to configuration for flexibility
- Extract duplicate code into shared utilities
- Add rate limiting and path validation for security
- Replace unsafe type assertions with runtime validation
- Add transaction boundaries for multi-step database operations
**Recommended Actions (Priority Order)**:
1. **Create shared validation middleware** - for Zod error handling, parameter extraction, and request validation
2. **Audit and fix security issues** - add path injection protection and rate limiting
3. **Standardize API patterns** - error responses, HTTP status codes, pagination
4. **Refactor duplicate code** - extract cache logic, error handlers, and API discovery to shared utilities
5. **Improve type safety** - replace type assertions with Zod validation
6. **Move configuration** - cache settings, limits, and URLs to environment variables
+11 -1
View File
@@ -139,12 +139,22 @@ export const settingsApi = {
message: string
oldVersion?: string
newVersion?: string
recovered?: boolean
recoveryMessage?: string
}> => {
const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-install-version`, { version })
return data
},
upgradeOpenCode: async (): Promise<{ success: boolean; message: string; oldVersion?: string; newVersion?: string; upgraded: boolean }> => {
upgradeOpenCode: async (): Promise<{
success: boolean
message: string
oldVersion?: string
newVersion?: string
upgraded: boolean
recovered?: boolean
recoveryMessage?: string
}> => {
const { data } = await axios.post(`${API_BASE_URL}/api/settings/opencode-upgrade`)
return data
},
@@ -8,6 +8,7 @@ import { AddMcpServerDialog } from './AddMcpServerDialog'
import { McpServerCard } from './McpServerCard'
import { useMcpServers } from '@/hooks/useMcpServers'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
interface McpServerConfig {
type: 'local' | 'remote'
@@ -61,8 +62,7 @@ export function McpManager({ config, onUpdate, onConfigUpdate }: McpManagerProps
await onUpdate(updatedConfig)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
invalidateConfigCaches(queryClient)
setDeleteConfirmServer(null)
},
})
@@ -18,6 +18,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useServerHealth } from '@/hooks/useServerHealth'
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
import { showToast } from '@/lib/toast'
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
import type { OpenCodeConfig } from '@/api/types/settings'
interface Command {
@@ -86,7 +87,7 @@ export function OpenCodeConfigManager() {
return await settingsApi.reloadOpenCodeConfig()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
},
})
@@ -95,7 +96,7 @@ export function OpenCodeConfigManager() {
return await settingsApi.restartOpenCodeServer()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
},
})
@@ -104,16 +105,30 @@ export function OpenCodeConfigManager() {
return await settingsApi.upgradeOpenCode()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['health'] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
if (data.upgraded) {
showToast.success(`Upgraded to v${data.newVersion} and server restarted`, { id: 'upgrade-opencode' })
} else {
showToast.success('OpenCode is already up to date', { id: 'upgrade-opencode' })
}
},
onError: () => {
showToast.error('Failed to upgrade OpenCode', { id: 'upgrade-opencode' })
onError: (error) => {
invalidateConfigCaches(queryClient)
const defaultMessage = 'Failed to upgrade OpenCode'
if (error && typeof error === 'object' && 'response' in error) {
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
const data = response?.data
if (data?.recovered) {
showToast.success(`Upgrade failed but server recovered at v${data.newVersion}`, { id: 'upgrade-opencode' })
} else {
showToast.error(data?.recoveryMessage || defaultMessage, { id: 'upgrade-opencode' })
}
} else {
showToast.error(defaultMessage, { id: 'upgrade-opencode' })
}
},
})
@@ -170,9 +185,8 @@ export function OpenCodeConfigManager() {
}
} else {
showToast.success('Configuration updated')
invalidateConfigCaches(queryClient)
}
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
console.error('Failed to update config:', error)
showToast.error(getApiErrorMessage(error, 'Failed to update config'), { id: 'update-restart' })
@@ -226,7 +240,7 @@ export function OpenCodeConfigManager() {
showToast.success('Configuration created', { id: 'create-config' })
}
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
} catch (error) {
console.error('Failed to create config:', error)
showToast.error(getApiErrorMessage(error, 'Failed to create configuration'), { id: 'create-config' })
@@ -243,9 +257,11 @@ export function OpenCodeConfigManager() {
setIsUpdating(true)
await settingsApi.deleteOpenCodeConfig(config.name)
setDeleteConfirmConfig(null)
if (selectedConfig?.id === config.id) {
setSelectedConfig(null)
}
fetchConfigs()
// Invalidate agents cache in case deleted config had agents
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
} catch (error) {
console.error('Failed to delete config:', error)
} finally {
@@ -485,7 +501,7 @@ export function OpenCodeConfigManager() {
? 'Configuration saved and server reloaded'
: 'Configuration saved'
showToast.success(successMsg, { id: 'edit-config' })
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
} catch (error) {
showToast.error(getApiErrorMessage(error, 'Failed to save configuration'), { id: 'edit-config' })
throw error
@@ -570,7 +586,7 @@ export function OpenCodeConfigManager() {
<div className="flex items-center gap-3 min-w-0">
<h4 className="text-sm font-medium truncate">Commands</h4>
<span className="text-xs text-muted-foreground">
{Object.keys(selectedConfig.content.command as Record<string, Command> || {}).length} configured
{Object.keys((selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}).length} configured
</span>
</div>
<Edit className={`h-4 w-4 transition-transform ${expandedSections.commands ? 'rotate-90' : ''}`} />
@@ -578,7 +594,7 @@ export function OpenCodeConfigManager() {
<div className={`${expandedSections.commands ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-1 sm:p-4 max-h-[50vh] overflow-y-auto">
<CommandsEditor
commands={(selectedConfig.content.command as Record<string, Command>) || {}}
commands={(selectedConfig.content?.command as Record<string, Command> | undefined) ?? {}}
onChange={(commands) => {
const updatedContent = {
...selectedConfig.content,
@@ -607,7 +623,7 @@ export function OpenCodeConfigManager() {
<div className="flex items-center gap-3 min-w-0">
<h4 className="text-sm font-medium truncate">Agents</h4>
<span className="text-xs text-muted-foreground">
{Object.keys(selectedConfig.content.agent as Record<string, Agent> || {}).length} configured
{Object.keys((selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}).length} configured
</span>
</div>
<Edit className={`h-4 w-4 transition-transform ${expandedSections.agents ? 'rotate-90' : ''}`} />
@@ -615,7 +631,7 @@ export function OpenCodeConfigManager() {
<div className={`${expandedSections.agents ? 'block' : 'hidden'} border-t border-border`}>
<div className="p-4 max-h-[50vh] overflow-y-auto">
<AgentsEditor
agents={(selectedConfig.content.agent as Record<string, Agent>) || {}}
agents={(selectedConfig.content?.agent as Record<string, Agent> | undefined) ?? {}}
onChange={(agents) => {
const updatedContent = {
...selectedConfig.content,
@@ -644,7 +660,7 @@ export function OpenCodeConfigManager() {
<div className="flex items-center gap-3 min-w-0">
<h4 className="text-sm font-medium truncate">MCP Servers</h4>
<span className="text-xs text-muted-foreground">
{Object.keys((selectedConfig.content.mcp as Record<string, unknown>) || {}).length} configured
{Object.keys((selectedConfig.content?.mcp as Record<string, unknown> | undefined) ?? {}).length} configured
</span>
</div>
<Edit className={`h-4 w-4 transition-transform ${expandedSections.mcp ? 'rotate-90' : ''}`} />
@@ -30,8 +30,22 @@ export function VersionSelectDialog({ open, onOpenChange }: VersionSelectDialogP
showToast.success(result.message)
onOpenChange(false)
},
onError: () => {
showToast.error('Failed to install version')
onError: (error) => {
queryClient.invalidateQueries({ queryKey: ['opencode-versions'] })
queryClient.invalidateQueries({ queryKey: ['server-health'] })
if (error && typeof error === 'object' && 'response' in error) {
const response = (error as { response?: { data?: { recovered?: boolean; recoveryMessage?: string; newVersion?: string } } }).response
const data = response?.data
if (data?.recovered) {
showToast.success(`Install failed but server recovered at v${data.newVersion}`)
} else {
showToast.error(data?.recoveryMessage || 'Failed to install version')
}
} else {
showToast.error('Failed to install version')
}
},
})
+1 -5
View File
@@ -1,7 +1,6 @@
import { useMemo } from 'react'
import { useMessages } from './useOpenCode'
import { useQuery } from '@tanstack/react-query'
import { useSessionAgent } from './useSessionAgent'
import { useModelSelection } from './useModelSelection'
interface ContextUsage {
@@ -43,11 +42,8 @@ async function fetchProviders(opcodeUrl: string): Promise<ProvidersResponse> {
export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string): ContextUsage => {
const { data: messages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionID, directory)
const sessionAgent = useSessionAgent(opcodeUrl, sessionID, directory)
const { modelString: globalModelString } = useModelSelection(opcodeUrl, directory)
const modelString = sessionAgent.model
? `${sessionAgent.model.providerID}/${sessionAgent.model.modelID}`
: globalModelString
const modelString = globalModelString
const { data: providersData } = useQuery({
queryKey: ['providers', opcodeUrl],
+4 -8
View File
@@ -1,8 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { settingsApi } from '@/api/settings'
import { useMutation } from '@tanstack/react-query'
import { useQueryClient } from '@tanstack/react-query'
import { invalidateConfigCaches, invalidateSettingsCaches } from '@/lib/queryInvalidation'
interface HealthResponse {
status: 'healthy' | 'degraded' | 'unhealthy'
@@ -34,8 +33,7 @@ export function useServerHealth(enabled = true) {
return await settingsApi.reloadOpenCodeConfig()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['health'] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateConfigCaches(queryClient)
toast.success('Server configuration reloaded successfully')
},
onError: (error: unknown) => {
@@ -53,9 +51,7 @@ export function useServerHealth(enabled = true) {
return await settingsApi.rollbackOpenCodeConfig()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['health'] })
queryClient.invalidateQueries({ queryKey: ['settings'] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
invalidateSettingsCaches(queryClient)
toast.success(data.message)
},
onError: () => {
+2 -1
View File
@@ -1,6 +1,7 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { settingsApi } from '@/api/settings'
import type { UserPreferences } from '@/api/types/settings'
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
export function useSettings(userId = 'default') {
const queryClient = useQueryClient()
@@ -43,8 +44,8 @@ export function useSettings(userId = 'default') {
}
},
onSettled: () => {
// Refetch to ensure server state
queryClient.invalidateQueries({ queryKey: ['settings', userId] })
invalidateConfigCaches(queryClient)
},
})
+30
View File
@@ -0,0 +1,30 @@
import type { QueryClient } from '@tanstack/react-query'
export function invalidateConfigCaches(queryClient: QueryClient) {
queryClient.invalidateQueries({ queryKey: ['opencode', 'config'] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
queryClient.invalidateQueries({ queryKey: ['health'] })
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
queryClient.invalidateQueries({ queryKey: ['providers'] })
}
export function invalidateSettingsCaches(queryClient: QueryClient, userId = 'default') {
queryClient.invalidateQueries({ queryKey: ['settings', userId] })
invalidateConfigCaches(queryClient)
}
export function invalidateSessionCaches(queryClient: QueryClient) {
queryClient.invalidateQueries({
predicate: (query) =>
query.queryKey[0] === 'opencode' &&
(query.queryKey[1] === 'sessions' ||
query.queryKey[1] === 'session' ||
query.queryKey[1] === 'messages'),
})
}
export function invalidateAllConfigRelatedCaches(queryClient: QueryClient, userId = 'default') {
invalidateSettingsCaches(queryClient, userId)
invalidateSessionCaches(queryClient)
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opencode-manager",
"version": "0.8.2",
"version": "0.8.21",
"private": false,
"type": "module",
"packageManager": "pnpm@10.28.1",