mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
loop: om-179-finish-adopting-op completed after 19 iterations
This commit is contained in:
1 parent
7c4cfd858c
commit
49bb4ebd36
25 files changed
+362
-198
No files matched your search
@@ -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()
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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++
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user