Skip to content

Commit 87c33b3

Browse files
committed
fix(plugin): reuse active server for client requests
Temporarily route plugin SDK calls through the active listener so they reuse its instance store instead of initializing plugins again through the default app. Keep the in-process fallback for commands without a listener. This is intentionally a narrow bridge until v2 owns plugin clients in the correct shared server runtime.
1 parent 3f81402 commit 87c33b3

3 files changed

Lines changed: 70 additions & 8 deletions

File tree

‎packages/opencode/src/plugin/index.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,11 +138,12 @@ export const layer = Layer.effect(
138138

139139
const { Server } = yield* Effect.promise(() => import("../server/server"))
140140

141+
const serverUrl = Server.url
141142
const client = createOpencodeClient({
142-
baseUrl: "http://localhost:4096",
143+
baseUrl: serverUrl?.toString() ?? "http://localhost:4096",
143144
directory: ctx.directory,
144145
headers: ServerAuth.headers(),
145-
fetch: async (...args) => Server.Default().app.fetch(...args),
146+
...(serverUrl ? {} : { fetch: async (...args) => Server.Default().app.fetch(...args) }),
146147
})
147148
const cfg = yield* config.get()
148149
const input: PluginInput = {

‎packages/opencode/src/server/server.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ export async function openapi() {
6767
return OpenApi.fromApi(PublicApi)
6868
}
6969

70-
export let url: URL
70+
export let url: URL | undefined
7171

7272
export async function listen(opts: ListenOptions): Promise<Listener> {
7373
const listener = await Effect.runPromise(listenEffect(opts))
@@ -84,15 +84,14 @@ const listenEffect: (opts: ListenOptions) => Effect.Effect<EffectListener, unkno
8484
const state = yield* startWithPortFallback(opts)
8585
const address = yield* tcpAddress(state)
8686
const listenerUrl = makeURL(opts.hostname, address.port)
87-
url = listenerUrl
88-
8987
const unpublishMdns = yield* setupMdns(opts, address.port, state.scope)
88+
url = listenerUrl
9089

9190
return {
9291
hostname: opts.hostname,
9392
port: address.port,
9493
url: listenerUrl,
95-
stop: yield* makeStop(state, unpublishMdns),
94+
stop: yield* makeStop(state, unpublishMdns, listenerUrl),
9695
}
9796
},
9897
)
@@ -169,10 +168,19 @@ function setupMdns(opts: ListenOptions, port: number, scope: Scope.Scope) {
169168
})
170169
}
171170

172-
function makeStop(state: ListenerState, unpublishMdns: Effect.Effect<void>) {
171+
function makeStop(state: ListenerState, unpublishMdns: Effect.Effect<void>, listenerUrl: URL) {
173172
return Effect.gen(function* () {
174173
const forceCloseOnce = yield* Effect.cached(forceClose(state).pipe(Effect.ignore))
175-
const closeScopeOnce = yield* Effect.cached(Scope.close(state.scope, Exit.void).pipe(Effect.ignore))
174+
const closeScopeOnce = yield* Effect.cached(
175+
Scope.close(state.scope, Exit.void).pipe(
176+
Effect.ignore,
177+
Effect.ensuring(
178+
Effect.sync(() => {
179+
if (url === listenerUrl) url = undefined
180+
}),
181+
),
182+
),
183+
)
176184

177185
return (close?: boolean) =>
178186
Effect.gen(function* () {

‎packages/opencode/test/server/httpapi-listen.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { afterEach, describe, expect, test } from "bun:test"
22
import net from "node:net"
3+
import path from "node:path"
4+
import { pathToFileURL } from "node:url"
35
import { Flag } from "@opencode-ai/core/flag/flag"
46
import { Server } from "../../src/server/server"
57
import { PtyPaths } from "../../src/server/routes/instance/httpapi/groups/pty"
@@ -300,6 +302,57 @@ describe("HttpApi Server.listen", () => {
300302
expect(output).not.toContain("Sent HTTP response")
301303
})
302304

305+
test("plugin client requests reuse the listening server instance", async () => {
306+
await using tmp = await tmpdir({
307+
init: async (directory) => {
308+
const plugin = path.join(directory, "plugin.ts")
309+
const initialized = path.join(directory, "initialized.txt")
310+
const completed = path.join(directory, "completed.txt")
311+
await Bun.write(
312+
plugin,
313+
[
314+
"export default async function plugin(input) {",
315+
` await Bun.write(${JSON.stringify(initialized)}, (await Bun.file(${JSON.stringify(initialized)}).text().catch(() => "")) + "initialized\\n")`,
316+
" setTimeout(async () => {",
317+
" await input.client.config.get()",
318+
` await Bun.write(${JSON.stringify(completed)}, "completed")`,
319+
" }, 50)",
320+
" return {}",
321+
"}",
322+
"",
323+
].join("\n"),
324+
)
325+
await Bun.write(
326+
path.join(directory, "opencode.json"),
327+
JSON.stringify({ formatter: false, lsp: false, plugin: [pathToFileURL(plugin).href] }),
328+
)
329+
return { initialized, completed }
330+
},
331+
})
332+
const previous = process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS
333+
process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS = "1"
334+
let listener: Awaited<ReturnType<typeof startListener>> | undefined
335+
try {
336+
listener = await startListener()
337+
const response = await fetch(new URL("/config", listener.url), {
338+
headers: { authorization: authorization(), "x-opencode-directory": tmp.path },
339+
})
340+
expect(response.status).toBe(200)
341+
await withTimeout(
342+
(async () => {
343+
while (!(await Bun.file(tmp.extra.completed).exists())) await Bun.sleep(10)
344+
})(),
345+
5_000,
346+
"timed out waiting for plugin client request",
347+
)
348+
expect(await Bun.file(tmp.extra.initialized).text()).toBe("initialized\n")
349+
} finally {
350+
if (listener) await stop(listener, "timed out cleaning up plugin client listener").catch(() => undefined)
351+
if (previous === undefined) delete process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS
352+
else process.env.OPENCODE_DISABLE_DEFAULT_PLUGINS = previous
353+
}
354+
})
355+
303356
test("port 0 prefers 4096 when free", async () => {
304357
if (!(await isPortFree(4096))) return
305358
const listener = await startListener()

0 commit comments

Comments
 (0)