Skip to content

Commit 3392451

Browse files
committed
fix(cli): isolate background service per config profile
Derive the managed service registration filename in global state and the default service port from the resolved OPENCODE_CONFIG_DIR path when a non-default config directory is active, and propagate the canonicalized config path into the spawned service environment before changing to the home directory. Previously, all profiles shared ~/.local/state/opencode/service.json and port 49374, causing secondary OPENCODE_CONFIG_DIR launches to attach to the first profile's background server and inherit its config and environment. Fixes anomalyco#58141
1 parent 58a2066 commit 3392451

4 files changed

Lines changed: 131 additions & 23 deletions

File tree

‎packages/cli/src/server-process.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
5858
),
5959
)
6060
const global = yield* Global.Service
61+
const profile = ServiceConfig.activeProfile()
62+
if (profile !== undefined) process.env.OPENCODE_CONFIG_DIR = profile
6163
// A sandbox may deny $HOME; the service then keeps the cwd it was launched from.
6264
if (options.mode === "service")
6365
yield* Effect.try(() => process.chdir(global.home)).pipe(
@@ -69,7 +71,10 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
6971
const serviceOptions = options.mode === "service" ? yield* ServiceConfig.options() : undefined
7072
const config = options.mode === "service" ? yield* ServiceConfig.read() : {}
7173
const hostname = options.hostname ?? config.hostname ?? "127.0.0.1"
72-
const port = options.port ?? config.port ?? (options.mode === "service" ? ServiceConfig.defaultPort() : undefined)
74+
const port =
75+
options.port ??
76+
config.port ??
77+
(options.mode === "service" ? ServiceConfig.defaultPort(OPENCODE_CHANNEL, process.platform, profile) : undefined)
7378
const findIncumbent =
7479
serviceOptions !== undefined && port !== undefined
7580
? Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })

‎packages/cli/src/services/service-config.ts‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,16 @@ const decodeLegacy = Schema.decodeUnknownOption(
3838
)
3939
const decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Service.Info))
4040

