mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +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')
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user