diff --git a/backend/src/index.ts b/backend/src/index.ts index 6688a0e5..ca4d5870 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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() diff --git a/backend/src/routes/opencode-server-proxy.ts b/backend/src/routes/opencode-server-proxy.ts index 38050678..67a9d124 100644 --- a/backend/src/routes/opencode-server-proxy.ts +++ b/backend/src/routes/opencode-server-proxy.ts @@ -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), diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index f1cf30e7..6c24b164 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -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 \`\` 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 { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function parseAssistantOpenCodeConfig(rawContent: string): Record | 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): 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[][] { 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) diff --git a/backend/src/services/opencode-config-effective.ts b/backend/src/services/opencode-config-effective.ts index 1af2ccdb..5b9427cd 100644 --- a/backend/src/services/opencode-config-effective.ts +++ b/backend/src/services/opencode-config-effective.ts @@ -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> { + const entries = await api.config.get(openCodeLocation(directory)) + const infoByPath = new Map() + + 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, ): Promise { - const entries = await api.config.get(openCodeLocation(getWorkspacePath())) - const infoByPath = new Map>() - - for (const entry of entries) { - if (entry.type !== 'document' || !entry.path) continue - infoByPath.set(path.resolve(entry.path), entry.info as Record) - } + const infoByPath = await readOpenCodeConfigDocuments(api, getWorkspacePath()) const merged = sources.reduce>((current, source) => { const info = infoByPath.get(path.resolve(source.path)) - return info ? mergeOpenCodeConfigValues(current, info) : current + return info ? mergeOpenCodeConfigValues(current, info as Record) : current }, {}) return merged as OpenCodeConfigInfo diff --git a/backend/src/services/opencode-config-file.ts b/backend/src/services/opencode-config-file.ts index 94dc839f..ebe6f814 100644 --- a/backend/src/services/opencode-config-file.ts +++ b/backend/src/services/opencode-config-file.ts @@ -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, key: string): boolean { return Object.prototype.hasOwnProperty.call(object, key) } +interface ReadOpenCodeConfigPathOptions { + nullAncestorCountsAsFound?: boolean +} + function readOpenCodeConfigPath( content: Record, 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, jsonPath: JSONP return readOpenCodeConfigPath(content, jsonPath).found } -function readPatchedOpenCodeConfigPath( - patch: Record, - 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, 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 }) } } diff --git a/backend/src/services/opencode-event-routing.ts b/backend/src/services/opencode-event-routing.ts index 65123f11..03d59b15 100644 --- a/backend/src/services/opencode-event-routing.ts +++ b/backend/src/services/opencode-event-routing.ts @@ -13,8 +13,6 @@ type SessionStatusEvent = Extract 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, -): Omit { +): 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, -): RoutedOpenCodeEvent { - return { ...resolveEventRouting(event, sessionDirectories), payloadJson: JSON.stringify(event) } -} - export async function collectPendingReplayEvents(request: PendingReplayRequest): Promise { 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) -} diff --git a/backend/src/services/opencode-event-subscription.ts b/backend/src/services/opencode-event-subscription.ts index 0bf823c6..b7ff5a39 100644 --- a/backend/src/services/opencode-event-subscription.ts +++ b/backend/src/services/opencode-event-subscription.ts @@ -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 | 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. * diff --git a/backend/src/services/remote-server-events.ts b/backend/src/services/remote-server-events.ts index 20b81eef..caf8a386 100644 --- a/backend/src/services/remote-server-events.ts +++ b/backend/src/services/remote-server-events.ts @@ -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() - 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++ } diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index 68df187e..17cfb875 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -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, 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') } diff --git a/backend/test/routes/opencode-server-proxy.test.ts b/backend/test/routes/opencode-server-proxy.test.ts index 515bab26..c46d6fb3 100644 --- a/backend/test/routes/opencode-server-proxy.test.ts +++ b/backend/test/routes/opencode-server-proxy.test.ts @@ -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 diff --git a/backend/test/services/assistant-mode.test.ts b/backend/test/services/assistant-mode.test.ts index 0e272856..8a14d3b0 100644 --- a/backend/test/services/assistant-mode.test.ts +++ b/backend/test/services/assistant-mode.test.ts @@ -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) diff --git a/backend/test/services/opencode-config-effective.test.ts b/backend/test/services/opencode-config-effective.test.ts index 049cae89..c2004175 100644 --- a/backend/test/services/opencode-config-effective.test.ts +++ b/backend/test/services/opencode-config-effective.test.ts @@ -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([ diff --git a/backend/test/services/opencode-config-file.test.ts b/backend/test/services/opencode-config-file.test.ts index e920bd92..0503ed3e 100644 --- a/backend/test/services/opencode-config-file.test.ts +++ b/backend/test/services/opencode-config-file.test.ts @@ -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') diff --git a/backend/test/services/opencode-event-routing.test.ts b/backend/test/services/opencode-event-routing.test.ts index 916c98c2..bc62bde0 100644 --- a/backend/test/services/opencode-event-routing.test.ts +++ b/backend/test/services/opencode-event-routing.test.ts @@ -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() 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') diff --git a/backend/test/services/sse-aggregator-remote.test.ts b/backend/test/services/sse-aggregator-remote.test.ts index f854717f..3b94644a 100644 --- a/backend/test/services/sse-aggregator-remote.test.ts +++ b/backend/test/services/sse-aggregator-remote.test.ts @@ -67,9 +67,13 @@ async function flushReplay(): Promise { } } -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() + } + }) }) diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 306dd035..c4698cf0 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -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 | null : OpenCodeProviderConfig[K] | null } - -export interface UpdateOpenCodeConfigPatchRequest { - patch: Record - source?: OpenCodeConfigSourceName - expectedRevision?: string -} diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index d763123f..a5535671 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -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, diff --git a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx index 09b0ac9e..818e0e29 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.test.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.test.tsx @@ -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() + + 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() + + 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', diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index 2211d9bc..5c234a02 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -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 ( +

+ + Loading configuration... +

+ ) + } + + if (unavailableMessage) { + return

{unavailableMessage}

+ } + + if (errorMessage) { + return ( +
+

OpenCode configuration unavailable

+

{errorMessage}

+
+ ) + } + + return null +} + export function OpenCodeConfigManager() { const sectionIdPrefix = useId() const agentsMdContentId = `${sectionIdPrefix}-agents-md` @@ -82,7 +114,11 @@ export function OpenCodeConfigManager() { const hostImportRef = useRef(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 ? ( + + ) : ( + content + ) + const applyOpenCodeConfigSave = (result: OpenCodeConfigSaveResponse) => { queryClient.setQueryData(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(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() {

Commands

- {Object.keys(managedCommands).length + directoryCommands.length} configured + {getManagedConfigCountLabel(Object.keys(managedCommands).length + directoryCommands.length)}
@@ -373,17 +427,14 @@ export function OpenCodeConfigManager() { id={commandsContentId} className={cn(SECTION_CONTENT_CLASS, expandedSections.commands ? 'block' : 'hidden')} > - {isManagedConfigUnavailable ? ( -

- OpenCode is not running, so the configured commands cannot be listed. Use Edit to change the config file directly. -

- ) : ( + {renderManagedConfigSection( + 'OpenCode is not running, so the configured commands cannot be listed. Use Edit to change the config file directly.', saveManagedEntity('commands', name, command, previousName)} onDelete={(name) => deleteManagedEntity('commands', name)} - /> + />, )} @@ -400,7 +451,7 @@ export function OpenCodeConfigManager() {

Agents

- {Object.keys(managedAgents).length + directoryAgents.length} configured + {getManagedConfigCountLabel(Object.keys(managedAgents).length + directoryAgents.length)}
@@ -409,17 +460,14 @@ export function OpenCodeConfigManager() { id={agentsContentId} className={cn(SECTION_CONTENT_CLASS, expandedSections.agents ? 'block' : 'hidden')} > - {isManagedConfigUnavailable ? ( -

- OpenCode is not running, so the configured agents cannot be listed. Use Edit to change the config file directly. -

- ) : ( + {renderManagedConfigSection( + 'OpenCode is not running, so the configured agents cannot be listed. Use Edit to change the config file directly.', saveManagedEntity('agents', name, agent, previousName)} onDelete={(name) => deleteManagedEntity('agents', name)} - /> + />, )} @@ -463,7 +511,7 @@ export function OpenCodeConfigManager() {

MCP Servers

- {Object.keys(managedMcpServers).length} configured + {getManagedConfigCountLabel(Object.keys(managedMcpServers).length)}
@@ -472,16 +520,13 @@ export function OpenCodeConfigManager() { id={mcpContentId} className={cn(SECTION_CONTENT_CLASS, expandedSections.mcp ? 'block' : 'hidden')} > - {isManagedConfigUnavailable ? ( -

- OpenCode is not running, so the configured MCP servers cannot be listed. Use Edit to change the config file directly. -

- ) : ( + {renderManagedConfigSection( + 'OpenCode is not running, so the configured MCP servers cannot be listed. Use Edit to change the config file directly.', patchManagedConfig({ mcp: { servers: { [serverId]: server } } })} onDelete={(serverId) => patchManagedConfig({ mcp: { servers: { [serverId]: null } } })} - /> + />, )} @@ -498,10 +543,12 @@ export function OpenCodeConfigManager() {

Models

- {Object.values(managedProviders).reduce( - (acc, provider) => acc + Object.keys(provider.models ?? {}).length, - 0, - )} configured + {getManagedConfigCountLabel( + Object.values(managedProviders).reduce( + (acc, provider) => acc + Object.keys(provider.models ?? {}).length, + 0, + ), + )}
@@ -510,15 +557,12 @@ export function OpenCodeConfigManager() { id={modelsContentId} className={cn(SECTION_CONTENT_CLASS, expandedSections.models ? 'block' : 'hidden')} > - {isManagedConfigUnavailable ? ( -

- OpenCode is not running, so the configured models cannot be listed. Use Edit to change the config file directly. -

- ) : ( + {renderManagedConfigSection( + 'OpenCode is not running, so the configured models cannot be listed. Use Edit to change the config file directly.', patchManagedConfigSafely({ providers })} - /> + />, )} diff --git a/frontend/src/components/settings/OpenCodeModelDialog.tsx b/frontend/src/components/settings/OpenCodeModelDialog.tsx index 0e1dbc11..708946bc 100644 --- a/frontend/src/components/settings/OpenCodeModelDialog.tsx +++ b/frontend/src/components/settings/OpenCodeModelDialog.tsx @@ -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 { - 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 = {} for (const key of Object.keys(previous)) { diff --git a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts index d8cce348..6ddb348b 100644 --- a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts +++ b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts @@ -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 { - return value !== null && typeof value === 'object' -} - function isEventPayload(value: unknown): value is V2Event | SSHHostKeyRequestEvent { return isRecord(value) && typeof value.type === 'string' } diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index ec5b99fa..f1f554f4 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -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'] }) diff --git a/shared/src/opencode/config-validation.ts b/shared/src/opencode/config-validation.ts index c2a86b4e..f1978bde 100644 --- a/shared/src/opencode/config-validation.ts +++ b/shared/src/opencode/config-validation.ts @@ -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 } diff --git a/shared/src/schemas/sse.ts b/shared/src/schemas/sse.ts index ca2653db..b98526e1 100644 --- a/shared/src/schemas/sse.ts +++ b/shared/src/schemas/sse.ts @@ -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; diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 83498221..f6e5e8d4 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -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 export type OpenCodeConfigValidationIssue = z.infer export type UpdateOpenCodeConfigRequest = z.infer +export type UpdateOpenCodeConfigPatchRequest = z.infer export type Repo = z.infer export type InternalRepoListResponse = z.infer