loop: om-179-finish-adopting-op completed after 19 iterations

This commit is contained in:
Chris Scott committed 2026-11-02 13:13:31 -05:00
1 parent 7c4cfd858c
commit 49bb4ebd36
25 files changed
+362 -198

No files matched your search

+5 -1
View File
@@ -254,7 +254,6 @@ try {
const openCodeStatus = await openCodeSupervisor.start()
if (openCodeStatus.healthy) {
logger.info(`OpenCode server running on port ${openCodeStatus.port}`)
void convertAssistantOpenCodeConfigToV2(openCodeClient.api)
} else {
logger.warn(`OpenCode server unavailable after startup recovery: ${openCodeStatus.lastError ?? openCodeStatus.state}`)
}
@@ -365,6 +364,11 @@ sseAggregator.onServerConnected((serverId) => {
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions(serverId).catch((err) => {
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, err)
})
if (serverId === LOCAL_OPENCODE_SERVER_ID) {
void convertAssistantOpenCodeConfigToV2(openCodeClient.api).catch((err) => {
logger.error('Failed to convert the Assistant OpenCode config to v2:', err)
})
}
})
sseAggregator.start()
+3 -5
View File
@@ -118,18 +118,16 @@ export function createOpenCodeServerProxyRoutes(
headers.Authorization = connection.authorization
}
const requestBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
? c.req.raw.body
: null
const isBodylessMethod = c.req.method === 'GET' || c.req.method === 'HEAD'
try {
return await forwardProxyRequest({
url: upstream.url.toString(),
method: c.req.method,
headers,
body: requestBody,
body: isBodylessMethod ? null : c.req.raw.body,
signal: c.req.raw.signal,
headersTimeoutMs: requestBody === null ? upstreamHeadersTimeoutMs : undefined,
headersTimeoutMs: isBodylessMethod ? upstreamHeadersTimeoutMs : undefined,
fetchFn,
buildResponseHeaders: (upstreamHeaders) => new Headers(
filterProxyHeaders(upstreamHeaders, RESPONSE_EXCLUDED_HEADERS),
+21 -26
View File
@@ -13,14 +13,14 @@ import {
} from './file-operations'
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY, MANAGER_TOOL_NAME } from '@opencode-manager/shared/schemas'
import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME, parseJsonc } from '@opencode-manager/shared/utils'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME, isRecord, parseJsonc } from '@opencode-manager/shared/utils'
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
import type { OpenCodeAgentConfig, OpenCodeApi, OpenCodeConfigInfo } from '@opencode-manager/shared/opencode'
import { openCodeLocation } from '@opencode-manager/shared/opencode'
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
import type { Database } from 'bun:sqlite'
import { ensureAssistantRepo } from '../db/queries'
import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, type OpenCodeConfigPathOperation } from './opencode-config-file'
import { readOpenCodeConfigDocuments } from './opencode-config-effective'
import { logger } from '../utils/logger'
@@ -846,6 +846,8 @@ List the configured MCP servers with their enabled state and live connection sta
}
\`\`\`
GET /opencode-config/mcp returns \`503\` when the OpenCode server is unreachable.
When the response contains \`restartRequired: true\`, tell the user to restart the OpenCode server from Settings. Never attempt the restart yourself: it would terminate your own session.
Only changes to how the OpenCode process is launched need a user restart from Settings: server environment variables, Git credentials and identity, sandbox enforcement, rotating the manager token, the server password, and installing or upgrading the OpenCode version. You cannot make these changes through this API.
@@ -853,7 +855,7 @@ Only changes to how the OpenCode process is launched need a user restart from Se
## Safety
- The settings PATCH endpoint rejects any attempt to modify credentials, API keys, or other sensitive settings; guide the user to the full UI for Git, TTS, and STT credentials
- PATCH /opencode-config patches only the paths you name, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
- PATCH /opencode-config patches only the paths you name, including \`plugins\`, \`mcp.servers\`, and \`providers\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
- GET /opencode-config redacts secrets; never reconstruct a secret you did not read, and never send a \`<redacted>\` value back
- The settings PATCH endpoint does NOT trigger an OpenCode reload or restart
`
@@ -1204,11 +1206,11 @@ export async function ensureAssistantMode(
const existingOpenCodeConfig = parsedOpenCodeConfig as OpenCodeConfigInfo | undefined
let opencodeJsonUpdated = false
if (!hasV1OpenCodeConfig) {
if (!opencodeJsonExists || overwriteOpenCodeConfig) {
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
opencodeJsonUpdated = true
} else if (existingOpenCodeConfig !== undefined) {
if (!opencodeJsonExists || overwriteOpenCodeConfig) {
await writeFileContent(opencodeJsonPath, JSON.stringify(buildAssistantOpenCodeConfig(), null, 2))
opencodeJsonUpdated = true
} else if (!hasV1OpenCodeConfig) {
if (existingOpenCodeConfig !== undefined) {
const repairedConfig = assistantOpenCodeConfigNeedsRepair(existingOpenCodeConfig)
? mergeAssistantOpenCodeConfig(existingOpenCodeConfig)
: existingOpenCodeConfig
@@ -1348,14 +1350,10 @@ export async function ensureAssistantMode(
}
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function parseAssistantOpenCodeConfig(rawContent: string): Record<string, unknown> | undefined {
try {
const parsed = parseJsonc(rawContent)
return isPlainObject(parsed) ? parsed : undefined
return isRecord(parsed) ? parsed : undefined
} catch {
return undefined
}
@@ -1363,7 +1361,7 @@ function parseAssistantOpenCodeConfig(rawContent: string): Record<string, unknow
function hasAssistantV1OpenCodeConfig(config: Record<string, unknown>): boolean {
if (config.permission !== undefined) return true
return isPlainObject(config.agent) && isPlainObject(config.agent.assistant)
return isRecord(config.agent) && isRecord(config.agent.assistant)
}
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean {
@@ -1436,9 +1434,9 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo
function buildAssistantV1ConfigRemovalPaths(config: Record<string, unknown>): string[][] {
const v1Agent = config.agent
const removeWholeAgent = isPlainObject(v1Agent) &&
const removeWholeAgent = isRecord(v1Agent) &&
Object.keys(v1Agent).length === 1 &&
isPlainObject(v1Agent.assistant)
isRecord(v1Agent.assistant)
const paths: string[][] = [removeWholeAgent ? ['agent'] : ['agent', ASSISTANT_DEFAULT_AGENT_NAME]]
if (config.permission !== undefined) {
@@ -1474,25 +1472,22 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom
const rawConfig = parseAssistantOpenCodeConfig(rawContent)
if (rawConfig === undefined || !hasAssistantV1OpenCodeConfig(rawConfig)) return false
const entries = await api.config.get(openCodeLocation(assistantDir))
const resolvedPath = path.resolve(opencodeJsonPath)
const documentEntry = entries.find(
(entry) => entry.type === 'document' && entry.path !== undefined && path.resolve(entry.path) === resolvedPath,
)
if (documentEntry === undefined || documentEntry.type !== 'document') return false
const documents = await readOpenCodeConfigDocuments(api, assistantDir)
const documentInfo = documents.get(path.resolve(opencodeJsonPath))
if (documentInfo === undefined) return false
const v1AssistantAgent = isPlainObject(rawConfig.agent) ? rawConfig.agent.assistant : undefined
const v1AssistantAgent = isRecord(rawConfig.agent) ? rawConfig.agent.assistant : undefined
const setOperations: OpenCodeConfigPathOperation[] = [
{
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
value: resolveConvertedAssistantAgent(
documentEntry.info.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
v1AssistantAgent,
),
},
]
if (documentEntry.info.permissions !== undefined) {
setOperations.push({ path: ['permissions'], value: documentEntry.info.permissions })
if (documentInfo.permissions !== undefined) {
setOperations.push({ path: ['permissions'], value: documentInfo.permissions })
}
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
@@ -11,21 +11,34 @@ interface ManagedConfigSource {
path: string
}
/**
* Reads the configuration documents OpenCode has loaded for a directory,
* keyed by each document's resolved file path.
*/
export async function readOpenCodeConfigDocuments(
api: OpenCodeApi,
directory: string,
): Promise<Map<string, OpenCodeConfigInfo>> {
const entries = await api.config.get(openCodeLocation(directory))
const infoByPath = new Map<string, OpenCodeConfigInfo>()
for (const entry of entries) {
if (entry.type !== 'document' || !entry.path) continue
infoByPath.set(path.resolve(entry.path), entry.info)
}
return infoByPath
}
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 infoByPath = await readOpenCodeConfigDocuments(api, getWorkspacePath())
const merged = sources.reduce<Record<string, unknown>>((current, source) => {
const info = infoByPath.get(path.resolve(source.path))
return info ? mergeOpenCodeConfigValues(current, info) : current
return info ? mergeOpenCodeConfigValues(current, info as Record<string, unknown>) : current
}, {})
return merged as OpenCodeConfigInfo
+11 -16
View File
@@ -157,6 +157,7 @@ interface OpenCodeConfigV1EntityPath {
v2Path: string[]
v1Path: string[]
named: boolean
reservedNames?: readonly string[]
}
interface OpenCodeConfigV1EntityRemoval {
@@ -168,7 +169,7 @@ const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [
{ v2Path: ['agents'], v1Path: ['agent'], named: true },
{ v2Path: ['commands'], v1Path: ['command'], named: true },
{ v2Path: ['providers'], v1Path: ['provider'], named: true },
{ v2Path: ['mcp', 'servers'], v1Path: ['mcp'], named: true },
{ v2Path: ['mcp', 'servers'], v1Path: ['mcp'], named: true, reservedNames: ['servers', 'timeout'] },
{ v2Path: ['permissions'], v1Path: ['permission'], named: false },
]
@@ -206,12 +207,18 @@ function hasOwn(object: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(object, key)
}
interface ReadOpenCodeConfigPathOptions {
nullAncestorCountsAsFound?: boolean
}
function readOpenCodeConfigPath(
content: Record<string, unknown>,
jsonPath: JSONPath,
options: ReadOpenCodeConfigPathOptions = {},
): { found: boolean; value: unknown } {
let current: unknown = content
for (const segment of jsonPath) {
if (options.nullAncestorCountsAsFound && current === null) return { found: true, value: null }
if (typeof segment === 'number') {
if (!Array.isArray(current) || segment < 0 || segment >= current.length) {
return { found: false, value: undefined }
@@ -229,19 +236,6 @@ function hasOpenCodeConfigPath(content: Record<string, unknown>, jsonPath: JSONP
return readOpenCodeConfigPath(content, jsonPath).found
}
function readPatchedOpenCodeConfigPath(
patch: Record<string, unknown>,
jsonPath: readonly string[],
): { found: boolean; value: unknown } {
let current: unknown = patch
for (const segment of jsonPath) {
if (current === null) return { found: true, value: null }
if (!isPlainObject(current) || !hasOwn(current, segment)) return { found: false, value: undefined }
current = current[segment]
}
return { found: true, value: current }
}
function defineOwnConfigValue(target: Record<string, unknown>, key: string, value: unknown): void {
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
}
@@ -505,14 +499,15 @@ function collectOpenCodeConfigV1EntityRemovals(
): OpenCodeConfigV1EntityRemoval[] {
const removals: OpenCodeConfigV1EntityRemoval[] = []
for (const mapping of V1_ENTITY_PATHS) {
const patched = readPatchedOpenCodeConfigPath(patch, mapping.v2Path)
const patched = readOpenCodeConfigPath(patch, mapping.v2Path, { nullAncestorCountsAsFound: true })
if (!patched.found) continue
if (!mapping.named || patched.value === null) {
removals.push({ path: mapping.v1Path })
if (!mapping.reservedNames) removals.push({ path: mapping.v1Path })
continue
}
if (!isPlainObject(patched.value)) continue
for (const name of Object.keys(patched.value)) {
if (mapping.reservedNames?.includes(name)) continue
removals.push({ path: [...mapping.v1Path, name], container: mapping.v1Path })
}
}
+9 -23
View File
@@ -13,8 +13,6 @@ type SessionStatusEvent = Extract<V2Event, { type: 'session.status' }>
export type ReplayEvent = PermissionAskedEvent | FormCreatedEvent | SessionStatusEvent
export type ReplayEventType = ReplayEvent['type']
type ReplayEventArguments =
| [type: PermissionAskedEvent['type'], directory: string, data: PermissionAskedEvent['data']]
| [type: FormCreatedEvent['type'], directory: string, data: { form: FormInfo }]
@@ -24,7 +22,6 @@ export type ReplayEventBuilder = (...args: ReplayEventArguments) => ReplayEvent
export interface RoutedOpenCodeEvent {
event: V2Event
payloadJson: string
directory: string | undefined
resolvedDirectory: string | undefined
}
@@ -107,10 +104,17 @@ export function createReplayEventBuilder(idPrefix: string): ReplayEventBuilder {
}
}
function resolveEventRouting(
/**
* Resolves the directory a parsed event belongs to and updates the remembered session directories.
*
* @param event Parsed event received from an OpenCode server.
* @param sessionDirectories Session directories remembered across events, updated in place.
* @returns The event with its resolved directories.
*/
export function routeOpenCodeEvent(
event: V2Event,
sessionDirectories: Map<string, string>,
): Omit<RoutedOpenCodeEvent, 'payloadJson'> {
): RoutedOpenCodeEvent {
const directory = event.location?.directory
const sessionID = sessionIDFromEvent(event)
const forkParentId = event.type === 'session.forked' ? event.data.parentID : undefined
@@ -127,20 +131,6 @@ function resolveEventRouting(
return { event, directory, resolvedDirectory }
}
/**
* Resolves the directory a parsed event belongs to and updates the remembered session directories.
*
* @param event Parsed event received from an OpenCode server.
* @param sessionDirectories Session directories remembered across events, updated in place.
* @returns The event with its serialized payload and resolved directories.
*/
export function routeOpenCodeEvent(
event: V2Event,
sessionDirectories: Map<string, string>,
): RoutedOpenCodeEvent {
return { ...resolveEventRouting(event, sessionDirectories), payloadJson: JSON.stringify(event) }
}
export async function collectPendingReplayEvents(request: PendingReplayRequest): Promise<PendingReplayEvents> {
const { api, directory, buildEvent, logScope, logTarget } = request
const [permissionsResult, formsResult] = await Promise.allSettled([
@@ -168,7 +158,3 @@ export async function collectPendingReplayEvents(request: PendingReplayRequest):
return { permissions, forms }
}
export function nextBackoffDelay(currentDelayMs: number, maxDelayMs: number): number {
return Math.min(currentDelayMs * 2, maxDelayMs)
}
@@ -1,7 +1,6 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
import type { OpenCodeApi, V2Event } from '@opencode-manager/shared/opencode'
import { logger } from '../utils/logger'
import { nextBackoffDelay } from './opencode-event-routing'
export interface OpenCodeEventSubscriptionOptions {
api: () => OpenCodeApi
@@ -25,6 +24,10 @@ interface SubscriptionAttempt {
watchdog: ReturnType<typeof setInterval> | null
}
function nextBackoffDelay(currentDelayMs: number, maxDelayMs: number): number {
return Math.min(currentDelayMs * 2, maxDelayMs)
}
/**
* Subscribes to an OpenCode event stream and owns its reconnect, backoff and stall detection.
*
+11 -19
View File
@@ -1,4 +1,3 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
import {
buildServerDirectoryKey,
LOCAL_OPENCODE_SERVER_ID,
@@ -22,11 +21,9 @@ import {
import { subscribeOpenCodeEvents, type OpenCodeEventSubscription } from './opencode-event-subscription'
import type { RemoteReplayHandler } from './sse-aggregator'
const { RECONNECT_DELAY_MS, MAX_RECONNECT_DELAY_MS } = DEFAULTS.SSE
export interface RemoteEventAggregator {
deliverRemoteEnvelope(serverId: string, directory: string | null, payloadJson: string): void
deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, payloadJson: string): void
deliverRemoteEnvelope(serverId: string, directory: string | null, event: V2Event): void
deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, event: V2Event): void
sendRemoteResync(serverId: string): void
hasClientDirectory(clientId: string, key: string): boolean
setRemoteReplayHandler(handler: RemoteReplayHandler | null): void
@@ -65,8 +62,6 @@ function describeStreamError(error: unknown): string {
export class RemoteServerEventHub {
private readonly streams = new Map<string, RemoteServerStream>()
private readonly reconnectDelayMs: number
private readonly maxReconnectDelayMs: number
private unsubscribeRegistry: (() => void) | null = null
private started = false
private versionProbeSequence = 0
@@ -75,11 +70,8 @@ export class RemoteServerEventHub {
constructor(
private readonly registry: OpenCodeServerRegistry,
private readonly aggregator: RemoteEventAggregator,
options: RemoteServerEventHubOptions = {},
) {
this.reconnectDelayMs = options.reconnectDelayMs ?? RECONNECT_DELAY_MS
this.maxReconnectDelayMs = options.maxReconnectDelayMs ?? MAX_RECONNECT_DELAY_MS
}
private readonly options: RemoteServerEventHubOptions = {},
) {}
start(): void {
if (this.started) return
@@ -169,7 +161,7 @@ export class RemoteServerEventHub {
events: V2Event[],
): void {
for (const event of events) {
this.aggregator.deliverRemoteEnvelopeToClient(clientId, serverId, directory, JSON.stringify(event))
this.aggregator.deliverRemoteEnvelopeToClient(clientId, serverId, directory, event)
}
}
@@ -209,8 +201,8 @@ export class RemoteServerEventHub {
onOpen: () => this.handleOpen(serverId, subscription),
onEvent: (event) => this.handleMessage(serverId, event),
onDisconnect: (error) => this.handleStreamError(serverId, error),
reconnectDelayMs: this.reconnectDelayMs,
maxReconnectDelayMs: this.maxReconnectDelayMs,
reconnectDelayMs: this.options.reconnectDelayMs,
maxReconnectDelayMs: this.options.maxReconnectDelayMs,
})
stream.subscription = subscription
@@ -243,7 +235,7 @@ export class RemoteServerEventHub {
const stream = this.streams.get(serverId)
if (!stream) return
const { resolvedDirectory, payloadJson } = routeOpenCodeEvent(event, stream.sessionDirectories)
const { resolvedDirectory } = routeOpenCodeEvent(event, stream.sessionDirectories)
const sessionID = sessionIDFromEvent(event)
if (sessionID) applySessionActivity(stream.busySessions, event)
if (sessionID && event.type === 'session.deleted') {
@@ -253,7 +245,7 @@ export class RemoteServerEventHub {
}
this.aggregator.notifyServerEvent(serverId, resolvedDirectory ?? null, event)
this.aggregator.deliverRemoteEnvelope(serverId, resolvedDirectory ?? null, payloadJson)
this.aggregator.deliverRemoteEnvelope(serverId, resolvedDirectory ?? null, event)
}
private handleRegistryChange(change: OpenCodeServerChange): void {
@@ -325,7 +317,7 @@ export class RemoteServerEventHub {
for (const { sessionID, directory } of plan.idle) {
const event = this.buildReplayEvent('session.status', directory, { sessionID, status: { type: 'idle' } })
this.aggregator.deliverRemoteEnvelope(serverId, directory, JSON.stringify(event))
this.aggregator.deliverRemoteEnvelope(serverId, directory, event)
stream.busySessions.delete(sessionID)
replayed++
}
@@ -333,7 +325,7 @@ export class RemoteServerEventHub {
for (const sessionID of plan.busy) {
const directory = stream.sessionDirectories.get(sessionID) ?? null
const event = this.buildReplayEvent('session.status', directory ?? '', { sessionID, status: { type: 'busy' } })
this.aggregator.deliverRemoteEnvelope(serverId, directory, JSON.stringify(event))
this.aggregator.deliverRemoteEnvelope(serverId, directory, event)
stream.busySessions.add(sessionID)
replayed++
}
+15 -15
View File
@@ -410,38 +410,38 @@ class SSEAggregator {
}
private handleUpstreamEvent(event: V2Event): void {
const { payloadJson, directory, resolvedDirectory } = routeOpenCodeEvent(event, this.sessionDirectories)
const { directory, resolvedDirectory } = routeOpenCodeEvent(event, this.sessionDirectories)
if (directory) {
if (LOCATION_CATALOG_EVENT_TYPES.has(event.type)) {
this.deliverResolvedEvent(directory, event, payloadJson)
this.deliverResolvedEvent(directory, event)
} else {
this.deliverEvent(directory, event, payloadJson)
this.deliverEvent(directory, event)
}
return
}
if (resolvedDirectory) {
this.deliverResolvedEvent(resolvedDirectory, event, payloadJson)
this.deliverResolvedEvent(resolvedDirectory, event)
return
}
this.notifyListeners(null, event)
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
this.writeEnvelopeToClients(this.clients.keys(), null, event)
}
private deliverEvent(directory: string, event: SSEEvent, payloadJson?: string): void {
private deliverEvent(directory: string, event: SSEEvent): void {
this.notifyEvent(directory, event)
const subscriberIds = this.directoryClients.get(directory)
if (!subscriberIds || subscriberIds.size === 0) return
this.writeEnvelopeToClients(subscriberIds, directory, payloadJson ?? JSON.stringify(event))
this.writeEnvelopeToClients(subscriberIds, directory, event)
}
private deliverResolvedEvent(directory: string, event: SSEEvent, payloadJson: string): void {
private deliverResolvedEvent(directory: string, event: SSEEvent): void {
this.notifyEvent(directory, event)
this.writeEnvelopeToClients(this.clients.keys(), null, payloadJson)
this.writeEnvelopeToClients(this.clients.keys(), null, event)
}
private notifyEvent(directory: string, event: SSEEvent): void {
@@ -459,14 +459,14 @@ class SSEAggregator {
private writeEnvelopeToClients(
clientIds: Iterable<string>,
directory: string | null,
payloadJson: string,
event: SSEEvent,
serverId?: string,
): void {
let frame: Uint8Array | null = null
for (const clientId of clientIds) {
const client = this.clients.get(clientId)
if (!client) continue
frame ??= encodeSSEFrame('message', serializeEnvelope(directory, payloadJson, serverId))
frame ??= encodeSSEFrame('message', serializeEnvelope(directory, JSON.stringify(event), serverId))
this.writeFrame(client, frame, 'Failed to send to client')
}
}
@@ -483,15 +483,15 @@ class SSEAggregator {
return this.clients.get(clientId)?.directories.has(key) ?? false
}
deliverRemoteEnvelope(serverId: string, directory: string | null, payloadJson: string): void {
this.writeEnvelopeToClients(this.clients.keys(), directory, payloadJson, serverId)
deliverRemoteEnvelope(serverId: string, directory: string | null, event: SSEEvent): void {
this.writeEnvelopeToClients(this.clients.keys(), directory, event, serverId)
}
deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, payloadJson: string): void {
deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, event: SSEEvent): void {
if (!this.hasClientDirectory(clientId, buildServerDirectoryKey(serverId, directory))) return
const client = this.clients.get(clientId)
if (!client) return
const frame = encodeSSEFrame('message', serializeEnvelope(directory, payloadJson, serverId))
const frame = encodeSSEFrame('message', serializeEnvelope(directory, JSON.stringify(event), serverId))
this.writeFrame(client, frame, 'Failed to send remote event to client')
}
@@ -236,6 +236,23 @@ describe('opencode server proxy routes', () => {
expect(receivedSignal?.aborted).toBe(false)
})
it('does not time out a bodyless POST that takes longer than the headers timeout', async () => {
let receivedSignal: AbortSignal | null | undefined
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
receivedSignal = init.signal
await new Promise((resolve) => setTimeout(resolve, 40))
return new Response('ok', { status: 200 })
})
const app = buildApp(fetchMock as unknown as typeof fetch, passThroughAuth, 10)
const res = await app.request('/api/opencode/servers/srv_1/api/session/ses_1/abort', {
method: 'POST',
})
expect(res.status).toBe(200)
expect(receivedSignal?.aborted).toBe(false)
})
it('keeps streaming the upstream body after headers arrive', async () => {
const encoder = new TextEncoder()
let receivedSignal: AbortSignal | null | undefined
@@ -162,6 +162,15 @@ describe('buildSettingsSkill', () => {
expect(skill).toContain('never copy this response into a save')
})
it('names v2 config keys and documents the unreachable server response', () => {
const skill = buildSettingsSkill()
expect(skill).toContain('`plugins`')
expect(skill).toContain('`mcp.servers`')
expect(skill).toContain('`providers`')
expect(skill).not.toContain('including `plugin`')
expect(skill).toContain('GET /opencode-config/mcp returns `503`')
})
it('documents the assistant reload as rebuilding every loaded location', () => {
const skill = buildSettingsSkill()
expect(skill).toContain('rebuilding every loaded location')
@@ -445,6 +454,22 @@ describe('ensureAssistantMode', () => {
expect(result.files.opencodeJson?.created).toBe(false)
})
it('writes the generated v2 config over a v1 config when overwrite is requested', async () => {
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
const v1Config = `{
"permission": { "read": "allow", "shell": "ask" },
"agent": { "assistant": { "mode": "primary", "prompt": "Custom v1 prompt" } }
}
`
await writeFile(opencodeJsonPath, v1Config)
const result = await ensureAssistantMode(mockRepo, { overwriteOpenCodeConfig: true })
expect(JSON.parse(await readFile(opencodeJsonPath, 'utf8'))).toEqual(buildAssistantOpenCodeConfig())
expect(result.files.opencodeJson?.created).toBe(true)
})
it('migrates generated legacy AGENTS.md and assistant.md to the new split', async () => {
await ensureAssistantMode(mockRepo)
@@ -1,13 +1,29 @@
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'
import { readManagedOpenCodeConfig, readOpenCodeConfigDocuments } 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('readOpenCodeConfigDocuments', () => {
it('keys document entries by resolved path for the requested directory', async () => {
const { api, get } = stubApi([
{ type: 'document', path: '/directory/./opencode.json', info: { theme: 'dark' } },
{ type: 'document', info: { theme: 'pathless' } },
{ type: 'directory', path: '/directory' },
])
const documents = await readOpenCodeConfigDocuments(api, '/directory')
expect([...documents.keys()]).toEqual(['/directory/opencode.json'])
expect(documents.get('/directory/opencode.json')).toEqual({ theme: 'dark' })
expect(get).toHaveBeenCalledWith(openCodeLocation('/directory'))
})
})
describe('readManagedOpenCodeConfig', () => {
it('merges only the documents whose path is a Manager source, in source order', async () => {
const { api, get } = stubApi([
@@ -833,6 +833,60 @@ describe('opencode-config-file', () => {
expect(onDisk).toContain('// keep this comment')
})
it('keeps the v2 mcp timeout when saving an MCP server named like a v2 mcp key', async () => {
await writeFile(
sourcePath('opencode.json'),
JSON.stringify({ mcp: { timeout: { connect: 5000 }, servers: {} } }),
'utf8',
)
const updated = await updateOpenCodeConfigFile(
{ mcp: { servers: { timeout: { type: 'remote', url: 'https://timeout.example.com' } } } },
{ mode: 'merge' },
)
expect(updated.content).toEqual({
mcp: {
timeout: { connect: 5000 },
servers: { timeout: { type: 'remote', url: 'https://timeout.example.com' } },
},
})
})
it('keeps the v2 mcp servers when saving an MCP server named like the v2 servers map', async () => {
await writeFile(
sourcePath('opencode.json'),
JSON.stringify({ mcp: { servers: { linear: { type: 'remote', url: 'https://linear.example.com' } } } }),
'utf8',
)
const updated = await updateOpenCodeConfigFile(
{ mcp: { servers: { servers: { type: 'remote', url: 'https://s.example.com' } } } },
{ mode: 'merge' },
)
expect(updated.content).toEqual({
mcp: {
servers: {
linear: { type: 'remote', url: 'https://linear.example.com' },
servers: { type: 'remote', url: 'https://s.example.com' },
},
},
})
})
it('keeps the v2 mcp object when the whole servers map is removed', async () => {
await writeFile(
sourcePath('opencode.json'),
JSON.stringify({ mcp: { timeout: { connect: 5000 }, servers: { linear: { type: 'remote', url: 'https://linear.example.com' } } } }),
'utf8',
)
const updated = await updateOpenCodeConfigFile({ mcp: { servers: null } }, { mode: 'merge' })
expect(updated.content).toEqual({ mcp: { timeout: { connect: 5000 } } })
})
it('keeps a comment that leads the sibling after the removed v1 container', async () => {
const raw = '{\n // lead\n "agent": {"reviewer":{"description":"Legacy reviewer"}},\n // theme comment\n "theme": "dark"\n}\n'
await writeFile(sourcePath('opencode.json'), raw, 'utf8')
@@ -45,13 +45,12 @@ const deletedSession = {
} satisfies V2Event
describe('routeOpenCodeEvent', () => {
it('serializes the event payload and remembers its directory by session', () => {
it('remembers the directory of a located event by session', () => {
const directories = new Map<string, string>()
const routed = routeOpenCodeEvent(locatedStatus, directories)
expect(routed.event).toBe(locatedStatus)
expect(routed.payloadJson).toBe(JSON.stringify(locatedStatus))
expect(routed.directory).toBe('/work/alpha')
expect(routed.resolvedDirectory).toBe('/work/alpha')
expect(directories.get('ses_1')).toBe('/work/alpha')
@@ -67,9 +67,13 @@ async function flushReplay(): Promise<void> {
}
}
const PAYLOAD = '{"id":"evt_1","created":1,"type":"session.idle","location":{"directory":"/repo"},"data":{"sessionID":"ses_1"}}'
const LOCAL_EVENT = JSON.parse(PAYLOAD) as V2Event
const LOCAL_EVENT = {
id: 'evt_1',
created: 1,
type: 'session.idle',
location: { directory: '/repo' },
data: { sessionID: 'ses_1' },
} satisfies V2Event
describe('SSEAggregator remote envelope delivery', () => {
beforeEach(() => {
@@ -90,9 +94,9 @@ describe('SSEAggregator remote envelope delivery', () => {
sseAggregator.addClient('local-dir', local.callback, local.writeFrame, ['/repo'])
sseAggregator.addClient('no-directories', unsubscribed.callback, unsubscribed.writeFrame, [])
sseAggregator.deliverRemoteEnvelope('srv_a', '/repo', PAYLOAD)
sseAggregator.deliverRemoteEnvelope('srv_a', '/repo', LOCAL_EVENT)
const expected = { directory: '/repo', serverId: 'srv_a', payload: JSON.parse(PAYLOAD) }
const expected = { directory: '/repo', serverId: 'srv_a', payload: LOCAL_EVENT }
expect(subscribed.frames.map(parseFrame)).toEqual([expected])
expect(otherDirectory.frames.map(parseFrame)).toEqual([expected])
expect(otherServer.frames.map(parseFrame)).toEqual([expected])
@@ -110,9 +114,9 @@ describe('SSEAggregator remote envelope delivery', () => {
sseAggregator.addClient('any-c', otherServer.callback, otherServer.writeFrame, ['srv_b|/repo'])
sseAggregator.addClient('any-d', local.callback, local.writeFrame, ['/repo'])
sseAggregator.deliverRemoteEnvelope('srv_a', null, PAYLOAD)
sseAggregator.deliverRemoteEnvelope('srv_a', null, LOCAL_EVENT)
const expected = { directory: null, serverId: 'srv_a', payload: JSON.parse(PAYLOAD) }
const expected = { directory: null, serverId: 'srv_a', payload: LOCAL_EVENT }
expect(first.frames.map(parseFrame)).toEqual([expected])
expect(second.frames.map(parseFrame)).toEqual([expected])
expect(otherServer.frames.map(parseFrame)).toEqual([expected])
@@ -124,7 +128,7 @@ describe('SSEAggregator remote envelope delivery', () => {
sseAggregator.addClient('targeted', client.callback, client.writeFrame, ['srv_a|/repo'])
sseAggregator.removeDirectories('targeted', ['srv_a|/repo'])
sseAggregator.deliverRemoteEnvelopeToClient('targeted', 'srv_a', '/repo', PAYLOAD)
sseAggregator.deliverRemoteEnvelopeToClient('targeted', 'srv_a', '/repo', LOCAL_EVENT)
expect(client.frames).toHaveLength(0)
})
@@ -133,10 +137,10 @@ describe('SSEAggregator remote envelope delivery', () => {
const client = createCapturingClient()
sseAggregator.addClient('targeted-ok', client.callback, client.writeFrame, ['srv_a|/repo'])
sseAggregator.deliverRemoteEnvelopeToClient('targeted-ok', 'srv_a', '/repo', PAYLOAD)
sseAggregator.deliverRemoteEnvelopeToClient('targeted-ok', 'srv_a', '/repo', LOCAL_EVENT)
expect(client.frames.map(parseFrame)).toEqual([
{ directory: '/repo', serverId: 'srv_a', payload: JSON.parse(PAYLOAD) },
{ directory: '/repo', serverId: 'srv_a', payload: LOCAL_EVENT },
])
})
@@ -218,8 +222,21 @@ describe('SSEAggregator remote envelope delivery', () => {
sseAggregator.addClient('removed', client.callback, client.writeFrame, ['srv_a|/repo'])
sseAggregator.removeClient('removed')
sseAggregator.deliverRemoteEnvelope('srv_a', null, PAYLOAD)
sseAggregator.deliverRemoteEnvelope('srv_a', null, LOCAL_EVENT)
expect(client.frames).toHaveLength(0)
})
it('does not serialize an envelope that no client receives', () => {
const stringify = vi.spyOn(JSON, 'stringify')
try {
sseAggregator.deliverRemoteEnvelope('srv_a', '/repo', LOCAL_EVENT)
sseAggregator.deliverRemoteEnvelopeToClient('absent', 'srv_a', '/repo', LOCAL_EVENT)
expect(stringify).not.toHaveBeenCalledWith(LOCAL_EVENT)
} finally {
stringify.mockRestore()
}
})
})
+2 -7
View File
@@ -15,6 +15,7 @@ import {
type OpenCodeConfigSourceFile,
type OpenCodeConfigSourceName,
type UpdateOpenCodeConfigRequest,
type UpdateOpenCodeConfigPatchRequest,
type SandboxPreferences,
type SkillFileInfo,
type CreateSkillRequest,
@@ -34,7 +35,7 @@ import type {
import type { NotificationPreferences } from '@opencode-manager/shared/types'
import { saveFile } from '@/lib/download'
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, UpdateOpenCodeConfigPatchRequest, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
export type { UserPreferences, UpdateSettingsRequest, CustomCommand, GitCredential, GitIdentity, GitIdentityProfile, KeyboardShortcutAction } from '@opencode-manager/shared'
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, DEFAULT_DIRECT_SHORTCUTS, BLOCKED_SERVER_ENV_KEYS, DEFAULT_ACTIVITY_WINDOW_MINUTES, ACTIVITY_WINDOW_MINUTE_OPTIONS }
export { isOpenCodeConfigSourceName } from '@opencode-manager/shared'
@@ -134,9 +135,3 @@ export type OpenCodeProviderPatch = {
? Record<string, OpenCodeProviderModelPatch | null> | null
: OpenCodeProviderConfig[K] | null
}
export interface UpdateOpenCodeConfigPatchRequest {
patch: Record<string, unknown>
source?: OpenCodeConfigSourceName
expectedRevision?: string
}
@@ -19,6 +19,7 @@ import {
isOpenCodeConfigSourceName,
} from '@/api/types/settings'
import type { OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName } from '@/api/types/settings'
import type { OpenCodeConfigValidationIssue } from '@opencode-manager/shared'
type ValidationIssue = {
path: string
@@ -121,14 +122,11 @@ export function OpenCodeConfigEditor({
const getIssueText = (issue: ValidationIssue) => `${issue.path}: ${issue.message}`
const resolveIssues = (
issues: Array<{ path: PropertyKey[] | string; message: string }>,
issues: OpenCodeConfigValidationIssue[],
): ValidationIssue[] =>
issues.map((issue) => {
const path = issue.path
const isStructured = Array.isArray(path)
const displaySegments = isStructured
? path.map(String)
: String(path).split('.').filter((segment) => segment.length > 0)
const displaySegments = path.split('.').filter((segment) => segment.length > 0)
const displayPath = displaySegments.length > 0 ? displaySegments.join('.') : 'root'
return {
path: displayPath,
@@ -850,6 +850,34 @@ describe('OpenCodeConfigManager', () => {
expect(await screen.findByLabelText('Config content')).toBeInTheDocument()
})
it('shows an error notice instead of empty managed sections when the managed config request fails', async () => {
mockGetManagedOpenCodeConfig.mockRejectedValue(new FetchError('Bad Gateway', 502))
renderWithQuery(<OpenCodeConfigManager />)
await screen.findByText('opencode.json')
expect(await screen.findAllByText('OpenCode configuration unavailable')).toHaveLength(4)
expect(screen.getAllByText('Bad Gateway')).toHaveLength(4)
const commandsHeader = screen.getByRole('button', { name: /^Commands/ })
expect(commandsHeader).toHaveTextContent('Unavailable')
expect(commandsHeader).not.toHaveTextContent('0 configured')
expect(screen.queryByText('No commands configured')).not.toBeInTheDocument()
expect(screen.queryByText('No agents configured')).not.toBeInTheDocument()
expect(screen.queryByText('No models configured')).not.toBeInTheDocument()
})
it('shows a loading state instead of empty managed sections while the managed config request is pending', async () => {
mockGetManagedOpenCodeConfig.mockReturnValue(new Promise(() => {}))
renderWithQuery(<OpenCodeConfigManager />)
await screen.findByText('opencode.json')
expect(await screen.findAllByText('Loading configuration...')).toHaveLength(4)
expect(screen.getByRole('button', { name: /^Commands/ })).toHaveTextContent('Loading...')
expect(screen.queryByText('No commands configured')).not.toBeInTheDocument()
})
it('saves an agent with an entity patch through the managed config endpoint', async () => {
mockGetManagedOpenCodeConfig.mockResolvedValue({
revision: 'rev-1',
@@ -40,6 +40,38 @@ const SECTION_META_CLASS = 'text-xs text-muted-foreground'
const getConfigFileName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
interface ManagedConfigSectionFallbackProps {
isLoading: boolean
unavailableMessage: string | null
errorMessage: string | null
}
function ManagedConfigSectionFallback({ isLoading, unavailableMessage, errorMessage }: ManagedConfigSectionFallbackProps) {
if (isLoading) {
return (
<p className="flex items-center gap-2 py-4 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Loading configuration...
</p>
)
}
if (unavailableMessage) {
return <p className="py-4 text-sm text-muted-foreground">{unavailableMessage}</p>
}
if (errorMessage) {
return (
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-3">
<p className="font-medium text-destructive">OpenCode configuration unavailable</p>
<p className="mt-1 text-sm text-destructive/90">{errorMessage}</p>
</div>
)
}
return null
}
export function OpenCodeConfigManager() {
const sectionIdPrefix = useId()
const agentsMdContentId = `${sectionIdPrefix}-agents-md`
@@ -82,7 +114,11 @@ export function OpenCodeConfigManager() {
const hostImportRef = useRef<HTMLButtonElement>(null)
const { data: config, isLoading } = useOpenCodeConfigFile()
const { data: managedConfig, error: managedConfigError } = useOpenCodeManagedConfig()
const {
data: managedConfig,
error: managedConfigError,
isLoading: isManagedConfigLoading,
} = useOpenCodeManagedConfig()
const managedAgents = managedConfig?.info.agents ?? {}
const managedCommands = managedConfig?.info.commands ?? {}
const managedProviders = managedConfig?.info.providers ?? {}
@@ -139,6 +175,28 @@ export function OpenCodeConfigManager() {
return getApiErrorMessage(error, 'Failed to import existing OpenCode host data')
}
const isManagedConfigPending = isManagedConfigLoading || Boolean(managedConfigError)
const managedConfigErrorMessage = managedConfigError && !isManagedConfigUnavailable
? getApiErrorMessage(managedConfigError, 'Failed to load the OpenCode configuration')
: null
const getManagedConfigCountLabel = (count: number): string => {
if (isManagedConfigLoading) return 'Loading...'
if (managedConfigError) return 'Unavailable'
return `${count} configured`
}
const renderManagedConfigSection = (unavailableMessage: string, content: React.ReactNode) =>
isManagedConfigPending ? (
<ManagedConfigSectionFallback
isLoading={isManagedConfigLoading}
unavailableMessage={isManagedConfigUnavailable ? unavailableMessage : null}
errorMessage={managedConfigErrorMessage}
/>
) : (
content
)
const applyOpenCodeConfigSave = (result: OpenCodeConfigSaveResponse) => {
queryClient.setQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY, result)
applyOpenCodeSaveFeedback({
@@ -152,11 +210,7 @@ export function OpenCodeConfigManager() {
OPEN_CODE_CONFIG_QUERY_KEY,
)?.revision
const result = await settingsApi.patchOpenCodeConfig({ patch, expectedRevision })
queryClient.setQueryData<OpenCodeConfigFile>(OPEN_CODE_CONFIG_QUERY_KEY, result)
applyOpenCodeSaveFeedback({
appliedMessage: 'Configuration updated',
restartRequired: result.restartRequired,
})
applyOpenCodeConfigSave(result)
queryClient.invalidateQueries({ queryKey: OPEN_CODE_MANAGED_CONFIG_QUERY_KEY })
}
@@ -364,7 +418,7 @@ export function OpenCodeConfigManager() {
<div className="flex min-w-0 items-center gap-3">
<h4 className={SECTION_TITLE_CLASS}>Commands</h4>
<span className={SECTION_META_CLASS}>
{Object.keys(managedCommands).length + directoryCommands.length} configured
{getManagedConfigCountLabel(Object.keys(managedCommands).length + directoryCommands.length)}
</span>
</div>
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.commands && 'rotate-180')} />
@@ -373,17 +427,14 @@ export function OpenCodeConfigManager() {
id={commandsContentId}
className={cn(SECTION_CONTENT_CLASS, expandedSections.commands ? 'block' : 'hidden')}
>
{isManagedConfigUnavailable ? (
<p className="py-4 text-sm text-muted-foreground">
OpenCode is not running, so the configured commands cannot be listed. Use Edit to change the config file directly.
</p>
) : (
{renderManagedConfigSection(
'OpenCode is not running, so the configured commands cannot be listed. Use Edit to change the config file directly.',
<CommandsEditor
commands={managedCommands}
directoryCommands={directoryCommands}
onSave={(name, command, previousName) => saveManagedEntity('commands', name, command, previousName)}
onDelete={(name) => deleteManagedEntity('commands', name)}
/>
/>,
)}
</div>
</div>
@@ -400,7 +451,7 @@ export function OpenCodeConfigManager() {
<div className="flex min-w-0 items-center gap-3">
<h4 className={SECTION_TITLE_CLASS}>Agents</h4>
<span className={SECTION_META_CLASS}>
{Object.keys(managedAgents).length + directoryAgents.length} configured
{getManagedConfigCountLabel(Object.keys(managedAgents).length + directoryAgents.length)}
</span>
</div>
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.agents && 'rotate-180')} />
@@ -409,17 +460,14 @@ export function OpenCodeConfigManager() {
id={agentsContentId}
className={cn(SECTION_CONTENT_CLASS, expandedSections.agents ? 'block' : 'hidden')}
>
{isManagedConfigUnavailable ? (
<p className="py-4 text-sm text-muted-foreground">
OpenCode is not running, so the configured agents cannot be listed. Use Edit to change the config file directly.
</p>
) : (
{renderManagedConfigSection(
'OpenCode is not running, so the configured agents cannot be listed. Use Edit to change the config file directly.',
<AgentsEditor
agents={managedAgents}
directoryAgents={directoryAgents}
onSave={(name, agent, previousName) => saveManagedEntity('agents', name, agent, previousName)}
onDelete={(name) => deleteManagedEntity('agents', name)}
/>
/>,
)}
</div>
</div>
@@ -463,7 +511,7 @@ export function OpenCodeConfigManager() {
<div className="flex min-w-0 items-center gap-3">
<h4 className={SECTION_TITLE_CLASS}>MCP Servers</h4>
<span className={SECTION_META_CLASS}>
{Object.keys(managedMcpServers).length} configured
{getManagedConfigCountLabel(Object.keys(managedMcpServers).length)}
</span>
</div>
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.mcp && 'rotate-180')} />
@@ -472,16 +520,13 @@ export function OpenCodeConfigManager() {
id={mcpContentId}
className={cn(SECTION_CONTENT_CLASS, expandedSections.mcp ? 'block' : 'hidden')}
>
{isManagedConfigUnavailable ? (
<p className="py-4 text-sm text-muted-foreground">
OpenCode is not running, so the configured MCP servers cannot be listed. Use Edit to change the config file directly.
</p>
) : (
{renderManagedConfigSection(
'OpenCode is not running, so the configured MCP servers cannot be listed. Use Edit to change the config file directly.',
<McpManager
mcp={managedConfig?.info.mcp}
onSave={(serverId, server) => patchManagedConfig({ mcp: { servers: { [serverId]: server } } })}
onDelete={(serverId) => patchManagedConfig({ mcp: { servers: { [serverId]: null } } })}
/>
/>,
)}
</div>
</div>
@@ -498,10 +543,12 @@ export function OpenCodeConfigManager() {
<div className="flex min-w-0 items-center gap-3">
<h4 className={SECTION_TITLE_CLASS}>Models</h4>
<span className={SECTION_META_CLASS}>
{Object.values(managedProviders).reduce<number>(
(acc, provider) => acc + Object.keys(provider.models ?? {}).length,
0,
)} configured
{getManagedConfigCountLabel(
Object.values(managedProviders).reduce<number>(
(acc, provider) => acc + Object.keys(provider.models ?? {}).length,
0,
),
)}
</span>
</div>
<ChevronDown className={cn(SECTION_CHEVRON_CLASS, expandedSections.models && 'rotate-180')} />
@@ -510,15 +557,12 @@ export function OpenCodeConfigManager() {
id={modelsContentId}
className={cn(SECTION_CONTENT_CLASS, expandedSections.models ? 'block' : 'hidden')}
>
{isManagedConfigUnavailable ? (
<p className="py-4 text-sm text-muted-foreground">
OpenCode is not running, so the configured models cannot be listed. Use Edit to change the config file directly.
</p>
) : (
{renderManagedConfigSection(
'OpenCode is not running, so the configured models cannot be listed. Use Edit to change the config file directly.',
<OpenCodeModelsEditor
providers={managedProviders}
onSave={(providers) => patchManagedConfigSafely({ providers })}
/>
/>,
)}
</div>
</div>
@@ -13,6 +13,7 @@ import { Combobox } from '@/components/ui/combobox'
import { Label } from '@/components/ui/label'
import { RefreshCw, Loader2 } from 'lucide-react'
import { settingsApi } from '@/api/settings'
import { isRecord } from '@opencode-manager/shared/utils'
import type { OpenCodeProviderConfig, OpenCodeProviderModelConfig } from '@opencode-manager/shared/opencode'
import type { OpenCodeProviderModelPatch } from '@/api/types/settings'
@@ -89,12 +90,8 @@ function parseOptionalNumber(value: string): number | undefined {
return Number.isFinite(parsed) ? parsed : undefined
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}
function withRemovedKeysAsNull(previous: unknown, next: unknown): unknown {
if (!isPlainObject(previous) || !isPlainObject(next)) return next
if (!isRecord(previous) || !isRecord(next)) return next
const patch: Record<string, unknown> = {}
for (const key of Object.keys(previous)) {
@@ -5,6 +5,7 @@ import {
type SSHHostKeyRequestEvent,
} from '@opencode-manager/shared/schemas'
import type { V2Event } from '@opencode-manager/shared/opencode'
import { isRecord } from '@opencode-manager/shared/utils'
import { createBrowserEventStreamTransport } from './browserTransport'
import type {
EventStreamHealthState,
@@ -508,10 +509,6 @@ function parseResyncServerId(data?: string): string | undefined {
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object'
}
function isEventPayload(value: unknown): value is V2Event | SSHHostKeyRequestEvent {
return isRecord(value) && typeof value.type === 'string'
}
-1
View File
@@ -80,7 +80,6 @@ export function invalidateConfigCaches(
queryClient.invalidateQueries({ queryKey: ['opencode', 'commands'] })
if (!options.skipOpenCodeConfig) {
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
queryClient.invalidateQueries({ queryKey: OPEN_CODE_MANAGED_CONFIG_QUERY_KEY })
}
queryClient.invalidateQueries({ queryKey: ['health'] })
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
+1 -5
View File
@@ -1,10 +1,6 @@
import { Info } from '@opencode/schema/config'
import { Schema } from 'effect'
export interface OpenCodeConfigValidationIssue {
path: string
message: string
}
import type { OpenCodeConfigValidationIssue } from '../types'
export type OpenCodeConfigValidationResult =
| { success: true }
-6
View File
@@ -22,12 +22,6 @@ export interface SSHHostKeyRequestEvent {
properties: SSHHostKeyRequest;
}
export interface SSEEventEnvelope {
directory?: string | null;
serverId?: string;
payload: V2Event | SSHHostKeyRequestEvent;
}
export type OpenCodeStreamEvent = (V2Event | SSHHostKeyRequestEvent) & {
directory?: string;
serverId?: string;
+2
View File
@@ -8,6 +8,7 @@ import {
OpenCodeConfigSourceFileSchema,
OpenCodeConfigValidationIssueSchema,
UpdateOpenCodeConfigRequestSchema,
UpdateOpenCodeConfigPatchRequestSchema,
ServerEnvVarSchema,
} from '../schemas/settings'
import {
@@ -76,6 +77,7 @@ export type { OpenCodeConfigSourceName } from '../config/defaults'
export type OpenCodeConfigSourceFile = z.infer<typeof OpenCodeConfigSourceFileSchema>
export type OpenCodeConfigValidationIssue = z.infer<typeof OpenCodeConfigValidationIssueSchema>
export type UpdateOpenCodeConfigRequest = z.infer<typeof UpdateOpenCodeConfigRequestSchema>
export type UpdateOpenCodeConfigPatchRequest = z.infer<typeof UpdateOpenCodeConfigPatchRequestSchema>
export type Repo = z.infer<typeof RepoSchema>
export type InternalRepoListResponse = z.infer<typeof InternalRepoListResponseSchema>