Skip to content

Commit 73e9a3f

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. Profile ports stay below 32768 so they never overlap the ephemeral port range. An existing unhashed service registration is adopted by the profile only when its password matches the one stored in that profile's config, so users who set one custom OPENCODE_CONFIG_DIR keep their running service across the upgrade instead of orphaning it. 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 8697644 commit 73e9a3f

4 files changed

Lines changed: 150 additions & 29 deletions

File tree

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

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

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

Lines changed: 61 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,18 @@ const decodeRegistration = Schema.decodeUnknownEffect(Schema.fromJsonString(Serv
4040

4141
// Released channels share one service, port and database, so switching between stable and beta keeps the same sessions.
4242
// Dev builds come from every merge to dev and run their own: sharing let a dev build replace the stable server, and a
43-
// beta app then adopt that dev server.
44-
export function filename(channel = OPENCODE_CHANNEL) {
45-
if (channel === "latest" || channel === "beta" || channel === "next") return "service.json"
46-
return `service-${channel.replace(/[^a-zA-Z0-9._-]/g, "-")}.json`
43+
// beta app then adopt that dev server. A non-default config dir gets its own registration, and follows the same
44+
// channel split so a dev profile does not attach to a released profile.
45+
export function filename(channel = OPENCODE_CHANNEL, profile?: string) {
46+
const suffix = profile === undefined ? undefined : Hash.fast(path.resolve(profile))
47+
if (channel === "latest" || channel === "beta" || channel === "next")
48+
return suffix ? `service-${suffix}.json` : "service.json"
49+
const prefix = `service-${channel.replace(/[^a-zA-Z0-9._-]/g, "-")}`
50+
return suffix ? `${prefix}-${suffix}.json` : `${prefix}.json`
4751
}
4852

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

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

6681
export function legacyFilename(channel = OPENCODE_CHANNEL) {
@@ -95,6 +110,21 @@ export const migrateRegistration = Effect.fnUntraced(function* (
95110
yield* fs.writeFileString(file, text.value, { flag: "wx", mode: 0o600 }).pipe(Effect.ignore)
96111
})
97112

113+
export const migrateProfileRegistration = Effect.fnUntraced(function* (
114+
legacy: string,
115+
file: string,
116+
expectedPassword?: string,
117+
) {
118+
if (!expectedPassword) return
119+
const fs = yield* FileSystem.FileSystem
120+
const text = yield* fs.readFileString(legacy).pipe(Effect.option)
121+
if (Option.isNone(text)) return
122+
const registration = yield* decodeRegistration(text.value).pipe(Effect.option)
123+
if (Option.isNone(registration) || registration.value.password !== expectedPassword) return
124+
yield* fs.writeFileString(file, text.value, { flag: "wx", mode: 0o600 }).pipe(Effect.ignore)
125+
yield* fs.remove(legacy).pipe(Effect.ignore)
126+
})
127+
98128
export const migrateConfig = Effect.fnUntraced(function* (legacy: string, file: string) {
99129
const fs = yield* FileSystem.FileSystem
100130
const text = yield* fs.readFileString(legacy).pipe(Effect.option)
@@ -120,21 +150,27 @@ function configKey(key: string): Key {
120150
const paths = Effect.gen(function* () {
121151
const fs = yield* FileSystem.FileSystem
122152
const global = yield* Global.Service
153+
const profile = activeProfile()
123154
const name = filename()
124155
const legacy = legacyFilename()
125-
const file = path.join(global.state, name)
156+
const file = path.join(global.state, filename(OPENCODE_CHANNEL, profile))
126157
return {
127158
fs,
128159
file,
160+
profile,
161+
legacyProfileRegistrationFile: profile !== undefined ? path.join(global.state, name) : undefined,
129162
legacyConfigFile: legacy ? path.join(global.config, legacy) : undefined,
130-
legacyRegistrationFiles: [
131-
...(legacy ? [path.join(global.state, legacy)] : []),
132-
// Dev never owned the shared registration, even while it wrote there; a dev server still in it belongs to an
133-
// older build and is left for a released client to replace.
134-
...(name !== "service.json" && OPENCODE_CHANNEL !== "local" && OPENCODE_CHANNEL !== "dev"
135-
? [path.join(global.state, "service.json")]
136-
: []),
137-
],
163+
legacyRegistrationFiles:
164+
profile !== undefined
165+
? []
166+
: [
167+
...(legacy ? [path.join(global.state, legacy)] : []),
168+
// Dev never owned the shared registration, even while it wrote there; a dev server still in it belongs to an
169+
// older build and is left for a released client to replace.
170+
...(name !== "service.json" && OPENCODE_CHANNEL !== "local" && OPENCODE_CHANNEL !== "dev"
171+
? [path.join(global.state, "service.json")]
172+
: []),
173+
],
138174
configFile: path.join(global.config, name),
139175
}
140176
})
@@ -149,12 +185,15 @@ export function processEnv(env: Info["env"]) {
149185
}
150186

151187
export const options = Effect.fnUntraced(function* (input: { readonly checkVersion?: boolean } = {}) {
152-
const { file, legacyRegistrationFiles } = yield* paths
188+
const { file, profile, legacyProfileRegistrationFile, legacyRegistrationFiles } = yield* paths
189+
const config = yield* read()
190+
if (legacyProfileRegistrationFile)
191+
yield* migrateProfileRegistration(legacyProfileRegistrationFile, file, config.password)
153192
yield* Effect.forEach(legacyRegistrationFiles, (legacy) => migrateRegistration(legacy, file))
154193
return {
155194
file,
156195
version: input.checkVersion ? OPENCODE_VERSION : undefined,
157-
env: processEnv((yield* read()).env),
196+
env: processEnv(profile === undefined ? config.env : { ...config.env, OPENCODE_CONFIG_DIR: profile }),
158197
command: [...selfCommand(), "serve", "--service"],
159198
}
160199
})

‎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
@@ -191,7 +192,7 @@ async function serviceHome(options: { readonly failBoot?: boolean } = {}) {
191192
root,
192193
port,
193194
entry: homeEntry,
194-
registration: path.join(root, "state", "opencode", "service-local.json"),
195+
registration: path.join(root, "state", "opencode", ServiceConfig.filename("local", path.join(root, "config"))),
195196
env: Object.fromEntries(
196197
Object.entries(isolatedEnv(root, overrides)).filter((entry): entry is [string, string] => entry[1] !== undefined),
197198
),

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

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,23 @@ test("managed service ports are stable per installation channel", () => {
2929
expect(ServiceConfig.defaultPort("latest", "darwin")).toBe(0xc0de)
3030
expect(ServiceConfig.defaultPort("preview-a", "linux")).toBe(ServiceConfig.defaultPort("preview-a", "linux"))
3131
expect(ServiceConfig.defaultPort("preview-a", "linux")).not.toBe(ServiceConfig.defaultPort("preview-b", "linux"))
32+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).toBe(
33+
ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA"),
34+
)
35+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).not.toBe(0xc0de)
36+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).not.toBe(
37+
ServiceConfig.defaultPort("latest", "linux", "/tmp/ocB"),
38+
)
39+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).toBe(
40+
ServiceConfig.defaultPort("beta", "linux", "/tmp/ocA"),
41+
)
42+
expect(ServiceConfig.defaultPort("latest", "linux", "/tmp/ocA")).not.toBe(
43+
ServiceConfig.defaultPort("dev", "linux", "/tmp/ocA"),
44+
)
45+
const profilePorts = Array.from({ length: 200 }, (_, index) =>
46+
ServiceConfig.defaultPort("latest", "linux", `/tmp/oc-${index}`),
47+
)
48+
expect(profilePorts.every((port) => port >= 10_000 && port < 0x8000)).toBe(true)
3249
})
3350

3451
test("managed service ports on Windows stay below the ranges Windows and WSL reserve", () => {
@@ -269,12 +286,69 @@ test("service filenames share release channels and identify dev and preview chan
269286
expect(ServiceConfig.filename("local")).toBe("service-local.json")
270287
expect(ServiceConfig.filename("preview-a")).toBe("service-preview-a.json")
271288
expect(ServiceConfig.filename("preview/a")).toBe("service-preview-a.json")
289+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).toBe(ServiceConfig.filename("beta", "/tmp/ocA"))
290+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).not.toBe(ServiceConfig.filename("dev", "/tmp/ocA"))
291+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).not.toBe("service.json")
292+
expect(ServiceConfig.filename("latest", "/tmp/ocA")).not.toBe(ServiceConfig.filename("latest", "/tmp/ocB"))
293+
expect(ServiceConfig.filename("local", "/tmp/ocA")).not.toBe(ServiceConfig.filename("latest", "/tmp/ocA"))
272294
expect(ServiceConfig.versionBelongsToChannel("0.0.0-preview-a-1234", "preview-a")).toBe(true)
273295
expect(ServiceConfig.versionBelongsToChannel("0.0.0-preview-a-1234.2", "preview-a")).toBe(true)
274296
expect(ServiceConfig.versionBelongsToChannel("0.0.0-preview-a-other-1234", "preview-a")).toBe(false)
275297
expect(ServiceConfig.versionBelongsToChannel("1.2.3", "preview-a")).toBe(false)
276298
})
277299

300+
test("custom OPENCODE_CONFIG_DIR profiles isolate registration and port in a shared state directory", async () => {
301+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-profiles-"))
302+
const state = path.join(root, "state")
303+
const configA = path.join(root, "ocA")
304+
const configB = path.join(root, "ocB")
305+
const previous = process.env.OPENCODE_CONFIG_DIR
306+
const run = (configDir: string) => {
307+
process.env.OPENCODE_CONFIG_DIR = configDir
308+
return Effect.runPromise(
309+
ServiceConfig.options().pipe(
310+
Effect.provide(Global.layerWith({ config: configDir, state })),
311+
Effect.provide(NodeFileSystem.layer),
312+
),
313+
)
314+
}
315+
try {
316+
const optionsA = await run(configA)
317+
const optionsB = await run(configB)
318+
expect(path.dirname(optionsA.file)).toBe(state)
319+
expect(path.dirname(optionsB.file)).toBe(state)
320+
expect(optionsA.file).not.toBe(path.join(state, ServiceConfig.filename()))
321+
expect(optionsA.file).not.toBe(optionsB.file)
322+
expect(optionsA.env?.OPENCODE_CONFIG_DIR).toBe(path.resolve(configA))
323+
expect(optionsB.env?.OPENCODE_CONFIG_DIR).toBe(path.resolve(configB))
324+
325+
// Upgrading with a single custom OPENCODE_CONFIG_DIR adopts an unhashed registration only when its password matches.
326+
const legacyRegistration = path.join(state, ServiceConfig.filename())
327+
const record = {
328+
id: "existing-profile-a",
329+
version: OPENCODE_VERSION,
330+
url: "http://127.0.0.1:49374",
331+
pid: 1234,
332+
password: "profile-a-secret",
333+
}
334+
await fs.writeFile(path.join(configA, ServiceConfig.filename()), JSON.stringify({ password: "profile-a-secret" }))
335+
await fs.writeFile(path.join(configB, ServiceConfig.filename()), JSON.stringify({ password: "profile-b-secret" }))
336+
await fs.writeFile(legacyRegistration, JSON.stringify(record))
337+
338+
await run(configB)
339+
expect(await Bun.file(optionsB.file).exists()).toBe(false)
340+
expect(await Bun.file(legacyRegistration).exists()).toBe(true)
341+
342+
await run(configA)
343+
expect(await Bun.file(optionsA.file).json()).toEqual(record)
344+
expect(await Bun.file(legacyRegistration).exists()).toBe(false)
345+
} finally {
346+
if (previous === undefined) delete process.env.OPENCODE_CONFIG_DIR
347+
else process.env.OPENCODE_CONFIG_DIR = previous
348+
await fs.rm(root, { recursive: true, force: true })
349+
}
350+
})
351+
278352
test("service config migrates from the hashed channel filename", async () => {
279353
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-config-migration-"))
280354
const legacy = path.join(root, ServiceConfig.legacyFilename("preview-a")!)
@@ -497,8 +571,9 @@ test.each([
497571
"managed service applies CORS configuration with flag overrides: $args",
498572
async ({ args, origins }) => {
499573
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-cors-"))
500-
const config = path.join(root, "config", ServiceConfig.filename())
501-
const registration = path.join(root, "state", "opencode", ServiceConfig.filename())
574+
const configDir = path.join(root, "config")
575+
const config = path.join(configDir, ServiceConfig.filename())
576+
const registration = path.join(root, "state", "opencode", ServiceConfig.filename(undefined, configDir))
502577
const cors = ["http://192.0.2.10:3001", "https://configured.example.com"]
503578
await fs.mkdir(path.dirname(config), { recursive: true })
504579
await fs.writeFile(config, JSON.stringify({ cors }))
@@ -544,10 +619,11 @@ test("the original managed service contender binds when the occupied port is rel
544619
})
545620
const port = listener.port
546621
if (port === undefined) throw new Error("Server did not bind a port")
547-
const registration = path.join(root, "state", "opencode", "service-local.json")
548-
await fs.mkdir(path.join(root, "config"), { recursive: true })
622+
const configDir = path.join(root, "config")
623+
const registration = path.join(root, "state", "opencode", ServiceConfig.filename("local", configDir))
624+
await fs.mkdir(configDir, { recursive: true })
549625
await fs.mkdir(path.dirname(registration), { recursive: true })
550-
await fs.writeFile(path.join(root, "config", "service-local.json"), JSON.stringify({ port }))
626+
await fs.writeFile(path.join(configDir, "service-local.json"), JSON.stringify({ port }))
551627
await fs.writeFile(
552628
registration,
553629
JSON.stringify({

0 commit comments

Comments
 (0)