mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix: keep config references on save and apply review batch 2 fixes (OM-179)
This commit is contained in:
1 parent
49bb4ebd36
commit
8a6fd56e9a
17 files changed
+524
-60
No files matched your search
@@ -19,7 +19,8 @@ import type { OpenCodeAgentConfig, OpenCodeApi, OpenCodeConfigInfo } from '@open
|
|||||||
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
|
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
|
||||||
import type { Database } from 'bun:sqlite'
|
import type { Database } from 'bun:sqlite'
|
||||||
import { ensureAssistantRepo } from '../db/queries'
|
import { ensureAssistantRepo } from '../db/queries'
|
||||||
import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, type OpenCodeConfigPathOperation } from './opencode-config-file'
|
import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, V1_ENTITY_PATHS, type OpenCodeConfigPathOperation } from './opencode-config-file'
|
||||||
|
import { readConfigValueAtPath, restoreOpenCodeConfigReferences } from './opencode-config-references'
|
||||||
import { readOpenCodeConfigDocuments } from './opencode-config-effective'
|
import { readOpenCodeConfigDocuments } from './opencode-config-effective'
|
||||||
import { logger } from '../utils/logger'
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
@@ -788,9 +789,9 @@ Read the merged persisted global configuration and its source files. Returns \`4
|
|||||||
|
|
||||||
### PATCH /opencode-config
|
### PATCH /opencode-config
|
||||||
|
|
||||||
Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; every path you do not name is left untouched, and a \`null\` value removes a path. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved.
|
Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; a path you do not name keeps its current value, and a \`null\` value removes a path. Naming a v2 entity (\`agents.<name>\`, \`commands.<name>\`, \`providers.<id>\`, \`mcp.servers.<name>\`, or \`permissions\`) also deletes its v1 counterpart (\`agent.<name>\`, \`command.<name>\`, \`provider.<id>\`, \`mcp.<name>\`, or \`permission\`) in the same edit. \`{env:…}\` and \`{file:…}\` references in fields whose value is sent back unchanged are kept. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved.
|
||||||
|
|
||||||
Send \`expectedRevision\` from a read. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content.
|
Send \`expectedRevision\` from a read. A \`409\` means either \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source (the \`OpenCodeConfigShadowedRemovalError\` case): read again and reconcile rather than retrying stale content.
|
||||||
|
|
||||||
**Request Body:**
|
**Request Body:**
|
||||||
\`\`\`ts
|
\`\`\`ts
|
||||||
@@ -818,11 +819,11 @@ Send \`expectedRevision\` from a read. A \`409\` means the source files changed:
|
|||||||
\`\`\`
|
\`\`\`
|
||||||
|
|
||||||
**Response:**
|
**Response:**
|
||||||
Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing. Saving never silently drops unsupported fields.
|
Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing.
|
||||||
|
|
||||||
The response adds \`restartRequired: true\` only when the automatic reload failed, for example because the OpenCode server is unavailable.
|
The response adds \`restartRequired: true\` only when the automatic reload failed, for example because the OpenCode server is unavailable.
|
||||||
|
|
||||||
Returns \`400\` for invalid configuration or a \`<redacted>\` value (\`paths\` lists them), and \`409\` for a stale revision.
|
Returns \`400\` for invalid configuration or a \`<redacted>\` value (\`paths\` lists them), and \`409\` when \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source.
|
||||||
|
|
||||||
### GET /opencode-config/mcp
|
### GET /opencode-config/mcp
|
||||||
|
|
||||||
@@ -1359,9 +1360,26 @@ function parseAssistantOpenCodeConfig(rawContent: string): Record<string, unknow
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the v1 container that OpenCode converts into the given v2 container.
|
||||||
|
*/
|
||||||
|
function resolveV1EntityPath(v2Path: readonly string[]): string[] {
|
||||||
|
const mapping = V1_ENTITY_PATHS.find(
|
||||||
|
(entry) => entry.v2Path.length === v2Path.length && entry.v2Path.every((segment, index) => segment === v2Path[index]),
|
||||||
|
)
|
||||||
|
if (mapping === undefined) {
|
||||||
|
throw new Error(`No v1 config path is defined for ${v2Path.join('.')}`)
|
||||||
|
}
|
||||||
|
return [...mapping.v1Path]
|
||||||
|
}
|
||||||
|
|
||||||
|
const ASSISTANT_V1_AGENT_PATH = resolveV1EntityPath(['agents'])
|
||||||
|
const ASSISTANT_V1_PERMISSION_PATH = resolveV1EntityPath(['permissions'])
|
||||||
|
|
||||||
function hasAssistantV1OpenCodeConfig(config: Record<string, unknown>): boolean {
|
function hasAssistantV1OpenCodeConfig(config: Record<string, unknown>): boolean {
|
||||||
if (config.permission !== undefined) return true
|
if (readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) return true
|
||||||
return isRecord(config.agent) && isRecord(config.agent.assistant)
|
const v1Agents = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH)
|
||||||
|
return isRecord(v1Agents) && isRecord(v1Agents[ASSISTANT_DEFAULT_AGENT_NAME])
|
||||||
}
|
}
|
||||||
|
|
||||||
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean {
|
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean {
|
||||||
@@ -1377,9 +1395,7 @@ function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean
|
|||||||
}
|
}
|
||||||
|
|
||||||
function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInfo): boolean {
|
function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInfo): boolean {
|
||||||
const agent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
return normalizeAssistantAgent(config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]) !== undefined
|
||||||
if (typeof agent !== 'object' || agent === null) return false
|
|
||||||
return matchesGeneratedAssistantAgentPrompt(agent.system)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
|
function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
|
||||||
@@ -1387,15 +1403,24 @@ function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
|
|||||||
return mode === 'primary' || mode === 'all' ? mode : 'primary'
|
return mode === 'primary' || mode === 'all' ? mode : 'primary'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reduces a generated assistant persona to a mode-only agent, leaving a customized persona to the caller.
|
||||||
|
*/
|
||||||
|
function normalizeAssistantAgent(agent: unknown): OpenCodeAgentConfig | undefined {
|
||||||
|
if (!isRecord(agent) || !matchesGeneratedAssistantAgentPrompt(agent.system)) return undefined
|
||||||
|
return { mode: resolveValidAssistantMode(agent) }
|
||||||
|
}
|
||||||
|
|
||||||
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo {
|
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo {
|
||||||
const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||||
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...config,
|
...config,
|
||||||
agents: {
|
agents: {
|
||||||
...(config.agents ?? {}),
|
...(config.agents ?? {}),
|
||||||
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: validMode },
|
[ASSISTANT_DEFAULT_AGENT_NAME]: normalizeAssistantAgent(existingAssistantAgent) ?? {
|
||||||
|
mode: resolveValidAssistantMode(existingAssistantAgent),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1404,20 +1429,10 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo
|
|||||||
const generated = buildAssistantOpenCodeConfig()
|
const generated = buildAssistantOpenCodeConfig()
|
||||||
const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
|
||||||
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
const validMode = resolveValidAssistantMode(existingAssistantAgent)
|
||||||
|
const mergedAssistantAgent: OpenCodeAgentConfig = normalizeAssistantAgent(existingAssistantAgent) ?? {
|
||||||
const existingIsGenerated = typeof existingAssistantAgent === 'object' &&
|
...(existingAssistantAgent ?? {}),
|
||||||
existingAssistantAgent !== null &&
|
mode: validMode,
|
||||||
matchesGeneratedAssistantAgentPrompt(existingAssistantAgent.system)
|
disabled: false,
|
||||||
|
|
||||||
let mergedAssistantAgent: OpenCodeAgentConfig
|
|
||||||
if (existingIsGenerated) {
|
|
||||||
mergedAssistantAgent = { mode: validMode }
|
|
||||||
} else {
|
|
||||||
mergedAssistantAgent = {
|
|
||||||
...(typeof existingAssistantAgent === 'object' && existingAssistantAgent !== null ? existingAssistantAgent : {}),
|
|
||||||
mode: validMode,
|
|
||||||
disabled: false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -1432,15 +1447,20 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildAssistantV1ConfigRemovalPaths(config: Record<string, unknown>): string[][] {
|
function buildAssistantV1ConfigRemovalPaths(
|
||||||
const v1Agent = config.agent
|
config: Record<string, unknown>,
|
||||||
|
convertedPermissions: unknown,
|
||||||
|
): string[][] {
|
||||||
|
const v1Agent = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH)
|
||||||
const removeWholeAgent = isRecord(v1Agent) &&
|
const removeWholeAgent = isRecord(v1Agent) &&
|
||||||
Object.keys(v1Agent).length === 1 &&
|
Object.keys(v1Agent).length === 1 &&
|
||||||
isRecord(v1Agent.assistant)
|
isRecord(v1Agent[ASSISTANT_DEFAULT_AGENT_NAME])
|
||||||
|
|
||||||
const paths: string[][] = [removeWholeAgent ? ['agent'] : ['agent', ASSISTANT_DEFAULT_AGENT_NAME]]
|
const paths: string[][] = [
|
||||||
if (config.permission !== undefined) {
|
removeWholeAgent ? ASSISTANT_V1_AGENT_PATH : [...ASSISTANT_V1_AGENT_PATH, ASSISTANT_DEFAULT_AGENT_NAME],
|
||||||
paths.push(['permission'])
|
]
|
||||||
|
if (convertedPermissions !== undefined && readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) {
|
||||||
|
paths.push(ASSISTANT_V1_PERMISSION_PATH)
|
||||||
}
|
}
|
||||||
return paths
|
return paths
|
||||||
}
|
}
|
||||||
@@ -1449,12 +1469,22 @@ function resolveConvertedAssistantAgent(
|
|||||||
agent: OpenCodeAgentConfig | undefined,
|
agent: OpenCodeAgentConfig | undefined,
|
||||||
v1Agent: unknown,
|
v1Agent: unknown,
|
||||||
): OpenCodeAgentConfig {
|
): OpenCodeAgentConfig {
|
||||||
if (agent === undefined) {
|
return normalizeAssistantAgent(agent) ?? agent ?? { mode: resolveValidAssistantMode(v1Agent) }
|
||||||
return { mode: resolveValidAssistantMode(v1Agent) }
|
}
|
||||||
}
|
|
||||||
return matchesGeneratedAssistantAgentPrompt(agent.system)
|
function restoreAssistantAgentReferences(
|
||||||
? { mode: resolveValidAssistantMode(agent) }
|
agent: OpenCodeAgentConfig,
|
||||||
: agent
|
resolved: OpenCodeConfigInfo,
|
||||||
|
raw: Record<string, unknown>,
|
||||||
|
): OpenCodeAgentConfig {
|
||||||
|
const restored = restoreOpenCodeConfigReferences(
|
||||||
|
{ agents: { [ASSISTANT_DEFAULT_AGENT_NAME]: agent } },
|
||||||
|
resolved as Record<string, unknown>,
|
||||||
|
raw,
|
||||||
|
)
|
||||||
|
const restoredAgent = readConfigValueAtPath(restored, ['agents', ASSISTANT_DEFAULT_AGENT_NAME])
|
||||||
|
if (typeof restoredAgent !== 'object' || restoredAgent === null) return agent
|
||||||
|
return restoredAgent as OpenCodeAgentConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1476,13 +1506,18 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom
|
|||||||
const documentInfo = documents.get(path.resolve(opencodeJsonPath))
|
const documentInfo = documents.get(path.resolve(opencodeJsonPath))
|
||||||
if (documentInfo === undefined) return false
|
if (documentInfo === undefined) return false
|
||||||
|
|
||||||
const v1AssistantAgent = isRecord(rawConfig.agent) ? rawConfig.agent.assistant : undefined
|
const v1Assistants = readConfigValueAtPath(rawConfig, ASSISTANT_V1_AGENT_PATH)
|
||||||
|
const v1AssistantAgent = isRecord(v1Assistants) ? v1Assistants[ASSISTANT_DEFAULT_AGENT_NAME] : undefined
|
||||||
const setOperations: OpenCodeConfigPathOperation[] = [
|
const setOperations: OpenCodeConfigPathOperation[] = [
|
||||||
{
|
{
|
||||||
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
|
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
|
||||||
value: resolveConvertedAssistantAgent(
|
value: restoreAssistantAgentReferences(
|
||||||
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
|
resolveConvertedAssistantAgent(
|
||||||
v1AssistantAgent,
|
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
|
||||||
|
v1AssistantAgent,
|
||||||
|
),
|
||||||
|
documentInfo,
|
||||||
|
rawConfig,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
@@ -1491,7 +1526,7 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom
|
|||||||
}
|
}
|
||||||
|
|
||||||
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
|
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
|
||||||
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig)) {
|
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) {
|
||||||
updatedText = removeOpenCodeConfigProperty(updatedText, removalPath)
|
updatedText = removeOpenCodeConfigProperty(updatedText, removalPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,12 @@ import {
|
|||||||
restoreOpenCodeConfigSnapshot,
|
restoreOpenCodeConfigSnapshot,
|
||||||
serializeOpenCodeConfigSnapshot,
|
serializeOpenCodeConfigSnapshot,
|
||||||
updateOpenCodeConfigFile,
|
updateOpenCodeConfigFile,
|
||||||
|
type OpenCodeConfigSnapshot,
|
||||||
type OpenCodeConfigUpdateMode,
|
type OpenCodeConfigUpdateMode,
|
||||||
withOpenCodeConfigLock,
|
withOpenCodeConfigLock,
|
||||||
} from './opencode-config-file'
|
} from './opencode-config-file'
|
||||||
|
import { readManagedOpenCodeConfig } from './opencode-config-effective'
|
||||||
|
import { restoreOpenCodeConfigReferences } from './opencode-config-references'
|
||||||
import { opencodeServerManager } from './opencode-single-server'
|
import { opencodeServerManager } from './opencode-single-server'
|
||||||
import { reloadOpenCodeConfig } from './opencode-restart'
|
import { reloadOpenCodeConfig } from './opencode-restart'
|
||||||
import type { OpenCodeClient } from './opencode/client'
|
import type { OpenCodeClient } from './opencode/client'
|
||||||
@@ -98,6 +101,20 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC
|
|||||||
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0
|
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function keepOpenCodeConfigReferences(
|
||||||
|
patch: Record<string, unknown>,
|
||||||
|
snapshot: OpenCodeConfigSnapshot,
|
||||||
|
openCodeClient: OpenCodeClient,
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
try {
|
||||||
|
const resolved = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
|
||||||
|
return restoreOpenCodeConfigReferences(patch, resolved as Record<string, unknown>, snapshot.content)
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Could not read the resolved OpenCode config; saving the patch without reference restoration:', error)
|
||||||
|
return patch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function applyOpenCodeConfigUpdate(
|
export async function applyOpenCodeConfigUpdate(
|
||||||
input: ApplyOpenCodeConfigOptions,
|
input: ApplyOpenCodeConfigOptions,
|
||||||
): Promise<ApplyOpenCodeConfigResult> {
|
): Promise<ApplyOpenCodeConfigResult> {
|
||||||
@@ -106,8 +123,11 @@ export async function applyOpenCodeConfigUpdate(
|
|||||||
|
|
||||||
const snapshot = await readOpenCodeConfigSnapshot()
|
const snapshot = await readOpenCodeConfigSnapshot()
|
||||||
const previous = await readOpenCodeConfigFile(snapshot)
|
const previous = await readOpenCodeConfigFile(snapshot)
|
||||||
|
const savedContent = mode === 'merge' && typeof content !== 'string'
|
||||||
|
? await keepOpenCodeConfigReferences(content, snapshot, input.openCodeClient)
|
||||||
|
: content
|
||||||
|
|
||||||
const next = await updateOpenCodeConfigFile(content, { source, expectedRevision, snapshot, mode })
|
const next = await updateOpenCodeConfigFile(savedContent, { source, expectedRevision, snapshot, mode })
|
||||||
|
|
||||||
if (previous?.isValid) {
|
if (previous?.isValid) {
|
||||||
const snapshot = serializeOpenCodeConfigSnapshot(previous)
|
const snapshot = serializeOpenCodeConfigSnapshot(previous)
|
||||||
|
|||||||
@@ -153,7 +153,8 @@ export interface OpenCodeConfigPathOperation {
|
|||||||
value: unknown
|
value: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
interface OpenCodeConfigV1EntityPath {
|
/** Maps a v2 config entity container to the v1 container OpenCode converts it from. */
|
||||||
|
export interface OpenCodeConfigV1EntityPath {
|
||||||
v2Path: string[]
|
v2Path: string[]
|
||||||
v1Path: string[]
|
v1Path: string[]
|
||||||
named: boolean
|
named: boolean
|
||||||
@@ -165,7 +166,7 @@ interface OpenCodeConfigV1EntityRemoval {
|
|||||||
container?: JSONPath
|
container?: JSONPath
|
||||||
}
|
}
|
||||||
|
|
||||||
const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [
|
export const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [
|
||||||
{ v2Path: ['agents'], v1Path: ['agent'], named: true },
|
{ v2Path: ['agents'], v1Path: ['agent'], named: true },
|
||||||
{ v2Path: ['commands'], v1Path: ['command'], named: true },
|
{ v2Path: ['commands'], v1Path: ['command'], named: true },
|
||||||
{ v2Path: ['providers'], v1Path: ['provider'], named: true },
|
{ v2Path: ['providers'], v1Path: ['provider'], named: true },
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
import { isRecord } from '@opencode-manager/shared/utils'
|
||||||
import type { OpenCodeConfigFile } from '../types/settings'
|
import type { OpenCodeConfigFile } from '../types/settings'
|
||||||
import { isRecord } from './opencode/enforcement-config'
|
|
||||||
import { OPENCODE_CONFIG_REDACTED_VALUE } from './opencode-config-file'
|
import { OPENCODE_CONFIG_REDACTED_VALUE } from './opencode-config-file'
|
||||||
|
|
||||||
const SECRET_KEYS = new Set([
|
const SECRET_KEYS = new Set([
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { isRecord } from '@opencode-manager/shared/utils'
|
||||||
|
import { V1_ENTITY_PATHS, type OpenCodeConfigV1EntityPath } from './opencode-config-file'
|
||||||
|
|
||||||
|
const CONFIG_REFERENCE_PATTERN = /\{(?:env|file):[^}]+\}/
|
||||||
|
|
||||||
|
type FieldAlias = readonly [v2Prefix: readonly string[], v1Prefix: readonly string[]]
|
||||||
|
|
||||||
|
const V1_FIELD_ALIASES: Readonly<Record<string, readonly FieldAlias[]>> = {
|
||||||
|
agents: [
|
||||||
|
[['system'], ['prompt']],
|
||||||
|
[['request', 'body', 'temperature'], ['temperature']],
|
||||||
|
[['request', 'body', 'top_p'], ['top_p']],
|
||||||
|
[['request', 'body'], ['options']],
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
[['settings', 'baseURL'], ['api']],
|
||||||
|
[['headers'], ['options', 'headers']],
|
||||||
|
[['body'], ['options', 'body']],
|
||||||
|
[['settings'], ['options']],
|
||||||
|
],
|
||||||
|
'mcp.servers': [
|
||||||
|
[['oauth', 'client_id'], ['oauth', 'clientId']],
|
||||||
|
[['oauth', 'client_secret'], ['oauth', 'clientSecret']],
|
||||||
|
[['oauth', 'redirect_uri'], ['oauth', 'redirectUri']],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RawEntityCandidate {
|
||||||
|
entity: unknown
|
||||||
|
aliases: readonly FieldAlias[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads a nested config value by object keys and array indices, or `undefined` when absent. */
|
||||||
|
export function readConfigValueAtPath(value: unknown, path: readonly string[]): unknown {
|
||||||
|
let current = value
|
||||||
|
for (const segment of path) {
|
||||||
|
if (Array.isArray(current)) {
|
||||||
|
current = current[Number(segment)]
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (!isRecord(current) || !Object.prototype.hasOwnProperty.call(current, segment)) return undefined
|
||||||
|
current = current[segment]
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
|
||||||
|
function startsWithPath(path: readonly string[], prefix: readonly string[]): boolean {
|
||||||
|
return prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment)
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRawReference(candidates: readonly RawEntityCandidate[], path: readonly string[]): string | undefined {
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const paths = [
|
||||||
|
path,
|
||||||
|
...candidate.aliases
|
||||||
|
.filter(([v2Prefix]) => startsWithPath(path, v2Prefix))
|
||||||
|
.map(([v2Prefix, v1Prefix]) => [...v1Prefix, ...path.slice(v2Prefix.length)]),
|
||||||
|
]
|
||||||
|
for (const rawPath of paths) {
|
||||||
|
const raw = readConfigValueAtPath(candidate.entity, rawPath)
|
||||||
|
if (typeof raw === 'string' && CONFIG_REFERENCE_PATTERN.test(raw)) return raw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function restoreEntityReferences(
|
||||||
|
next: unknown,
|
||||||
|
path: readonly string[],
|
||||||
|
resolvedEntity: unknown,
|
||||||
|
candidates: readonly RawEntityCandidate[],
|
||||||
|
): unknown {
|
||||||
|
if (typeof next === 'string') {
|
||||||
|
if (readConfigValueAtPath(resolvedEntity, path) !== next) return next
|
||||||
|
return readRawReference(candidates, path) ?? next
|
||||||
|
}
|
||||||
|
if (Array.isArray(next)) {
|
||||||
|
return next.map((item, index) => restoreEntityReferences(item, [...path, String(index)], resolvedEntity, candidates))
|
||||||
|
}
|
||||||
|
if (isRecord(next)) {
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(next).map(([key, value]) => [key, restoreEntityReferences(value, [...path, key], resolvedEntity, candidates)]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
function findRenameSource(
|
||||||
|
patchContainer: Record<string, unknown>,
|
||||||
|
resolvedContainer: Record<string, unknown>,
|
||||||
|
): string | undefined {
|
||||||
|
const removed = Object.keys(patchContainer).filter(
|
||||||
|
(name) => patchContainer[name] === null && Object.prototype.hasOwnProperty.call(resolvedContainer, name),
|
||||||
|
)
|
||||||
|
return removed.length === 1 ? removed[0] : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function restoreContainerReferences(
|
||||||
|
mapping: OpenCodeConfigV1EntityPath,
|
||||||
|
patchContainer: Record<string, unknown>,
|
||||||
|
resolved: Record<string, unknown>,
|
||||||
|
raw: Record<string, unknown>,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const resolvedContainer = readConfigValueAtPath(resolved, mapping.v2Path)
|
||||||
|
if (!isRecord(resolvedContainer)) return patchContainer
|
||||||
|
const rawV2Container = readConfigValueAtPath(raw, mapping.v2Path)
|
||||||
|
const rawV1Container = readConfigValueAtPath(raw, mapping.v1Path)
|
||||||
|
const aliases = V1_FIELD_ALIASES[mapping.v2Path.join('.')] ?? []
|
||||||
|
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(patchContainer).map(([name, value]) => {
|
||||||
|
if (!isRecord(value)) return [name, value]
|
||||||
|
const sourceName = Object.prototype.hasOwnProperty.call(resolvedContainer, name)
|
||||||
|
? name
|
||||||
|
: findRenameSource(patchContainer, resolvedContainer)
|
||||||
|
if (sourceName === undefined) return [name, value]
|
||||||
|
|
||||||
|
const candidates: RawEntityCandidate[] = [
|
||||||
|
{ entity: isRecord(rawV2Container) ? rawV2Container[sourceName] : undefined, aliases: [] },
|
||||||
|
]
|
||||||
|
if (!mapping.reservedNames?.includes(sourceName)) {
|
||||||
|
candidates.push({ entity: isRecord(rawV1Container) ? rawV1Container[sourceName] : undefined, aliases })
|
||||||
|
}
|
||||||
|
return [name, restoreEntityReferences(value, [], resolvedContainer[sourceName], candidates)]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setValueAtPath(target: Record<string, unknown>, path: readonly string[], value: unknown): Record<string, unknown> {
|
||||||
|
const [head, ...rest] = path
|
||||||
|
if (head === undefined) return target
|
||||||
|
const child = target[head]
|
||||||
|
return {
|
||||||
|
...target,
|
||||||
|
[head]: rest.length === 0 ? value : setValueAtPath(isRecord(child) ? child : {}, rest, value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps `{env:…}` and `{file:…}` references in a merge patch of named config entities.
|
||||||
|
*
|
||||||
|
* Settings edits entities from OpenCode's resolved config, so an untouched field arrives with its
|
||||||
|
* substituted value. A string that still equals the resolved value is replaced by the reference
|
||||||
|
* stored in the raw config: the same entity, the entity being renamed, or its v1 definition.
|
||||||
|
*/
|
||||||
|
export function restoreOpenCodeConfigReferences(
|
||||||
|
patch: Record<string, unknown>,
|
||||||
|
resolved: Record<string, unknown>,
|
||||||
|
raw: Record<string, unknown>,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
return V1_ENTITY_PATHS.filter((mapping) => mapping.named).reduce((current, mapping) => {
|
||||||
|
const patchContainer = readConfigValueAtPath(current, mapping.v2Path)
|
||||||
|
if (!isRecord(patchContainer)) return current
|
||||||
|
return setValueAtPath(current, mapping.v2Path, restoreContainerReferences(mapping, patchContainer, resolved, raw))
|
||||||
|
}, patch)
|
||||||
|
}
|
||||||
@@ -130,14 +130,24 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
|
|||||||
|
|
||||||
if (closed || token !== loopToken) return
|
if (closed || token !== loopToken) return
|
||||||
|
|
||||||
options.onDisconnect(stallError ?? failure)
|
try {
|
||||||
|
options.onDisconnect(stallError ?? failure)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`${options.label}: disconnect handler failed`, error)
|
||||||
|
}
|
||||||
await wait(currentDelay)
|
await wait(currentDelay)
|
||||||
if (closed || token !== loopToken) return
|
if (closed || token !== loopToken) return
|
||||||
currentDelay = nextBackoffDelay(currentDelay, maxReconnectDelayMs)
|
currentDelay = nextBackoffDelay(currentDelay, maxReconnectDelayMs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void run(loopToken)
|
const startLoop = (token: number): void => {
|
||||||
|
void run(token).catch((error) => {
|
||||||
|
logger.error(`${options.label}: subscription loop failed`, error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
startLoop(loopToken)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
close: () => {
|
close: () => {
|
||||||
@@ -153,7 +163,7 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
|
|||||||
stopDelay()
|
stopDelay()
|
||||||
stopAttempt()
|
stopAttempt()
|
||||||
currentDelay = reconnectDelayMs
|
currentDelay = reconnectDelayMs
|
||||||
void run(loopToken)
|
startLoop(loopToken)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
export type EnforcementRemovedSections = Record<string, unknown>
|
import { isRecord } from '@opencode-manager/shared/utils'
|
||||||
|
|
||||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
export type EnforcementRemovedSections = Record<string, unknown>
|
||||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeRecordSections(target: Record<string, unknown>, key: string, value: Record<string, unknown>): void {
|
function mergeRecordSections(target: Record<string, unknown>, key: string, value: Record<string, unknown>): void {
|
||||||
const current = isRecord(target[key]) ? { ...(target[key] as Record<string, unknown>) } : {}
|
const current = isRecord(target[key]) ? { ...(target[key] as Record<string, unknown>) } : {}
|
||||||
|
|||||||
@@ -553,6 +553,7 @@ class SSEAggregator {
|
|||||||
}
|
}
|
||||||
case 'session.deleted': {
|
case 'session.deleted': {
|
||||||
this.unmarkSubagentSession(directory, event.data.sessionID)
|
this.unmarkSubagentSession(directory, event.data.sessionID)
|
||||||
|
this.markSessionIdle(directory, event.data.sessionID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -171,6 +171,16 @@ describe('buildSettingsSkill', () => {
|
|||||||
expect(skill).toContain('GET /opencode-config/mcp returns `503`')
|
expect(skill).toContain('GET /opencode-config/mcp returns `503`')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('documents v1 counterpart removal, reference preservation, and both 409 causes', () => {
|
||||||
|
const skill = buildSettingsSkill()
|
||||||
|
expect(skill).toContain('also deletes its v1 counterpart')
|
||||||
|
expect(skill).toContain('`{env:…}` and `{file:…}` references')
|
||||||
|
expect(skill).toContain('OpenCodeConfigShadowedRemovalError')
|
||||||
|
expect(skill).toContain('expectedRevision')
|
||||||
|
expect(skill).not.toContain('Saving never silently drops unsupported fields')
|
||||||
|
expect(skill).not.toContain('every path you do not name is left untouched')
|
||||||
|
})
|
||||||
|
|
||||||
it('documents the assistant reload as rebuilding every loaded location', () => {
|
it('documents the assistant reload as rebuilding every loaded location', () => {
|
||||||
const skill = buildSettingsSkill()
|
const skill = buildSettingsSkill()
|
||||||
expect(skill).toContain('rebuilding every loaded location')
|
expect(skill).toContain('rebuilding every loaded location')
|
||||||
@@ -866,6 +876,52 @@ describe('convertAssistantOpenCodeConfigToV2', () => {
|
|||||||
expect(config.agents.assistant).toEqual({ mode: 'all' })
|
expect(config.agents.assistant).toEqual({ mode: 'all' })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keeps the v1 permission block when the converted document has no permissions', async () => {
|
||||||
|
await ensureAssistantMode(mockRepo)
|
||||||
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||||
|
await writeFile(opencodeJsonPath, v1Config)
|
||||||
|
|
||||||
|
const api = createConfigApi((assistantDir) => [{
|
||||||
|
type: 'document',
|
||||||
|
path: path.join(assistantDir, 'opencode.json'),
|
||||||
|
info: {
|
||||||
|
default_agent: 'assistant',
|
||||||
|
agents: { assistant: { mode: 'primary', system: 'Converted prompt' } },
|
||||||
|
},
|
||||||
|
}])
|
||||||
|
|
||||||
|
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
|
||||||
|
|
||||||
|
const config = parseJsonc<Record<string, unknown>>(await readFile(opencodeJsonPath, 'utf8'))
|
||||||
|
expect(config.agents).toEqual({ assistant: { mode: 'primary', system: 'Converted prompt' } })
|
||||||
|
expect(config.permission).toEqual({ read: 'allow', shell: 'ask' })
|
||||||
|
expect(config.agent).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restores a config reference from the v1 agent definition', async () => {
|
||||||
|
await ensureAssistantMode(mockRepo)
|
||||||
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||||
|
await writeFile(opencodeJsonPath, JSON.stringify({
|
||||||
|
default_agent: 'assistant',
|
||||||
|
agent: { assistant: { mode: 'primary', prompt: '{file:./p.md}' } },
|
||||||
|
}, null, 2))
|
||||||
|
|
||||||
|
const api = createConfigApi((assistantDir) => [{
|
||||||
|
type: 'document',
|
||||||
|
path: path.join(assistantDir, 'opencode.json'),
|
||||||
|
info: {
|
||||||
|
default_agent: 'assistant',
|
||||||
|
agents: { assistant: { mode: 'primary', system: 'Resolved prompt text' } },
|
||||||
|
},
|
||||||
|
}])
|
||||||
|
|
||||||
|
expect(await convertAssistantOpenCodeConfigToV2(api)).toBe(true)
|
||||||
|
|
||||||
|
const config = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
||||||
|
expect(config.agents.assistant).toEqual({ mode: 'primary', system: '{file:./p.md}' })
|
||||||
|
expect(config.agent).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
it('leaves the file unchanged when the OpenCode client fails', async () => {
|
it('leaves the file unchanged when the OpenCode client fails', async () => {
|
||||||
await ensureAssistantMode(mockRepo)
|
await ensureAssistantMode(mockRepo)
|
||||||
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
|
|||||||
getOpenCodeConfigFilePath: () => paths.config,
|
getOpenCodeConfigFilePath: () => paths.config,
|
||||||
getOpenCodeConfigHome: () => paths.configHome,
|
getOpenCodeConfigHome: () => paths.configHome,
|
||||||
getOpenCodeHealthWatchPath: () => paths.healthWatch,
|
getOpenCodeHealthWatchPath: () => paths.healthWatch,
|
||||||
|
getWorkspacePath: () => paths.configDir,
|
||||||
OPENCODE_CONFIG_SOURCE_NAMES: ['opencode.json', 'opencode.jsonc'],
|
OPENCODE_CONFIG_SOURCE_NAMES: ['opencode.json', 'opencode.jsonc'],
|
||||||
}))
|
}))
|
||||||
|
|
||||||
@@ -67,8 +68,10 @@ function parseSnapshot(snapshot: string): { version: number; sources: Array<{ na
|
|||||||
const locationReloadMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
|
const locationReloadMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
|
||||||
const mcpAddMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
|
const mcpAddMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
|
||||||
const mcpRemoveMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
|
const mcpRemoveMock = vi.hoisted(() => vi.fn<() => Promise<void>>())
|
||||||
|
const configGetMock = vi.hoisted(() => vi.fn<() => Promise<unknown[]>>())
|
||||||
const openCodeClient = {
|
const openCodeClient = {
|
||||||
api: {
|
api: {
|
||||||
|
config: { get: configGetMock },
|
||||||
location: { reload: locationReloadMock },
|
location: { reload: locationReloadMock },
|
||||||
mcp: { add: mcpAddMock, remove: mcpRemoveMock },
|
mcp: { add: mcpAddMock, remove: mcpRemoveMock },
|
||||||
},
|
},
|
||||||
@@ -88,6 +91,7 @@ describe('opencode-config-apply', () => {
|
|||||||
locationReloadMock.mockReset().mockResolvedValue(undefined)
|
locationReloadMock.mockReset().mockResolvedValue(undefined)
|
||||||
mcpAddMock.mockReset().mockResolvedValue(undefined)
|
mcpAddMock.mockReset().mockResolvedValue(undefined)
|
||||||
mcpRemoveMock.mockReset().mockResolvedValue(undefined)
|
mcpRemoveMock.mockReset().mockResolvedValue(undefined)
|
||||||
|
configGetMock.mockReset().mockRejectedValue(new Error('OpenCode unavailable'))
|
||||||
workDir = await mkdtemp(path.join(tmpdir(), 'opencode-config-apply-'))
|
workDir = await mkdtemp(path.join(tmpdir(), 'opencode-config-apply-'))
|
||||||
paths.config = path.join(workDir, 'opencode.json')
|
paths.config = path.join(workDir, 'opencode.json')
|
||||||
paths.configDir = workDir
|
paths.configDir = workDir
|
||||||
@@ -126,6 +130,34 @@ describe('opencode-config-apply', () => {
|
|||||||
expect(result.config.content).toEqual(change)
|
expect(result.config.content).toEqual(change)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keeps an unchanged {env:} reference when a merge patch resends the resolved value', async () => {
|
||||||
|
await writeFile(
|
||||||
|
sourcePath('opencode.json'),
|
||||||
|
'{\n // keep me\n "providers": { "acme": { "settings": { "apiKey": "{env:ACME_KEY}" } } }\n}\n',
|
||||||
|
'utf8',
|
||||||
|
)
|
||||||
|
configGetMock.mockResolvedValue([
|
||||||
|
{
|
||||||
|
type: 'document',
|
||||||
|
path: sourcePath('opencode.json'),
|
||||||
|
info: { providers: { acme: { settings: { apiKey: 'secret' } } } },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
|
await applyOpenCodeConfigUpdate({
|
||||||
|
content: { providers: { acme: { name: 'Acme', settings: { apiKey: 'secret' } } } },
|
||||||
|
mode: 'merge',
|
||||||
|
settingsService,
|
||||||
|
openCodeClient,
|
||||||
|
})
|
||||||
|
|
||||||
|
const written = await readFile(sourcePath('opencode.json'), 'utf8')
|
||||||
|
expect(written).toContain('"apiKey": "{env:ACME_KEY}"')
|
||||||
|
expect(written).toContain('"name": "Acme"')
|
||||||
|
expect(written).toContain('// keep me')
|
||||||
|
expect(written).not.toContain('secret')
|
||||||
|
})
|
||||||
|
|
||||||
it('marks a restart pending when the reload fails', async () => {
|
it('marks a restart pending when the reload fails', async () => {
|
||||||
await writeFile(sourcePath('opencode.json'), '{"theme":"dark"}', 'utf8')
|
await writeFile(sourcePath('opencode.json'), '{"theme":"dark"}', 'utf8')
|
||||||
locationReloadMock.mockRejectedValue(new Error('OpenCode server unavailable'))
|
locationReloadMock.mockRejectedValue(new Error('OpenCode server unavailable'))
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { restoreOpenCodeConfigReferences } from '../../src/services/opencode-config-references'
|
||||||
|
|
||||||
|
describe('restoreOpenCodeConfigReferences', () => {
|
||||||
|
it('keeps unchanged references of a v2 entity and writes edited values', () => {
|
||||||
|
const raw = {
|
||||||
|
agents: { reviewer: { system: '{file:./prompt.md}', description: 'old' } },
|
||||||
|
providers: { acme: { settings: { apiKey: '{env:ACME_KEY}' } } },
|
||||||
|
}
|
||||||
|
const resolved = {
|
||||||
|
agents: { reviewer: { system: 'Prompt text', description: 'old' } },
|
||||||
|
providers: { acme: { settings: { apiKey: 'secret' } } },
|
||||||
|
}
|
||||||
|
const patch = {
|
||||||
|
agents: { reviewer: { system: 'Prompt text', description: 'new' } },
|
||||||
|
providers: { acme: { settings: { apiKey: 'secret' } } },
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual({
|
||||||
|
agents: { reviewer: { system: '{file:./prompt.md}', description: 'new' } },
|
||||||
|
providers: { acme: { settings: { apiKey: '{env:ACME_KEY}' } } },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('writes an edited value over a reference', () => {
|
||||||
|
const raw = { agents: { reviewer: { system: '{file:./prompt.md}' } } }
|
||||||
|
const resolved = { agents: { reviewer: { system: 'Prompt text' } } }
|
||||||
|
const patch = { agents: { reviewer: { system: 'Rewritten prompt' } } }
|
||||||
|
|
||||||
|
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual(patch)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('carries references across a rename', () => {
|
||||||
|
const raw = { commands: { old: { template: '{file:./cmd.md}' } } }
|
||||||
|
const resolved = { commands: { old: { template: 'Run it' } } }
|
||||||
|
const patch = { commands: { renamed: { template: 'Run it' }, old: null } }
|
||||||
|
|
||||||
|
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual({
|
||||||
|
commands: { renamed: { template: '{file:./cmd.md}' }, old: null },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('restores references from the v1 definition through renamed fields', () => {
|
||||||
|
const raw = {
|
||||||
|
agent: { reviewer: { prompt: '{file:./prompt.md}' } },
|
||||||
|
provider: { acme: { options: { apiKey: '{env:ACME_KEY}', headers: { Authorization: 'Bearer {env:TOKEN}' } } } },
|
||||||
|
mcp: { docs: { type: 'remote', url: 'https://x', headers: { key: '{env:MCP_KEY}' } } },
|
||||||
|
}
|
||||||
|
const resolved = {
|
||||||
|
agents: { reviewer: { system: 'Prompt text' } },
|
||||||
|
providers: { acme: { settings: { apiKey: 'secret' }, headers: { Authorization: 'Bearer t' } } },
|
||||||
|
mcp: { servers: { docs: { type: 'remote', url: 'https://x', headers: { key: 'm' } } } },
|
||||||
|
}
|
||||||
|
const patch = {
|
||||||
|
agents: { reviewer: { system: 'Prompt text', description: 'added' } },
|
||||||
|
providers: { acme: { settings: { apiKey: 'secret' }, headers: { Authorization: 'Bearer t' } } },
|
||||||
|
mcp: { servers: { docs: { type: 'remote', url: 'https://x', headers: { key: 'm' } } } },
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(restoreOpenCodeConfigReferences(patch, resolved, raw)).toEqual({
|
||||||
|
agents: { reviewer: { system: '{file:./prompt.md}', description: 'added' } },
|
||||||
|
providers: { acme: { settings: { apiKey: '{env:ACME_KEY}' }, headers: { Authorization: 'Bearer {env:TOKEN}' } } },
|
||||||
|
mcp: { servers: { docs: { type: 'remote', url: 'https://x', headers: { key: '{env:MCP_KEY}' } } } },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('leaves new entities and non-entity keys unchanged', () => {
|
||||||
|
const patch = { agents: { fresh: { system: 'x' } }, theme: 'dark' }
|
||||||
|
|
||||||
|
expect(restoreOpenCodeConfigReferences(patch, { agents: {} }, { agents: {} })).toEqual(patch)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -52,4 +52,22 @@ describe('validateOpenCodeConfig', () => {
|
|||||||
}),
|
}),
|
||||||
).toEqual({ success: true })
|
).toEqual({ success: true })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('reports the legacy v1 skills object with an actionable message', () => {
|
||||||
|
const result = validateOpenCodeConfig({ skills: { paths: ['/home/user/skills'] } })
|
||||||
|
|
||||||
|
expect(result.success).toBe(false)
|
||||||
|
if (result.success) return
|
||||||
|
expect(result.issues).toEqual([
|
||||||
|
{
|
||||||
|
path: 'skills',
|
||||||
|
message:
|
||||||
|
'skills must be a list of skill paths. Replace the legacy `skills: { paths: [...] }` object with `skills: [...]`.',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts the v2 skills array', () => {
|
||||||
|
expect(validateOpenCodeConfig({ skills: ['/home/user/skills'] })).toEqual({ success: true })
|
||||||
|
})
|
||||||
})
|
})
|
||||||
@@ -216,6 +216,41 @@ describe('subscribeOpenCodeEvents', () => {
|
|||||||
subscription.close()
|
subscription.close()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('keeps reconnecting when the disconnect handler throws', async () => {
|
||||||
|
const { api, subscriptions } = createFakeApi()
|
||||||
|
const onOpen = vi.fn()
|
||||||
|
const onDisconnect = vi.fn(() => {
|
||||||
|
throw new Error('disconnect failure')
|
||||||
|
})
|
||||||
|
|
||||||
|
const subscription = subscribeOpenCodeEvents({
|
||||||
|
api: () => api,
|
||||||
|
label: 'test',
|
||||||
|
onOpen,
|
||||||
|
onEvent: () => undefined,
|
||||||
|
onDisconnect,
|
||||||
|
reconnectDelayMs: 100,
|
||||||
|
maxReconnectDelayMs: 1000,
|
||||||
|
})
|
||||||
|
|
||||||
|
subscriptions[0]!.stream.push(serverConnected)
|
||||||
|
await flush()
|
||||||
|
expect(onOpen).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
subscriptions[0]!.stream.end()
|
||||||
|
await flush()
|
||||||
|
expect(onDisconnect).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(100)
|
||||||
|
expect(subscriptions).toHaveLength(2)
|
||||||
|
|
||||||
|
subscriptions[1]!.stream.push(serverConnected)
|
||||||
|
await flush()
|
||||||
|
expect(onOpen).toHaveBeenCalledTimes(2)
|
||||||
|
|
||||||
|
subscription.close()
|
||||||
|
})
|
||||||
|
|
||||||
it('doubles the reconnect delay after a thrown transport error and caps it', async () => {
|
it('doubles the reconnect delay after a thrown transport error and caps it', async () => {
|
||||||
const { api, subscriptions } = createFakeApi()
|
const { api, subscriptions } = createFakeApi()
|
||||||
const onDisconnect = vi.fn()
|
const onDisconnect = vi.fn()
|
||||||
|
|||||||
@@ -206,6 +206,16 @@ describe('SSEAggregator V2 event handling', () => {
|
|||||||
expect(sseAggregator.getActiveSessions()).toEqual({})
|
expect(sseAggregator.getActiveSessions()).toEqual({})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('clears a busy session from the active set when it is deleted without going idle', () => {
|
||||||
|
emitEvent({ type: 'session.status', location: { directory: '/r' }, data: { sessionID: 'ses_deleted', status: { type: 'busy' } } })
|
||||||
|
|
||||||
|
expect(sseAggregator.getActiveSessions()).toEqual({ '/r': ['ses_deleted'] })
|
||||||
|
|
||||||
|
emitEvent({ type: 'session.deleted', location: { directory: '/r' }, data: { sessionID: 'ses_deleted' } })
|
||||||
|
|
||||||
|
expect(sseAggregator.getActiveSessions()).toEqual({})
|
||||||
|
})
|
||||||
|
|
||||||
it('records subagent sessions from session.created parentID and forgets deleted ones', () => {
|
it('records subagent sessions from session.created parentID and forgets deleted ones', () => {
|
||||||
emitEvent({
|
emitEvent({
|
||||||
type: 'session.created',
|
type: 'session.created',
|
||||||
|
|||||||
@@ -1230,6 +1230,7 @@ describe('EventProvider permissions and forms', () => {
|
|||||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] })
|
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] })
|
||||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] })
|
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] })
|
||||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
|
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
|
||||||
|
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config', 'managed'] })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -3109,6 +3110,7 @@ describe('EventProvider permissions and forms', () => {
|
|||||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents', 'srv_remote'] })
|
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents', 'srv_remote'] })
|
||||||
})
|
})
|
||||||
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'commands'] })
|
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'commands'] })
|
||||||
|
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode-config', 'managed'] })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('reconciles only linked directories with active work on a remote resync', async () => {
|
it('reconciles only linked directories with active work on a remote resync', async () => {
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ import {
|
|||||||
invalidateQueryKeysDebounced,
|
invalidateQueryKeysDebounced,
|
||||||
invalidateRepoGitCachesDebounced,
|
invalidateRepoGitCachesDebounced,
|
||||||
invalidateSessionListCachesDebounced,
|
invalidateSessionListCachesDebounced,
|
||||||
|
OPEN_CODE_MANAGED_CONFIG_QUERY_KEY,
|
||||||
} from '@/lib/queryInvalidation'
|
} from '@/lib/queryInvalidation'
|
||||||
|
|
||||||
const STATUS_POLL_INTERVAL_MS = 5000
|
const STATUS_POLL_INTERVAL_MS = 5000
|
||||||
@@ -1273,7 +1274,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
|||||||
void fetchInitialSessionStatuses()
|
void fetchInitialSessionStatuses()
|
||||||
void syncRunningShells(directories)
|
void syncRunningShells(directories)
|
||||||
invalidateChildSessionCaches(queryClient)
|
invalidateChildSessionCaches(queryClient)
|
||||||
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
|
invalidateQueryKeysDebounced(queryClient, [
|
||||||
|
...LOCATION_CATALOG_QUERY_KEYS,
|
||||||
|
OPEN_CODE_MANAGED_CONFIG_QUERY_KEY,
|
||||||
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))]
|
const initialDirectories = [...new Set((reposRef.current ?? []).map(r => r.fullPath))]
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Info } from '@opencode/schema/config'
|
import { Info } from '@opencode/schema/config'
|
||||||
import { Schema } from 'effect'
|
import { Schema } from 'effect'
|
||||||
import type { OpenCodeConfigValidationIssue } from '../types'
|
import type { OpenCodeConfigValidationIssue } from '../types'
|
||||||
|
import { isRecord } from '../utils/record'
|
||||||
|
|
||||||
export type OpenCodeConfigValidationResult =
|
export type OpenCodeConfigValidationResult =
|
||||||
| { success: true }
|
| { success: true }
|
||||||
@@ -10,6 +11,9 @@ const standardSchema = Schema.toStandardSchemaV1(Info, {
|
|||||||
parseOptions: { errors: 'all', onExcessProperty: 'ignore' },
|
parseOptions: { errors: 'all', onExcessProperty: 'ignore' },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const LEGACY_SKILLS_MESSAGE =
|
||||||
|
'skills must be a list of skill paths. Replace the legacy `skills: { paths: [...] }` object with `skills: [...]`.'
|
||||||
|
|
||||||
function toIssuePath(path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined): string {
|
function toIssuePath(path: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined): string {
|
||||||
if (!path || path.length === 0) return 'root'
|
if (!path || path.length === 0) return 'root'
|
||||||
return path
|
return path
|
||||||
@@ -17,9 +21,14 @@ function toIssuePath(path: ReadonlyArray<PropertyKey | { readonly key: PropertyK
|
|||||||
.join('.')
|
.join('.')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function hasLegacySkillsObject(value: unknown): boolean {
|
||||||
|
return isRecord(value) && isRecord(value.skills)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates a parsed OpenCode config document against the v2 `Config.Info` schema, ignoring
|
* Validates a parsed OpenCode config document against the v2 `Config.Info` schema, ignoring
|
||||||
* unknown keys so v1-only fields in existing files stay loadable.
|
* unknown keys so v1-only fields in existing files stay loadable. A legacy v1 `skills` object
|
||||||
|
* is reported with an actionable message naming the v2 list form.
|
||||||
*/
|
*/
|
||||||
export function validateOpenCodeConfig(value: unknown): OpenCodeConfigValidationResult {
|
export function validateOpenCodeConfig(value: unknown): OpenCodeConfigValidationResult {
|
||||||
const result = standardSchema['~standard'].validate(value)
|
const result = standardSchema['~standard'].validate(value)
|
||||||
@@ -27,11 +36,16 @@ export function validateOpenCodeConfig(value: unknown): OpenCodeConfigValidation
|
|||||||
throw new Error('OpenCode config validation must be synchronous')
|
throw new Error('OpenCode config validation must be synchronous')
|
||||||
}
|
}
|
||||||
if (!result.issues) return { success: true }
|
if (!result.issues) return { success: true }
|
||||||
|
const legacySkillsObject = hasLegacySkillsObject(value)
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
issues: result.issues.map((issue) => ({
|
issues: result.issues.map((issue) => {
|
||||||
path: toIssuePath(issue.path),
|
const path = toIssuePath(issue.path)
|
||||||
message: issue.message,
|
const isLegacySkillsIssue = legacySkillsObject && path === 'skills'
|
||||||
})),
|
return {
|
||||||
|
path,
|
||||||
|
message: isLegacySkillsIssue ? LEGACY_SKILLS_MESSAGE : issue.message,
|
||||||
|
}
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user