fix(cli): reuse a running background service instead of starting a second one

When the configured port already serves a managed service (including one
registered under another state directory or running another version), connect
to it and warn on a version mismatch, or fail clearly when it rejects the
password, instead of spawning a contender. Probes stay within the build's own
channel and send each password only to the URL it belongs to. Reusing a
registered service probes it once through the new Service.reuse, which also
settles a stale persistent-terminal handoff.
This commit is contained in:
Kit Langton 2026-10-23 10:17:58 -07:00
parent 552e802e4c
commit d39dcd06d6
7 changed files with 443 additions and 27 deletions

View file

@ -56,7 +56,9 @@ export default Runtime.handler(Commands.commands.debug.commands["heap-dump"], (i
const running = Effect.fnUntraced(function* (server: string | undefined) {
if (server !== undefined) return (yield* ServerConnection.resolve({ server })).endpoint
const options = yield* ServiceConfig.options()
const endpoint = yield* Service.discover({ ...options, version: undefined })
const endpoint =
(yield* Service.discover({ ...options, version: undefined })) ??
(yield* ServiceConfig.discover(options.file))?.endpoint
if (endpoint) return endpoint
return yield* Effect.fail(
new Error("No background server is running. Pass --server <url> to capture a server started another way."),

View file

@ -9,7 +9,9 @@ export default Runtime.handler(
Commands.commands.service.commands.status,
Effect.fn("cli.service.status")(function* () {
const options = yield* ServiceConfig.options()
const found = yield* Service.discover({ ...options, version: undefined })
const found =
(yield* Service.discover({ ...options, version: undefined })) ??
(yield* ServiceConfig.discover(options.file))?.endpoint
process.stdout.write((found?.url ?? "stopped") + EOL)
}),
)

View file

@ -37,10 +37,7 @@ export const resolve = Effect.fn("cli.server-connection.resolve")(function* (arg
try: () => client.server.info({ signal: AbortSignal.timeout(5_000) }),
catch: (cause) => connectError(endpoint, cause),
})
if (health.version !== OPENCODE_VERSION)
process.stderr.write(
`Warning: Server at ${endpoint.url} has version ${health.version}; this client is ${OPENCODE_VERSION}. Continuing anyway.\n`,
)
if (health.version !== OPENCODE_VERSION) warnVersionMismatch(endpoint.url, health.version)
return { endpoint } satisfies Resolved
}
if (standalone || (yield* ServiceConfig.read()).disabled === true) {
@ -55,6 +52,12 @@ export const resolve = Effect.fn("cli.server-connection.resolve")(function* (arg
} satisfies Resolved
})
function warnVersionMismatch(url: string, version: string) {
process.stderr.write(
`Warning: Server at ${url} has version ${version}; this client is ${OPENCODE_VERSION}. Continuing anyway.\n`,
)
}
function managedService(options: EnsureOptions) {
const reconnectOptions = { ...options, version: undefined }
return {
@ -70,33 +73,76 @@ function managedService(options: EnsureOptions) {
export const shutdownPersistentPty = Effect.fn("cli.server-connection.shutdown-persistent-pty")(function* (
options: EnsureOptions,
) {
const endpoint = yield* Service.discover({ ...options, version: undefined })
const endpoint =
(yield* Service.discover({ ...options, version: undefined })) ??
(yield* ServiceConfig.discover(options.file))?.endpoint
if (!endpoint) return
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
yield* Effect.tryPromise(() => client.experimental.persistentPty.shutdown())
})
const resolveManaged = Effect.fnUntraced(function* (options: EnsureOptions, mismatch: NonNullable<Args["mismatch"]>) {
if (mismatch === "replace") return yield* Service.ensure(options)
if (mismatch === "ignore") return yield* Service.ensure({ ...options, version: undefined })
if (mismatch === "ignore") {
const registered = yield* Service.reuse({ ...options, version: undefined })
if (registered !== undefined) {
const version = yield* ServiceConfig.registeredVersion(options.file)
if (version !== undefined && version !== OPENCODE_VERSION) warnVersionMismatch(registered.url, version)
return registered
}
const configured = yield* ServiceConfig.probeConfigured({ file: options.file })
if (configured?.state === "ready") {
if (configured.version !== OPENCODE_VERSION) warnVersionMismatch(configured.endpoint.url, configured.version)
return configured.endpoint
}
if (configured?.state === "unauthorized") return yield* Effect.fail(unauthorizedError(configured.endpoint))
if (configured?.state === "incompatible")
return yield* Effect.fail(
new Error(`Server at ${configured.endpoint.url} did not provide a compatible V2 health response`),
)
return yield* Service.ensure({ ...options, version: undefined })
}
const compatible = yield* Service.discover(options)
if (compatible !== undefined) return compatible
const compatible = yield* Service.reuse(options)
if (compatible !== undefined) {
if (options.version === undefined) {
const version = yield* ServiceConfig.registeredVersion(options.file)
if (version !== undefined && version !== OPENCODE_VERSION) warnVersionMismatch(compatible.url, version)
}
return compatible
}
const existing = yield* Service.discover({ ...options, version: undefined })
if (existing !== undefined)
return yield* Effect.fail(new Error("Background server version does not match this client"))
if (existing !== undefined) {
if (mismatch === "error")
return yield* Effect.fail(new Error("Background server version does not match this client"))
return yield* Service.ensure(options)
}
const configured = yield* ServiceConfig.probeConfigured({ file: options.file })
if (configured?.state === "ready") {
if (mismatch === "error" && configured.version !== OPENCODE_VERSION)
return yield* Effect.fail(new Error("Background server version does not match this client"))
if (configured.version !== OPENCODE_VERSION) warnVersionMismatch(configured.endpoint.url, configured.version)
return configured.endpoint
}
if (configured?.state === "unauthorized") return yield* Effect.fail(unauthorizedError(configured.endpoint))
if (configured?.state === "incompatible")
return yield* Effect.fail(
new Error(`Server at ${configured.endpoint.url} did not provide a compatible V2 health response`),
)
return yield* Service.ensure(options)
})
function unauthorizedError(endpoint: Endpoint, cause?: unknown) {
return new Error(
endpoint.auth === undefined
? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`
: `Server at ${endpoint.url} rejected the password`,
cause === undefined ? undefined : { cause },
)
}
function connectError(endpoint: Endpoint, cause: unknown) {
if (isUnauthorizedError(cause)) {
return new Error(
endpoint.auth === undefined
? `Server at ${endpoint.url} requires a password; set OPENCODE_PASSWORD`
: `Server at ${endpoint.url} rejected the password`,
{ cause },
)
}
if (isUnauthorizedError(cause)) return unauthorizedError(endpoint, cause)
if (cause instanceof ClientError && cause.reason === "Transport")
return new Error(`Could not reach server at ${endpoint.url}`, { cause })
return new Error(`Server at ${endpoint.url} did not provide a compatible V2 health response`, { cause })

View file

@ -1,7 +1,7 @@
import { Global } from "@opencode/util/global"
import { OPENCODE_CHANNEL, OPENCODE_VERSION } from "../version"
import { Hash } from "@opencode/util/hash"
import { Service } from "@opencode/client/effect/service"
import { Service, type Endpoint, type Info as RegistrationInfo } from "@opencode/client/effect/service"
import { Effect, FileSystem, Option, Schedule, Schema } from "effect"
import { randomBytes } from "crypto"
import path from "path"
@ -126,6 +126,8 @@ const paths = Effect.gen(function* () {
return {
fs,
file,
name,
home: global.home,
legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,
legacyRegistrationFiles: [
...(legacy ? [path.join(global.state, legacy)] : []),
@ -149,16 +151,168 @@ export function processEnv(env: Info["env"]) {
}
export const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) {
const { file, legacyRegistrationFiles } = yield* paths
yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))
const { fs, file: primaryFile, home, legacyRegistrationFiles, name } = yield* paths
yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, primaryFile))
const config = yield* read()
const configuredState = config.env?.XDG_STATE_HOME ? path.join(config.env.XDG_STATE_HOME, "opencode") : undefined
const homeState =
config.env?.XDG_STATE_HOME !== undefined && config.password !== undefined
? path.join(home, ".local", "state", "opencode")
: undefined
const homeStateFiles = new Set(homeState ? [path.join(homeState, name)] : [])
const candidates = [
...new Set([primaryFile, ...(configuredState ? [path.join(configuredState, name)] : []), ...homeStateFiles]),
]
const file = yield* findActiveRegistrationFile(fs, candidates, primaryFile, homeStateFiles, config.password)
return {
file,
version: input.checkVersion ? OPENCODE_VERSION : undefined,
env: processEnv((yield* read()).env),
version: input.checkVersion && file === primaryFile ? OPENCODE_VERSION : undefined,
env: processEnv(config.env),
command: [...selfCommand(), "serve", "--service"],
}
})
const findActiveRegistrationFile = Effect.fnUntraced(function* (
fs: FileSystem.FileSystem,
candidates: ReadonlyArray<string>,
primaryFile: string,
homeStateFiles: ReadonlySet<string>,
configuredPassword: string | undefined,
) {
if (candidates.length <= 1) return primaryFile
const secondary: string[] = []
for (const candidate of candidates.slice(1)) {
const text = yield* fs.readFileString(candidate).pipe(Effect.option)
if (Option.isNone(text)) continue
const info = yield* decodeRegistration(text.value).pipe(Effect.option)
if (Option.isNone(info)) continue
if (homeStateFiles.has(candidate) && info.value.password !== configuredPassword) continue
secondary.push(candidate)
}
if (secondary.length === 0) return primaryFile
const primaryText = yield* fs.readFileString(primaryFile).pipe(Effect.option)
if (Option.isSome(primaryText)) {
const primaryInfo = yield* decodeRegistration(primaryText.value).pipe(Effect.option)
// Preserve damaged registrations so the running owner can notice and self-evict.
if (Option.isNone(primaryInfo)) return primaryFile
if ((yield* Service.discover({ file: primaryFile, version: undefined })) !== undefined) return primaryFile
}
for (const candidate of secondary) {
if ((yield* Service.discover({ file: candidate, version: undefined })) !== undefined) return candidate
}
return primaryFile
})
export const registeredVersion = Effect.fnUntraced(function* (file?: string) {
const { fs, file: defaultFile } = yield* paths
const text = yield* fs.readFileString(file ?? defaultFile).pipe(Effect.option)
if (Option.isNone(text)) return undefined
const info = yield* decodeRegistration(text.value).pipe(Effect.option)
return Option.isSome(info) ? info.value.version : undefined
})
export type ConfiguredProbe =
| {
readonly state: "ready" | "waiting" | "failed"
readonly endpoint: Endpoint
readonly version: string
readonly pid: number
}
| {
readonly state: "unauthorized" | "incompatible"
readonly endpoint: Endpoint
}
export const probeConfigured = Effect.fnUntraced(function* (options: { readonly file?: string } = {}) {
const { fs } = yield* paths
let registeredInfo: RegistrationInfo | undefined
if (options.file !== undefined) {
const text = yield* fs.readFileString(options.file).pipe(Effect.option)
if (Option.isSome(text)) {
const decoded = yield* decodeRegistration(text.value).pipe(Effect.option)
if (Option.isNone(decoded)) return undefined
registeredInfo = decoded.value
}
}
const config = yield* read()
const rawHost = config.hostname ?? "127.0.0.1"
const connectHost = rawHost === "0.0.0.0" ? "127.0.0.1" : rawHost === "::" ? "::1" : rawHost
const configuredURL =
config.port !== undefined || config.password !== undefined || config.hostname !== undefined
? `http://${connectHost.includes(":") ? `[${connectHost}]` : connectHost}:${config.port ?? defaultPort()}`
: undefined
// Each password is only ever sent to the URL it belongs to.
const targets = [
...(configuredURL === undefined ? [] : [{ url: configuredURL, password: config.password || undefined }]),
...(registeredInfo === undefined
? []
: [{ url: registeredInfo.url, password: registeredInfo.password || undefined }]),
].filter(
(target, index, all) =>
all.findIndex((other) => other.url === target.url && other.password === target.password) === index,
)
let unauthorized: Endpoint | undefined
let incompatible: Endpoint | undefined
for (const target of targets) {
const endpoint = {
url: target.url,
auth:
target.password === undefined
? undefined
: { type: "basic" as const, username: "opencode", password: target.password },
} satisfies Endpoint
const result = yield* Effect.promise(() =>
fetch(new URL("/api/info", target.url), {
headers: Service.headers(endpoint),
signal: AbortSignal.timeout(1_500),
})
.then(async (response) => ({
status: response.status,
ok: response.ok,
body: (await response.json().catch(() => undefined)) as unknown,
}))
.catch(() => undefined),
)
if (result === undefined) continue
if (result.status === 401 && isUnauthorizedBody(result.body)) {
unauthorized = endpoint
continue
}
const serverInfo = decodeServerInfo(result.body)
if (serverInfo === undefined) {
if (target.url === configuredURL) incompatible = { url: target.url }
continue
}
return {
state: result.ok ? ("ready" as const) : result.status === 500 ? ("failed" as const) : ("waiting" as const),
endpoint,
version: serverInfo.version,
pid: serverInfo.pid,
} satisfies ConfiguredProbe
}
if (unauthorized !== undefined)
return { state: "unauthorized" as const, endpoint: unauthorized } satisfies ConfiguredProbe
if (incompatible !== undefined)
return { state: "incompatible" as const, endpoint: incompatible } satisfies ConfiguredProbe
return undefined
})
export const discover = Effect.fnUntraced(function* (file?: string) {
const found = yield* probeConfigured({ file })
return found?.state === "ready" ? found : undefined
})
function isUnauthorizedBody(input: unknown) {
return typeof input === "object" && input !== null && "_tag" in input && input._tag === "UnauthorizedError"
}
function decodeServerInfo(input: unknown) {
if (typeof input !== "object" || input === null) return
if (!("version" in input) || typeof input.version !== "string") return
if (!("pid" in input) || typeof input.pid !== "number" || !Number.isInteger(input.pid) || input.pid < 0) return
return { version: input.version, pid: input.pid }
}
export const read = Effect.fn("cli.service-config.read")(function* () {
const { fs, configFile, legacyConfigFile } = yield* paths
if (legacyConfigFile) yield* migrateConfig(legacyConfigFile, configFile)

View file

@ -211,3 +211,185 @@ test("local config commands do not start or require a server", async () => {
await fs.rm(root, { recursive: true, force: true })
}
})
test("connects to an already-running service on the configured port without spawning a contender and warns on version mismatch", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-configured-port-discovery-"))
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(request) {
if (request.headers.get("authorization") !== `Basic ${btoa("opencode:configured-secret")}`) {
return Response.json({ _tag: "UnauthorizedError", message: "Unauthorized" }, { status: 401 })
}
return Response.json({
version: "0.0.0-older-server",
pid: process.pid,
urls: [],
})
},
})
const configDir = path.join(root, "config")
const stateDir = path.join(root, "state")
const layer = Global.layerWith({ home: root, config: configDir, state: stateDir })
const runPromise = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem | Scope.Scope>) =>
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer), Effect.scoped))
const warnings: string[] = []
const originalWrite = process.stderr.write.bind(process.stderr)
process.stderr.write = ((chunk: string | Uint8Array) => {
warnings.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"))
return true
}) as typeof process.stderr.write
try {
await fs.mkdir(configDir, { recursive: true })
await fs.writeFile(
path.join(configDir, ServiceConfig.filename()),
JSON.stringify({
hostname: "127.0.0.1",
port: server.port,
password: "configured-secret",
}),
)
const resolved = await runPromise(ServerConnection.resolve())
expect(resolved.endpoint).toEqual({
url: `http://127.0.0.1:${server.port}`,
auth: { type: "basic", username: "opencode", password: "configured-secret" },
})
expect(warnings.join("")).toContain(
`Warning: Server at http://127.0.0.1:${server.port} has version 0.0.0-older-server; this client is ${OPENCODE_VERSION}. Continuing anyway.`,
)
expect(await Bun.file(path.join(stateDir, ServiceConfig.filename())).exists()).toBe(false)
// Also discovers a registration written to ~/.local/state/opencode when config.env.XDG_STATE_HOME differs.
const homeRegistration = path.join(root, ".local", "state", "opencode", ServiceConfig.filename())
await fs.mkdir(path.dirname(homeRegistration), { recursive: true })
await fs.writeFile(
homeRegistration,
JSON.stringify({
id: "desktop-owner",
version: "0.0.0-older-server",
url: `http://127.0.0.1:${server.port}`,
pid: process.pid,
password: "configured-secret",
}),
)
await fs.writeFile(
path.join(configDir, ServiceConfig.filename()),
JSON.stringify({
hostname: "127.0.0.1",
port: server.port,
password: "configured-secret",
env: { XDG_STATE_HOME: stateDir },
}),
)
const options = await runPromise(ServiceConfig.options())
expect(options.file).toBe(homeRegistration)
// Fails clearly without spawning when the configured server rejects the password.
await fs.rm(homeRegistration, { force: true })
await fs.writeFile(
path.join(configDir, ServiceConfig.filename()),
JSON.stringify({
hostname: "127.0.0.1",
port: server.port,
password: "wrong-password",
}),
)
await expect(runPromise(ServerConnection.resolve())).rejects.toThrow(
`Server at http://127.0.0.1:${server.port} rejected the password`,
)
} finally {
process.stderr.write = originalWrite
await server.stop(true)
await fs.rm(root, { recursive: true, force: true })
}
})
test("a build ignores another channel's service config and never sends it that password", async () => {
expect(ServiceConfig.filename()).not.toBe("service.json")
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-channel-isolation-"))
const seen: Array<string | null> = []
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(request) {
seen.push(request.headers.get("authorization"))
return Response.json({ version: "0.0.0-production", pid: process.pid, urls: [] })
},
})
const configDir = path.join(root, "config")
const stateDir = path.join(root, "state")
const layer = Global.layerWith({ home: root, config: configDir, state: stateDir })
const runPromise = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem | Scope.Scope>) =>
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer), Effect.scoped))
try {
await fs.mkdir(configDir, { recursive: true })
await fs.writeFile(
path.join(configDir, "service.json"),
JSON.stringify({ hostname: "127.0.0.1", port: server.port, password: "prod-secret" }),
)
const options = await runPromise(ServiceConfig.options())
expect(options.file).toBe(path.join(stateDir, ServiceConfig.filename()))
expect(options.env).toBeUndefined()
expect(await runPromise(ServiceConfig.probeConfigured({ file: options.file }))).toBeUndefined()
expect(seen).toEqual([])
} finally {
await server.stop(true)
await fs.rm(root, { recursive: true, force: true })
}
})
test("probing sends each password only to its own URL and never sends OPENCODE_PASSWORD", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-probe-pairing-"))
const stub = () => {
const seen: Array<string | null> = []
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(request) {
seen.push(request.headers.get("authorization"))
return Response.json({ _tag: "UnauthorizedError", message: "Unauthorized" }, { status: 401 })
},
})
return { seen, server }
}
const configured = stub()
const registered = stub()
const configDir = path.join(root, "config")
const stateDir = path.join(root, "state")
const layer = Global.layerWith({ home: root, config: configDir, state: stateDir })
const runPromise = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem | Scope.Scope>) =>
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer), Effect.scoped))
const originalPassword = process.env.OPENCODE_PASSWORD
process.env.OPENCODE_PASSWORD = "env-secret"
try {
await fs.mkdir(configDir, { recursive: true })
await fs.mkdir(stateDir, { recursive: true })
await fs.writeFile(
path.join(configDir, ServiceConfig.filename()),
JSON.stringify({ hostname: "127.0.0.1", port: configured.server.port, password: "config-secret" }),
)
const file = path.join(stateDir, ServiceConfig.filename())
await fs.writeFile(
file,
JSON.stringify({
id: "owner",
version: "0.0.0-other",
url: `http://127.0.0.1:${registered.server.port}`,
pid: process.pid,
password: "registration-secret",
}),
)
const result = await runPromise(ServiceConfig.probeConfigured({ file }))
expect(result?.state).toBe("unauthorized")
expect(configured.seen).toEqual([`Basic ${btoa("opencode:config-secret")}`])
expect(registered.seen).toEqual([`Basic ${btoa("opencode:registration-secret")}`])
} finally {
if (originalPassword === undefined) delete process.env.OPENCODE_PASSWORD
else process.env.OPENCODE_PASSWORD = originalPassword
await configured.server.stop(true)
await registered.server.stop(true)
await fs.rm(root, { recursive: true, force: true })
}
})