41-
export function filename(channel = OPENCODE_CHANNEL) {
42-
if (channel === "latest" || channel === "dev" || channel === "beta" || channel === "next") return "service.json"
43-
return `service-${channel.replace(/[^a-zA-Z0-9._-]/g, "-")}.json`
41+
export function filename(channel = OPENCODE_CHANNEL, profile?: string) {
42+
const suffix = profile === undefined ? undefined : Hash.fast(path.resolve(profile))
43+
if (channel === "latest" || channel === "dev" || channel === "beta" || channel === "next")
44+
return suffix ? `service-${suffix}.json` : "service.json"
45+
const prefix = `service-${channel.replace(/[^a-zA-Z0-9._-]/g, "-")}`
46+
return suffix ? `${prefix}-${suffix}.json` : `${prefix}.json`
4447
}
4548

46-
export function defaultPort(channel = OPENCODE_CHANNEL, platform = process.platform) {
47-
const port = channelPort(channel)
49+
export function defaultPort(channel = OPENCODE_CHANNEL, platform = process.platform, profile?: string) {
50+
const port = channelPort(channel, profile)
4851
// Windows hands out 0xC000-0xFFFF for outgoing connections, Hyper-V and WinNAT reserve blocks of that range at boot,
4952
// and WSL mirrored networking reserves a 4096-port block that usually covers 44620-48715. A reserved port fails as in
5053
// use while nothing listens on it. Moving into the 0x7000 block, below 32768, avoids all of them and keeps the low
@@ -53,10 +56,20 @@ export function defaultPort(channel = OPENCODE_CHANNEL, platform = process.platf
5356
return port
5457
}
5558

56-
function channelPort(channel: string) {
57-
if (channel === "latest" || channel === "dev" || channel === "beta" || channel === "next") return 0xc0de
58-
if (channel === "local") return 0xc0df
59-
return 10_000 + (Number.parseInt(Hash.fast(channel).slice(0, 8), 16) % 50_000)
59+
function channelPort(channel: string, profile?: string) {
60+
const release = channel === "latest" || channel === "dev" || channel === "beta" || channel === "next"
61+
if (profile === undefined) {
62+
if (release) return 0xc0de
63+
if (channel === "local") return 0xc0df
64+
}
65+
const key = profile === undefined ? channel : `${release ? "latest" : channel}:${path.resolve(profile)}`
66+
return 10_000 + (Number.parseInt(Hash.fast(key).slice(0, 8), 16) % 50_000)
67+
}
68+
69+
export function activeProfile(configDir = process.env.OPENCODE_CONFIG_DIR) {
70+
if (!configDir) return undefined
71+
const resolved = path.resolve(configDir)
72+
return resolved === path.resolve(Global.Path.config) ? undefined : resolved
6073
}
6174

6275
export function legacyFilename(channel = OPENCODE_CHANNEL) {
@@ -116,28 +129,34 @@ function configKey(key: string): Key {
116129
const paths = Effect.gen(function* () {
117130
const fs = yield* FileSystem.FileSystem
118131
const global = yield* Global.Service
132+
const profile = activeProfile()
119133
const name = filename()
120134
const legacy = legacyFilename()
121-
const file = path.join(global.state, name)
135+
const file = path.join(global.state, filename(OPENCODE_CHANNEL, profile))
122136
return {
123137
fs,
124138
file,
139+
profile,
125140
legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,
126-
legacyRegistrationFiles: [
127-
...(legacy ? [path.join(global.state, legacy)] : []),
128-
...(name !== "service.json" && OPENCODE_CHANNEL !== "local" ? [path.join(global.state, "service.json")] : []),
129-
],
141+
legacyRegistrationFiles:
142+
profile !== undefined
143+
? []
144+
: [
145+
...(legacy ? [path.join(global.state, legacy)] : []),
146+
...(name !== "service.json" && OPENCODE_CHANNEL !== "local" ? [path.join(global.state, "service.json")] : []),
147+
],
130148
configFile: path.join(global.config, name),
131149
}
132150
})
133151

134152
export const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) {
135-
const { file, legacyRegistrationFiles } = yield* paths
153+
const { file, profile, legacyRegistrationFiles } = yield* paths
136154
yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))
155+
const env = (yield* read()).env
137156
return {
138157
file,
139158
version: input.checkVersion ? OPENCODE_VERSION : undefined,
140-
env: (yield* read()).env,
159+
env: profile === undefined ? env : { ...env, OPENCODE_CONFIG_DIR: profile },
141160
command: [
142161
...selfCommand(),
143162
"serve",

‎packages/cli/test/service-lifecycle.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import fs from "node:fs/promises"
66
import os from "node:os"
77
import path from "node:path"
88
import { OPENCODE_VERSION } from "../src/version"
9+
import { ServiceConfig } from "../src/services/service-config"
910
import { isolatedEnv } from "./fixture/environment"
1011

1112
// Real `serve --service` processes driven by the real CLI commands and client. Only behavior that
@@ -187,7 +188,7 @@ async function serviceHome(options: { readonly failBoot?: boolean } = {}) {
187188
root,
188189
port,
189190
entry: homeEntry,
190-
registration: path.join(root, "state", "opencode", "service-local.json"),
191+
registration: path.join(root, "state", "opencode", ServiceConfig.filename("local", path.join(root, "config"))),
191192
env: Object.fromEntries(
192193
Object.entries(isolatedEnv(root, overrides)).filter((entry): entry is [string, string] => entry[1] !== undefined),
193194
),

‎packages/cli/test/service.test.ts‎

Lines changed: 88 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ test("managed service ports are stable per installation channel", () => {
2626
expect(ServiceConfig.defaultPort("latest", "darwin")).toBe(0xc0de)
2727
expect(ServiceConfig.defaultPort("preview-a", "linux")).toBe(ServiceConfig.defaultPort("preview-a", "linux"))
2828
expect(ServiceConfig.defaultPort("preview-a", "linux")).not.toBe(ServiceConfig.defaultPort("preview-b", "linux"))
29+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).toBe(
30+
ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA"),
31+
)
32+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).not.toBe(0xc0de)
33+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).not.toBe(
34+
ServiceConfig.defaultPort("latest", "linux", "/tmp/ocB"),
35+
)
2936
})
3037

3138
test("managed service ports on Windows stay below the ranges Windows and WSL reserve", () => {
@@ -200,12 +207,86 @@ test("service filenames share release channels and identify preview channels", (
200207
expect(ServiceConfig.filename("local")).toBe("service-local.json")
201208
expect(ServiceConfig.filename("preview-a")).toBe("service-preview-a.json")
202209
expect(ServiceConfig.filename("preview/a")).toBe("service-preview-a.json")
210+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).toBe(ServiceConfig.filename("dev", "/tmp/ocA"))
211+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).not.toBe("service.json")
212+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).not.toBe(ServiceConfig.filename("latest", "/tmp/ocB"))
213+
expect(ServiceConfig.filename("local", "/tmp/ocA")).not.toBe(ServiceConfig.filename("latest", "/tmp/ocA"))
203214
expect(ServiceConfig.versionBelongsToChannel("0.0.0-preview-a-1234", "preview-a")).toBe(true)
204215
expect(ServiceConfig.versionBelongsToChannel("0.0.0-preview-a-1234.2", "preview-a")).toBe(true)
205216
expect(ServiceConfig.versionBelongsToChannel("0.0.0-preview-a-other-1234", "preview-a")).toBe(false)
206217
expect(ServiceConfig.versionBelongsToChannel("1.2.3", "preview-a")).toBe(false)
207218
})
208219

220+
test("custom OPENCODE_CONFIG_DIR profiles isolate registration and port in a shared state directory", async () => {
221+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-profiles-"))
222+
const state = path.join(root, "state")
223+
const configA = path.join(root, "ocA")
224+
const configB = path.join(root, "ocB")
225+
const previous = process.env.OPENCODE_CONFIG_DIR
226+
const run = (configDir: string) => {
227+
process.env.OPENCODE_CONFIG_DIR = configDir
228+
return Effect.runPromise(
229+
ServiceConfig.options().pipe(
230+
Effect.provide(Global.layerWith({ config: configDir, state })),
231+
Effect.provide(NodeFileSystem.layer),
232+
),
233+
)
234+
}
235+
try {
236+
const optionsA = await run(configA)
237+
const optionsB = await run(configB)
238+
expect(path.dirname(optionsA.file)).toBe(state)
239+
expect(path.dirname(optionsB.file)).toBe(state)
240+
expect(optionsA.file).not.toBe(path.join(state, ServiceConfig.filename()))
241+
expect(optionsA.file).not.toBe(optionsB.file)
242+
expect(optionsA.env?.OPENCODE_CONFIG_DIR).toBe(path.resolve(configA))
243+
expect(optionsB.env?.OPENCODE_CONFIG_DIR).toBe(path.resolve(configB))
244+
} finally {
245+
if (previous === undefined) delete process.env.OPENCODE_CONFIG_DIR
246+
else process.env.OPENCODE_CONFIG_DIR = previous
247+
await fs.rm(root, { recursive: true, force: true })
248+
}
249+
})
250+
251+
test("distinct OPENCODE_CONFIG_DIR profiles start, report status, and stop independent services", async () => {
252+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-profile-processes-"))
253+
const entry = path.join(import.meta.dir, "../src/index.ts")
254+
const configA = path.join(root, "ocA")
255+
const configB = path.join(root, "ocB")
256+
const envA = { ...serviceEnv(root), OPENCODE_CONFIG_DIR: configA }
257+
const envB = { ...serviceEnv(root), OPENCODE_CONFIG_DIR: configB }
258+
const cli = async (env: Record<string, string | undefined>, ...args: string[]) => {
259+
const child = Bun.spawn([process.execPath, entry, ...args], { env, stdout: "pipe", stderr: "pipe" })
260+
const [code, stdout, stderr] = await Promise.all([
261+
child.exited,
262+
new Response(child.stdout).text(),
263+
new Response(child.stderr).text(),
264+
])
265+
if (code !== 0) throw new Error(`opencode ${args.join(" ")} exited ${code}: ${stderr.trim()}`)
266+
return stdout.trim()
267+
}
268+
try {
269+
const urlA = await cli(envA, "service", "start")
270+
const urlB = await cli(envB, "service", "start")
271+
expect(urlA).not.toBe(urlB)
272+
expect(new URL(urlA).port).toBe(String(ServiceConfig.defaultPort("local", process.platform, configA)))
273+
expect(new URL(urlB).port).toBe(String(ServiceConfig.defaultPort("local", process.platform, configB)))
274+
expect(await cli(envA, "service", "status")).toBe(urlA)
275+
expect(await cli(envB, "service", "status")).toBe(urlB)
276+
277+
await cli(envA, "service", "stop")
278+
expect(await cli(envA, "service", "status")).toBe("stopped")
279+
expect(await cli(envB, "service", "status")).toBe(urlB)
280+
281+
await cli(envB, "service", "stop")
282+
expect(await cli(envB, "service", "status")).toBe("stopped")
283+
} finally {
284+
await cli(envA, "service", "stop").catch(() => undefined)
285+
await cli(envB, "service", "stop").catch(() => undefined)
286+
await fs.rm(root, { recursive: true, force: true })
287+
}
288+
}, 60_000)
289+
209290
test("service config migrates from the hashed channel filename", async () => {
210291
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-config-migration-"))
211292
const legacy = path.join(root, ServiceConfig.legacyFilename("preview-a")!)
@@ -427,8 +508,9 @@ test.each([
427508
"managed service applies CORS configuration with flag overrides: $args",
428509
async ({ args, origins }) => {
429510
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-cors-"))
430-
const config = path.join(root, "config", ServiceConfig.filename())
431-
const registration = path.join(root, "state", "opencode", ServiceConfig.filename())
511+
const configDir = path.join(root, "config")
512+
const config = path.join(configDir, ServiceConfig.filename())
513+
const registration = path.join(root, "state", "opencode", ServiceConfig.filename(undefined, configDir))
432514
const cors = ["http://192.0.2.10:3001", "https://configured.example.com"]
433515
await fs.mkdir(path.dirname(config), { recursive: true })
434516
await fs.writeFile(config, JSON.stringify({ cors }))
@@ -474,10 +556,11 @@ test("the original managed service contender binds when the occupied port is rel
474556
})
475557
const port = listener.port
476558
if (port === undefined) throw new Error("Server did not bind a port")
477-
const registration = path.join(root, "state", "opencode", "service-local.json")
478-
await fs.mkdir(path.join(root, "config"), { recursive: true })
559+
const configDir = path.join(root, "config")
560+
const registration = path.join(root, "state", "opencode", ServiceConfig.filename("local", configDir))
561+
await fs.mkdir(configDir, { recursive: true })
479562
await fs.mkdir(path.dirname(registration), { recursive: true })
480-
await fs.writeFile(path.join(root, "config", "service-local.json"), JSON.stringify({ port }))
563+
await fs.writeFile(path.join(configDir, "service-local.json"), JSON.stringify({ port }))
481564
await fs.writeFile(
482565
registration,
483566
JSON.stringify({

0 commit comments

Comments
 (0)