diff --git a/src/v2/commands.ts b/src/v2/commands.ts index 66c2893b..5a16fac1 100644 --- a/src/v2/commands.ts +++ b/src/v2/commands.ts @@ -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 | null +} + +const serverRegistryKey = Symbol.for('opencode-pty.v2.server') +const runtime = globalThis as typeof globalThis & Record + +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 { - 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 } } diff --git a/test/v2.test.ts b/test/v2.test.ts index 47f979ee..433ae76b 100644 --- a/test/v2.test.ts +++ b/test/v2.test.ts @@ -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()