mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
refactor: remove proxy service and add opencode client implementation
This commit is contained in:
1 parent
5abaaa5cc0
commit
568d44832c
24 files changed
+1478
-1030
No files matched your search
+13
-12
@@ -39,7 +39,7 @@ import { sseAggregator } from './services/sse-aggregator'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { NotificationService } from './services/notification'
|
||||
import { ScheduleRunner, ScheduleService } from './services/schedules'
|
||||
import { migrateGlobalSkills } from './services/skills'
|
||||
@@ -85,6 +85,7 @@ app.use('/*', cors({
|
||||
const db = initializeDatabase(DB_PATH)
|
||||
const auth = createAuth(db)
|
||||
const requireAuth = createAuthMiddleware(auth)
|
||||
const openCodeClient = createOpenCodeClient()
|
||||
|
||||
import { DEFAULT_AGENTS_MD } from './constants'
|
||||
|
||||
@@ -263,6 +264,7 @@ try {
|
||||
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
|
||||
|
||||
opencodeServerManager.setDatabase(db)
|
||||
opencodeServerManager.setOpenCodeClient(openCodeClient)
|
||||
const openCodeStatus = await openCodeSupervisor.start()
|
||||
if (openCodeStatus.healthy) {
|
||||
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
|
||||
@@ -275,7 +277,7 @@ try {
|
||||
logger.error('Failed to initialize workspace:', error)
|
||||
}
|
||||
|
||||
const scheduleService = new ScheduleService(db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient)
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db)
|
||||
@@ -305,22 +307,22 @@ app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
|
||||
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
|
||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
|
||||
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeSupervisor))
|
||||
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeSupervisor))
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/files', createFileRoutes())
|
||||
protectedApi.route('/providers', createProvidersRoutes(db, openCodeSupervisor))
|
||||
protectedApi.route('/oauth', createOAuthRoutes(openCodeSupervisor))
|
||||
protectedApi.route('/providers', createProvidersRoutes(db, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/oauth', createOAuthRoutes(openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/tts', createTTSRoutes(db))
|
||||
protectedApi.route('/stt', createSTTRoutes(db))
|
||||
protectedApi.route('/sse', createSSERoutes())
|
||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/memory', createMemoryRoutes(db))
|
||||
protectedApi.route('/memory', createMemoryRoutes(db, openCodeClient))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
|
||||
@@ -329,18 +331,17 @@ app.route('/api', protectedApi)
|
||||
app.post('/api/opencode/mcp/:name/auth', requireAuth, async (c) => {
|
||||
const serverName = c.req.param('name')
|
||||
const directory = c.req.query('directory')
|
||||
return proxyMcpAuthStart(serverName, directory)
|
||||
return openCodeClient.startMcpAuth(serverName, directory)
|
||||
})
|
||||
|
||||
app.post('/api/opencode/mcp/:name/auth/authenticate', requireAuth, async (c) => {
|
||||
const serverName = c.req.param('name')
|
||||
const directory = c.req.query('directory')
|
||||
return proxyMcpAuthAuthenticate(serverName, directory)
|
||||
return openCodeClient.authenticateMcp(serverName, directory)
|
||||
})
|
||||
|
||||
app.all('/api/opencode/*', requireAuth, async (c) => {
|
||||
const request = c.req.raw
|
||||
return proxyRequest(request)
|
||||
return openCodeClient.forwardRaw(c.req.raw)
|
||||
})
|
||||
|
||||
const isProduction = ENV.SERVER.NODE_ENV === 'production'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { z } from 'zod'
|
||||
import crypto from 'crypto'
|
||||
import path from 'path'
|
||||
@@ -6,7 +7,6 @@ import { readFile, writeFile, mkdir } from 'fs/promises'
|
||||
import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy'
|
||||
|
||||
const StartSchema = z.object({
|
||||
serverName: z.string(),
|
||||
@@ -132,8 +132,10 @@ async function registerClient(
|
||||
return result
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function createMcpOauthProxyRoutes(requireAuth?: any) {
|
||||
|
||||
import type { MiddlewareHandler } from 'hono'
|
||||
|
||||
export function createMcpOauthProxyRoutes(openCodeClient: OpenCodeClient, requireAuth?: MiddlewareHandler) {
|
||||
const app = new Hono()
|
||||
|
||||
if (requireAuth) {
|
||||
@@ -292,21 +294,15 @@ export function createMcpOauthProxyRoutes(requireAuth?: any) {
|
||||
markMcpOAuthFlowCompleted(state, flow.serverName)
|
||||
|
||||
try {
|
||||
let reconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect`
|
||||
if (flow.directory) {
|
||||
const url = new URL(reconnectUrl)
|
||||
url.searchParams.set('directory', flow.directory)
|
||||
reconnectUrl = url.toString()
|
||||
}
|
||||
await fetch(reconnectUrl, {
|
||||
await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
headers: withOpenCodeAuth(),
|
||||
path: `/mcp/${encodeURIComponent(flow.serverName)}/connect`,
|
||||
directory: flow.directory,
|
||||
})
|
||||
if (flow.directory) {
|
||||
const globalReconnectUrl = `${OPENCODE_SERVER_URL}/mcp/${encodeURIComponent(flow.serverName)}/connect`
|
||||
await fetch(globalReconnectUrl, {
|
||||
await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
headers: withOpenCodeAuth(),
|
||||
path: `/mcp/${encodeURIComponent(flow.serverName)}/connect`,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { resolveProjectId } from '../services/project-id-resolver'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { getWorkspacePath, getConfigPath } from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { OPENCODE_SERVER_URL, withOpenCodeAuth } from '../services/proxy'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import {
|
||||
CreateMemoryRequestSchema,
|
||||
UpdateMemoryRequestSchema,
|
||||
@@ -134,7 +134,7 @@ function savePluginConfigToDisk(config: PluginConfig): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function createMemoryRoutes(db: Database): Hono {
|
||||
export function createMemoryRoutes(db: Database, openCodeClient: OpenCodeClient): Hono {
|
||||
const app = new Hono()
|
||||
const pluginMemory = new PluginMemoryService()
|
||||
|
||||
@@ -638,9 +638,11 @@ export function createMemoryRoutes(db: Database): Hono {
|
||||
pluginMemory.setKv(projectId, `loop:${worktreeNameToUse}`, updatedState)
|
||||
|
||||
try {
|
||||
const abortUrl = new URL(`${OPENCODE_SERVER_URL}/session/${state.sessionId}/abort`)
|
||||
abortUrl.searchParams.set('directory', repo.fullPath)
|
||||
await fetch(abortUrl.toString(), { method: 'POST', headers: withOpenCodeAuth() })
|
||||
await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${state.sessionId}/abort`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
} catch {
|
||||
// Session may already be idle
|
||||
}
|
||||
|
||||
+18
-31
@@ -1,6 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { z } from 'zod'
|
||||
import { proxyRequest, OPENCODE_SERVER_URL } from '../services/proxy'
|
||||
import { logger } from '../utils/logger'
|
||||
import {
|
||||
OAuthAuthorizeRequestSchema,
|
||||
@@ -19,7 +19,7 @@ async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Pr
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
export function createOAuthRoutes(openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
|
||||
app.post('/:id/oauth/authorize', async (c) => {
|
||||
@@ -28,17 +28,12 @@ export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const body = await c.req.json()
|
||||
const validated = OAuthAuthorizeRequestSchema.parse(body)
|
||||
|
||||
// Proxy to OpenCode server - only method and inputs are supported
|
||||
const response = await proxyRequest(
|
||||
new Request(
|
||||
`${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/authorize`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(validated)
|
||||
}
|
||||
)
|
||||
)
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/provider/${encodeURIComponent(providerId)}/oauth/authorize`,
|
||||
body: JSON.stringify(validated),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text()
|
||||
@@ -65,17 +60,12 @@ export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const body = await c.req.json()
|
||||
const validated = OAuthCallbackRequestSchema.parse(body)
|
||||
|
||||
// Proxy to OpenCode server
|
||||
const response = await proxyRequest(
|
||||
new Request(
|
||||
`${OPENCODE_SERVER_URL}/provider/${providerId}/oauth/callback`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(validated)
|
||||
}
|
||||
)
|
||||
)
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/provider/${encodeURIComponent(providerId)}/oauth/callback`,
|
||||
body: JSON.stringify(validated),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text()
|
||||
@@ -103,13 +93,10 @@ export function createOAuthRoutes(openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
|
||||
app.get('/auth-methods', async (c) => {
|
||||
try {
|
||||
// Proxy to OpenCode server
|
||||
const response = await proxyRequest(
|
||||
new Request(`${OPENCODE_SERVER_URL}/provider/auth`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
)
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/provider/auth',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text()
|
||||
|
||||
@@ -7,10 +7,11 @@ import { createProvidersRoutes } from './providers'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/providers', createProvidersRoutes(db, undefined))
|
||||
app.route('/providers', createProvidersRoutes(db, createStubOpenCodeClient()))
|
||||
return app
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from 'path'
|
||||
import { AuthService } from '../services/auth'
|
||||
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
|
||||
import { logger } from '../utils/logger'
|
||||
import { setOpenCodeAuth, deleteOpenCodeAuth } from '../services/proxy'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
@@ -61,7 +61,7 @@ async function reloadOpenCodeConfig(openCodeSupervisor?: OpenCodeSupervisor): Pr
|
||||
await opencodeServerManager.reloadConfig()
|
||||
}
|
||||
|
||||
export function createProvidersRoutes(db: Database, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
const authService = new AuthService()
|
||||
|
||||
@@ -129,7 +129,7 @@ export function createProvidersRoutes(db: Database, openCodeSupervisor?: OpenCod
|
||||
const body = await c.req.json()
|
||||
const validated = SetCredentialRequestSchema.parse(body)
|
||||
|
||||
const openCodeSuccess = await setOpenCodeAuth(providerId, validated.apiKey)
|
||||
const openCodeSuccess = await openCodeClient.setProviderAuth(providerId, validated.apiKey)
|
||||
if (!openCodeSuccess) {
|
||||
logger.warn(`Failed to set OpenCode auth for ${providerId}, saving locally only`)
|
||||
}
|
||||
@@ -156,7 +156,7 @@ export function createProvidersRoutes(db: Database, openCodeSupervisor?: OpenCod
|
||||
try {
|
||||
const providerId = c.req.param('id')
|
||||
|
||||
const openCodeSuccess = await deleteOpenCodeAuth(providerId)
|
||||
const openCodeSuccess = await openCodeClient.deleteProviderAuth(providerId)
|
||||
if (!openCodeSuccess) {
|
||||
logger.warn(`Failed to delete OpenCode auth for ${providerId}, removing locally only`)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { proxyToOpenCodeWithDirectory } from '../services/proxy'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
||||
@@ -34,6 +34,7 @@ export function createRepoRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
scheduleService: ScheduleService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
openCodeSupervisor?: OpenCodeSupervisor,
|
||||
) {
|
||||
const app = new Hono()
|
||||
@@ -373,11 +374,11 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
'/instance/dispose',
|
||||
'POST',
|
||||
repo.fullPath
|
||||
)
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: '/instance/dispose',
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
|
||||
@@ -6,7 +6,8 @@ import { resolve, dirname } from 'path'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
|
||||
import { patchOpenCodeConfig, proxyToOpenCodeWithDirectory } from '../services/proxy'
|
||||
import { patchConfigWithRecovery } from '../services/opencode/config-recovery'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
@@ -219,7 +220,7 @@ async function extractOpenCodeError(response: Response, defaultError: string): P
|
||||
: defaultError
|
||||
}
|
||||
|
||||
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
const settingsService = new SettingsService(db)
|
||||
|
||||
@@ -371,7 +372,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const patchResult = await patchOpenCodeConfig(provisionalConfig.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, provisionalConfig.content)
|
||||
if (!patchResult.success) {
|
||||
settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId)
|
||||
return c.json({
|
||||
@@ -448,7 +449,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
opencodeServerManager.clearStartupError()
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
} else {
|
||||
const patchResult = await patchOpenCodeConfig(config.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config saved but failed to apply',
|
||||
@@ -459,7 +460,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
}
|
||||
|
||||
const contentToWrite = patchResult.removedFields && patchResult.removedFields.length > 0
|
||||
? JSON.stringify(config.content, null, 2)
|
||||
? JSON.stringify(patchResult.appliedConfig ?? config.content, null, 2)
|
||||
: config.rawContent
|
||||
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
@@ -526,7 +527,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const patchResult = await patchOpenCodeConfig(existingConfig.content)
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, existingConfig.content)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config validation failed',
|
||||
@@ -1406,11 +1407,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/connect`,
|
||||
'POST',
|
||||
directory
|
||||
)
|
||||
const response = await (openCodeClient).forward({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/connect`,
|
||||
directory,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to connect MCP server')
|
||||
@@ -1433,11 +1434,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/disconnect`,
|
||||
'POST',
|
||||
directory
|
||||
)
|
||||
const response = await (openCodeClient).forward({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/disconnect`,
|
||||
directory,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to disconnect MCP server')
|
||||
@@ -1460,11 +1461,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const body = await c.req.json()
|
||||
const { directory } = McpAuthDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
'POST',
|
||||
const response = await (openCodeClient).forward({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
directory,
|
||||
)
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to authenticate MCP server')
|
||||
@@ -1487,11 +1488,11 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
'DELETE',
|
||||
directory
|
||||
)
|
||||
const response = await (openCodeClient).forward({
|
||||
method: 'DELETE',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
directory,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to remove MCP auth')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { proxyToOpenCodeWithDirectory } from './proxy'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
interface OpenCodeConfigResponse {
|
||||
model?: string
|
||||
@@ -63,29 +63,16 @@ function uniqueCandidates(candidates: Array<string | null | undefined>): string[
|
||||
return [...new Set(normalizedCandidates)]
|
||||
}
|
||||
|
||||
async function fetchOpenCodeConfig(directory?: string): Promise<OpenCodeConfigResponse> {
|
||||
const response = await proxyToOpenCodeWithDirectory('/config', 'GET', directory)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(errorText || 'Failed to fetch OpenCode config')
|
||||
}
|
||||
|
||||
return await response.json() as OpenCodeConfigResponse
|
||||
async function fetchOpenCodeConfig(client: OpenCodeClient, directory?: string): Promise<OpenCodeConfigResponse> {
|
||||
return client.getJson<OpenCodeConfigResponse>('/config', { directory })
|
||||
}
|
||||
|
||||
async function fetchOpenCodeProviders(directory?: string): Promise<OpenCodeProviderResponse> {
|
||||
const response = await proxyToOpenCodeWithDirectory('/config/providers', 'GET', directory)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(errorText || 'Failed to fetch OpenCode providers')
|
||||
}
|
||||
|
||||
return await response.json() as OpenCodeProviderResponse
|
||||
async function fetchOpenCodeProviders(client: OpenCodeClient, directory?: string): Promise<OpenCodeProviderResponse> {
|
||||
return client.getJson<OpenCodeProviderResponse>('/config/providers', { directory })
|
||||
}
|
||||
|
||||
export async function resolveOpenCodeModel(
|
||||
client: OpenCodeClient,
|
||||
directory: string | undefined,
|
||||
options?: {
|
||||
preferredModel?: string | null
|
||||
@@ -93,8 +80,8 @@ export async function resolveOpenCodeModel(
|
||||
},
|
||||
): Promise<ResolvedOpenCodeModel> {
|
||||
const [config, providersResponse] = await Promise.all([
|
||||
fetchOpenCodeConfig(directory),
|
||||
fetchOpenCodeProviders(directory),
|
||||
fetchOpenCodeConfig(client, directory),
|
||||
fetchOpenCodeProviders(client, directory),
|
||||
])
|
||||
|
||||
const availableModels = buildAvailableModels(providersResponse)
|
||||
|
||||
@@ -20,18 +20,18 @@ import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-mana
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import { patchOpenCodeConfig } from './proxy'
|
||||
import { patchConfigWithRecovery } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { writeFileContent } from './file-operations'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
||||
const OPENCODE_SERVER_PUBLIC_URL = ENV.OPENCODE.PUBLIC_URL
|
||||
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
|
||||
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
|
||||
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
|
||||
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
|
||||
: ''
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
const MAX_STDERR_SIZE = 10240
|
||||
const HEALTH_CHECK_TIMEOUT_MS = 3000
|
||||
|
||||
type StartupValidationIssue = {
|
||||
path: string
|
||||
@@ -101,6 +101,7 @@ class OpenCodeServerManager {
|
||||
private version: string | null = null
|
||||
private lastStartupError: string | null = null
|
||||
private opInProgress: boolean = false
|
||||
private openCodeClient: OpenCodeClient | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
@@ -108,6 +109,17 @@ class OpenCodeServerManager {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
setOpenCodeClient(client: OpenCodeClient) {
|
||||
this.openCodeClient = client
|
||||
}
|
||||
|
||||
private requireClient(): OpenCodeClient {
|
||||
if (!this.openCodeClient) {
|
||||
throw new Error('OpenCodeClient not configured on OpenCodeServerManager. Call setOpenCodeClient() during startup.')
|
||||
}
|
||||
return this.openCodeClient
|
||||
}
|
||||
|
||||
static getInstance(): OpenCodeServerManager {
|
||||
if (!OpenCodeServerManager.instance) {
|
||||
OpenCodeServerManager.instance = new OpenCodeServerManager()
|
||||
@@ -480,10 +492,10 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const fileContent = await fs.readFile(configPath, 'utf-8')
|
||||
const fileConfig = JSON.parse(fileContent) as Record<string, unknown>
|
||||
const fileConfig = parseJsonc(fileContent) as Record<string, unknown>
|
||||
logger.info(`Read config from file for reload: ${configPath}`)
|
||||
|
||||
const patchResult = await patchOpenCodeConfig(fileConfig)
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), fileConfig)
|
||||
if (!patchResult.success) {
|
||||
const errorMessage = patchResult.error || 'Failed to reload config'
|
||||
const validationIssues = patchResult.details || []
|
||||
@@ -498,6 +510,11 @@ class OpenCodeServerManager {
|
||||
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
|
||||
}
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
|
||||
await writeFileContent(configPath, JSON.stringify(patchResult.appliedConfig, null, 2))
|
||||
logger.info(`Persisted cleaned config to ${configPath} after removing fields: ${patchResult.removedFields.join(', ')}`)
|
||||
}
|
||||
|
||||
logger.info('OpenCode configuration reloaded successfully')
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
const healthy = await this.checkHealth()
|
||||
@@ -544,14 +561,14 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
async checkHealth(): Promise<boolean> {
|
||||
if (!this.openCodeClient) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
if (OPENCODE_BASIC_AUTH) {
|
||||
headers.Authorization = OPENCODE_BASIC_AUTH
|
||||
}
|
||||
const response = await fetch(`http://${OPENCODE_SERVER_HOST}:${OPENCODE_SERVER_PORT}/doc`, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
headers
|
||||
const response = await this.openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/doc',
|
||||
signal: AbortSignal.timeout(HEALTH_CHECK_TIMEOUT_MS),
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { logger } from '../../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
export interface ForwardRequest {
|
||||
method: string
|
||||
path: string
|
||||
body?: string
|
||||
headers?: Record<string, string>
|
||||
directory?: string
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface JsonRequestOptions {
|
||||
directory?: string
|
||||
headers?: Record<string, string>
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export class UpstreamError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
public readonly bodyText: string,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `OpenCode upstream returned ${status}`)
|
||||
this.name = 'UpstreamError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenCodeClient {
|
||||
forward(req: ForwardRequest): Promise<Response>
|
||||
forwardRaw(request: Request): Promise<Response>
|
||||
getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T>
|
||||
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
|
||||
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
|
||||
deleteProviderAuth(providerId: string): Promise<boolean>
|
||||
startMcpAuth(serverName: string, directory?: string): Promise<Response>
|
||||
authenticateMcp(serverName: string, directory?: string): Promise<Response>
|
||||
}
|
||||
|
||||
export interface FetchOpenCodeClientConfig {
|
||||
baseUrl: string
|
||||
basicAuth: string
|
||||
fetchFn?: typeof fetch
|
||||
}
|
||||
|
||||
export class FetchOpenCodeClient implements OpenCodeClient {
|
||||
constructor(private readonly config: FetchOpenCodeClientConfig) {}
|
||||
|
||||
private get fetchFn(): typeof fetch {
|
||||
return this.config.fetchFn ?? fetch
|
||||
}
|
||||
|
||||
private async request(req: ForwardRequest): Promise<Response> {
|
||||
const url = new URL(this.config.baseUrl + req.path)
|
||||
|
||||
if (req.directory) {
|
||||
url.searchParams.set('directory', req.directory)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = { ...(req.headers ?? {}) }
|
||||
|
||||
if (this.config.basicAuth) {
|
||||
headers.Authorization = this.config.basicAuth
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.fetchFn(url, {
|
||||
method: req.method,
|
||||
headers,
|
||||
body: req.body,
|
||||
signal: req.signal,
|
||||
})
|
||||
|
||||
const filteredHeaders: Record<string, string> = {}
|
||||
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!skipHeaders.has(key.toLowerCase())) {
|
||||
filteredHeaders[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const noBodyStatuses = new Set([101, 204, 205, 304])
|
||||
if (noBodyStatuses.has(response.status)) {
|
||||
return new Response(null, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: filteredHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
const body = await response.text()
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: filteredHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Proxy request failed for ${req.path}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async forward(req: ForwardRequest): Promise<Response> {
|
||||
return this.request(req)
|
||||
}
|
||||
|
||||
async forwardRaw(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
|
||||
|
||||
if (url.pathname.includes('/permissions/')) {
|
||||
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${cleanPathname}${url.search}`)
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
request.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!['host', 'connection', 'authorization'].includes(lowerKey)) {
|
||||
headers[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const body = request.method !== 'GET' && request.method !== 'HEAD'
|
||||
? await request.text()
|
||||
: undefined
|
||||
|
||||
return this.request({
|
||||
method: request.method,
|
||||
path: cleanPathname + url.search,
|
||||
body,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
|
||||
async getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T> {
|
||||
const response = await this.request({
|
||||
method: 'GET',
|
||||
path,
|
||||
directory: opts?.directory,
|
||||
headers: opts?.headers,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(opts?.headers ?? {}),
|
||||
}
|
||||
|
||||
const response = await this.request({
|
||||
method: 'POST',
|
||||
path,
|
||||
body: JSON.stringify(body),
|
||||
headers,
|
||||
directory: opts?.directory,
|
||||
signal: opts?.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const bodyText = await response.text()
|
||||
throw new UpstreamError(response.status, bodyText)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
async setProviderAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'PUT',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Set OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to set OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async deleteProviderAuth(providerId: string): Promise<boolean> {
|
||||
const response = await this.request({
|
||||
method: 'DELETE',
|
||||
path: `/auth/${encodeURIComponent(providerId)}`,
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
if (response.status === 502) {
|
||||
logger.error(`Failed to delete OpenCode auth for provider: ${providerId}`)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
}
|
||||
|
||||
async startMcpAuth(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
|
||||
async authenticateMcp(serverName: string, directory?: string): Promise<Response> {
|
||||
return this.request({
|
||||
method: 'POST',
|
||||
path: `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
directory,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpenCodeClient(): OpenCodeClient {
|
||||
const baseUrl = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
|
||||
const password = ENV.OPENCODE.SERVER_PASSWORD
|
||||
const username = ENV.OPENCODE.SERVER_USERNAME
|
||||
const basicAuth = password
|
||||
? `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
|
||||
: ''
|
||||
|
||||
return new FetchOpenCodeClient({ baseUrl, basicAuth })
|
||||
}
|
||||
@@ -1,63 +1,7 @@
|
||||
import { logger } from '../utils/logger'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { OpenCodeClient } from './client'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
|
||||
export const OPENCODE_SERVER_URL = `http://${ENV.OPENCODE.HOST}:${ENV.OPENCODE.PORT}`
|
||||
const OPENCODE_SERVER_PASSWORD = ENV.OPENCODE.SERVER_PASSWORD
|
||||
const OPENCODE_SERVER_USERNAME = ENV.OPENCODE.SERVER_USERNAME
|
||||
|
||||
const OPENCODE_BASIC_AUTH = OPENCODE_SERVER_PASSWORD
|
||||
? `Basic ${Buffer.from(`${OPENCODE_SERVER_USERNAME}:${OPENCODE_SERVER_PASSWORD}`).toString('base64')}`
|
||||
: ''
|
||||
|
||||
export function withOpenCodeAuth(headers: Record<string, string> = {}): Record<string, string> {
|
||||
if (OPENCODE_BASIC_AUTH) {
|
||||
return { ...headers, Authorization: OPENCODE_BASIC_AUTH }
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
|
||||
method: 'PUT',
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Set OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
} catch (error) {
|
||||
logger.error('Failed to set OpenCode auth:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOpenCodeAuth(providerId: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
|
||||
method: 'DELETE',
|
||||
headers: withOpenCodeAuth(),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete OpenCode auth:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export type PatchConfigValidationIssue = {
|
||||
path: string
|
||||
message: string
|
||||
@@ -206,12 +150,16 @@ function parseErrorResponse(responseText: string): { details: PatchConfigValidat
|
||||
return { details, errorMessage }
|
||||
}
|
||||
|
||||
export async function patchOpenCodeConfig(config: Record<string, unknown>): Promise<PatchConfigResult> {
|
||||
export async function patchConfigWithRecovery(
|
||||
client: OpenCodeClient,
|
||||
config: Record<string, unknown>,
|
||||
): Promise<PatchConfigResult> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
|
||||
const response = await client.forward({
|
||||
method: 'PATCH',
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
path: '/config',
|
||||
body: JSON.stringify(config),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
@@ -254,10 +202,11 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
|
||||
}
|
||||
|
||||
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
|
||||
const retryResponse = await fetch(`${OPENCODE_SERVER_URL}/config`, {
|
||||
const retryResponse = await client.forward({
|
||||
method: 'PATCH',
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
path: '/config',
|
||||
body: JSON.stringify(cleanedConfig),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (retryResponse.ok) {
|
||||
@@ -286,156 +235,3 @@ export async function patchOpenCodeConfig(config: Record<string, unknown>): Prom
|
||||
return { success: false, error: errorMessage }
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyRequest(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
|
||||
// Remove /api/opencode prefix from pathname before forwarding
|
||||
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
|
||||
const targetUrl = `${OPENCODE_SERVER_URL}${cleanPathname}${url.search}`
|
||||
|
||||
if (url.pathname.includes('/permissions/')) {
|
||||
logger.info(`Proxying permission request: ${url.pathname}${url.search} -> ${targetUrl}`)
|
||||
}
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
request.headers.forEach((value, key) => {
|
||||
if (!['host', 'connection', 'authorization'].includes(key.toLowerCase())) {
|
||||
headers[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: request.method,
|
||||
headers: withOpenCodeAuth(headers),
|
||||
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined,
|
||||
})
|
||||
|
||||
const responseHeaders: Record<string, string> = {}
|
||||
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!skipHeaders.has(key.toLowerCase())) {
|
||||
responseHeaders[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const body = await response.text()
|
||||
return new Response(body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Proxy request failed for ${url.pathname}${url.search}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyToOpenCodeWithDirectory(
|
||||
path: string,
|
||||
method: string,
|
||||
directory: string | undefined,
|
||||
body?: string,
|
||||
headers?: Record<string, string>
|
||||
): Promise<Response> {
|
||||
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
|
||||
|
||||
if (directory) {
|
||||
url.searchParams.set('directory', directory)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method,
|
||||
headers: withOpenCodeAuth(headers || { 'Content-Type': 'application/json' }),
|
||||
body,
|
||||
})
|
||||
|
||||
const responseHeaders: Record<string, string> = {}
|
||||
const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!skipHeaders.has(key.toLowerCase())) {
|
||||
responseHeaders[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
const responseBody = await response.text()
|
||||
return new Response(responseBody, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Proxy to OpenCode failed for ${path}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyMcpAuthStart(
|
||||
serverName: string,
|
||||
directory: string | undefined,
|
||||
): Promise<Response> {
|
||||
const path = `/mcp/${encodeURIComponent(serverName)}/auth`
|
||||
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
|
||||
|
||||
if (directory) {
|
||||
url.searchParams.set('directory', directory)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: 'POST',
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
})
|
||||
|
||||
const responseBody = await response.text()
|
||||
return new Response(responseBody, {
|
||||
status: response.status,
|
||||
headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`MCP auth start failed for ${serverName}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'MCP auth start failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyMcpAuthAuthenticate(
|
||||
serverName: string,
|
||||
directory: string | undefined,
|
||||
): Promise<Response> {
|
||||
const path = `/mcp/${encodeURIComponent(serverName)}/auth/authenticate`
|
||||
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
|
||||
|
||||
if (directory) {
|
||||
url.searchParams.set('directory', directory)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: 'POST',
|
||||
headers: withOpenCodeAuth({ 'Content-Type': 'application/json' }),
|
||||
})
|
||||
|
||||
const responseBody = await response.text()
|
||||
return new Response(responseBody, {
|
||||
status: response.status,
|
||||
headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`MCP auth authenticate failed for ${serverName}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'MCP auth authenticate failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
computeNextRunAtForJob,
|
||||
} from './schedule-config'
|
||||
import { resolveOpenCodeModel } from './opencode-models'
|
||||
import { proxyToOpenCodeWithDirectory } from './proxy'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { sseAggregator, type SSEEvent } from './sse-aggregator'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -118,9 +118,13 @@ type SkillInfo = {
|
||||
content: string
|
||||
}
|
||||
|
||||
async function fetchSkillContent(slugs: string[], repoPath: string): Promise<string[]> {
|
||||
async function fetchSkillContent(slugs: string[], repoPath: string, openCodeClient: OpenCodeClient): Promise<string[]> {
|
||||
try {
|
||||
const response = await proxyToOpenCodeWithDirectory('/skill', 'GET', repoPath)
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/skill',
|
||||
directory: repoPath,
|
||||
})
|
||||
if (!response.ok) {
|
||||
logger.warn(`Failed to fetch skills from OpenCode (${response.status}), falling back to name-only injection`)
|
||||
return []
|
||||
@@ -159,11 +163,12 @@ async function fetchSkillContent(slugs: string[], repoPath: string): Promise<str
|
||||
async function buildPromptWithSkills(
|
||||
prompt: string,
|
||||
skillMetadata: ScheduleJob['skillMetadata'],
|
||||
repoPath: string
|
||||
repoPath: string,
|
||||
openCodeClient: OpenCodeClient,
|
||||
): Promise<string> {
|
||||
if (!skillMetadata || !skillMetadata.skillSlugs || skillMetadata.skillSlugs.length === 0) return prompt
|
||||
|
||||
const skillBlocks = await fetchSkillContent(skillMetadata.skillSlugs, repoPath)
|
||||
const skillBlocks = await fetchSkillContent(skillMetadata.skillSlugs, repoPath, openCodeClient)
|
||||
const notesLine = skillMetadata.notes ? `\nSkill notes: ${skillMetadata.notes}` : ''
|
||||
|
||||
if (skillBlocks.length === 0) {
|
||||
@@ -353,7 +358,10 @@ export class ScheduleService {
|
||||
private static activeRuns = new Set<number>()
|
||||
private onJobChange: ((job: ScheduleJob | null, jobId: number) => void) | null = null
|
||||
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
) {}
|
||||
|
||||
setJobChangeHandler(handler: ((job: ScheduleJob | null, jobId: number) => void) | null): void {
|
||||
this.onJobChange = handler
|
||||
@@ -479,19 +487,20 @@ export class ScheduleService {
|
||||
})
|
||||
|
||||
try {
|
||||
const model = await resolveOpenCodeModel(repo.fullPath, {
|
||||
const model = await resolveOpenCodeModel(this.openCodeClient, repo.fullPath, {
|
||||
preferredModel: job.model,
|
||||
})
|
||||
const sessionTitle = buildSessionTitle(job)
|
||||
const sessionResponse = await proxyToOpenCodeWithDirectory(
|
||||
'/session',
|
||||
'POST',
|
||||
repo.fullPath,
|
||||
JSON.stringify({
|
||||
const sessionResponse = await this.openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: '/session',
|
||||
directory: repo.fullPath,
|
||||
body: JSON.stringify({
|
||||
title: sessionTitle,
|
||||
agent: job.agentSlug ?? undefined,
|
||||
}),
|
||||
)
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (!sessionResponse.ok) {
|
||||
throw new ScheduleServiceError('Failed to create OpenCode session', 502)
|
||||
@@ -591,11 +600,11 @@ export class ScheduleService {
|
||||
return this.getRun(repoId, jobId, runId)
|
||||
}
|
||||
|
||||
const abortResponse = await proxyToOpenCodeWithDirectory(
|
||||
`/session/${run.sessionId}/abort`,
|
||||
'POST',
|
||||
repo.fullPath,
|
||||
)
|
||||
const abortResponse = await this.openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${run.sessionId}/abort`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
|
||||
if (!abortResponse.ok) {
|
||||
const errorText = await abortResponse.text()
|
||||
@@ -650,15 +659,16 @@ export class ScheduleService {
|
||||
const repo = this.assertRepo(input.repoId)
|
||||
|
||||
try {
|
||||
const promptResponse = await proxyToOpenCodeWithDirectory(
|
||||
`/session/${input.sessionId}/message`,
|
||||
'POST',
|
||||
repo.fullPath,
|
||||
JSON.stringify({
|
||||
parts: [{ type: 'text', text: await buildPromptWithSkills(input.job.prompt, input.job.skillMetadata, repo.fullPath) }],
|
||||
const promptResponse = await this.openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: `/session/${input.sessionId}/message`,
|
||||
directory: repo.fullPath,
|
||||
body: JSON.stringify({
|
||||
parts: [{ type: 'text', text: await buildPromptWithSkills(input.job.prompt, input.job.skillMetadata, repo.fullPath, this.openCodeClient) }],
|
||||
model: input.model,
|
||||
}),
|
||||
)
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (!promptResponse.ok) {
|
||||
const errorText = await promptResponse.text()
|
||||
@@ -1020,11 +1030,11 @@ export class ScheduleService {
|
||||
}
|
||||
|
||||
private async listSessionMessages(directory: string, sessionId: string): Promise<SessionMessage[]> {
|
||||
const messagesResponse = await proxyToOpenCodeWithDirectory(
|
||||
`/session/${sessionId}/message`,
|
||||
'GET',
|
||||
const messagesResponse = await this.openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: `/session/${sessionId}/message`,
|
||||
directory,
|
||||
)
|
||||
})
|
||||
|
||||
if (!messagesResponse.ok) {
|
||||
const errorText = await messagesResponse.text()
|
||||
@@ -1035,7 +1045,11 @@ export class ScheduleService {
|
||||
}
|
||||
|
||||
private async getSessionStatuses(directory: string): Promise<Record<string, SessionStatus>> {
|
||||
const response = await proxyToOpenCodeWithDirectory('/session/status', 'GET', directory)
|
||||
const response = await this.openCodeClient.forward({
|
||||
method: 'GET',
|
||||
path: '/session/status',
|
||||
directory,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { vi } from 'vitest'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
export function createStubOpenCodeClient(overrides: Partial<OpenCodeClient> = {}): OpenCodeClient {
|
||||
return {
|
||||
forward: vi.fn(async () => new Response(JSON.stringify({}), { status: 200 })),
|
||||
forwardRaw: vi.fn(async () => new Response(JSON.stringify({}), { status: 200 })),
|
||||
getJson: vi.fn(async () => ({}) as unknown),
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response(JSON.stringify({}), { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response(JSON.stringify({}), { status: 200 })),
|
||||
...overrides,
|
||||
} as OpenCodeClient
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '../../../shared/src/types'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { ScheduleService } from '../../src/services/schedules'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
@@ -59,7 +60,7 @@ describe('Git Routes', () => {
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
} as unknown as GitAuthService
|
||||
app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService)
|
||||
app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient())
|
||||
})
|
||||
|
||||
describe('GET /:id/git/status', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn().mockImplementation(() => ({})),
|
||||
@@ -74,7 +75,7 @@ describe('Memory Routes - Loop Status', () => {
|
||||
mockGetRepoById.mockReset()
|
||||
|
||||
testDb = {} as any
|
||||
memoryApp = createMemoryRoutes(testDb)
|
||||
memoryApp = createMemoryRoutes(testDb, createStubOpenCodeClient())
|
||||
})
|
||||
|
||||
describe('GET /loop/status', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
|
||||
const mockDb = {
|
||||
prepare: vi.fn(),
|
||||
@@ -58,7 +59,7 @@ describe('Repo Routes', () => {
|
||||
it('should return 404 when repo not found', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(null)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/access', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
@@ -81,7 +82,7 @@ describe('Repo Routes', () => {
|
||||
}
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/access', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
@@ -107,7 +108,7 @@ describe('Repo Routes', () => {
|
||||
throw new Error('Database error')
|
||||
})
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/access', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
@@ -120,7 +121,7 @@ describe('Repo Routes', () => {
|
||||
it('should return 404 when repo not found', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(null)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/assistant-mode', { method: 'GET' })
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
@@ -155,7 +156,7 @@ describe('Repo Routes', () => {
|
||||
|
||||
vi.mocked(getAssistantModeStatus).mockResolvedValue(mockStatus)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/assistant-mode', { method: 'GET' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
@@ -169,7 +170,7 @@ describe('Repo Routes', () => {
|
||||
it('should return 404 when repo not found', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(null)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/assistant-mode', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -208,7 +209,7 @@ describe('Repo Routes', () => {
|
||||
|
||||
vi.mocked(ensureAssistantMode).mockResolvedValue(mockStatus)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/assistant-mode', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -237,7 +238,7 @@ describe('Repo Routes', () => {
|
||||
|
||||
vi.mocked(ensureAssistantMode).mockRejectedValue(new Error('Test error'))
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient())
|
||||
const res = await app.request('/1/assistant-mode', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { execSync, spawnSync } from 'child_process'
|
||||
import { createStubOpenCodeClient } from '../helpers/stub-opencode-client'
|
||||
|
||||
const mockGetSettings = vi.fn()
|
||||
const mockUpdateSettings = vi.fn()
|
||||
@@ -62,9 +63,21 @@ vi.mock('../../src/services/file-operations', () => ({
|
||||
fileExists: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/proxy', () => ({
|
||||
patchOpenCodeConfig: vi.fn(),
|
||||
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||
vi.mock('../../src/services/opencode/config-recovery', () => ({
|
||||
patchConfigWithRecovery: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode/client', () => ({
|
||||
createOpenCodeClient: () => ({
|
||||
forward: vi.fn(),
|
||||
forwardRaw: vi.fn(),
|
||||
getJson: vi.fn(),
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', async (importOriginal) => {
|
||||
@@ -146,7 +159,7 @@ import { writeFileContent } from '../../src/services/file-operations'
|
||||
import { getImportedSessionDirectories, getOpenCodeImportStatus, OpenCodeImportProtectionError, syncOpenCodeImport } from '../../src/services/opencode-import'
|
||||
import { relinkReposFromSessionDirectories } from '../../src/services/repo'
|
||||
import { opencodeServerManager, ConfigReloadError } from '../../src/services/opencode-single-server'
|
||||
import { patchOpenCodeConfig } from '../../src/services/proxy'
|
||||
import { patchConfigWithRecovery } from '../../src/services/opencode/config-recovery'
|
||||
|
||||
const mockExecSync = execSync as ReturnType<typeof vi.fn>
|
||||
const mockSpawnSync = spawnSync as ReturnType<typeof vi.fn>
|
||||
@@ -160,7 +173,7 @@ const mockSyncOpenCodeImport = syncOpenCodeImport as ReturnType<typeof vi.fn>
|
||||
const mockGetImportedSessionDirectories = getImportedSessionDirectories as ReturnType<typeof vi.fn>
|
||||
const mockRelinkReposFromSessionDirectories = relinkReposFromSessionDirectories as ReturnType<typeof vi.fn>
|
||||
const mockWriteFileContent = writeFileContent as ReturnType<typeof vi.fn>
|
||||
const mockPatchOpenCodeConfig = patchOpenCodeConfig as ReturnType<typeof vi.fn>
|
||||
const mockPatchConfigWithRecovery = patchConfigWithRecovery as ReturnType<typeof vi.fn>
|
||||
|
||||
describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
let settingsApp: ReturnType<typeof createSettingsRoutes>
|
||||
@@ -187,15 +200,15 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
mockGetImportedSessionDirectories.mockReset()
|
||||
mockRelinkReposFromSessionDirectories.mockReset()
|
||||
mockWriteFileContent.mockReset()
|
||||
mockPatchOpenCodeConfig.mockReset()
|
||||
mockPatchConfigWithRecovery.mockReset()
|
||||
|
||||
testDb = {} as any
|
||||
settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any)
|
||||
settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any, createStubOpenCodeClient())
|
||||
|
||||
mockReloadConfig.mockResolvedValue(undefined)
|
||||
mockRestart.mockResolvedValue(undefined)
|
||||
mockClearStartupError.mockReturnValue(undefined)
|
||||
mockPatchOpenCodeConfig.mockResolvedValue({ success: true, appliedConfig: { $schema: 'https://opencode.ai/config.json' } })
|
||||
mockPatchConfigWithRecovery.mockResolvedValue({ success: true, appliedConfig: { $schema: 'https://opencode.ai/config.json' } } as any)
|
||||
mockWriteFileContent.mockResolvedValue(undefined)
|
||||
mockGetOpenCodeImportStatus.mockResolvedValue({
|
||||
configSourcePath: null,
|
||||
@@ -229,7 +242,7 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
})
|
||||
mockPatchOpenCodeConfig.mockResolvedValueOnce({
|
||||
mockPatchConfigWithRecovery.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'command.review: Invalid field',
|
||||
details: [{ path: 'command.review', message: 'Invalid field' }],
|
||||
@@ -275,7 +288,7 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
})
|
||||
mockPatchOpenCodeConfig.mockResolvedValueOnce({
|
||||
mockPatchConfigWithRecovery.mockResolvedValueOnce({
|
||||
success: true,
|
||||
appliedConfig: { theme: 'dark' },
|
||||
removedFields: ['command.review'],
|
||||
@@ -331,7 +344,7 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
})
|
||||
mockPatchOpenCodeConfig.mockResolvedValueOnce({
|
||||
mockPatchConfigWithRecovery.mockResolvedValueOnce({
|
||||
success: false,
|
||||
error: 'command.review: Invalid field',
|
||||
details: [{ path: 'command.review', message: 'Invalid field' }],
|
||||
@@ -360,7 +373,7 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
})
|
||||
mockPatchOpenCodeConfig.mockResolvedValueOnce({
|
||||
mockPatchConfigWithRecovery.mockResolvedValueOnce({
|
||||
success: true,
|
||||
appliedConfig: { theme: 'dark' },
|
||||
removedFields: ['command.review'],
|
||||
|
||||
@@ -1,42 +1,31 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { proxyToOpenCodeWithDirectory } = vi.hoisted(() => ({
|
||||
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/proxy', () => ({
|
||||
proxyToOpenCodeWithDirectory,
|
||||
}))
|
||||
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { resolveOpenCodeModel } from '../../src/services/opencode-models'
|
||||
|
||||
function jsonResponse(body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('resolveOpenCodeModel', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns the preferred model when it is available', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5' }))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({ model: 'openai/gpt-5' })
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project', {
|
||||
preferredModel: 'openai/gpt-5',
|
||||
})
|
||||
|
||||
@@ -48,20 +37,24 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('falls back to the provider default when the preferred model is unavailable', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5.4' }))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({ model: 'openai/gpt-5.4' })
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5.3-codex-spark': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5.3-codex-spark' },
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5.3-codex-spark': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5.3-codex-spark' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project', {
|
||||
preferredModel: 'openai/gpt-5.4',
|
||||
})
|
||||
|
||||
@@ -73,23 +66,27 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('prefers the configured small model when requested', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
model: 'openai/gpt-5',
|
||||
small_model: 'openai/gpt-5-mini',
|
||||
}))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({
|
||||
model: 'openai/gpt-5',
|
||||
small_model: 'openai/gpt-5-mini',
|
||||
})
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5' },
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project', {
|
||||
preferSmallModel: true,
|
||||
})
|
||||
|
||||
@@ -101,23 +98,27 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('falls back to config.model when small_model is unavailable', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
model: 'openai/gpt-5',
|
||||
small_model: 'openai/gpt-5-unavailable',
|
||||
}))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({
|
||||
model: 'openai/gpt-5',
|
||||
small_model: 'openai/gpt-5-unavailable',
|
||||
})
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project', {
|
||||
preferSmallModel: true,
|
||||
})
|
||||
|
||||
@@ -129,23 +130,27 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('falls back to provider default only after all configured candidates fail', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
model: 'openai/gpt-5-configured',
|
||||
small_model: 'openai/gpt-5-small-unavailable',
|
||||
}))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({
|
||||
model: 'openai/gpt-5-configured',
|
||||
small_model: 'openai/gpt-5-small-unavailable',
|
||||
})
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5-mini': {}, 'gpt-5-turbo': {}, 'gpt-5-configured': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5-mini': {}, 'gpt-5-turbo': {}, 'gpt-5-configured': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project', {
|
||||
preferSmallModel: true,
|
||||
})
|
||||
|
||||
@@ -157,23 +162,27 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('falls back to provider default when both small_model and model are unavailable', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({
|
||||
model: 'openai/gpt-5-unavailable',
|
||||
small_model: 'openai/gpt-5-also-unavailable',
|
||||
}))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({
|
||||
model: 'openai/gpt-5-unavailable',
|
||||
small_model: 'openai/gpt-5-also-unavailable',
|
||||
})
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5-mini': {}, 'gpt-5-turbo': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'openai', models: { 'gpt-5-mini': {}, 'gpt-5-turbo': {} } },
|
||||
],
|
||||
default: { openai: 'gpt-5-mini' },
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project', {
|
||||
preferSmallModel: true,
|
||||
})
|
||||
|
||||
@@ -185,19 +194,23 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('falls back to the first available model when defaults are missing', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({}))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({})
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{ id: 'anthropic', models: { 'claude-sonnet-4': {}, 'claude-haiku-4': {} } },
|
||||
],
|
||||
})
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({
|
||||
providers: [
|
||||
{ id: 'anthropic', models: { 'claude-sonnet-4': {}, 'claude-haiku-4': {} } },
|
||||
],
|
||||
}))
|
||||
})
|
||||
|
||||
const result = await resolveOpenCodeModel('/workspace/repos/sample-project')
|
||||
const result = await resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project')
|
||||
|
||||
expect(result).toEqual({
|
||||
providerID: 'anthropic',
|
||||
@@ -207,15 +220,19 @@ describe('resolveOpenCodeModel', () => {
|
||||
})
|
||||
|
||||
it('throws when no configured models are available', async () => {
|
||||
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5' }))
|
||||
}
|
||||
const mockClient = {
|
||||
getJson: vi.fn().mockImplementation((path: string) => {
|
||||
if (path === '/config') {
|
||||
return Promise.resolve({ model: 'openai/gpt-5' })
|
||||
}
|
||||
if (path === '/config/providers') {
|
||||
return Promise.resolve({ providers: [], default: {} })
|
||||
}
|
||||
throw new Error(`Unexpected path: ${path}`)
|
||||
}),
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return Promise.resolve(jsonResponse({ providers: [], default: {} }))
|
||||
})
|
||||
|
||||
await expect(resolveOpenCodeModel('/workspace/repos/sample-project')).rejects.toThrow(
|
||||
await expect(resolveOpenCodeModel(mockClient, '/workspace/repos/sample-project')).rejects.toThrow(
|
||||
'No configured OpenCode models are available',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -46,8 +46,21 @@ vi.mock('child_process', () => ({
|
||||
execSync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/proxy', () => ({
|
||||
patchOpenCodeConfig: vi.fn(),
|
||||
vi.mock('../../src/services/opencode/config-recovery', () => ({
|
||||
patchConfigWithRecovery: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode/client', () => ({
|
||||
createOpenCodeClient: () => ({
|
||||
forward: vi.fn().mockResolvedValue(new Response(null, { status: 200 })),
|
||||
forwardRaw: vi.fn(),
|
||||
getJson: vi.fn(),
|
||||
postJson: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
import { promises as fs } from 'fs'
|
||||
@@ -250,13 +263,13 @@ describe('OpenCodeServerManager - reloadConfig', () => {
|
||||
const mockReadFile = vi.fn().mockResolvedValue(JSON.stringify({ command: { review: 'test' } }))
|
||||
fs.readFile = mockReadFile
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const { patchConfigWithRecovery } = await import('../../src/services/opencode/config-recovery')
|
||||
const mockPatchResult = { success: true }
|
||||
vi.mocked(patchOpenCodeConfig).mockResolvedValue(mockPatchResult)
|
||||
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 200 }))
|
||||
vi.mocked(patchConfigWithRecovery).mockResolvedValue(mockPatchResult as any)
|
||||
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { createStubOpenCodeClient } = await import('../helpers/stub-opencode-client')
|
||||
opencodeServerManager.setOpenCodeClient(createStubOpenCodeClient())
|
||||
|
||||
await opencodeServerManager.reloadConfig()
|
||||
|
||||
@@ -264,8 +277,34 @@ describe('OpenCodeServerManager - reloadConfig', () => {
|
||||
expect.stringContaining('.config/opencode.json'),
|
||||
'utf-8'
|
||||
)
|
||||
expect(patchOpenCodeConfig).toHaveBeenCalled()
|
||||
|
||||
fetchSpy.mockRestore()
|
||||
expect(patchConfigWithRecovery).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('OpenCodeServerManager - checkHealth', () => {
|
||||
it('returns false when the upstream times out and aborts the upstream fetch', async () => {
|
||||
const { opencodeServerManager } = await import('../../src/services/opencode-single-server')
|
||||
const { createStubOpenCodeClient } = await import('../helpers/stub-opencode-client')
|
||||
|
||||
let capturedSignal: AbortSignal | undefined
|
||||
let aborted = false
|
||||
const stubClient = createStubOpenCodeClient({
|
||||
forward: vi.fn(async (req: { signal?: AbortSignal }) => {
|
||||
capturedSignal = req.signal
|
||||
return await new Promise<Response>((resolve) => {
|
||||
req.signal?.addEventListener('abort', () => {
|
||||
aborted = true
|
||||
resolve(new Response(JSON.stringify({ error: 'Proxy request failed' }), { status: 502 }))
|
||||
})
|
||||
})
|
||||
}),
|
||||
})
|
||||
opencodeServerManager.setOpenCodeClient(stubClient)
|
||||
|
||||
const healthy = await opencodeServerManager.checkHealth()
|
||||
|
||||
expect(healthy).toBe(false)
|
||||
expect(capturedSignal).toBeDefined()
|
||||
expect(aborted).toBe(true)
|
||||
}, 5000)
|
||||
})
|
||||
@@ -0,0 +1,392 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
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('../../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { FetchOpenCodeClient, UpstreamError } from '../../../src/services/opencode/client'
|
||||
|
||||
describe('OpenCodeClient', () => {
|
||||
const baseUrl = 'http://127.0.0.1:5551'
|
||||
const basicAuth = 'Basic dXNlcjpwYXNz'
|
||||
|
||||
describe('forward', () => {
|
||||
it('should build URL from baseUrl and path, inject auth when present, and strip hop-by-hop headers', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({ data: 'test' }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': '100',
|
||||
'Content-Encoding': 'gzip',
|
||||
'Transfer-Encoding': 'chunked',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
})
|
||||
|
||||
let capturedUrl: URL | undefined
|
||||
let capturedInit: RequestInit | undefined
|
||||
const fetchFn = async (input: URL | Request | string, init?: RequestInit) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
capturedInit = init
|
||||
return mockResponse
|
||||
}
|
||||
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth, fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.forward({
|
||||
method: 'POST',
|
||||
path: '/config',
|
||||
body: 'request-body-content',
|
||||
headers: { 'X-Caller': 'caller-value' },
|
||||
})
|
||||
|
||||
expect(capturedUrl?.toString()).toBe(baseUrl + '/config')
|
||||
expect(capturedInit?.method).toBe('POST')
|
||||
expect(capturedInit?.body).toBe('request-body-content')
|
||||
expect(capturedInit?.headers).toEqual(expect.objectContaining({
|
||||
Authorization: basicAuth,
|
||||
'X-Caller': 'caller-value',
|
||||
}))
|
||||
|
||||
const resultHeaders: Record<string, string> = {}
|
||||
result.headers.forEach((value, key) => {
|
||||
resultHeaders[key] = value
|
||||
})
|
||||
|
||||
expect(resultHeaders['content-length']).toBeUndefined()
|
||||
expect(resultHeaders['content-encoding']).toBeUndefined()
|
||||
expect(resultHeaders['transfer-encoding']).toBeUndefined()
|
||||
expect(resultHeaders['connection']).toBeUndefined()
|
||||
expect(resultHeaders['content-type']).toBe('application/json')
|
||||
})
|
||||
|
||||
it('should return 502 JSON Response when fetchFn throws', async () => {
|
||||
const fetchFn = async () => {
|
||||
throw new Error('Network error')
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.forward({
|
||||
method: 'GET',
|
||||
path: '/config',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(502)
|
||||
const body = await result.json()
|
||||
expect(body).toEqual({ error: 'Proxy request failed' })
|
||||
})
|
||||
|
||||
it('should honour directory by adding URL-encoded query param and preserve existing query string', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
await client.forward({
|
||||
method: 'GET',
|
||||
path: '/config?foo=bar',
|
||||
directory: '/test/dir',
|
||||
})
|
||||
|
||||
expect(capturedUrl?.searchParams.get('directory')).toBe('/test/dir')
|
||||
expect(capturedUrl?.searchParams.get('foo')).toBe('bar')
|
||||
})
|
||||
|
||||
it('should forward an AbortSignal to fetchFn when provided', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedInit: RequestInit | undefined
|
||||
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
|
||||
capturedInit = init
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
const controller = new AbortController()
|
||||
|
||||
await client.forward({ method: 'GET', path: '/doc', signal: controller.signal })
|
||||
|
||||
expect(capturedInit?.signal).toBe(controller.signal)
|
||||
})
|
||||
|
||||
it('should return 502 Response when fetchFn rejects with AbortError', async () => {
|
||||
const fetchFn = async (_input: URL | Request | string, init?: RequestInit) => {
|
||||
const signal = init?.signal
|
||||
if (signal?.aborted) {
|
||||
throw Object.assign(new Error('Aborted'), { name: 'AbortError' })
|
||||
}
|
||||
return new Response(JSON.stringify({}), { status: 200 })
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
|
||||
const result = await client.forward({ method: 'GET', path: '/doc', signal: controller.signal })
|
||||
|
||||
expect(result.status).toBe(502)
|
||||
const body = await result.json()
|
||||
expect(body).toEqual({ error: 'Proxy request failed' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('forwardRaw', () => {
|
||||
it('should strip /api/opencode prefix from path, preserve search string, and strip host/connection/authorization headers', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedUrl: URL | undefined
|
||||
let capturedInit: RequestInit | undefined
|
||||
const fetchFn = async (input: URL | Request | string, init?: RequestInit) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
capturedInit = init
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const request = new Request('http://localhost:5003/api/opencode/config?query=1', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Host': 'localhost:5003',
|
||||
'Connection': 'keep-alive',
|
||||
'Authorization': 'Bearer token',
|
||||
'X-Custom-Header': 'value',
|
||||
},
|
||||
})
|
||||
|
||||
await client.forwardRaw(request)
|
||||
|
||||
expect(capturedUrl?.pathname).toBe('/config')
|
||||
expect(capturedUrl?.searchParams.get('query')).toBe('1')
|
||||
|
||||
expect(capturedInit?.headers).toEqual(expect.objectContaining({
|
||||
'x-custom-header': 'value',
|
||||
}))
|
||||
expect((capturedInit?.headers as Record<string, string>)['host']).toBeUndefined()
|
||||
expect((capturedInit?.headers as Record<string, string>)['connection']).toBeUndefined()
|
||||
expect((capturedInit?.headers as Record<string, string>)['authorization']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should read body for POST but not for GET/HEAD', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
const capturedBodies: unknown[] = []
|
||||
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
|
||||
capturedBodies.push(init?.body)
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const postRequest = new Request('http://localhost:5003/api/opencode/test', {
|
||||
method: 'POST',
|
||||
body: 'test body',
|
||||
})
|
||||
|
||||
await client.forwardRaw(postRequest)
|
||||
|
||||
const getRequest = new Request('http://localhost:5003/api/opencode/test', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
await client.forwardRaw(getRequest)
|
||||
|
||||
const headRequest = new Request('http://localhost:5003/api/opencode/test', {
|
||||
method: 'HEAD',
|
||||
})
|
||||
|
||||
await client.forwardRaw(headRequest)
|
||||
|
||||
expect(capturedBodies[0]).toBe('test body')
|
||||
expect(capturedBodies[1]).toBeUndefined()
|
||||
expect(capturedBodies[2]).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getJson', () => {
|
||||
it('should return parsed body on 200', async () => {
|
||||
const mockData = { config: 'test' }
|
||||
const mockResponse = new Response(JSON.stringify(mockData), { status: 200 })
|
||||
const fetchFn = async () => mockResponse
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.getJson('/config')
|
||||
expect(result).toEqual(mockData)
|
||||
})
|
||||
|
||||
it('should throw UpstreamError on 404 with status and bodyText', async () => {
|
||||
const mockResponse = new Response('Not found', { status: 404 })
|
||||
const fetchFn = async () => {
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
let caughtErr: UpstreamError | undefined
|
||||
try {
|
||||
await client.getJson('/not-found')
|
||||
} catch (err) {
|
||||
caughtErr = err as UpstreamError
|
||||
}
|
||||
|
||||
expect(caughtErr).toBeDefined()
|
||||
expect(caughtErr?.status).toBe(404)
|
||||
expect(caughtErr?.bodyText).toBe('Not found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('postJson', () => {
|
||||
it('should post JSON with Content-Type header and merge caller headers', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({ success: true }), { status: 200 })
|
||||
let capturedInit: RequestInit | undefined
|
||||
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
|
||||
capturedInit = init
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
await client.postJson('/test', { data: 'test' }, {
|
||||
headers: { 'X-Custom': 'value' },
|
||||
})
|
||||
|
||||
expect(capturedInit?.headers).toEqual({
|
||||
'Content-Type': 'application/json',
|
||||
'X-Custom': 'value',
|
||||
})
|
||||
expect(capturedInit?.body).toBe(JSON.stringify({ data: 'test' }))
|
||||
})
|
||||
|
||||
it('should throw UpstreamError on 500', async () => {
|
||||
const mockResponse = new Response('Internal error', { status: 500 })
|
||||
const fetchFn = async () => mockResponse
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
await expect(client.postJson('/test', {})).rejects.toThrow(UpstreamError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setProviderAuth', () => {
|
||||
it('should return true on 200', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
const fetchFn = async () => mockResponse
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.setProviderAuth('test-provider', 'api-key')
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false on 401', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 401 })
|
||||
const fetchFn = async () => mockResponse
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.setProviderAuth('test-provider', 'api-key')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false when fetchFn throws', async () => {
|
||||
const fetchFn = async () => {
|
||||
throw new Error('Network error')
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.setProviderAuth('test-provider', 'api-key')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteProviderAuth', () => {
|
||||
it('should return true on 200 with DELETE method and no body', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedInit: RequestInit | undefined
|
||||
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
|
||||
capturedInit = init
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.deleteProviderAuth('test-provider')
|
||||
expect(result).toBe(true)
|
||||
expect(capturedInit?.method).toBe('DELETE')
|
||||
expect(capturedInit?.body).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should return false on 401', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 401 })
|
||||
const fetchFn = async () => mockResponse
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.deleteProviderAuth('test-provider')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false when fetchFn throws', async () => {
|
||||
const fetchFn = async () => {
|
||||
throw new Error('Network error')
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.deleteProviderAuth('test-provider')
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startMcpAuth', () => {
|
||||
it('should build path with encoded serverName and directory param', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.startMcpAuth('foo bar', '/dir')
|
||||
|
||||
expect(capturedUrl?.pathname).toBe('/mcp/foo%20bar/auth')
|
||||
expect(capturedUrl?.searchParams.get('directory')).toBe('/dir')
|
||||
expect(result).toBeInstanceOf(Response)
|
||||
})
|
||||
})
|
||||
|
||||
describe('authenticateMcp', () => {
|
||||
it('should build path with auth/authenticate suffix', async () => {
|
||||
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
|
||||
let capturedUrl: URL | undefined
|
||||
const fetchFn = async (input: URL | Request | string) => {
|
||||
capturedUrl = input instanceof URL ? input : new URL(input.toString())
|
||||
return mockResponse
|
||||
}
|
||||
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
|
||||
|
||||
const result = await client.authenticateMcp('name', undefined)
|
||||
|
||||
expect(capturedUrl?.pathname).toBe('/mcp/name/auth/authenticate')
|
||||
expect(capturedUrl?.searchParams.has('directory')).toBe(false)
|
||||
expect(result).toBeInstanceOf(Response)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,303 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
|
||||
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('../../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { patchConfigWithRecovery } from '../../../src/services/opencode/config-recovery'
|
||||
import type { OpenCodeClient, ForwardRequest } from '../../../src/services/opencode/client'
|
||||
|
||||
function createStubClient(
|
||||
responses: Array<{ status: number; text: string }>,
|
||||
capturedRequests?: ForwardRequest[],
|
||||
): OpenCodeClient {
|
||||
let callIndex = 0
|
||||
return {
|
||||
|
||||
async forward(req: ForwardRequest) {
|
||||
capturedRequests?.push(req)
|
||||
const response = responses[callIndex++] ?? responses[responses.length - 1]!
|
||||
return new Response(response.text, {
|
||||
status: response.status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
},
|
||||
|
||||
async forwardRaw(_request: Request) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async getJson<T>(_path: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async postJson<T>(_path: string, _body: unknown) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async setProviderAuth(_providerId: string, _apiKey: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async deleteProviderAuth(_providerId: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async startMcpAuth(_serverName: string, _directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
|
||||
async authenticateMcp(_serverName: string, _directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('patchConfigWithRecovery', () => {
|
||||
it('should return success on 200 response with single forward call', async () => {
|
||||
const config = { agent: { name: 'test' } }
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 200, text: '{}' },
|
||||
], captured)
|
||||
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.appliedConfig).toBe(config)
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(captured).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should recover by removing command.review on 400 with structured errors', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: { command: { review: 'some value' } },
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Invalid command review field' },
|
||||
],
|
||||
}
|
||||
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 400, text: JSON.stringify(errorResponse) },
|
||||
{ status: 200, text: '{}' },
|
||||
], captured)
|
||||
|
||||
const config = { command: { review: 'test', other: 'value' }, agent: { name: 'test' } }
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.removedFields).toContain('command.review')
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(captured).toHaveLength(2)
|
||||
|
||||
const retryBody = JSON.parse(captured[1]!.body!) as { command?: { review?: unknown; other?: unknown }; agent?: unknown }
|
||||
expect(retryBody.command?.review).toBeUndefined()
|
||||
expect(retryBody.command?.other).toBe('value')
|
||||
expect(retryBody.agent).toEqual({ name: 'test' })
|
||||
|
||||
expect(result.appliedConfig).toBeDefined()
|
||||
expect((result.appliedConfig as { command?: { review?: unknown } }).command?.review).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should recover from ConfigInvalidError data.issues shape', async () => {
|
||||
const errorResponse = {
|
||||
name: 'ConfigInvalidError',
|
||||
data: {
|
||||
issues: [
|
||||
{ path: ['command', 'review'], message: 'Invalid review' },
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 400, text: JSON.stringify(errorResponse) },
|
||||
{ status: 200, text: '{}' },
|
||||
], captured)
|
||||
|
||||
const config = { command: { review: 'test' } }
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.removedFields).toContain('command.review')
|
||||
expect(captured).toHaveLength(2)
|
||||
|
||||
const retryBody = JSON.parse(captured[1]!.body!) as { command?: { review?: unknown } }
|
||||
expect(retryBody.command?.review).toBeUndefined()
|
||||
|
||||
expect((result.appliedConfig as { command?: { review?: unknown } }).command?.review).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should NOT retry if path depth > 3', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['a', 'b', 'c', 'd'], message: 'Too deep' },
|
||||
],
|
||||
}
|
||||
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 400, text: JSON.stringify(errorResponse) },
|
||||
], captured)
|
||||
|
||||
const config = { a: { b: { c: { d: 'value' } } } }
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toBeUndefined()
|
||||
expect(captured).toHaveLength(1)
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(result.details?.[0]?.message).toBe('Too deep')
|
||||
})
|
||||
|
||||
it('should NOT retry if path is root', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['root'], message: 'Invalid configuration' },
|
||||
],
|
||||
}
|
||||
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 400, text: JSON.stringify(errorResponse) },
|
||||
], captured)
|
||||
|
||||
const config = { invalid: 'config' }
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toBeUndefined()
|
||||
expect(captured).toHaveLength(1)
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(result.details?.[0]?.path).toBe('root')
|
||||
})
|
||||
|
||||
it('should return retry errors when retry also fails', async () => {
|
||||
const initialError = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Initial error' },
|
||||
],
|
||||
}
|
||||
|
||||
const retryError = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['agent'], message: 'Retry error - agent invalid' },
|
||||
],
|
||||
}
|
||||
|
||||
let callCount = 0
|
||||
const client: OpenCodeClient = {
|
||||
async forward(_req: ForwardRequest) {
|
||||
callCount++
|
||||
if (callCount === 1) {
|
||||
return new Response(JSON.stringify(initialError), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
return new Response(JSON.stringify(retryError), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
},
|
||||
async forwardRaw(_request: Request) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async getJson<T>(_path: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async postJson<T>(_path: string, _body: unknown) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async setProviderAuth(providerId: string, apiKey: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async deleteProviderAuth(providerId: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async startMcpAuth(serverName: string, directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
async authenticateMcp(serverName: string, directory?: string) {
|
||||
throw new Error('not used')
|
||||
},
|
||||
}
|
||||
|
||||
const config = { command: { review: 'test' } }
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toContain('command.review')
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(result.details?.[0]?.message).toBe('Retry error - agent invalid')
|
||||
expect(callCount).toBe(2)
|
||||
})
|
||||
|
||||
it('should return error with Parse error on unparseable response', async () => {
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 400, text: 'not valid json at all' },
|
||||
], captured)
|
||||
|
||||
const config = {}
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toContain('Parse error')
|
||||
expect(captured).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should return error on 502 from client.forward', async () => {
|
||||
const error502Response = { error: 'Proxy request failed' }
|
||||
const captured: ForwardRequest[] = []
|
||||
const client = createStubClient([
|
||||
{ status: 502, text: JSON.stringify(error502Response) },
|
||||
], captured)
|
||||
|
||||
const config = {}
|
||||
const result = await patchConfigWithRecovery(client, config)
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toBeDefined()
|
||||
expect(captured).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -1,445 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } 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(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const createMockFetch = (response: Response) => {
|
||||
return vi.fn().mockResolvedValue(response) as unknown as typeof fetch
|
||||
}
|
||||
|
||||
describe('proxy service', () => {
|
||||
describe('patchOpenCodeConfig', () => {
|
||||
const originalFetch = global.fetch
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
|
||||
describe('when OpenCode returns 400 with structured errors', () => {
|
||||
it('should parse errors array and extract path and message', async () => {
|
||||
const mockResponse = {
|
||||
success: false,
|
||||
data: { command: { review: 'some value' } },
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Invalid command review field' },
|
||||
{ path: ['agent', 'temperature'], message: 'Temperature must be between 0 and 2' }
|
||||
]
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(mockResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.details).toHaveLength(2)
|
||||
expect(result.details?.[0]).toEqual({ path: 'command.review', message: 'Invalid command review field' })
|
||||
expect(result.details?.[1]).toEqual({ path: 'agent.temperature', message: 'Temperature must be between 0 and 2' })
|
||||
expect(result.error).toBe('command.review: Invalid command review field; agent.temperature: Temperature must be between 0 and 2')
|
||||
})
|
||||
|
||||
it('should handle errors with string path format', async () => {
|
||||
const mockResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: 'command.review', message: 'Invalid field' }
|
||||
]
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(mockResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(result.details?.[0]).toEqual({ path: 'command.review', message: 'Invalid field' })
|
||||
})
|
||||
|
||||
it('should handle errors with missing path (defaults to root)', async () => {
|
||||
const mockResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ message: 'Configuration is invalid' }
|
||||
]
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(mockResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({})
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(result.details?.[0]).toEqual({ path: 'root', message: 'Configuration is invalid' })
|
||||
})
|
||||
|
||||
it('should parse nested data.issues from runtime validation payloads', async () => {
|
||||
const mockResponse = {
|
||||
success: false,
|
||||
data: {
|
||||
issues: [
|
||||
{ path: ['command', 'review'], message: 'Invalid review command' },
|
||||
{ path: ['provider', 'openai', 'models'], message: 'Expected object' }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(mockResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.details).toEqual([
|
||||
{ path: 'command.review', message: 'Invalid review command' },
|
||||
{ path: 'provider.openai.models', message: 'Expected object' }
|
||||
])
|
||||
expect(result.error).toBe('command.review: Invalid review command; provider.openai.models: Expected object')
|
||||
})
|
||||
})
|
||||
|
||||
describe('when OpenCode returns 400 with only data (no errors)', () => {
|
||||
it('should not use data as error message source', async () => {
|
||||
const mockResponse = {
|
||||
success: false,
|
||||
data: { command: { review: 'some long value that should not be the error message' } }
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(mockResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).not.toContain('some long value')
|
||||
expect(result.details).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('when OpenCode returns 400 with unstructured text', () => {
|
||||
it('should create bounded fallback message without giant config blobs', async () => {
|
||||
const longConfig = 'x'.repeat(1000)
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => longConfig
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ config: longConfig })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error?.length).toBeLessThan(400)
|
||||
expect(result.details).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle JSON parse errors gracefully', async () => {
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => 'not valid json at all'
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({})
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toContain('Parse error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('retry logic with removable paths', () => {
|
||||
it('should retry after removing a valid nested path like command.review', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Invalid field' }
|
||||
]
|
||||
}
|
||||
|
||||
let callCount = 0
|
||||
global.fetch = vi.fn().mockImplementation(async () => {
|
||||
callCount++
|
||||
if (callCount === 1) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(errorResponse)
|
||||
} as unknown as Response
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
text: async () => '{}'
|
||||
} as unknown as Response
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({
|
||||
command: { review: 'test', other: 'value' },
|
||||
agent: { name: 'test' }
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.removedFields).toContain('command.review')
|
||||
expect(result.details).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('should not retry if any path is non-removable (root level)', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['root'], message: 'Invalid configuration' }
|
||||
]
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(errorResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ invalid: 'config' })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toEqual(undefined)
|
||||
expect(result.error).toContain('Invalid configuration')
|
||||
})
|
||||
|
||||
it('should not retry if any path exceeds depth limit', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['a', 'b', 'c', 'd'], message: 'Too deep' }
|
||||
]
|
||||
}
|
||||
|
||||
global.fetch = createMockFetch({
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(errorResponse)
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ a: { b: { c: { d: 'value' } } } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toEqual(undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('retry failure handling', () => {
|
||||
it('should return retry-specific details when retry fails with structured errors', async () => {
|
||||
const initialError = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Initial error' }
|
||||
]
|
||||
}
|
||||
|
||||
const retryError = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['agent'], message: 'Retry error - agent invalid' }
|
||||
]
|
||||
}
|
||||
|
||||
let callCount = 0
|
||||
global.fetch = vi.fn().mockImplementation(async () => {
|
||||
callCount++
|
||||
if (callCount === 1) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(initialError)
|
||||
} as unknown as Response
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(retryError)
|
||||
} as unknown as Response
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toContain('command.review')
|
||||
expect(result.details).toHaveLength(1)
|
||||
expect(result.details?.[0]?.message).toBe('Retry error - agent invalid')
|
||||
expect(result.error).toContain('Retry error')
|
||||
})
|
||||
|
||||
it('should fall back to initial details if retry response is unstructured', async () => {
|
||||
const initialError = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Initial error' }
|
||||
]
|
||||
}
|
||||
|
||||
let callCount = 0
|
||||
global.fetch = vi.fn().mockImplementation(async () => {
|
||||
callCount++
|
||||
if (callCount === 1) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(initialError)
|
||||
} as unknown as Response
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => 'Internal Server Error'
|
||||
} as unknown as Response
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.removedFields).toContain('command.review')
|
||||
expect(result.details?.[0]?.message).toBe('Initial error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('path deduplication', () => {
|
||||
it('should deduplicate paths before removal', async () => {
|
||||
const errorResponse = {
|
||||
success: false,
|
||||
data: {},
|
||||
errors: [
|
||||
{ path: ['command', 'review'], message: 'Error 1' },
|
||||
{ path: ['command', 'review'], message: 'Error 2' }
|
||||
]
|
||||
}
|
||||
|
||||
let callCount = 0
|
||||
global.fetch = vi.fn().mockImplementation(async () => {
|
||||
callCount++
|
||||
if (callCount === 1) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
text: async () => JSON.stringify(errorResponse)
|
||||
} as unknown as Response
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
text: async () => '{}'
|
||||
} as unknown as Response
|
||||
}) as unknown as typeof fetch
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.removedFields).toHaveLength(1)
|
||||
expect(result.removedFields?.[0]).toBe('command.review')
|
||||
})
|
||||
})
|
||||
|
||||
describe('successful patch without errors', () => {
|
||||
it('should return success without details', async () => {
|
||||
global.fetch = createMockFetch({
|
||||
ok: true,
|
||||
text: async () => '{}'
|
||||
} as Response)
|
||||
|
||||
const { patchOpenCodeConfig } = await import('../../src/services/proxy')
|
||||
const result = await patchOpenCodeConfig({ command: { review: 'test' } })
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.details).toBeUndefined()
|
||||
expect(result.removedFields).toBeUndefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -22,7 +22,7 @@ const mocks = vi.hoisted(() => ({
|
||||
computeNextRunAtForJob: vi.fn(),
|
||||
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||
forward: vi.fn(),
|
||||
addClient: vi.fn(),
|
||||
onEvent: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
@@ -59,9 +59,7 @@ vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/proxy', () => ({
|
||||
proxyToOpenCodeWithDirectory: mocks.proxyToOpenCodeWithDirectory,
|
||||
}))
|
||||
|
||||
|
||||
vi.mock('../../src/services/sse-aggregator', () => ({
|
||||
sseAggregator: {
|
||||
@@ -90,6 +88,7 @@ vi.mock('croner', () => ({
|
||||
}))
|
||||
|
||||
import { ScheduleRunner, ScheduleService } from '../../src/services/schedules'
|
||||
import type { ForwardRequest, OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
@@ -102,6 +101,23 @@ function textResponse(body: string, status: number = 200): Response {
|
||||
return new Response(body, { status })
|
||||
}
|
||||
|
||||
function createOpenCodeClientStub(): OpenCodeClient {
|
||||
return {
|
||||
forward: mocks.forward,
|
||||
forwardRaw: vi.fn(async () => new Response('', { status: 200 })),
|
||||
getJson: vi.fn(async () => ({}) as unknown),
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response('', { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response('', { status: 200 })),
|
||||
} as OpenCodeClient
|
||||
}
|
||||
|
||||
function routeForward(handler: (req: ForwardRequest) => Promise<Response> | Response) {
|
||||
mocks.forward.mockImplementation((req: ForwardRequest) => Promise.resolve(handler(req)))
|
||||
}
|
||||
|
||||
const repo = {
|
||||
id: 42,
|
||||
fullPath: '/workspace/repos/sample-project',
|
||||
@@ -166,7 +182,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('starts a run immediately and completes it after polling session messages', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-1',
|
||||
@@ -175,7 +191,7 @@ describe('ScheduleService', () => {
|
||||
}
|
||||
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-run-1' }))
|
||||
}
|
||||
@@ -222,8 +238,48 @@ describe('ScheduleService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('sends session and message JSON POSTs with Content-Type: application/json', async () => {
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-content-type',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started. Waiting for assistant response...',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-content-type' })
|
||||
}
|
||||
if (path === '/session/ses-content-type/message' && method === 'POST') {
|
||||
return textResponse(JSON.stringify({ parts: [{ type: 'text', text: 'Done.' }] }))
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
path: '/session',
|
||||
headers: expect.objectContaining({ 'Content-Type': 'application/json' }),
|
||||
}),
|
||||
)
|
||||
expect(mocks.forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
path: '/session/ses-content-type/message',
|
||||
headers: expect.objectContaining({ 'Content-Type': 'application/json' }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('completes a run immediately when the prompt endpoint returns JSON', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-2',
|
||||
@@ -233,7 +289,7 @@ describe('ScheduleService', () => {
|
||||
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-run-2' }))
|
||||
}
|
||||
@@ -264,7 +320,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('rejects a new run when the job already has a running entry', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue({
|
||||
...baseRun,
|
||||
@@ -279,7 +335,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('surfaces setup failures when the model cannot be resolved', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
|
||||
mocks.resolveOpenCodeModel.mockRejectedValueOnce(new Error('No configured models are available.'))
|
||||
mocks.updateScheduleRun.mockReturnValue({
|
||||
@@ -307,7 +363,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('marks the run failed when prompt submission is rejected after session creation', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-6',
|
||||
@@ -317,7 +373,7 @@ describe('ScheduleService', () => {
|
||||
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-run-6' }))
|
||||
}
|
||||
@@ -349,7 +405,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('cancels an in-progress run by aborting the linked session', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-3',
|
||||
@@ -365,7 +421,7 @@ describe('ScheduleService', () => {
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.updateScheduleRun.mockReturnValue(cancelledRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session/ses-run-3/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]))
|
||||
}
|
||||
@@ -380,10 +436,12 @@ describe('ScheduleService', () => {
|
||||
const result = await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(result).toEqual(cancelledRun)
|
||||
expect(mocks.proxyToOpenCodeWithDirectory).toHaveBeenCalledWith(
|
||||
'/session/ses-run-3/abort',
|
||||
'POST',
|
||||
repo.fullPath,
|
||||
expect(mocks.forward).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
path: '/session/ses-run-3/abort',
|
||||
method: 'POST',
|
||||
directory: repo.fullPath,
|
||||
}),
|
||||
)
|
||||
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
@@ -395,7 +453,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('rejects cancellation for runs that already finished', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue({
|
||||
...baseRun,
|
||||
@@ -411,7 +469,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('cancels a running entry without a linked session', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: null,
|
||||
@@ -430,11 +488,11 @@ describe('ScheduleService', () => {
|
||||
const result = await service.cancelRun(42, 7, 5)
|
||||
|
||||
expect(result).toEqual(cancelledRun)
|
||||
expect(mocks.proxyToOpenCodeWithDirectory).not.toHaveBeenCalled()
|
||||
expect(mocks.forward).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces abort failures when cancellation cannot reach OpenCode', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-7',
|
||||
@@ -442,7 +500,7 @@ describe('ScheduleService', () => {
|
||||
}
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session/ses-run-7/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]))
|
||||
}
|
||||
@@ -461,7 +519,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('marks orphaned idle runs as failed during recovery', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const orphanedRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
triggerSource: 'schedule',
|
||||
@@ -471,7 +529,7 @@ describe('ScheduleService', () => {
|
||||
}
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([orphanedRun])
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session/ses-run-4/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
@@ -506,7 +564,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('finalizes interrupted runs without a linked session during recovery', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([
|
||||
{
|
||||
@@ -531,7 +589,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('completes recoverable runs when the assistant already finished', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const completedRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
triggerSource: 'schedule',
|
||||
@@ -540,7 +598,7 @@ describe('ScheduleService', () => {
|
||||
}
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([completedRun])
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session/ses-run-8/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
@@ -568,7 +626,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('resumes recoverable runs when the session is still active', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const resumedRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
triggerSource: 'schedule',
|
||||
@@ -579,7 +637,7 @@ describe('ScheduleService', () => {
|
||||
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([resumedRun])
|
||||
mocks.getScheduleRunById.mockReturnValue(resumedRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session/ses-run-9/message' && method === 'GET') {
|
||||
messageRequests += 1
|
||||
|
||||
@@ -622,7 +680,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('lists jobs and runs through the persistence layer', () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const listedRun = { ...baseRun, status: 'completed', finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0) }
|
||||
|
||||
mocks.listScheduleJobsByRepo.mockReturnValue([job])
|
||||
@@ -635,7 +693,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('creates and updates jobs using normalized persistence input', () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const createdJob = { ...job, id: 8, name: 'Daily release summary' }
|
||||
const updatedJob = { ...job, name: 'Updated release summary' }
|
||||
|
||||
@@ -660,7 +718,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('throws when deleting or loading missing records', () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
|
||||
mocks.deleteScheduleJob.mockReturnValue(false)
|
||||
mocks.getScheduleRunById.mockReturnValue(null)
|
||||
@@ -670,7 +728,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('cancels by finalizing the run when the assistant already completed', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runningRun: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-run-5',
|
||||
@@ -684,7 +742,7 @@ describe('ScheduleService', () => {
|
||||
}
|
||||
|
||||
mocks.getScheduleRunById.mockReturnValueOnce(runningRun).mockReturnValueOnce(completedRun)
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session/ses-run-5/message' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{
|
||||
@@ -711,7 +769,7 @@ describe('ScheduleService', () => {
|
||||
|
||||
describe('skill injection in prompt', () => {
|
||||
it('appends skill content to the prompt when skillSlugs are set', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const jobWithSkills: ScheduleJob = {
|
||||
...job,
|
||||
skillMetadata: { skillSlugs: ['git-release', 'code-review'], notes: undefined },
|
||||
@@ -728,7 +786,7 @@ describe('ScheduleService', () => {
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
|
||||
let capturedPromptBody: string | undefined
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => {
|
||||
routeForward(({ path, method, body }) => {
|
||||
if (path === '/skill' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{ name: 'git-release', description: 'Git release workflow', location: '/path/SKILL.md', content: 'Release instructions here' },
|
||||
@@ -761,7 +819,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('appends skill notes when provided', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const jobWithSkillsAndNotes: ScheduleJob = {
|
||||
...job,
|
||||
skillMetadata: { skillSlugs: ['git-release'], notes: 'Focus on changelog' },
|
||||
@@ -778,7 +836,7 @@ describe('ScheduleService', () => {
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
|
||||
let capturedPromptBody: string | undefined
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => {
|
||||
routeForward(({ path, method, body }) => {
|
||||
if (path === '/skill' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([
|
||||
{ name: 'git-release', description: 'Git release workflow', location: '/path/SKILL.md', content: 'Release instructions here' },
|
||||
@@ -809,7 +867,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('does not modify the prompt when skillSlugs is empty', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const jobWithEmptySkills: ScheduleJob = {
|
||||
...job,
|
||||
skillMetadata: { skillSlugs: [], notes: 'some notes' },
|
||||
@@ -826,7 +884,7 @@ describe('ScheduleService', () => {
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
|
||||
let capturedPromptBody: string | undefined
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => {
|
||||
routeForward(({ path, method, body }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return Promise.resolve(jsonResponse({ id: 'ses-skills-3' }))
|
||||
}
|
||||
@@ -850,7 +908,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('falls back to name-only injection when skill endpoint fails', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const jobWithSkills: ScheduleJob = {
|
||||
...job,
|
||||
skillMetadata: { skillSlugs: ['git-release'], notes: undefined },
|
||||
@@ -867,7 +925,7 @@ describe('ScheduleService', () => {
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
|
||||
let capturedPromptBody: string | undefined
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => {
|
||||
routeForward(({ path, method, body }) => {
|
||||
if (path === '/skill' && method === 'GET') {
|
||||
return Promise.resolve(new Response('error', { status: 500 }))
|
||||
}
|
||||
@@ -894,7 +952,7 @@ describe('ScheduleService', () => {
|
||||
})
|
||||
|
||||
it('falls back gracefully when a skill slug is not found in the list', async () => {
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const jobWithUnknownSkill: ScheduleJob = {
|
||||
...job,
|
||||
skillMetadata: { skillSlugs: ['unknown-skill'], notes: undefined },
|
||||
@@ -911,7 +969,7 @@ describe('ScheduleService', () => {
|
||||
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||
|
||||
let capturedPromptBody: string | undefined
|
||||
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string, _dir: string, body?: string) => {
|
||||
routeForward(({ path, method, body }) => {
|
||||
if (path === '/skill' && method === 'GET') {
|
||||
return Promise.resolve(jsonResponse([]))
|
||||
}
|
||||
@@ -968,7 +1026,7 @@ describe('ScheduleRunner', () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
@@ -1002,7 +1060,7 @@ describe('ScheduleRunner', () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
@@ -1034,7 +1092,7 @@ describe('ScheduleRunner', () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
@@ -1065,7 +1123,7 @@ describe('ScheduleRunner', () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
@@ -1096,7 +1154,7 @@ describe('ScheduleRunner', () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||
|
||||
const service = new ScheduleService({} as never)
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub())
|
||||
const runner = new ScheduleRunner(service)
|
||||
await runner.start()
|
||||
|
||||
|
||||
Reference in new issue
Block a user