Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 38 additions & 8 deletions src/v2/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,53 @@ import type { CommandDraft } from './types.ts'
export const PTY_OPEN_CLIENT_COMMAND = 'pty-open-background-spy'
export const PTY_SHOW_SERVER_URL_COMMAND = 'pty-show-server-url'

let activeServer: PTYServer | null = null
interface ServerRegistry {
active: PTYServer | null
pending: Promise<PTYServer> | null
}

const serverRegistryKey = Symbol.for('opencode-pty.v2.server')
const runtime = globalThis as typeof globalThis & Record<symbol, unknown>

function getServerRegistry(): ServerRegistry {
let registry = runtime[serverRegistryKey] as ServerRegistry | undefined
if (!registry) {
registry = { active: null, pending: null }
runtime[serverRegistryKey] = registry
}
return registry
}

export async function getOrCreateServer(options?: ServerOptions): Promise<PTYServer> {
if (!activeServer) {
activeServer = await PTYServer.createServer(options)
const registry = getServerRegistry()
if (registry.active) {
return registry.active
}
if (registry.pending) {
return registry.pending
}

const pending = PTYServer.createServer(options)
registry.pending = pending
try {
registry.active = await pending
return registry.active
} finally {
if (registry.pending === pending) {
registry.pending = null
}
}
return activeServer
}

export function getActiveServer(): PTYServer | null {
return activeServer
return getServerRegistry().active
}

export function stopActiveServer(): void {
if (activeServer) {
activeServer[Symbol.dispose]()
activeServer = null
const registry = getServerRegistry()
if (registry.active) {
registry.active[Symbol.dispose]()
registry.active = null
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,16 @@ describe('OpenCode V2 Plugin API', () => {
expect(server.server.url.hostname).toBe('127.0.0.1')
})

it('shares one server across concurrent initialization', async () => {
const [first, second] = await Promise.all([
getOrCreateServer({ port: 0, hostname: '127.0.0.1' }),
getOrCreateServer({ port: 0, hostname: '127.0.0.1' }),
])

expect(second).toBe(first)
expect(getActiveServer()).toBe(first)
})

it('autostarts server when autostart option is true in ctx.options', async () => {
expect(getActiveServer()).toBeNull()

Expand Down