Skip to content

Commit be6f5a3

Browse files
authored
fix(cli): update npm installs through their own prefix (#63152)
1 parent 63b42f6 commit be6f5a3

4 files changed

Lines changed: 274 additions & 28 deletions

File tree

‎packages/cli/src/commands/handlers/upgrade.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ export default Runtime.handler(
1616
const method = Option.getOrUndefined(input.method) ?? (yield* updater.method())
1717
if (!method)
1818
return yield* Effect.fail(
19-
new Error("Could not detect the installation method. Pass --method to choose how to upgrade OpenCode."),
19+
(yield* updater.managed(Option.getOrUndefined(input.target))) ??
20+
new Error("Could not detect the installation method. Pass --method to choose how to upgrade OpenCode."),
2021
)
2122

2223
log.info(`Using method: ${method}`)

‎packages/cli/src/services/updater.ts‎

Lines changed: 97 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ export class UpgradeError extends Error {
4444
const decodeVpPackages = Schema.decodeUnknownOption(
4545
Schema.fromJsonString(Schema.Array(Schema.Struct({ name: Schema.String }))),
4646
)
47+
const decodeManifestVersion = Schema.decodeUnknownOption(
48+
Schema.fromJsonString(Schema.Struct({ version: Schema.String })),
49+
)
4750

4851
const installNames: Record<Method, string> = {
4952
curl: "The OpenCode installer",
@@ -110,6 +113,8 @@ export interface Interface {
110113
readonly check: () => Effect.Effect<CheckResult | undefined, Error>
111114
readonly apply: (version: string) => Effect.Effect<void, Error>
112115
readonly method: () => Effect.Effect<Method | undefined>
116+
/** Explains how to update a copy that Volta or mise manages, which `method` leaves undetected. */
117+
readonly managed: (version?: string) => Effect.Effect<UpgradeError | undefined, Error>
113118
readonly latest: (method?: Method) => Effect.Effect<string, Error>
114119
readonly upgrade: (method: Method, version: string) => Effect.Effect<void, Error>
115120
readonly removal: (
@@ -160,6 +165,35 @@ const make = Effect.gen(function* () {
160165
)
161166
// WinGet extracts portable packages into a directory named after the package identifier.
162167
const installedWinget = /[\\/]winget[\\/]packages[\\/]anomaly\.opencode_/i.test(executable)
168+
// Volta packages (tools/image/packages) and mise's npm backend (installs/npm-<name>) keep their own record of the
169+
// installed version, so updating the copy in place would leave it stale. npm globals under a Volta or mise Node
170+
// (tools/image/node, installs/node) are ordinary npm installs.
171+
const installedOwner = !installedPackage
172+
? undefined
173+
: /[\\/]tools[\\/]image[\\/]packages[\\/]/.test(executable)
174+
? { name: "Volta", command: "volta install " }
175+
: /[\\/]installs[\\/]npm-[^\\/]+[\\/]/.test(executable)
176+
? { name: "mise", command: "mise use -g npm:" }
177+
: undefined
178+
// npm keeps global packages in <prefix>/lib/node_modules on POSIX. The npm on PATH may belong to another Node
179+
// install (fnm, nvm, mise) or prefix, so target the prefix that owns the running binary. Windows uses
180+
// <prefix>\node_modules, which Bun and pnpm global installs share, so it keeps the npm on PATH.
181+
const packageDirectory = path.dirname(path.dirname(executable))
182+
const npmPackageDirectory = installedPackage ? path.join("/lib/node_modules", installedPackage) : undefined
183+
const npmPrefix =
184+
npmPackageDirectory &&
185+
!installedOwner &&
186+
process.platform !== "win32" &&
187+
packageDirectory.endsWith(npmPackageDirectory)
188+
? packageDirectory.slice(0, -npmPackageDirectory.length) || undefined
189+
: undefined
190+
const npmPrefixArgs = npmPrefix ? ["--prefix", npmPrefix] : []
191+
const npmBin = npmPrefix ? path.join(npmPrefix, "bin") : undefined
192+
const prefixNpm =
193+
npmBin && (yield* fs.exists(path.join(npmBin, "npm")).pipe(Effect.orElseSucceed(() => false)))
194+
? path.join(npmBin, "npm")
195+
: undefined
196+
const npm = prefixNpm ?? "npm"
163197

164198
const readPolicy = Effect.fnUntraced(function* () {
165199
const values = yield* Effect.forEach(["config.json", "opencode.json", "opencode.jsonc"], (name) =>
@@ -172,8 +206,14 @@ const make = Effect.gen(function* () {
172206
})
173207

174208
const exec = Effect.fnUntraced(function* (command: string[], timeout: Duration.Input = "30 seconds") {
209+
// The prefix's npm and the package's postinstall run `node` from PATH, which may be missing or belong to another
210+
// Node install, so put the prefix's own node first.
211+
const options =
212+
command[0] === prefixNpm
213+
? { env: { PATH: [npmBin, process.env.PATH].filter(Boolean).join(path.delimiter) }, extendEnv: true }
214+
: undefined
175215
return yield* appProcess
176-
.run(ChildProcess.make(command[0], command.slice(1)), {
216+
.run(ChildProcess.make(command[0], command.slice(1), options), {
177217
timeout,
178218
maxOutputBytes: 100_000,
179219
maxErrorBytes: 100_000,
@@ -215,11 +255,11 @@ const make = Effect.gen(function* () {
215255
if (executable === curlBinary) return "curl"
216256
if (installedFormula) return "brew"
217257
if (installedWinget) return "winget"
218-
if (!installedPackage) return
258+
if (!installedPackage || installedOwner) return
219259

220260
const parts = executable.toLowerCase().split(path.sep).map((part) => part.replace(/^\./, ""))
221261
const checks: Array<{ method: Method; command: string[] }> = [
222-
{ method: "npm", command: ["npm", "list", "-g", "--depth=0", installedPackage] },
262+
{ method: "npm", command: [npm, "list", "-g", "--depth=0", ...npmPrefixArgs, installedPackage] },
223263
{ method: "pnpm", command: ["pnpm", "list", "-g", "--depth=0", installedPackage] },
224264
{ method: "bun", command: ["bun", "pm", "ls", "-g"] },
225265
{ method: "yarn", command: ["yarn", "global", "list"] },
@@ -248,7 +288,7 @@ const make = Effect.gen(function* () {
248288
if (method === "winget") return ["winget", "uninstall", ...wingetArgs]
249289
if (method === "curl" || method === "brew" || !installedPackage) return undefined
250290
const commands = {
251-
npm: ["npm", "uninstall", "--global", installedPackage],
291+
npm: [npm, "uninstall", "--global", ...npmPrefixArgs, installedPackage],
252292
pnpm: ["pnpm", "remove", "--global", installedPackage],
253293
bun: ["bun", "remove", "--global", installedPackage],
254294
yarn: ["yarn", "global", "remove", installedPackage],
@@ -365,6 +405,24 @@ const make = Effect.gen(function* () {
365405
),
366406
)
367407

408+
const managedError = (owner: { name: string; command: string }, target: string) =>
409+
new UpgradeError({
410+
title: `OpenCode is managed by ${owner.name}`,
411+
detail: `This copy was installed with ${owner.name}, which keeps its own record of the installed version, so OpenCode won't update it directly.`,
412+
command: `${owner.command}${target}`,
413+
retry: "Run the command above, then restart OpenCode.",
414+
})
415+
416+
const managedMessage = (error: UpgradeError) => `${error.title}. Update it with ${error.command}`
417+
418+
const managed = Effect.fnUntraced(function* (input?: string) {
419+
if (!installedOwner) return
420+
if (input !== undefined && !parseReleaseVersion(input))
421+
return yield* Effect.fail(new Error(`Invalid version: ${input}`))
422+
const data = yield* release("npm")
423+
return managedError(installedOwner, `${data.package}@${input?.trim().replace(/^v/, "") ?? data.version}`)
424+
})
425+
368426
const temporaryDirectory = (prefix: string) =>
369427
Effect.acquireRelease(fs.makeTempDirectory({ directory: global.cache, prefix }), (directory) =>
370428
fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore),
@@ -438,9 +496,10 @@ const make = Effect.gen(function* () {
438496
const commands: Record<Exclude<Method, "bun" | "curl" | "brew" | "winget">, string[]> = {
439497
// Keep the old package: uninstalling it can unlink the replacement command.
440498
npm: [
441-
"npm",
499+
npm,
442500
"install",
443501
"--global",
502+
...npmPrefixArgs,
444503
`--allow-scripts=${packageName}`,
445504
...((OPENCODE_ARTIFACT === "cli" && !installedPackage?.endsWith("/cli-node")) ||
446505
(installedPackage && packageName !== installedPackage)
@@ -527,8 +586,22 @@ const make = Effect.gen(function* () {
527586
{ cause },
528587
),
529588
),
530-
Effect.asVoid,
531589
)
590+
// A package manager can succeed while updating a different copy, for example another prefix. pnpm keeps each
591+
// version in its own store directory, so the running copy never changes there.
592+
if (installedPackage !== packageName || !(method === "npm" || method === "bun" || method === "yarn")) return
593+
const installed = yield* fs.readFileString(path.join(packageDirectory, "package.json")).pipe(
594+
Effect.map((text) => Option.getOrUndefined(decodeManifestVersion(text))?.version),
595+
Effect.orElseSucceed(() => undefined),
596+
)
597+
if (installed !== version)
598+
return yield* Effect.fail(
599+
new UpgradeError({
600+
title: `${installNames[method]} did not update this copy of OpenCode`,
601+
detail: `${installNames[method]} reported success, but ${executable} is still version ${installed ?? "unknown"}.`,
602+
retry: `Update the copy at ${executable} with the package manager that installed it, then run opencode upgrade again.`,
603+
}),
604+
)
532605
})
533606

534607
const inspect = Effect.fnUntraced(function* () {
@@ -575,12 +648,15 @@ const make = Effect.gen(function* () {
575648
})
576649

577650
const apply = Effect.fn("cli.updater.apply")(function* (version: string) {
578-
if (!(yield* install(version)))
579-
return yield* Effect.fail(
580-
new Error(
581-
"Could not detect the installation method. Update with your package manager or download the latest release.",
582-
),
583-
)
651+
if (yield* install(version)) return
652+
const error = yield* managed(version)
653+
return yield* Effect.fail(
654+
new Error(
655+
error
656+
? managedMessage(error)
657+
: "Could not detect the installation method. Update with your package manager or download the latest release.",
658+
),
659+
)
584660
})
585661

586662
const check = Effect.fn("cli.updater.check")(function* () {
@@ -590,6 +666,14 @@ const make = Effect.gen(function* () {
590666
message: "This build runs from a source checkout. Use an installed OpenCode release to check for updates.",
591667
}
592668
const detected = yield* method()
669+
if (!detected && installedOwner) {
670+
const data = yield* release("npm")
671+
if (action(OPENCODE_VERSION, data.version, "auto") === "none") return undefined
672+
return {
673+
type: "unavailable" as const,
674+
message: managedMessage(managedError(installedOwner, `${data.package}@${data.version}`)),
675+
}
676+
}
593677
if (!detected)
594678
return {
595679
type: "unavailable" as const,
@@ -620,7 +704,7 @@ const make = Effect.gen(function* () {
620704
Effect.catch((error) => Effect.logWarning("update check failed", { error }).pipe(Effect.as(undefined))),
621705
)
622706

623-
return Service.of({ run, check, apply, method, latest, upgrade, removal })
707+
return Service.of({ run, check, apply, method, managed, latest, upgrade, removal })
624708
})
625709

626710
export const layer = Layer.effect(Service, make)

‎packages/cli/test/fixture/upgrade.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ await Effect.runPromise(
1616
check: () => Effect.die("Manual upgrades must not check for TUI updates"),
1717
apply: () => Effect.die("Manual upgrades must not apply TUI updates"),
1818
removal: () => undefined,
19+
managed: () => Effect.succeed(undefined),
1920
method: () =>
2021
Effect.sync(() => {
2122
record("method")

0 commit comments

Comments
 (0)