mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
section 8: Phase 8: Managed effective config read through api.config.ge
This commit is contained in:
1 parent
19d4ae25b6
commit
6578e11eeb
11 files changed
+406
-69
No files matched your search
@@ -21,8 +21,10 @@ import {
|
||||
OpenCodeConfigSourceInvalidError,
|
||||
OpenCodeConfigValidationError,
|
||||
readOpenCodeConfigFile,
|
||||
readOpenCodeConfigSnapshot,
|
||||
withOpenCodeConfigLock,
|
||||
} from '../services/opencode-config-file'
|
||||
import { readManagedOpenCodeConfig } from '../services/opencode-config-effective'
|
||||
import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply'
|
||||
import { redactOpenCodeConfigContent, redactOpenCodeConfigFile } from '../services/opencode-config-redact'
|
||||
import { logger } from '../utils/logger'
|
||||
@@ -53,6 +55,16 @@ function mergeMcpServerStatus(views: McpServerView[], status: McpStatusMap) {
|
||||
})
|
||||
}
|
||||
|
||||
function toClientReadErrorResponse(c: Context, error: unknown, message: string) {
|
||||
if (error instanceof ClientError) {
|
||||
if (error.reason === 'Transport') {
|
||||
return c.json({ error: 'OpenCode server unavailable' }, 503)
|
||||
}
|
||||
return c.json({ error: message }, 502)
|
||||
}
|
||||
return c.json({ error: message }, 500)
|
||||
}
|
||||
|
||||
export function createOpenCodeConfigRoutes(
|
||||
settingsService: SettingsService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
@@ -90,30 +102,41 @@ export function createOpenCodeConfigRoutes(
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to get effective OpenCode config:', error)
|
||||
if (error instanceof ClientError) {
|
||||
if (error.reason === 'Transport') {
|
||||
return c.json({ error: 'OpenCode server unavailable' }, 503)
|
||||
}
|
||||
return c.json({ error: 'Failed to get effective OpenCode config' }, 502)
|
||||
}
|
||||
return c.json({ error: 'Failed to get effective OpenCode config' }, 500)
|
||||
return toClientReadErrorResponse(c, error, 'Failed to get effective OpenCode config')
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/managed', async (c) => {
|
||||
try {
|
||||
const snapshot = await withOpenCodeConfigLock(readOpenCodeConfigSnapshot)
|
||||
const info = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
|
||||
return c.json({
|
||||
revision: snapshot.revision,
|
||||
info: options.redactSecrets
|
||||
? redactOpenCodeConfigContent(info as Record<string, unknown>).content
|
||||
: info,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to get managed OpenCode config:', error)
|
||||
return toClientReadErrorResponse(c, error, 'Failed to get managed OpenCode config')
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/mcp', async (c) => {
|
||||
try {
|
||||
const [config, status] = await Promise.all([
|
||||
withOpenCodeConfigLock(readOpenCodeConfigFile),
|
||||
const snapshot = await withOpenCodeConfigLock(readOpenCodeConfigSnapshot)
|
||||
const [info, status] = await Promise.all([
|
||||
readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources),
|
||||
readMcpStatus(openCodeClient),
|
||||
])
|
||||
const views = mcpServerViewsFromConfig(config?.content.mcp)
|
||||
const views = mcpServerViewsFromConfig(info.mcp)
|
||||
return c.json({
|
||||
revision: config?.revision ?? null,
|
||||
revision: snapshot.revision,
|
||||
servers: mergeMcpServerStatus(views, status),
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to get OpenCode MCP servers:', error)
|
||||
return c.json({ error: 'Failed to get OpenCode MCP servers' }, 500)
|
||||
return toClientReadErrorResponse(c, error, 'Failed to get OpenCode MCP servers')
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -822,21 +822,20 @@ Returns \`400\` for invalid configuration or a \`<redacted>\` value (\`paths\` l
|
||||
|
||||
### GET /opencode-config/mcp
|
||||
|
||||
List the configured MCP servers with their stored shape, enabled state, and live connection status. Use this to answer questions about MCP servers instead of reading the whole configuration. Header and environment values are never returned.
|
||||
List the configured MCP servers with their enabled state and live connection status. Use this to answer questions about MCP servers instead of reading the whole configuration. Header and environment values are never returned.
|
||||
|
||||
\`type\` is \`local\` or \`remote\`, and \`command\` or \`url\` is included for the matching type. \`enabled\` reflects the stored flag. \`shape\` is \`servers\` for a native \`mcp.servers.<name>\` entry or \`legacy\` for a flat \`mcp.<name>\` entry, so you can address the entry by the path it actually uses. \`status\` is the live OpenCode status (\`connected\`, \`pending\`, \`disabled\`, \`failed\`, or \`needs_auth\`) when the server is reachable, and \`error\` carries the failure reason.
|
||||
\`type\` is \`local\` or \`remote\`, and \`command\` or \`url\` is included for the matching type. \`enabled\` reflects the stored flag. Every entry comes from a native \`mcp.servers.<name>\` entry, so address it by that path; saving \`mcp.servers.<name>\` replaces a flat \`mcp.<name>\` entry left by an older config. \`status\` is the live OpenCode status (\`connected\`, \`pending\`, \`disabled\`, \`failed\`, or \`needs_auth\`) when the server is reachable, and \`error\` carries the failure reason.
|
||||
|
||||
**Response:**
|
||||
\`\`\`ts
|
||||
{
|
||||
revision: string | null
|
||||
revision: string
|
||||
servers: Array<{
|
||||
name: string
|
||||
type: 'local' | 'remote'
|
||||
command?: string[]
|
||||
url?: string
|
||||
enabled: boolean
|
||||
shape: 'servers' | 'legacy'
|
||||
status?: 'connected' | 'pending' | 'disabled' | 'failed' | 'needs_auth'
|
||||
error?: string
|
||||
}>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import path from 'path'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
openCodeLocation,
|
||||
type OpenCodeApi,
|
||||
type OpenCodeConfigInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { mergeOpenCodeConfigValues } from './opencode-config-file'
|
||||
|
||||
interface ManagedConfigSource {
|
||||
path: string
|
||||
}
|
||||
|
||||
export async function readManagedOpenCodeConfig(
|
||||
api: OpenCodeApi,
|
||||
sources: ReadonlyArray<ManagedConfigSource>,
|
||||
): Promise<OpenCodeConfigInfo> {
|
||||
const entries = await api.config.get(openCodeLocation(getWorkspacePath()))
|
||||
const infoByPath = new Map<string, Record<string, unknown>>()
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.type !== 'document' || !entry.path) continue
|
||||
infoByPath.set(path.resolve(entry.path), entry.info as Record<string, unknown>)
|
||||
}
|
||||
|
||||
const merged = sources.reduce<Record<string, unknown>>((current, source) => {
|
||||
const info = infoByPath.get(path.resolve(source.path))
|
||||
return info ? mergeOpenCodeConfigValues(current, info) : current
|
||||
}, {})
|
||||
|
||||
return merged as OpenCodeConfigInfo
|
||||
}
|
||||
@@ -288,7 +288,7 @@ interface MergeOpenCodeConfigValuesOptions {
|
||||
deleteNullValues?: boolean
|
||||
}
|
||||
|
||||
function mergeOpenCodeConfigValues(
|
||||
export function mergeOpenCodeConfigValues(
|
||||
target: Record<string, unknown>,
|
||||
source: Record<string, unknown>,
|
||||
options: MergeOpenCodeConfigValuesOptions = {},
|
||||
|
||||
@@ -55,22 +55,18 @@ function isSecretKey(key: string): boolean {
|
||||
|
||||
function keysAreNames(path: string[]): boolean {
|
||||
const [head] = path
|
||||
if (head === 'provider') {
|
||||
if (head === 'providers') {
|
||||
return path.length === 1 || (path.length === 3 && path[2] === 'models')
|
||||
}
|
||||
if (head === 'agent') {
|
||||
if (head === 'agents' || head === 'commands') {
|
||||
return path.length === 1
|
||||
}
|
||||
if (head === 'mcp') {
|
||||
return path.length === 1 || (path.length === 2 && path[1] === 'servers')
|
||||
return path.length === 2 && path[1] === 'servers'
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function isNameMapException(key: string): boolean {
|
||||
return key === 'servers' || key === 'timeout'
|
||||
}
|
||||
|
||||
function redactOpaqueValue(value: unknown, path: string[], redactedPaths: string[]): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item, index) => redactOpaqueValue(item, [...path, String(index)], redactedPaths))
|
||||
@@ -95,7 +91,7 @@ function redactValue(value: unknown, path: string[], redactedPaths: string[]): u
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, child]) => {
|
||||
const childPath = [...path, key]
|
||||
if (names && !isNameMapException(key)) {
|
||||
if (names) {
|
||||
return [key, redactValue(child, childPath, redactedPaths)]
|
||||
}
|
||||
if (OPAQUE_VALUE_KEYS.has(key)) {
|
||||
|
||||
@@ -253,7 +253,7 @@ describe('internal/opencode-config routes', () => {
|
||||
expect(body.actualRevision).not.toBe(initial.revision!)
|
||||
})
|
||||
|
||||
it('GET /api/internal/opencode-config/mcp lists configured servers with redacted config and live status', async () => {
|
||||
it('GET /api/internal/opencode-config/mcp lists managed servers with live status and no shape', async () => {
|
||||
await writeOpenCodeConfigFile(
|
||||
JSON.stringify({
|
||||
mcp: {
|
||||
@@ -265,11 +265,24 @@ describe('internal/opencode-config routes', () => {
|
||||
},
|
||||
local: { type: 'local', command: ['npx', 'local'], disabled: true },
|
||||
},
|
||||
legacy: { type: 'local', command: ['npx', 'legacy'], enabled: false },
|
||||
},
|
||||
}),
|
||||
'opencode.jsonc',
|
||||
)
|
||||
configGetMock.mockImplementation(() => Promise.resolve([
|
||||
{
|
||||
type: 'document',
|
||||
path: configPath('opencode.jsonc'),
|
||||
info: {
|
||||
mcp: {
|
||||
servers: {
|
||||
linear: { type: 'remote', url: 'https://linear.example.com' },
|
||||
local: { type: 'local', command: ['npx', 'local'], disabled: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]))
|
||||
mcpListMock.mockResolvedValue({
|
||||
data: [
|
||||
{ name: 'linear', status: { status: 'connected' } },
|
||||
@@ -281,31 +294,37 @@ describe('internal/opencode-config routes', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as {
|
||||
revision: string | null
|
||||
revision: string
|
||||
servers: Array<{
|
||||
name: string
|
||||
type: string
|
||||
command?: string[]
|
||||
url?: string
|
||||
enabled: boolean
|
||||
shape: string
|
||||
status?: string
|
||||
}>
|
||||
}
|
||||
expect(body.revision).toMatch(/^[a-f0-9]{64}$/)
|
||||
expect(body.servers).toEqual([
|
||||
{ name: 'legacy', type: 'local', command: ['npx', 'legacy'], enabled: false, shape: 'legacy' },
|
||||
{ name: 'linear', type: 'remote', url: 'https://linear.example.com', enabled: true, shape: 'servers', status: 'connected' },
|
||||
{ name: 'local', type: 'local', command: ['npx', 'local'], enabled: false, shape: 'servers', status: 'disabled' },
|
||||
{ name: 'linear', type: 'remote', url: 'https://linear.example.com', enabled: true, status: 'connected' },
|
||||
{ name: 'local', type: 'local', command: ['npx', 'local'], enabled: false, status: 'disabled' },
|
||||
])
|
||||
expect(body.servers.every((server) => !('shape' in server))).toBe(true)
|
||||
expect(mcpListMock).toHaveBeenCalledWith({ location: { directory: ws.workspacePath } })
|
||||
})
|
||||
|
||||
it('GET /api/internal/opencode-config/mcp returns config-only when the server is unreachable', async () => {
|
||||
it('GET /api/internal/opencode-config/mcp returns managed servers when the status list is unreachable', async () => {
|
||||
await writeOpenCodeConfigFile(
|
||||
JSON.stringify({ mcp: { servers: { local: { type: 'local', command: ['npx', 'local'] } } } }),
|
||||
'opencode.jsonc',
|
||||
)
|
||||
configGetMock.mockImplementation(() => Promise.resolve([
|
||||
{
|
||||
type: 'document',
|
||||
path: configPath('opencode.jsonc'),
|
||||
info: { mcp: { servers: { local: { type: 'local', command: ['npx', 'local'] } } } },
|
||||
},
|
||||
]))
|
||||
mcpListMock.mockRejectedValue(new Error('unreachable'))
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config/mcp', { headers: authHeaders() })
|
||||
@@ -313,10 +332,20 @@ describe('internal/opencode-config routes', () => {
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { servers: Array<Record<string, unknown>> }
|
||||
expect(body.servers).toEqual([
|
||||
{ name: 'local', type: 'local', command: ['npx', 'local'], enabled: true, shape: 'servers' },
|
||||
{ name: 'local', type: 'local', command: ['npx', 'local'], enabled: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('GET /api/internal/opencode-config/mcp returns 503 when OpenCode is unreachable', async () => {
|
||||
configGetMock.mockImplementation(() => Promise.reject(new ClientError('Transport')))
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config/mcp', { headers: authHeaders() })
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('OpenCode server unavailable')
|
||||
})
|
||||
|
||||
it('PUT /api/internal/opencode-config writes the file and applies it through a location reload without a restart', async () => {
|
||||
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc')
|
||||
|
||||
@@ -526,4 +555,76 @@ describe('internal/opencode-config routes', () => {
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('Failed to get effective OpenCode config')
|
||||
})
|
||||
|
||||
it('GET /api/internal/opencode-config/managed merges only Manager source documents and redacts secrets', async () => {
|
||||
await writeOpenCodeConfigFile(JSON.stringify({ theme: 'light' }), 'opencode.json')
|
||||
const snapshot = await writeOpenCodeConfigFile(JSON.stringify({ theme: 'dark' }), 'opencode.jsonc')
|
||||
configGetMock.mockImplementation(() => Promise.resolve([
|
||||
{
|
||||
type: 'document',
|
||||
path: configPath('opencode.json'),
|
||||
info: { theme: 'light', providers: { example: { apiKey: 'secret-key' } } },
|
||||
},
|
||||
{
|
||||
type: 'document',
|
||||
path: configPath('opencode.jsonc'),
|
||||
info: {
|
||||
theme: 'dark',
|
||||
mcp: { servers: { local: { type: 'local', command: ['npx', 'local'] } } },
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'document',
|
||||
path: path.join(ws.workspacePath, 'unmanaged', 'opencode.json'),
|
||||
info: { theme: 'ignored' },
|
||||
},
|
||||
{ type: 'directory', path: path.join(ws.workspacePath, '.config', 'opencode') },
|
||||
]))
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config/managed', { headers: authHeaders() })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
revision: snapshot.revision,
|
||||
info: {
|
||||
theme: 'dark',
|
||||
providers: { example: { apiKey: '<redacted>' } },
|
||||
mcp: { servers: { local: { type: 'local', command: ['npx', 'local'] } } },
|
||||
},
|
||||
})
|
||||
expect(configGetMock).toHaveBeenCalledWith({ location: { directory: ws.workspacePath } })
|
||||
})
|
||||
|
||||
it('GET /api/internal/opencode-config/managed reports a v1-only file through the converted entries the client returns', async () => {
|
||||
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.json')
|
||||
await writeFile(configPath('opencode.json'), JSON.stringify({
|
||||
agent: { reviewer: { mode: 'subagent' } },
|
||||
}), 'utf8')
|
||||
configGetMock.mockImplementation(() => Promise.resolve([
|
||||
{
|
||||
type: 'document',
|
||||
path: configPath('opencode.json'),
|
||||
info: { agents: { reviewer: { mode: 'subagent' } } },
|
||||
},
|
||||
]))
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config/managed', { headers: authHeaders() })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { info: Record<string, unknown> }
|
||||
expect(body.info).toEqual({ agents: { reviewer: { mode: 'subagent' } } })
|
||||
const persisted = JSON.parse(await readFile(configPath('opencode.json'), 'utf8')) as Record<string, unknown>
|
||||
expect(persisted.agent).toEqual({ reviewer: { mode: 'subagent' } })
|
||||
expect((await readOpenCodeConfigFile())?.path).toBe(configPath('opencode.json'))
|
||||
})
|
||||
|
||||
it('GET /api/internal/opencode-config/managed returns 503 when OpenCode is unreachable', async () => {
|
||||
configGetMock.mockImplementation(() => Promise.reject(new ClientError('Transport')))
|
||||
|
||||
const res = await app.request('/api/internal/opencode-config/managed', { headers: authHeaders() })
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('OpenCode server unavailable')
|
||||
})
|
||||
})
|
||||
@@ -12,12 +12,14 @@ const mockResetSettings = vi.fn()
|
||||
const mockGetLastKnownGoodConfig = vi.fn()
|
||||
const {
|
||||
mockReadOpenCodeConfigFile,
|
||||
mockReadOpenCodeConfigSnapshot,
|
||||
mockDeleteOpenCodeConfigFile,
|
||||
mockArchiveBrokenOpenCodeConfigFile,
|
||||
mockRestoreOpenCodeConfigSnapshot,
|
||||
mockApplyOpenCodeConfigUpdate,
|
||||
} = vi.hoisted(() => ({
|
||||
mockReadOpenCodeConfigFile: vi.fn(),
|
||||
mockReadOpenCodeConfigSnapshot: vi.fn(),
|
||||
mockDeleteOpenCodeConfigFile: vi.fn(),
|
||||
mockArchiveBrokenOpenCodeConfigFile: vi.fn(),
|
||||
mockRestoreOpenCodeConfigSnapshot: vi.fn(),
|
||||
@@ -183,6 +185,7 @@ vi.mock('../../src/services/opencode-config-file', async (importOriginal) => {
|
||||
return {
|
||||
...actual,
|
||||
readOpenCodeConfigFile: mockReadOpenCodeConfigFile,
|
||||
readOpenCodeConfigSnapshot: mockReadOpenCodeConfigSnapshot,
|
||||
deleteOpenCodeConfigFile: mockDeleteOpenCodeConfigFile,
|
||||
archiveBrokenOpenCodeConfigFile: mockArchiveBrokenOpenCodeConfigFile,
|
||||
restoreOpenCodeConfigSnapshot: mockRestoreOpenCodeConfigSnapshot,
|
||||
@@ -327,6 +330,7 @@ import { detectSandboxCapability } from '../../src/services/sandbox/capability'
|
||||
import { forceProcessAttestation } from '../../src/services/opencode/process-identity'
|
||||
import { sseAggregator } from '../../src/services/sse-aggregator'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
import { ClientError } from '@opencode-manager/shared/opencode'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
const mockSpawnSync = spawnSync as ReturnType<typeof vi.fn>
|
||||
@@ -363,6 +367,7 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
mockGetImportedSessionDirectories.mockReset()
|
||||
mockRelinkReposFromSessionDirectories.mockReset()
|
||||
mockReadOpenCodeConfigFile.mockReset()
|
||||
mockReadOpenCodeConfigSnapshot.mockReset()
|
||||
mockDeleteOpenCodeConfigFile.mockReset()
|
||||
mockArchiveBrokenOpenCodeConfigFile.mockReset()
|
||||
mockRestoreOpenCodeConfigSnapshot.mockReset()
|
||||
@@ -443,6 +448,114 @@ describe('Settings Routes - OpenCode Upgrade', () => {
|
||||
expect(json.error).toBe('No OpenCode config file found')
|
||||
})
|
||||
|
||||
it('returns the managed config merged from Manager source documents', async () => {
|
||||
mockReadOpenCodeConfigSnapshot.mockResolvedValueOnce({
|
||||
sources: [
|
||||
{ name: 'opencode.json', path: '/tmp/test-workspace/config/opencode.json', rawContent: '{}', content: {}, isValid: true, updatedAt: 1 },
|
||||
{ name: 'opencode.jsonc', path: '/tmp/test-workspace/config/opencode.jsonc', rawContent: '{}', content: {}, isValid: true, updatedAt: 1 },
|
||||
],
|
||||
content: {},
|
||||
revision: 'rev-managed',
|
||||
updatedAt: 1,
|
||||
path: '/tmp/test-workspace/config/opencode.jsonc',
|
||||
rawContent: '{}',
|
||||
})
|
||||
const configGet = vi.fn(async () => [
|
||||
{ type: 'document', path: '/tmp/test-workspace/config/opencode.json', info: { theme: 'light', model: 'a/b' } },
|
||||
{ type: 'document', path: '/tmp/test-workspace/config/opencode.jsonc', info: { theme: 'dark' } },
|
||||
{ type: 'document', path: '/tmp/test-workspace/unmanaged.json', info: { theme: 'ignored' } },
|
||||
{ type: 'directory', path: '/tmp/test-workspace' },
|
||||
])
|
||||
const app = createSettingsRoutes(
|
||||
testDb,
|
||||
{ getGitEnvironment: vi.fn().mockReturnValue({}) } as any,
|
||||
createStubOpenCodeClient({ api: { config: { get: configGet } } as unknown as OpenCodeClient['api'] }),
|
||||
)
|
||||
|
||||
const res = await app.fetch(new Request('http://localhost/opencode-config/managed'))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
revision: 'rev-managed',
|
||||
info: { theme: 'dark', model: 'a/b' },
|
||||
})
|
||||
expect(configGet).toHaveBeenCalledWith({ location: { directory: '/tmp/test-workspace' } })
|
||||
})
|
||||
|
||||
it('returns 503 from GET /opencode-config/managed when OpenCode is unavailable', async () => {
|
||||
mockReadOpenCodeConfigSnapshot.mockResolvedValueOnce({
|
||||
sources: [
|
||||
{ name: 'opencode.jsonc', path: '/tmp/test-workspace/config/opencode.jsonc', rawContent: '{}', content: {}, isValid: true, updatedAt: 1 },
|
||||
],
|
||||
content: {},
|
||||
revision: 'rev-managed',
|
||||
updatedAt: 1,
|
||||
path: '/tmp/test-workspace/config/opencode.jsonc',
|
||||
rawContent: '{}',
|
||||
})
|
||||
const app = createSettingsRoutes(
|
||||
testDb,
|
||||
{ getGitEnvironment: vi.fn().mockReturnValue({}) } as any,
|
||||
createStubOpenCodeClient({
|
||||
api: {
|
||||
config: {
|
||||
get: vi.fn(async () => {
|
||||
throw new ClientError('Transport')
|
||||
}),
|
||||
},
|
||||
} as unknown as OpenCodeClient['api'],
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await app.fetch(new Request('http://localhost/opencode-config/managed'))
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
expect(json.error).toBe('OpenCode server unavailable')
|
||||
})
|
||||
|
||||
it('returns MCP servers from the managed config without a shape field', async () => {
|
||||
mockReadOpenCodeConfigSnapshot.mockResolvedValueOnce({
|
||||
sources: [
|
||||
{ name: 'opencode.jsonc', path: '/tmp/test-workspace/config/opencode.jsonc', rawContent: '{}', content: {}, isValid: true, updatedAt: 1 },
|
||||
],
|
||||
content: {},
|
||||
revision: 'rev-managed',
|
||||
updatedAt: 1,
|
||||
path: '/tmp/test-workspace/config/opencode.jsonc',
|
||||
rawContent: '{}',
|
||||
})
|
||||
const configGet = vi.fn(async () => [
|
||||
{
|
||||
type: 'document',
|
||||
path: '/tmp/test-workspace/config/opencode.jsonc',
|
||||
info: { mcp: { servers: { local: { type: 'local', command: ['npx', 'local'] } } } },
|
||||
},
|
||||
])
|
||||
const mcpList = vi.fn(async () => ({
|
||||
data: [{ name: 'local', status: { status: 'connected' } }],
|
||||
}))
|
||||
const app = createSettingsRoutes(
|
||||
testDb,
|
||||
{ getGitEnvironment: vi.fn().mockReturnValue({}) } as any,
|
||||
createStubOpenCodeClient({
|
||||
api: { config: { get: configGet }, mcp: { list: mcpList } } as unknown as OpenCodeClient['api'],
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await app.fetch(new Request('http://localhost/opencode-config/mcp'))
|
||||
const json = await res.json() as { revision: string; servers: Array<Record<string, unknown>> }
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(json).toEqual({
|
||||
revision: 'rev-managed',
|
||||
servers: [
|
||||
{ name: 'local', type: 'local', command: ['npx', 'local'], enabled: true, status: 'connected' },
|
||||
],
|
||||
})
|
||||
expect(json.servers.every((server) => !('shape' in server))).toBe(true)
|
||||
})
|
||||
|
||||
it('maps a restart-pending apply result to 200 with restartRequired', async () => {
|
||||
const config = {
|
||||
path: '/tmp/test-workspace/.config/opencode.json',
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { ClientError, openCodeLocation, type OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import { readManagedOpenCodeConfig } from '../../src/services/opencode-config-effective'
|
||||
|
||||
function stubApi(entries: unknown[]) {
|
||||
const get = vi.fn(async () => entries)
|
||||
return { api: { config: { get } } as unknown as OpenCodeApi, get }
|
||||
}
|
||||
|
||||
describe('readManagedOpenCodeConfig', () => {
|
||||
it('merges only the documents whose path is a Manager source, in source order', async () => {
|
||||
const { api, get } = stubApi([
|
||||
{
|
||||
type: 'document',
|
||||
path: '/workspace/config/opencode.json',
|
||||
info: { theme: 'light', mcp: { servers: { local: { type: 'local', command: ['npx', 'local'] } } } },
|
||||
},
|
||||
{
|
||||
type: 'document',
|
||||
path: '/workspace/config/opencode.jsonc',
|
||||
info: { theme: 'dark', mcp: { servers: { remote: { type: 'remote', url: 'https://remote.example.com' } } } },
|
||||
},
|
||||
{ type: 'document', path: '/workspace/unmanaged/opencode.json', info: { theme: 'ignored' } },
|
||||
{ type: 'document', info: { theme: 'pathless' } },
|
||||
{ type: 'directory', path: '/workspace/config' },
|
||||
])
|
||||
|
||||
const info = await readManagedOpenCodeConfig(api, [
|
||||
{ path: '/workspace/config/opencode.json' },
|
||||
{ path: '/workspace/config/opencode.jsonc' },
|
||||
])
|
||||
|
||||
expect(info).toEqual({
|
||||
theme: 'dark',
|
||||
mcp: {
|
||||
servers: {
|
||||
local: { type: 'local', command: ['npx', 'local'] },
|
||||
remote: { type: 'remote', url: 'https://remote.example.com' },
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(get).toHaveBeenCalledWith(openCodeLocation(getWorkspacePath()))
|
||||
})
|
||||
|
||||
it('resolves both the source and reported path before matching', async () => {
|
||||
const { api } = stubApi([
|
||||
{
|
||||
type: 'document',
|
||||
path: '/workspace/config/./opencode.json',
|
||||
info: { theme: 'dark' },
|
||||
},
|
||||
])
|
||||
|
||||
await expect(
|
||||
readManagedOpenCodeConfig(api, [{ path: '/workspace/config/opencode.json' }]),
|
||||
).resolves.toEqual({ theme: 'dark' })
|
||||
})
|
||||
|
||||
it('returns the converted v1 entries the server reports for a Manager file', async () => {
|
||||
const { api } = stubApi([
|
||||
{
|
||||
type: 'document',
|
||||
path: '/workspace/config/opencode.json',
|
||||
info: { agents: { reviewer: { mode: 'subagent' } } },
|
||||
},
|
||||
])
|
||||
|
||||
await expect(
|
||||
readManagedOpenCodeConfig(api, [{ path: '/workspace/config/opencode.json' }]),
|
||||
).resolves.toEqual({ agents: { reviewer: { mode: 'subagent' } } })
|
||||
})
|
||||
|
||||
it('returns an empty config when no reported document matches a Manager source', async () => {
|
||||
const { api } = stubApi([
|
||||
{ type: 'document', path: '/workspace/other/opencode.json', info: { theme: 'dark' } },
|
||||
])
|
||||
|
||||
await expect(
|
||||
readManagedOpenCodeConfig(api, [{ path: '/workspace/config/opencode.json' }]),
|
||||
).resolves.toEqual({})
|
||||
})
|
||||
|
||||
it('propagates client errors', async () => {
|
||||
const get = vi.fn(async () => {
|
||||
throw new ClientError('Transport')
|
||||
})
|
||||
const api = { config: { get } } as unknown as OpenCodeApi
|
||||
|
||||
await expect(
|
||||
readManagedOpenCodeConfig(api, [{ path: '/workspace/config/opencode.json' }]),
|
||||
).rejects.toBeInstanceOf(ClientError)
|
||||
})
|
||||
})
|
||||
@@ -96,7 +96,7 @@ describe('redactOpenCodeConfigFile', () => {
|
||||
expect(redacted.redactedPaths).toEqual([])
|
||||
})
|
||||
|
||||
it('does not mask server, provider, or model names that look like secret keys', () => {
|
||||
it('does not mask server, provider, agent, command, or model names that look like secret keys', () => {
|
||||
const redacted = redactOpenCodeConfigFile(
|
||||
buildConfig({
|
||||
mcp: {
|
||||
@@ -108,12 +108,14 @@ describe('redactOpenCodeConfigFile', () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
provider: {
|
||||
providers: {
|
||||
'secret-provider': {
|
||||
apiKey: 'provider-secret',
|
||||
models: { 'token-model': { name: 'gpt' } },
|
||||
},
|
||||
},
|
||||
agents: { 'token-agent': { model: 'openai/gpt' } },
|
||||
commands: { 'secret-command': { template: 'hello' } },
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -127,16 +129,18 @@ describe('redactOpenCodeConfigFile', () => {
|
||||
},
|
||||
},
|
||||
},
|
||||
provider: {
|
||||
providers: {
|
||||
'secret-provider': {
|
||||
apiKey: '<redacted>',
|
||||
models: { 'token-model': { name: 'gpt' } },
|
||||
},
|
||||
},
|
||||
agents: { 'token-agent': { model: 'openai/gpt' } },
|
||||
commands: { 'secret-command': { template: 'hello' } },
|
||||
})
|
||||
expect(redacted.redactedPaths).toEqual([
|
||||
'mcp.servers.github-token.headers.Authorization',
|
||||
'provider.secret-provider.apiKey',
|
||||
'providers.secret-provider.apiKey',
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@@ -49,37 +49,28 @@ describe('mcpServersFromConfig', () => {
|
||||
})
|
||||
|
||||
describe('mcpServerViewsFromConfig', () => {
|
||||
it('normalizes native and legacy servers, reporting each shape and enabled state', () => {
|
||||
it('normalizes native servers and their enabled state', () => {
|
||||
expect(
|
||||
mcpServerViewsFromConfig({
|
||||
timeout: { catalog: 5000 },
|
||||
legacy: { type: 'local', command: ['npx', 'legacy'], enabled: false },
|
||||
flat: { type: 'local', command: ['npx', 'flat'], enabled: false },
|
||||
servers: {
|
||||
remote: { type: 'remote', url: 'https://native.example.com', disabled: true },
|
||||
local: { type: 'local', command: ['npx', 'native'] },
|
||||
},
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
name: 'legacy',
|
||||
type: 'local',
|
||||
command: ['npx', 'legacy'],
|
||||
enabled: false,
|
||||
shape: 'legacy',
|
||||
},
|
||||
{
|
||||
name: 'local',
|
||||
type: 'local',
|
||||
command: ['npx', 'native'],
|
||||
enabled: true,
|
||||
shape: 'servers',
|
||||
},
|
||||
{
|
||||
name: 'remote',
|
||||
type: 'remote',
|
||||
url: 'https://native.example.com',
|
||||
enabled: false,
|
||||
shape: 'servers',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
@@ -27,43 +27,27 @@ export function mcpServersFromConfig(mcp: unknown): Record<string, McpServerConf
|
||||
return Object.fromEntries(Object.entries(mcp.servers).filter((entry): entry is [string, McpServerConfig] => isMcpServerConfig(entry[1])))
|
||||
}
|
||||
|
||||
export type McpServerShape = 'servers' | 'legacy'
|
||||
|
||||
export interface McpServerView {
|
||||
name: string
|
||||
type: 'local' | 'remote'
|
||||
command?: string[]
|
||||
url?: string
|
||||
enabled: boolean
|
||||
shape: McpServerShape
|
||||
}
|
||||
|
||||
function toMcpServerView(
|
||||
name: string,
|
||||
config: McpServerConfig,
|
||||
enabled: boolean,
|
||||
shape: McpServerShape,
|
||||
): McpServerView {
|
||||
function toMcpServerView(name: string, config: McpServerConfig, enabled: boolean): McpServerView {
|
||||
return {
|
||||
name,
|
||||
type: config.type,
|
||||
...(config.type === 'local' ? { command: config.command } : { url: config.url }),
|
||||
enabled,
|
||||
shape,
|
||||
}
|
||||
}
|
||||
|
||||
export function mcpServerViewsFromConfig(mcp: unknown): McpServerView[] {
|
||||
if (!isRecord(mcp)) return []
|
||||
const nativeViews = Object.entries(mcpServersFromConfig(mcp)).map(([name, config]) =>
|
||||
toMcpServerView(name, config, config.disabled !== true, 'servers'),
|
||||
)
|
||||
const legacyViews = Object.entries(mcp).flatMap(([name, value]) => {
|
||||
if (name === 'servers' || name === 'timeout' || !isMcpServerConfig(value)) return []
|
||||
const enabled = (value as { enabled?: unknown }).enabled !== false
|
||||
return [toMcpServerView(name, value, enabled, 'legacy')]
|
||||
})
|
||||
return [...nativeViews, ...legacyViews].sort((left, right) => left.name.localeCompare(right.name))
|
||||
return Object.entries(mcpServersFromConfig(mcp))
|
||||
.map(([name, config]) => toMcpServerView(name, config, config.disabled !== true))
|
||||
.sort((left, right) => left.name.localeCompare(right.name))
|
||||
}
|
||||
|
||||
export function mcpStatusByName(servers: McpServer[]): McpStatusMap {
|
||||
|
||||
Reference in new issue
Block a user