Skip to content

Commit b20748f

Browse files
fix(cli): prevent repeated updates and npm cache growth (#45091)
Co-authored-by: neriousy <[email protected]>
1 parent f0d5b5e commit b20748f

4 files changed

Lines changed: 105 additions & 13 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { NodeFileSystem } from "@effect/platform-node"
2+
import { Global } from "@opencode-ai/util/global"
3+
import { AppProcess } from "@opencode-ai/util/process"
4+
import { Effect, FileSystem, Layer, Stream } from "effect"
5+
import { ChildProcessSpawner } from "effect/unstable/process"
6+
import assert from "node:assert/strict"
7+
import path from "node:path"
8+
import { Updater } from "../updater"
9+
10+
const latest = { version: "0.0.0-beta-17498" }
11+
const installs: string[] = []
12+
13+
// This fixture runs in its own process; no real update requests or installs occur.
14+
globalThis.fetch = Object.assign(async () => Response.json(latest), { preconnect() {} })
15+
16+
await Effect.runPromise(
17+
Effect.gen(function* () {
18+
const fs = yield* FileSystem.FileSystem
19+
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-updater-" })
20+
const dependencies = Layer.mergeAll(
21+
Layer.succeed(FileSystem.FileSystem, fs),
22+
Layer.succeed(
23+
Global.Service,
24+
Global.make({ home: directory, config: directory, cache: path.join(directory, "cache") }),
25+
),
26+
Layer.succeed(AppProcess.Service, {
27+
...ChildProcessSpawner.make(() => Effect.die("Unexpected process spawn")),
28+
runStream: () => Stream.die("Unexpected streaming process"),
29+
run: (command) => {
30+
assert.equal(command._tag, "StandardCommand")
31+
if (command.command === "npm" && command.args[0] === "install") {
32+
assert.ok(command.args.includes("--global"))
33+
installs.push(command.args.at(-1)!)
34+
}
35+
return Effect.succeed({
36+
command: command.command,
37+
exitCode: 0,
38+
stdout: Buffer.from(command.command === "npm" ? "@opencode-ai/cli" : ""),
39+
stderr: Buffer.alloc(0),
40+
stdoutTruncated: false,
41+
stderrTruncated: false,
42+
})
43+
},
44+
}),
45+
)
46+
yield* Effect.gen(function* () {
47+
const updater = yield* Updater.Service
48+
yield* updater.check()
49+
assert.deepEqual(installs, ["@opencode-ai/[email protected]"])
50+
yield* updater.check()
51+
yield* updater.check()
52+
assert.deepEqual(installs, ["@opencode-ai/[email protected]"])
53+
latest.version = "0.0.0-beta-17499"
54+
yield* updater.check()
55+
assert.deepEqual(installs, ["@opencode-ai/[email protected]", "@opencode-ai/[email protected]"])
56+
}).pipe(Effect.provide(Updater.layer.pipe(Layer.provide(dependencies))))
57+
}).pipe(Effect.scoped, Effect.provide(NodeFileSystem.layer)),
58+
)

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ const maximumComponent = "9007199254740991"
55
const versionPattern =
66
/^v?([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
77

8-
export function action(current: string, latest: string, policy: Policy): Action {
8+
export function action(current: string, latest: string, policy: Policy, installed = current): Action {
99
if (policy === false) return "none"
10-
const currentVersion = parseReleaseVersion(current)
10+
const currentVersion = parseReleaseVersion(installed)
1111
const latestVersion = parseReleaseVersion(latest)
1212
if (!currentVersion || !latestVersion || sameRelease(currentVersion, latestVersion)) return "none"
1313
// Major upgrades are never installed automatically.

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,30 @@
11
import { describe, expect, test } from "bun:test"
2+
import path from "node:path"
23
import { action } from "./updater-action"
34
import { decodePolicy } from "./updater"
45

56
describe("updater", () => {
7+
test("remembers successful installs across checks and accepts the next release", async () => {
8+
// Isolate compiled version constants and the update endpoint from other tests.
9+
const child = Bun.spawn(
10+
[
11+
process.execPath,
12+
"--define",
13+
'OPENCODE_VERSION="0.0.0-next-16473"',
14+
"--define",
15+
'OPENCODE_CHANNEL="beta"',
16+
path.join(import.meta.dir, "fixtures/updater.ts"),
17+
],
18+
{ env: { ...process.env, OPENCODE_DISABLE_AUTOUPDATE: "" }, stdout: "pipe", stderr: "pipe" },
19+
)
20+
const [code, stdout, stderr] = await Promise.all([
21+
child.exited,
22+
new Response(child.stdout).text(),
23+
new Response(child.stderr).text(),
24+
])
25+
expect(code, stdout + stderr).toBe(0)
26+
})
27+
628
test("reads autoupdate from JSONC", () => {
729
expect(decodePolicy('{ // preference\n "autoupdate": "notify",\n}')).toBe("notify")
830
expect(decodePolicy('{ "autoupdate": false }')).toBe(false)
@@ -32,6 +54,14 @@ describe("updater", () => {
3254
expect(action("1.2.3", "1.2.3", true)).toBe("none")
3355
})
3456

57+
test("skips an installed update but still accepts the next release", () => {
58+
const current = "0.0.0-next-16473"
59+
const installed = "0.0.0-beta-17498"
60+
expect(action(current, installed, true)).toBe("upgrade")
61+
expect(action(current, installed, true, installed)).toBe("none")
62+
expect(action(current, "0.0.0-beta-17499", true, installed)).toBe("upgrade")
63+
})
64+
3565
test("upgrades when latest is lower (rollback)", () => {
3666
expect(action("1.2.4", "1.2.3", true)).toBe("upgrade")
3767
})

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

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Global } from "@opencode-ai/util/global"
22
import { AppProcess } from "@opencode-ai/util/process"
33
import { OPENCODE_CHANNEL, OPENCODE_LOCAL, OPENCODE_VERSION } from "../version"
4-
import { Context, Duration, Effect, FileSystem, Layer } from "effect"
4+
import { Context, Duration, Effect, FileSystem, Layer, Ref } from "effect"
55
import { ChildProcess } from "effect/unstable/process"
66
import { parse, type ParseError } from "jsonc-parser"
77
import path from "node:path"
@@ -38,6 +38,7 @@ export const layer = Layer.effect(
3838
const fs = yield* FileSystem.FileSystem
3939
const global = yield* Global.Service
4040
const appProcess = yield* AppProcess.Service
41+
const installed = yield* Ref.make(OPENCODE_VERSION)
4142
const channel = OPENCODE_CHANNEL.replace(/[^a-zA-Z0-9._-]/g, "-")
4243

4344
const readPolicy = Effect.fnUntraced(function* () {
@@ -112,18 +113,20 @@ export const layer = Layer.effect(
112113

113114
const upgrade = Effect.fnUntraced(function* (method: Method, version: string) {
114115
const target = `${packageName}@${version}`
115-
const commands: Record<Exclude<Method, "bun" | "curl">, string[]> = {
116-
npm: ["npm", "install", "--global", target],
116+
const commands: Record<Exclude<Method, "bun" | "curl" | "npm">, string[]> = {
117117
pnpm: ["pnpm", "add", "--global", `--allow-build=${packageName}`, target],
118118
yarn: ["yarn", "global", "add", target],
119119
}
120120
const result = yield* Effect.scoped(
121121
Effect.gen(function* () {
122-
if (method === "bun") {
123-
// Bun does not prune old versions from its shared package cache.
122+
if (method === "bun" || method === "npm") {
124123
yield* fs.makeDirectory(global.cache, { recursive: true })
125124
const cache = yield* fs.makeTempDirectoryScoped({ directory: global.cache, prefix: "update-" })
126-
return yield* run(["bun", "install", "--global", "--trust", "--cache-dir", cache, target], "5 minutes")
125+
const command =
126+
method === "bun"
127+
? ["bun", "install", "--global", "--trust", "--cache-dir", cache, target]
128+
: ["npm", "install", "--global", "--cache", cache, target]
129+
return yield* run(command, "5 minutes")
127130
}
128131
if (method === "curl") {
129132
yield* fs.makeDirectory(global.cache, { recursive: true })
@@ -156,18 +159,19 @@ export const layer = Layer.effect(
156159

157160
return yield* Effect.gen(function* () {
158161
const version = yield* latest()
162+
const current = yield* Ref.get(installed)
159163
yield* Effect.logInfo("update check", {
160-
current: OPENCODE_VERSION,
164+
current,
161165
latest: version,
162166
})
163-
const next = action(OPENCODE_VERSION, version, policy)
167+
const next = action(OPENCODE_VERSION, version, policy, current)
164168
if (next === "none") return yield* Effect.logInfo("update check done", { action: "up-to-date" })
165-
if (next === "notify")
166-
return yield* Effect.logInfo("OpenCode update available", { current: OPENCODE_VERSION, latest: version })
169+
if (next === "notify") return yield* Effect.logInfo("OpenCode update available", { current, latest: version })
167170
const detected = yield* method()
168171
if (!detected) return yield* Effect.logWarning("automatic update skipped: installation method not found")
169172
yield* upgrade(detected, version)
170-
yield* Effect.logInfo("updated OpenCode", { from: OPENCODE_VERSION, to: version, method: detected })
173+
yield* Ref.set(installed, version)
174+
yield* Effect.logInfo("updated OpenCode", { from: current, to: version, method: detected })
171175
})
172176
},
173177
Effect.catchCause((cause) => Effect.logWarning("automatic update failed", { cause })),

0 commit comments

Comments
 (0)