diff --git a/install b/install index b0716d53208..1f21325b48b 100755 --- a/install +++ b/install @@ -65,6 +65,18 @@ while [[ $# -gt 0 ]]; do esac done +requested_version="${requested_version#v}" + +# This installer only installs OpenCode 1. OpenCode 1 clients run it with VERSION set when upgrading, +# so refusing 2.x also keeps older clients from replacing themselves with OpenCode 2 by accident. +if [[ "$requested_version" =~ ^([0-9]+)\. ]] && [ "${BASH_REMATCH[1]}" -ge 2 ]; then + echo -e "${RED}Error: OpenCode ${requested_version} is not an OpenCode 1 release, so this installer can't install it.${NC}" + echo -e "${MUTED}To install OpenCode 2, run: ${NC}curl -fsSL https://opencode.ai/v2/install | bash" + echo -e "${MUTED}To upgrade an existing OpenCode 1 install, run: ${NC}opencode upgrade --major" + echo -e "${MUTED}Docs: https://opencode.ai/v2/docs${NC}" + exit 1 +fi + INSTALL_DIR=$HOME/.opencode/bin mkdir -p "$INSTALL_DIR" @@ -181,23 +193,35 @@ else fi if [ -z "$requested_version" ]; then - url="https://github.com/anomalyco/opencode/releases/latest/download/$filename" - specific_version=$(curl -s https://api.github.com/repos/anomalyco/opencode/releases/latest | sed -n 's/.*"tag_name": *"v\([^"]*\)".*/\1/p') + # The opencode-ai npm package only contains OpenCode 1 (OpenCode 2 ships as @opencode/cli). npm is + # published before the GitHub release, so fall back to the newest v1 entry in GitHub's release list + # until its assets exist. GitHub's Latest release may be OpenCode 2, so it's never used. + specific_version=$(curl -fsSL --max-time 10 "https://registry.npmjs.org/opencode-ai/latest" 2>/dev/null | grep -o '"version": *"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)"$/\1/' || true) + if [[ "$specific_version" =~ ^1\.[0-9]+\.[0-9]+$ ]]; then + asset_status=$(curl -sIL --max-time 10 -o /dev/null -w "%{http_code}" "https://github.com/anomalyco/opencode/releases/download/v${specific_version}/$filename" || true) + if [ "$asset_status" != "200" ]; then + specific_version="" + fi + else + specific_version="" + fi + if [ -z "$specific_version" ]; then + specific_version=$(curl -fsSL --max-time 30 "https://api.github.com/repos/anomalyco/opencode/releases?per_page=100" 2>/dev/null | grep -o '"tag_name": *"v1\.[0-9]*\.[0-9]*"' | head -n 1 | sed 's/.*"v\([^"]*\)"$/\1/' || true) + fi - if [[ $? -ne 0 || -z "$specific_version" ]]; then + if [[ -z "$specific_version" ]]; then echo -e "${RED}Failed to fetch version information${NC}" exit 1 fi + url="https://github.com/anomalyco/opencode/releases/download/v${specific_version}/$filename" else - # Strip leading 'v' if present - requested_version="${requested_version#v}" url="https://github.com/anomalyco/opencode/releases/download/v${requested_version}/$filename" specific_version=$requested_version - # Verify the release exists before downloading - http_status=$(curl -sI -o /dev/null -w "%{http_code}" "https://github.com/anomalyco/opencode/releases/tag/v${requested_version}") + # Verify the release asset exists before downloading. A release that is still publishing has none yet. + http_status=$(curl -sIL -o /dev/null -w "%{http_code}" "$url" || true) if [ "$http_status" = "404" ]; then - echo -e "${RED}Error: Release v${requested_version} not found${NC}" + echo -e "${RED}Error: Release v${requested_version} not found. If it was just released, try again in a few minutes.${NC}" echo -e "${MUTED}Available releases: https://github.com/anomalyco/opencode/releases${NC}" exit 1 fi diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index f84ffc428ba..3a837ba31bb 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -74,7 +74,9 @@ function createUpdater(latest: () => Promise): UpdateS }, check: async () => { const { Installation } = await import("@/installation") - return { current: InstallationVersion, latest: await Installation.latest(await Installation.method()) } + // A failed check leaves latest unset, which /update reports as "Couldn't check for updates." + const latest = await Installation.latest(await Installation.method()).catch(() => undefined) + return { current: InstallationVersion, latest } }, apply: async (target) => { const { Installation } = await import("@/installation") diff --git a/packages/opencode/src/cli/cmd/upgrade.ts b/packages/opencode/src/cli/cmd/upgrade.ts index e64529e050a..b329317f704 100644 --- a/packages/opencode/src/cli/cmd/upgrade.ts +++ b/packages/opencode/src/cli/cmd/upgrade.ts @@ -65,7 +65,14 @@ export const UpgradeCommand = { return } - const target = args.target ? args.target.replace(/^v/, "") : await Installation.latest() + const target = args.target + ? args.target.replace(/^v/, "") + : await Installation.latest(method).catch(() => undefined) + if (!target) { + prompts.log.error("Couldn't check for updates") + prompts.outro("Done") + return + } if (InstallationVersion === target) { prompts.log.warn(`opencode upgrade skipped: ${target} is already installed`) diff --git a/packages/opencode/src/cli/upgrade.ts b/packages/opencode/src/cli/upgrade.ts index de009f71915..579de526bac 100644 --- a/packages/opencode/src/cli/upgrade.ts +++ b/packages/opencode/src/cli/upgrade.ts @@ -14,7 +14,7 @@ export function shouldNotify(input: { }) { if (input.autoupdate === false || input.disabled) return false if (input.always) return true - return input.current !== input.latest + return Installation.isUpdate(input.current, input.latest) } // Returns undefined when checks are disabled or fail, so the TUI only suggests OpenCode 2 after a successful check. diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index b91a0314d26..439dc8486cf 100644 --- a/packages/opencode/src/installation/index.ts +++ b/packages/opencode/src/installation/index.ts @@ -60,17 +60,27 @@ export class UpgradeFailedError extends Schema.TaggedErrorClass Effect.Effect @@ -226,6 +236,36 @@ const layer: Layer.Layer 0 + }) + + const tapVersion = Effect.fnUntraced( + function* (formula: string) { + const infoJson = yield* text(["brew", "info", "--json=v2", formula]) + const info = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(BrewInfoV2))(infoJson) + return info.formulae[0].versions.stable + }, + Effect.orElseSucceed(() => undefined), + ) + const result: Interface = { info: Effect.fn("Installation.info")(function* () { return { @@ -267,64 +307,24 @@ const layer: Layer.Layer= 2) + return yield* new UpgradeFailedError({ + stderr: `OpenCode ${target} is OpenCode 2. Upgrade with \`opencode upgrade --major\` or see ${MAJOR_INSTRUCTIONS}`, + }) let upgradeResult: { code: number; stdout: string; stderr: string } | undefined switch (m) { case "curl": @@ -339,25 +339,36 @@ const layer: Layer.Layer { - test("notifies about every newer release, including patches", () => { + test("notifies about every newer OpenCode 1 release, including patches", () => { expect(shouldNotify(base)).toBe(true) - expect(shouldNotify({ ...base, latest: "2.0.0" })).toBe(true) + expect(shouldNotify({ ...base, latest: "1.10.0" })).toBe(true) + }) + + test("does not treat OpenCode 2 or older releases as updates", () => { + expect(shouldNotify({ ...base, latest: "2.0.0" })).toBe(false) + expect(shouldNotify({ ...base, latest: "1.3.9" })).toBe(false) }) test("treats true and notify the same", () => { diff --git a/packages/opencode/test/installation/installation.test.ts b/packages/opencode/test/installation/installation.test.ts index 891725dfbee..6154d364fa6 100644 --- a/packages/opencode/test/installation/installation.test.ts +++ b/packages/opencode/test/installation/installation.test.ts @@ -1,19 +1,24 @@ -import { describe, expect } from "bun:test" +import { describe, expect, test } from "bun:test" import { makeGlobalNode } from "@opencode-ai/core/effect/app-node" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/app-node-platform" -import { Effect, Layer, Stream } from "effect" +import { Effect, Exit, Fiber, Layer, Stream } from "effect" +import * as TestClock from "effect/testing/TestClock" import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" import { Installation } from "../../src/installation" -import { InstallationChannel } from "@opencode-ai/core/installation/version" +import { InstallationVersion } from "@opencode-ai/core/installation/version" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { testEffect } from "../lib/effect" const encoder = new TextEncoder() -function mockHttpClient(handler: (request: HttpClientRequest.HttpClientRequest) => Response) { - const client = HttpClient.make((request) => Effect.succeed(HttpClientResponse.fromWeb(request, handler(request)))) +// A handler that returns undefined never responds. +function mockHttpClient(handler: (request: HttpClientRequest.HttpClientRequest) => Response | undefined) { + const client = HttpClient.make((request) => { + const response = handler(request) + return response ? Effect.succeed(HttpClientResponse.fromWeb(request, response)) : Effect.never + }) return Layer.succeed(HttpClient.HttpClient, client) } @@ -52,7 +57,7 @@ function jsonResponse(body: unknown) { } function testLayer( - httpHandler: (request: HttpClientRequest.HttpClientRequest) => Response, + httpHandler: (request: HttpClientRequest.HttpClientRequest) => Response | undefined, spawnHandler?: (cmd: string, args: readonly string[]) => string | { code: number; stdout?: string; stderr?: string }, ) { const spawnerNode = makeGlobalNode({ @@ -67,116 +72,126 @@ function testLayer( } describe("installation", () => { - describe("latest", () => { - testEffect(testLayer(() => jsonResponse({ tag_name: "v1.2.3" }))).effect( - "reads release version from GitHub releases", - () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("unknown") - expect(result).toBe("1.2.3") - }), - ) - - testEffect(testLayer(() => jsonResponse({ tag_name: "v4.0.0-beta.1" }))).effect( - "strips v prefix from GitHub release tag", - () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("curl") - expect(result).toBe("4.0.0-beta.1") - }), - ) - - const npmCalls: string[] = [] - testEffect( - testLayer((request) => { - npmCalls.push(request.url) - return jsonResponse({ version: "1.5.0" }) - }), - ).effect("reads npm versions via registry", () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("npm") - expect(result).toBe("1.5.0") - expect(npmCalls).toContain(`https://registry.npmjs.org/opencode-ai/${InstallationChannel}`) - }), - ) - - const bunCalls: string[] = [] - testEffect( - testLayer((request) => { - bunCalls.push(request.url) - return jsonResponse({ version: "1.6.0" }) - }), - ).effect("reads bun versions via registry", () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("bun") - expect(result).toBe("1.6.0") - expect(bunCalls).toContain(`https://registry.npmjs.org/opencode-ai/${InstallationChannel}`) - }), - ) - - const pnpmCalls: string[] = [] - testEffect( - testLayer((request) => { - pnpmCalls.push(request.url) - return jsonResponse({ version: "1.7.0" }) - }), - ).effect("reads pnpm versions via registry", () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("pnpm") - expect(result).toBe("1.7.0") - expect(pnpmCalls).toContain(`https://registry.npmjs.org/opencode-ai/${InstallationChannel}`) - }), - ) - - testEffect(testLayer(() => jsonResponse({ version: "2.3.4" }))).effect("reads scoop manifest versions", () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("scoop") - expect(result).toBe("2.3.4") - }), - ) - - testEffect(testLayer(() => jsonResponse({ d: { results: [{ Version: "3.4.5" }] } }))).effect( - "reads chocolatey feed versions", - () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("choco") - expect(result).toBe("3.4.5") - }), - ) - - testEffect( - testLayer( - () => jsonResponse({ versions: { stable: "2.0.0" } }), - (cmd, args) => { - // getBrewFormula: return core formula (no tap) - if (cmd === "brew" && args.includes("--formula") && args.includes("anomalyco/tap/opencode")) return "" - if (cmd === "brew" && args.includes("--formula") && args.includes("opencode")) return "opencode" - return "" - }, - ), - ).effect("reads brew formulae API versions", () => - Effect.gen(function* () { - const result = yield* Installation.use.latest("brew") - expect(result).toBe("2.0.0") - }), - ) - - const brewInfoJson = JSON.stringify({ - formulae: [{ versions: { stable: "2.1.0" } }], + describe("isUpdate", () => { + test("only counts newer releases in the installed major version", () => { + expect(Installation.isUpdate("1.19.0", "1.19.1")).toBe(true) + expect(Installation.isUpdate("1.19.0", "1.20.0")).toBe(true) + expect(Installation.isUpdate("1.19.0", "1.19.0")).toBe(false) + expect(Installation.isUpdate("1.19.0", "1.18.35")).toBe(false) + expect(Installation.isUpdate("1.19.0", "2.0.0")).toBe(false) + expect(Installation.isUpdate("1.9.0", "1.10.0")).toBe(true) }) + + test("compares preview builds within their channel", () => { + expect(Installation.isUpdate("0.0.0-dev-202610110139", "0.0.0-dev-202610120000")).toBe(true) + expect(Installation.isUpdate("0.0.0-dev-202610120000", "0.0.0-dev-202610110139")).toBe(false) + }) + + test("source builds only accept OpenCode 1 releases", () => { + expect(Installation.isUpdate("local", "1.19.0")).toBe(true) + expect(Installation.isUpdate("local", "2.0.0")).toBe(false) + expect(Installation.isUpdate("1.19.0", "not-a-version")).toBe(false) + }) + }) + + describe("latest", () => { + const npm = "https://registry.npmjs.org/opencode-ai/latest" + const choco = "https://community.chocolatey.org/api/v2/Packages" + const tap = (cmd: string, args: readonly string[]) => + cmd === "brew" && args.join(" ") === "list --formula anomalyco/tap/opencode" ? "opencode" : "" + const core = (cmd: string, args: readonly string[]) => + cmd === "brew" && args.join(" ") === "list --formula opencode" ? "opencode" : "" + const registry = (version: string, calls: string[], feed: string[] = [version]) => + testLayer((request) => { + calls.push(request.url) + if (request.url.startsWith(choco)) + return jsonResponse({ + d: { results: feed.filter((v) => request.url.includes(`%27${v}%27`)).map((Version) => ({ Version })) }, + }) + return jsonResponse({ version }) + }) + + const methods = ["curl", "yarn", "unknown", "npm", "bun", "pnpm", "scoop", "choco"] as const + for (const method of methods) { + const calls: string[] = [] + testEffect(registry("1.19.2", calls)).effect(`reads ${method} versions from the opencode-ai npm package`, () => + Effect.gen(function* () { + calls.length = 0 + expect(yield* Installation.use.latest(method)).toBe("1.19.2") + expect(calls[0]).toBe(npm) + expect(calls.slice(1).every((url) => url.startsWith(choco))).toBe(true) + }), + ) + + testEffect(registry("2.0.27", [])).effect(`ignores OpenCode 2 versions for ${method}`, () => + Effect.gen(function* () { + expect(yield* Installation.use.latest(method)).toBe(InstallationVersion) + }), + ) + } + + const tapCalls: string[] = [] testEffect( - testLayer( - () => jsonResponse({}), // HTTP not used for tap formula - (cmd, args) => { - if (cmd === "brew" && args.includes("anomalyco/tap/opencode") && args.includes("--formula")) return "opencode" - if (cmd === "brew" && args.includes("--json=v2")) return brewInfoJson - return "" - }, - ), - ).effect("reads brew tap info JSON via CLI", () => + testLayer((request) => { + tapCalls.push(request.url) + return jsonResponse({ version: "1.19.2" }) + }, tap), + ).effect("reads Homebrew tap versions from the opencode-ai npm package", () => Effect.gen(function* () { - const result = yield* Installation.use.latest("brew") - expect(result).toBe("2.1.0") + tapCalls.length = 0 + expect(yield* Installation.use.latest("brew")).toBe("1.19.2") + expect(tapCalls).toEqual([npm]) + }), + ) + + const coreCalls: string[] = [] + testEffect( + testLayer((request) => { + coreCalls.push(request.url) + return jsonResponse({ version: "1.19.2" }) + }, core), + ).effect("never offers an OpenCode 1 update Homebrew Core can't install", () => + Effect.gen(function* () { + coreCalls.length = 0 + expect(yield* Installation.use.latest("brew")).toBe(InstallationVersion) + expect(coreCalls).toEqual([]) + }), + ) + + testEffect(registry("1.19.2", [], ["1.19.1"])).effect("waits until Chocolatey has published the npm version", () => + Effect.gen(function* () { + expect(yield* Installation.use.latest("choco")).toBe(InstallationVersion) + }), + ) + + const errorCalls: string[] = [] + testEffect( + testLayer((request) => { + errorCalls.push(request.url) + return new Response("unavailable", { status: 503 }) + }), + ).live("fails when the npm registry fails, without consulting GitHub", () => + Effect.gen(function* () { + errorCalls.length = 0 + expect(Exit.isFailure(yield* Installation.use.latest("curl").pipe(Effect.exit))).toBe(true) + expect(errorCalls.length).toBeGreaterThan(0) + expect(errorCalls.every((url) => url === npm)).toBe(true) + }), + ) + + testEffect(testLayer(() => jsonResponse({ name: "opencode-ai" }))).effect( + "fails when the npm registry returns no version", + () => + Effect.gen(function* () { + expect(Exit.isFailure(yield* Installation.use.latest("npm").pipe(Effect.exit))).toBe(true) + }), + ) + + testEffect(testLayer(() => undefined)).effect("gives up when the npm registry doesn't answer in time", () => + Effect.gen(function* () { + const fiber = yield* Installation.use.latest("curl").pipe(Effect.exit, Effect.forkChild) + yield* TestClock.adjust("10 seconds") + expect(Exit.isFailure(yield* Fiber.join(fiber))).toBe(true) }), ) }) @@ -192,7 +207,7 @@ describe("installation", () => { ), ).effect("returns sanitized typed errors for failed package upgrades", () => Effect.gen(function* () { - const error = yield* Effect.flip(Installation.use.upgrade("npm", "9.9.9")) + const error = yield* Effect.flip(Installation.use.upgrade("npm", "1.99.9")) expect(error).toBeInstanceOf(Installation.UpgradeFailedError) expect(error.stderr).toBe("Upgrade failed for npm (exit code 1).") expect(error.message).toBe(error.stderr) @@ -212,7 +227,7 @@ describe("installation", () => { ), ).effect("returns sanitized typed errors when the curl install script fails", () => Effect.gen(function* () { - const error = yield* Effect.flip(Installation.use.upgrade("curl", "9.9.9")) + const error = yield* Effect.flip(Installation.use.upgrade("curl", "1.99.9")) expect(error).toBeInstanceOf(Installation.UpgradeFailedError) expect(error.stderr).toBe("Upgrade failed for curl (exit code 1).") expect(error.message).toBe(error.stderr) @@ -233,11 +248,105 @@ describe("installation", () => { ), ).effect("falls back to sh when bash is unavailable during curl upgrade", () => Effect.gen(function* () { - yield* Installation.use.upgrade("curl", "9.9.9") + yield* Installation.use.upgrade("curl", "1.99.9") }), ) }) + describe("upgrade per method", () => { + const packageCalls: string[] = [] + testEffect( + testLayer( + () => jsonResponse({}), + (cmd, args) => { + packageCalls.push([cmd, ...args].join(" ")) + return "" + }, + ), + ).effect("installs the OpenCode 1 package with each package manager", () => + Effect.gen(function* () { + for (const method of ["npm", "pnpm", "bun", "yarn"] as const) { + packageCalls.length = 0 + yield* Installation.use.upgrade(method, "1.19.2") + expect(packageCalls[0]).toContain("opencode-ai@1.19.2") + } + }), + ) + + const majorCalls: string[] = [] + testEffect( + testLayer( + () => jsonResponse({}), + (cmd, args) => { + majorCalls.push([cmd, ...args].join(" ")) + return "" + }, + ), + ).effect("refuses OpenCode 2 targets for every method", () => + Effect.gen(function* () { + for (const method of ["curl", "npm", "pnpm", "bun", "yarn", "brew", "choco", "scoop"] as const) { + majorCalls.length = 0 + const error = yield* Effect.flip(Installation.use.upgrade(method, "2.0.27")) + expect(error.stderr).toContain("opencode upgrade --major") + expect(majorCalls).toEqual([]) + } + }), + ) + + const coreCalls: string[] = [] + testEffect( + testLayer( + () => jsonResponse({}), + (cmd, args) => { + coreCalls.push([cmd, ...args].join(" ")) + if (args.join(" ") === "list --formula opencode") return "opencode" + return "" + }, + ), + ).effect("never runs brew upgrade for Homebrew Core, whose formula is OpenCode 2", () => + Effect.gen(function* () { + coreCalls.length = 0 + const error = yield* Effect.flip(Installation.use.upgrade("brew", "1.19.2")) + expect(error.stderr).toContain("Homebrew Core") + expect(coreCalls.some((call) => call.startsWith("brew upgrade"))).toBe(false) + }), + ) + + const tap = (stable: string, calls: string[]) => + testLayer( + () => jsonResponse({}), + (cmd, args) => { + calls.push([cmd, ...args].join(" ")) + if (args.join(" ") === "list --formula anomalyco/tap/opencode") return "opencode" + if (args.join(" ") === "--repo anomalyco/tap") return "/tmp/opencode-test-tap" + if (args.includes("--json=v2")) return JSON.stringify({ formulae: [{ versions: { stable } }] }) + return "" + }, + ) + + const tapCalls: string[] = [] + testEffect(tap("1.19.2", tapCalls)).effect("upgrades the Homebrew tap once it has the version", () => + Effect.gen(function* () { + tapCalls.length = 0 + yield* Installation.use.upgrade("brew", "1.19.2") + expect(tapCalls).toContain("git pull --ff-only") + expect(tapCalls).toContain("brew upgrade anomalyco/tap/opencode") + }), + ) + + for (const stable of ["1.19.1", "2.0.0"]) { + const calls: string[] = [] + testEffect(tap(stable, calls)).effect(`asks to retry when the Homebrew tap is at ${stable}`, () => + Effect.gen(function* () { + calls.length = 0 + const error = yield* Effect.flip(Installation.use.upgrade("brew", "1.19.2")) + expect(error.stderr).toContain("Try again in a few minutes") + expect(calls.some((call) => call.startsWith("brew upgrade"))).toBe(false) + }), + ) + } + }) + describe("upgradeMajor", () => { const calls: string[] = [] testEffect( diff --git a/packages/tui/src/component/dialog-update.tsx b/packages/tui/src/component/dialog-update.tsx index 5461beafb45..3b6624963a7 100644 --- a/packages/tui/src/component/dialog-update.tsx +++ b/packages/tui/src/component/dialog-update.tsx @@ -1,7 +1,7 @@ import { TextAttributes } from "@opentui/core" import { createEffect, createMemo, createResource, createSignal, For, Match, Show, Switch } from "solid-js" import { useTheme } from "../context/theme" -import type { UpdateState, UpdateTarget } from "../context/update-notification" +import { isVersionGreater, type UpdateState, type UpdateTarget } from "../context/update-notification" import { useDialog } from "../ui/dialog" import { useBindings } from "../keymap" import { errorMessage } from "../util/error" @@ -14,10 +14,16 @@ type Version = { current: string; latest?: string } // A newer OpenCode 1 release uses the normal update flow; OpenCode 2.0 is only offered when OpenCode 1 is current. export function updateTarget(version: Version): UpdateTarget { - if (version.latest && version.latest !== version.current) return { type: "latest", version: version.latest } + if (version.latest && isUpdate(version.current, version.latest)) return { type: "latest", version: version.latest } return { type: "major" } } +// Only a newer release in the installed major version is a normal update. OpenCode 2 has its own offer. +export function isUpdate(current: string, latest: string) { + const major = (value: string) => value.replace(/^v/, "").split(".")[0] + return major(latest) === major(current) && isVersionGreater(latest, current) +} + export function DialogUpdate(props: { check: () => Promise state: () => UpdateState | undefined diff --git a/packages/tui/test/component/dialog-update.test.ts b/packages/tui/test/component/dialog-update.test.ts index fef27432874..2dffef441cc 100644 --- a/packages/tui/test/component/dialog-update.test.ts +++ b/packages/tui/test/component/dialog-update.test.ts @@ -11,6 +11,12 @@ describe("dialog update", () => { expect(updateTarget({ current: "1.4.2", latest: "1.4.2" })).toEqual({ type: "major" }) }) + test("never treats OpenCode 2 or an older release as a normal update", () => { + expect(updateTarget({ current: "1.4.2", latest: "2.0.0" })).toEqual({ type: "major" }) + expect(updateTarget({ current: "1.4.2", latest: "1.4.1" })).toEqual({ type: "major" }) + expect(updateTarget({ current: "1.9.0", latest: "1.10.0" })).toEqual({ type: "latest", version: "1.10.0" }) + }) + test("skipping an OpenCode 1 version hides it until a newer one ships", () => { const now = 1_000_000 expect(visibleNotice({ type: "available", version: "1.4.2" }, {}, now)).toEqual({ diff --git a/script/install.test.ts b/script/install.test.ts new file mode 100644 index 00000000000..78f89b8bf6e --- /dev/null +++ b/script/install.test.ts @@ -0,0 +1,142 @@ +import { afterAll, describe, expect, test } from "bun:test" +import { $ } from "bun" +import { mkdtemp, rm } from "fs/promises" +import os from "os" +import path from "path" + +const script = path.resolve(import.meta.dir, "../install") +const root = await mkdtemp(path.join(os.tmpdir(), "opencode-install-test-")) +afterAll(() => rm(root, { recursive: true, force: true })) + +// Stands in for curl: answers the npm registry, the GitHub release list, and release downloads. +// HEAD requests for a release asset report ASSET_STATUS (200 by default). +const curl = `#!/usr/bin/env bash +echo "$*" >> "$CURL_LOG" +out="" +url="" +head=false +while [ $# -gt 0 ]; do + case "$1" in + -o) out="$2"; shift 2 ;; + -w|--max-time) shift 2 ;; + -I|-sI|-sIL) head=true; shift ;; + -*) shift ;; + *) url="$1"; shift ;; + esac +done +case "$url" in + https://registry.npmjs.org/opencode-ai/latest) [ -n "$NPM_BODY" ] || exit 22; printf '%s' "$NPM_BODY" ;; + https://api.github.com/repos/anomalyco/opencode/releases*) printf '%s' "$GITHUB_BODY" ;; + https://github.com/anomalyco/opencode/releases/download/*) + if [ "$head" = true ]; then printf '%s' "\${ASSET_STATUS:-200}"; else cp "$ARCHIVE" "$out"; fi ;; + *) exit 22 ;; +esac +` + +const bin = path.join(root, "bin") +await Bun.write(path.join(bin, "curl"), curl) +await $`chmod +x ${path.join(bin, "curl")}` +const archive = path.join(root, "opencode.tar.gz") +await Bun.write(path.join(root, "payload", "opencode"), "#!/bin/sh\necho installed\n") +await $`tar -czf ${archive} -C ${path.join(root, "payload")} opencode` + +let run = 0 +async function install(input: { env?: Record; args?: string[] }) { + const home = path.join(root, `home-${run++}`) + const log = path.join(home, "curl.log") + await Bun.write(log, "") + const proc = Bun.spawn(["bash", script, "--no-modify-path", ...(input.args ?? [])], { + env: { + PATH: `${bin}:/usr/bin:/bin`, + HOME: home, + SHELL: "/bin/bash", + TMPDIR: home, + CURL_LOG: log, + ARCHIVE: archive, + ...input.env, + }, + stdout: "pipe", + stderr: "pipe", + }) + const [stdout, stderr, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]) + return { + code, + output: stdout + stderr, + curl: (await Bun.file(log).text()).trim().split("\n").filter(Boolean), + installed: await Bun.file(path.join(home, ".opencode", "bin", "opencode")).exists(), + } +} + +describe("install script", () => { + test("refuses an OpenCode 2 VERSION before downloading anything", async () => { + for (const version of ["2.0.0", "v2.0.27", "10.1.0"]) { + const result = await install({ env: { VERSION: version } }) + expect(result.code).toBe(1) + expect(result.output).toContain("https://opencode.ai/v2/install") + expect(result.curl).toEqual([]) + expect(result.installed).toBe(false) + } + }) + + test("refuses an OpenCode 2 --version", async () => { + const result = await install({ args: ["--version", "2.0.0"] }) + expect(result.code).toBe(1) + expect(result.output).toContain("opencode upgrade --major") + }) + + test.skipIf(process.platform !== "linux")("installs an explicit OpenCode 1 version", async () => { + const result = await install({ env: { VERSION: "1.18.35" } }) + expect(result.code).toBe(0) + expect(result.installed).toBe(true) + expect(result.curl.at(-1)).toContain("releases/download/v1.18.35/") + }) + + test.skipIf(process.platform !== "linux")("reads the version from npm", async () => { + const result = await install({ + env: { NPM_BODY: '{"name":"opencode-ai","_npmVersion":"11.0.0","version":"1.19.2"}' }, + }) + expect(result.code).toBe(0) + expect(result.output).toContain("version: \x1b[0m1.19.2") + expect(result.curl.some((line) => line.includes("api.github.com"))).toBe(false) + expect(result.curl.at(-1)).toContain("releases/download/v1.19.2/") + }) + + test.skipIf(process.platform !== "linux")("falls back to the newest v1 GitHub release when npm fails", async () => { + const result = await install({ + env: { GITHUB_BODY: '[{"tag_name": "v2.0.28"},{"tag_name": "v1.19.0"},{"tag_name": "v1.18.35"}]' }, + }) + expect(result.code).toBe(0) + expect(result.curl.some((line) => line.includes("releases/latest"))).toBe(false) + expect(result.curl.at(-1)).toContain("releases/download/v1.19.0/") + }) + + test.skipIf(process.platform !== "linux")( + "falls back to GitHub while the npm version's release is still publishing", + async () => { + const result = await install({ + env: { NPM_BODY: '{"version":"1.19.2"}', ASSET_STATUS: "404", GITHUB_BODY: '[{"tag_name": "v1.19.1"}]' }, + }) + expect(result.code).toBe(0) + expect(result.curl.at(-1)).toContain("releases/download/v1.19.1/") + }, + ) + + test.skipIf(process.platform !== "linux")("ignores an OpenCode 2 version from npm", async () => { + const result = await install({ + env: { NPM_BODY: '{"version":"2.0.27"}', GITHUB_BODY: '[{"tag_name": "v1.19.0"}]' }, + }) + expect(result.code).toBe(0) + expect(result.curl.at(-1)).toContain("releases/download/v1.19.0/") + }) + + test("reports a missing explicit release", async () => { + const result = await install({ env: { VERSION: "1.19.9", ASSET_STATUS: "404" } }) + expect(result.code).toBe(1) + expect(result.output).toContain("Release v1.19.9 not found") + expect(result.installed).toBe(false) + }) +}) diff --git a/script/publish.ts b/script/publish.ts index 40a470d2e6f..f5519084e92 100755 --- a/script/publish.ts +++ b/script/publish.ts @@ -66,5 +66,6 @@ if (Script.release && !Script.preview) { } if (Script.release) { - await $`gh release edit ${tag} --draft=false --repo ${process.env.GH_REPO}` + // OpenCode 1 clients resolve updates through GitHub's Latest release, so keep it on 1.x explicitly. + await $`gh release edit ${tag} --draft=false --latest --repo ${process.env.GH_REPO}` } diff --git a/script/raw-changelog.test.ts b/script/raw-changelog.test.ts new file mode 100644 index 00000000000..0f767295ee7 --- /dev/null +++ b/script/raw-changelog.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, test } from "bun:test" +import { latestV1 } from "./raw-changelog" + +describe("raw changelog", () => { + test("starts from the newest published OpenCode 1 release", () => { + expect( + latestV1([ + { tag_name: "v2.0.28", draft: false }, + { tag_name: "v1.19.2", draft: true }, + { tag_name: "v2.0.27", draft: false }, + { tag_name: "v1.19.1", draft: false }, + { tag_name: "v1.19.0", draft: false }, + ]), + ).toBe("1.19.1") + }) + + test("ignores OpenCode 2 releases entirely", () => { + expect(latestV1([{ tag_name: "v2.0.0", draft: false }])).toBeUndefined() + }) +}) diff --git a/script/raw-changelog.ts b/script/raw-changelog.ts index 2ea76247d58..e4a459b654d 100644 --- a/script/raw-changelog.ts +++ b/script/raw-changelog.ts @@ -50,11 +50,16 @@ function ref(input: string) { return input } +// OpenCode 2 releases share this repository, so only OpenCode 1 tags are candidates. +export function latestV1(releases: Release[]) { + return releases.find((item) => !item.draft && /^v1\.\d+\.\d+$/.test(item.tag_name))?.tag_name.replace(/^v/, "") +} + async function latest() { const data = await $`gh api "/repos/${repo}/releases?per_page=100"`.json() - const release = (data as Release[]).find((item) => !item.draft) - if (!release) throw new Error("No releases found") - return release.tag_name.replace(/^v/, "") + const release = latestV1(data as Release[]) + if (!release) throw new Error("No OpenCode 1 releases found") + return release } async function diff(base: string, head: string) {