View file

@ -30,6 +30,16 @@ export const discover = Effect.fn("service.discover")(function* (options: Discov
return found.endpoint
})
/** Discover like `discover`, then settle a stale persistent-terminal handoff as `ensure` does when it reuses a service. */
export const reuse = Effect.fn("service.reuse")(function* (options: DiscoverOptions = {}) {
const found = (yield* registered(options.file)).service
if (found?.state !== "ready") return undefined
if (!found.compatible) return undefined
if (!matchesVersion(found.version, options)) return undefined
yield* Effect.tryPromise(() => PtyHandoff.complete(options.file ?? fallback(), found.info))
return found.endpoint
})
/** Recognize an authenticated compatible service bound to an expected URL, including while it starts or fails. */
export const incumbent = Effect.fn("service.incumbent")(function* (
options: DiscoverOptions & { readonly url: string },
@ -197,4 +207,4 @@ const terminate = Effect.fnUntraced(function* (info: Info, options: { readonly f
})
/** Effect-based local service lifecycle operations. */
export const Service = { discover, incumbent, ensure, stop, headers, Info }
export const Service = { discover, reuse, incumbent, ensure, stop, headers, Info }

View file

@ -384,6 +384,26 @@ test("retains a contender failure until the deadline while its survivor stalls",
expect(() => process.kill(second, 0)).not.toThrow()
})
test("reuse returns a ready service and clears a stale persistent-terminal handoff", async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
fixture.spawn("graceful")
await fixture.waitForFile()
const info = await Bun.file(registration).json()
await writeFile(
registration + ".pty-handoff",
JSON.stringify({
source: { id: "old", pid: 1, url: "http://127.0.0.1:1" },
handoff: null,
expiresAt: Date.now() + 30_000,
}),
)
expect((await run(Service.reuse({ file: registration, version: "test" })))?.url).toBe(info.url)
expect(await Bun.file(registration + ".pty-handoff").exists()).toBe(false)
expect(await run(Service.reuse({ file: registration, version: "other" }))).toBeUndefined()
})
test("accepts a surviving contender after a failure without recruiting replacements", async () => {
await using fixture = await serviceFixture()
const pending = run(ensure({ file: fixture.registration, version: "test", command: fixture.command("controlled") }))