From eee02ca4be77d926869ecc9d79194c58946677fb Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:12:24 +1000 Subject: [PATCH] feat(desktop): ship the CLI as opencode and put it on the Windows PATH --- .github/workflows/publish.yml | 2 +- packages/cli/test/retained-image.test.ts | 2 +- packages/desktop/.gitignore | 2 +- .../desktop/electron-builder.config.test.ts | 4 +- packages/desktop/electron-builder.config.ts | 10 +-- .../desktop/resources/windows/installer.nsh | 10 +++ packages/desktop/scripts/bench-startup.ts | 4 +- packages/desktop/scripts/dev.ts | 4 +- packages/desktop/scripts/utils.ts | 8 +-- .../src/main/service/background-service.ts | 8 +++ .../desktop/src/main/service/cli-path.test.ts | 49 +++++++++++++ packages/desktop/src/main/service/cli-path.ts | 70 +++++++++++++++++++ .../src/main/service/cli-stages.test.ts | 8 +-- .../desktop/src/main/service/desktop-cli.ts | 6 +- .../desktop/src/main/service/sidecar-probe.ts | 2 +- 15 files changed, 163 insertions(+), 26 deletions(-) create mode 100644 packages/desktop/src/main/service/cli-path.test.ts create mode 100644 packages/desktop/src/main/service/cli-path.ts diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index fb9bf7d0924..e98a7a59057 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -641,7 +641,7 @@ jobs: $files = @() $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*.exe" | Select-Object -ExpandProperty FullName $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\*.exe" | Select-Object -ExpandProperty FullName - $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\resources\opencode-cli.exe" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName + $files += Get-ChildItem "${{ github.workspace }}\packages\desktop\dist\*unpacked\resources\opencode.exe" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName foreach ($file in $files | Select-Object -Unique) { $sig = Get-AuthenticodeSignature $file diff --git a/packages/cli/test/retained-image.test.ts b/packages/cli/test/retained-image.test.ts index e6e8f659327..ba53097ec45 100644 --- a/packages/cli/test/retained-image.test.ts +++ b/packages/cli/test/retained-image.test.ts @@ -81,7 +81,7 @@ windows("installed accepts package-manager and curl binaries only", () => ), true, ], - [path.join(home, "AppData", "Local", "Programs", "OpenCode", "resources", "opencode-cli.exe"), false], + [path.join(home, "AppData", "Local", "Programs", "OpenCode", "resources", "opencode.exe"), false], [path.join(home, "node_modules", "bun", "bin", "bun.exe"), false], ] as const const results = cases.map(([executable]) => { diff --git a/packages/desktop/.gitignore b/packages/desktop/.gitignore index 6923045cd9b..32765355d64 100644 --- a/packages/desktop/.gitignore +++ b/packages/desktop/.gitignore @@ -24,6 +24,6 @@ dist-ssr *.sw? out/ -resources/opencode-cli* +resources/opencode* resources/icons resources/*.metainfo.xml diff --git a/packages/desktop/electron-builder.config.test.ts b/packages/desktop/electron-builder.config.test.ts index f9e62d80333..39ea2d50c3f 100644 --- a/packages/desktop/electron-builder.config.test.ts +++ b/packages/desktop/electron-builder.config.test.ts @@ -78,9 +78,9 @@ test("shared packaging defaults", async () => { const include = path.join(import.meta.dirname, "resources/windows/installer.nsh") expect(config.nsis?.include).toBe(include) expect(await Bun.file(include).exists()).toBe(true) - expect(config.files).toContain("!resources/opencode-cli*") + expect(config.files).toContain("!resources/opencode*") expect(config.extraResources).toEqual([ - { from: "resources/", to: "", filter: ["opencode-cli", "opencode-cli.exe", "opencode-cli.version"] }, + { from: "resources/", to: "", filter: ["opencode", "opencode.exe", "opencode.version"] }, ]) }) diff --git a/packages/desktop/electron-builder.config.ts b/packages/desktop/electron-builder.config.ts index c29c0d3c12a..a42df51f5ac 100644 --- a/packages/desktop/electron-builder.config.ts +++ b/packages/desktop/electron-builder.config.ts @@ -49,7 +49,7 @@ function macSignOptions(options: CustomMacSignOptions): CustomMacSignOptions { optionsForFile: (file) => { const defaults = options.optionsForFile?.(file) - if (file !== path.join(options.app, "Contents/Resources/opencode-cli")) return defaults ?? {} + if (file !== path.join(options.app, "Contents/Resources/opencode")) return defaults ?? {} // The Bun CLI loads bun-pty's native library; Electron and its helpers do not need this exception. return { ...defaults, entitlements: path.join(packageDir, "resources/entitlements.cli.plist") } @@ -93,7 +93,7 @@ const getBase = (appId: string): Configuration => { files: [ "out/**/*", "resources/**/*", - "!resources/opencode-cli*", + "!resources/opencode*", // Keep only the target platform's node-pty prebuild when cross-packaging with --cpu=*. ...CLI_BINARIES.filter((item) => item.os !== target.os || item.cpu !== target.cpu).map( (item) => `!**/node_modules/@lydell/node-pty-${item.os}-${item.cpu}{,/**/*}`, @@ -117,7 +117,7 @@ const getBase = (appId: string): Configuration => { { from: "resources/", to: "", - filter: ["opencode-cli", "opencode-cli.exe", "opencode-cli.version"], + filter: ["opencode", "opencode.exe", "opencode.version"], }, ], afterPack: async (context) => { @@ -128,13 +128,13 @@ const getBase = (appId: string): Configuration => { if (arch !== target.cpu) throw new Error(`Packaging ${arch} Electron with the ${target.target} CLI`) const resources = context.packager.getResourcesDir(context.appOutDir) - const cli = path.join(resources, context.electronPlatformName === "win32" ? "opencode-cli.exe" : "opencode-cli") + const cli = path.join(resources, context.electronPlatformName === "win32" ? "opencode.exe" : "opencode") const file = await stat(cli) if (!file.isFile() || file.size === 0) throw new Error(`Bundled CLI must be a non-empty file: ${cli}`) await NativeArch.verify(cli, arch) - const version = path.join(path.dirname(cli), "opencode-cli.version") + const version = path.join(path.dirname(cli), "opencode.version") if ((await stat(version)).size === 0) throw new Error(`Bundled CLI version must be a non-empty file: ${version}`) diff --git a/packages/desktop/resources/windows/installer.nsh b/packages/desktop/resources/windows/installer.nsh index 6c994e5d5d3..89975a14e55 100644 --- a/packages/desktop/resources/windows/installer.nsh +++ b/packages/desktop/resources/windows/installer.nsh @@ -8,9 +8,19 @@ !macro customUnInstall ${IfNot} ${isUpdated} !insertmacro removeStagedUpdates $INSTDIR + !insertmacro removeCliFromPath ${EndIf} !macroend +; The app links the CLI into "\bin" and adds that directory to the user PATH once. Remove both, +; so a later install adds the entry again. The raw registry value keeps entries such as %USERPROFILE%\bin. +!macro removeCliFromPath + nsExec::Exec `"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$$d = $$env:APPDATA + '\${APP_ID}\bin'; $$k = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment'); $$o = @(([string]$$k.GetValue('Path', '', 'DoNotExpandEnvironmentNames')) -split ';' | Where-Object { $$_ }); $$n = @($$o | Where-Object { $$_ -ne $$d }); if ($$n.Count -lt $$o.Count) { $$k.SetValue('Path', ($$n -join ';'), 'ExpandString') }"` + Pop $0 + System::Call 'user32::SendMessageTimeout(p 0xffff, i 0x1a, p 0, t "Environment", i 2, i 5000, *p .r0)' + RMDir /r "$APPDATA\${APP_ID}\bin" +!macroend + ; The stock check starts Windows PowerShell up to five times per installer and again in the old ; uninstaller, about 1.2 s each. This walks the process list in-process instead and keeps the stock ; behaviour: stop every process whose image lives under $INSTDIR. An update gives the quitting app diff --git a/packages/desktop/scripts/bench-startup.ts b/packages/desktop/scripts/bench-startup.ts index 7afac1cfe7b..6800bf13082 100644 --- a/packages/desktop/scripts/bench-startup.ts +++ b/packages/desktop/scripts/bench-startup.ts @@ -883,7 +883,7 @@ function summarize(list: Sample[]) { function bundledCli(exe: string) { const resources = process.platform === "darwin" ? join(dirname(exe), "..", "Resources") : join(dirname(exe), "resources") - return join(resources, process.platform === "win32" ? "opencode-cli.exe" : "opencode-cli") + return join(resources, process.platform === "win32" ? "opencode.exe" : "opencode") } async function warmService() { @@ -891,7 +891,7 @@ async function warmService() { const clis = builds.map((build) => bundledCli(build.exe)) const identity = (cli: string) => { - const version = join(dirname(cli), "opencode-cli.version") + const version = join(dirname(cli), "opencode.version") return existsSync(version) ? readFileSync(version, "utf8").trim() : String(statSync(cli).size) } diff --git a/packages/desktop/scripts/dev.ts b/packages/desktop/scripts/dev.ts index bd544f34e40..89cfbee4aa6 100644 --- a/packages/desktop/scripts/dev.ts +++ b/packages/desktop/scripts/dev.ts @@ -51,13 +51,13 @@ function selectOptions(): DevOptions { async function prepareServer(source: ServerSource) { if (source.type === "download") - return downloadCliToResources(source.version, windowsify("resources/opencode-cli-dev")) + return downloadCliToResources(source.version, windowsify("resources/opencode-dev")) buildWebUi() process.env.OPENCODE_DESKTOP_CLI_DEV = join(import.meta.dirname, "../../cli") if (process.platform !== "win32") return process.env.OPENCODE_DESKTOP_WSL_CLI_BUILD = join(import.meta.dirname, "../../cli/script/build.ts") - process.env.OPENCODE_DESKTOP_WSL_CLI_OUTPUT = join(import.meta.dirname, "../resources/opencode-cli-wsl") + process.env.OPENCODE_DESKTOP_WSL_CLI_OUTPUT = join(import.meta.dirname, "../resources/opencode-wsl") } // The source CLI serves packages/app/dist only to paired devices, and nothing on the way to the diff --git a/packages/desktop/scripts/utils.ts b/packages/desktop/scripts/utils.ts index b1542d79dd0..3ba90d87bbb 100644 --- a/packages/desktop/scripts/utils.ts +++ b/packages/desktop/scripts/utils.ts @@ -85,10 +85,10 @@ export function nodePtyPackage(target?: string) { return `@lydell/node-pty-${cli.os}-${cli.cpu}` } -export async function downloadCliToResources(version = CLI_VERSION, dest = windowsify("resources/opencode-cli")) { +export async function downloadCliToResources(version = CLI_VERSION, dest = windowsify("resources/opencode")) { const { $ } = await import("bun") const cli = getCurrentCli() - const directory = await mkdtemp(join(tmpdir(), "opencode-cli-")) + const directory = await mkdtemp(join(tmpdir(), "opencode-download-")) try { await $`bun install --no-save --cwd ${directory} ${`${cli.package}@${version}`} ${`--os=${cli.os}`} ${`--cpu=${cli.cpu}`}` @@ -100,7 +100,7 @@ export async function downloadCliToResources(version = CLI_VERSION, dest = windo console.log(`Copied ${cli.package}@${version} to ${dest}`) } -export async function copyBuiltCliToResources(root: string, dest = windowsify("resources/opencode-cli")) { +export async function copyBuiltCliToResources(root: string, dest = windowsify("resources/opencode")) { const cli = getCurrentCli() const directory = cli.package.replace("@opencode/", "") await copyCliToResources(join(root, directory), dest) @@ -123,7 +123,7 @@ async function copyCliToResources(pkg: string, dest: string) { } export function versionFile(cli: string) { - return join(dirname(cli), "opencode-cli.version") + return join(dirname(cli), "opencode.version") } async function prepareCli(dest: string) { diff --git a/packages/desktop/src/main/service/background-service.ts b/packages/desktop/src/main/service/background-service.ts index 2d156b25e8a..5ea7d432aa7 100644 --- a/packages/desktop/src/main/service/background-service.ts +++ b/packages/desktop/src/main/service/background-service.ts @@ -1,6 +1,7 @@ import { app } from "electron" import { Context, Effect, FileSystem, Layer, Path } from "effect" import { BackgroundServiceState } from "./background-service-state" +import { exposeCli } from "./cli-path" import { cleanStages } from "./cli-stages" import { DesktopCli } from "./desktop-cli" import { SidecarCredentials } from "./sidecar-credentials" @@ -85,6 +86,13 @@ const connect = Effect.fn("BackgroundService.connect")(function* (mode: "initial Effect.catch((error) => Effect.logError("failed to clean staged v2 CLIs", { error })), ), ) + + if (mode === "initial" && app.isPackaged && process.platform === "win32" && cli.binary) + runFork( + exposeCli(cli.binary, path.join(app.getPath("userData"), "bin")).pipe( + Effect.catch((error) => Effect.logError("failed to put the v2 CLI on PATH", { error })), + ), + ) const ready = { url: url.origin, password: service.auth.password } satisfies SidecarCredentials.Data SidecarCredentials.set(ready) diff --git a/packages/desktop/src/main/service/cli-path.test.ts b/packages/desktop/src/main/service/cli-path.test.ts new file mode 100644 index 00000000000..702d4a92ea3 --- /dev/null +++ b/packages/desktop/src/main/service/cli-path.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, test } from "bun:test" +import { linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import path from "node:path" +import { NodeFileSystem, NodePath } from "@effect/platform-node" +import { Effect, Layer } from "effect" + +import { linkCli } from "./cli-path" + +const run = (binary: string, directory: string) => + Effect.runPromise(linkCli(binary, directory).pipe(Effect.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)))) + +// PATH holds one fixed directory while every version stages its own CLI, so the link there must +// always follow the current stage, without copying 200 MB or leaving old versions behind. +describe("linkCli", () => { + test.each([ + { name: "a first launch", linked: undefined, current: "2.0.20" }, + { name: "an upgrade", linked: "2.0.19", current: "2.0.20" }, + { name: "a downgrade", linked: "2.0.20", current: "2.0.19" }, + { name: "a relaunch", linked: "2.0.20", current: "2.0.20" }, + ])("links the current stage after $name", async (input) => { + const root = mkdtempSync(path.join(tmpdir(), "opencode-link-")) + + try { + const stage = (version: string) => path.join(root, "cli", version, "opencode") + ;["2.0.19", "2.0.20"].forEach((version) => { + mkdirSync(path.dirname(stage(version)), { recursive: true }) + writeFileSync(stage(version), version) + }) + const bin = path.join(root, "bin") + const link = path.join(bin, "opencode") + + if (input.linked) { + mkdirSync(bin) + linkSync(stage(input.linked), link) + } + + expect(await run(stage(input.current), bin)).toBe(link) + expect(readFileSync(link, "utf8")).toBe(input.current) + expect(statSync(link).ino).toBe(statSync(stage(input.current)).ino) + + // The next launch removes the replaced link once nothing runs it. + await run(stage(input.current), bin) + expect(readdirSync(bin)).toEqual(["opencode"]) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/desktop/src/main/service/cli-path.ts b/packages/desktop/src/main/service/cli-path.ts new file mode 100644 index 00000000000..29e3a041e77 --- /dev/null +++ b/packages/desktop/src/main/service/cli-path.ts @@ -0,0 +1,70 @@ +import { execFile } from "node:child_process" +import { stat } from "node:fs/promises" +import { promisify } from "node:util" +import { Effect, FileSystem, Path } from "effect" + +const execFileAsync = promisify(execFile) + +// Each version stages its CLI in its own directory, so the user PATH holds one fixed directory with a +// link to the current stage instead. PATH is edited only when that directory is first created: a user +// who removes the entry keeps it removed, and the uninstaller deletes both to start over on reinstall. +export const exposeCli = Effect.fn("DesktopCli.expose")(function* (binary: string, directory: string) { + const fs = yield* FileSystem.FileSystem + + if (!(yield* fs.exists(directory))) yield* addToUserPath(directory) + const target = yield* linkCli(binary, directory) + yield* Effect.logInfo("v2 CLI linked on PATH", { path: target }) +}) + +export const linkCli = Effect.fn("DesktopCli.link")(function* (binary: string, directory: string) { + const fs = yield* FileSystem.FileSystem + const path = yield* Path.Path + const target = path.join(directory, path.basename(binary)) + yield* fs.makeDirectory(directory, { recursive: true }) + + // Windows refuses to delete an image that a terminal still runs, so a replaced link waits here until + // a later launch can remove it. + const names = yield* fs.readDirectory(directory) + yield* Effect.forEach( + names.filter((name) => name.endsWith(".old")), + (name) => fs.remove(path.join(directory, name)).pipe(Effect.ignore), + ) + + // NTFS file IDs exceed 2^53, so only the bigint form tells two files apart reliably. + const current = yield* Effect.promise(() => stat(target, { bigint: true }).catch(() => undefined)) + const source = yield* Effect.tryPromise(() => stat(binary, { bigint: true })) + + if (current?.ino === source.ino && current.dev === source.dev) return target + const temp = `${target}.${process.pid}.tmp` + yield* fs.remove(temp, { force: true }) + yield* fs.link(binary, temp).pipe(Effect.catch(() => fs.copyFile(binary, temp))) + + // Renaming a running image is allowed, so a terminal that still runs the old link does not block the update. + if (current) yield* fs.rename(target, `${target}.${process.pid}-${Date.now()}.old`) + yield* fs.rename(temp, target) + + return target +}) + +// Reads the raw value so entries such as %USERPROFILE%\bin stay unexpanded; .NET would write Path back as +// REG_SZ. Clearing an unused variable through .NET broadcasts WM_SETTINGCHANGE, so Explorer and the +// terminals it starts see the entry without signing out. +const addToUserPath = Effect.fn("DesktopCli.addToUserPath")(function* (directory: string) { + yield* Effect.tryPromise(() => + execFileAsync( + `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, + ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", addToUserPathScript], + { env: { ...process.env, OPENCODE_CLI_DIRECTORY: directory }, windowsHide: true }, + ), + ) + yield* Effect.logInfo("v2 CLI directory added to user PATH", { directory }) +}) + +const addToUserPathScript = ` +$directory = $env:OPENCODE_CLI_DIRECTORY +$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment') +$entries = @(([string]$key.GetValue('Path', '', 'DoNotExpandEnvironmentNames')) -split ';' | Where-Object { $_ }) +if ($entries -contains $directory) { exit 0 } +$key.SetValue('Path', (($entries + $directory) -join ';'), 'ExpandString') +[Environment]::SetEnvironmentVariable('OPENCODE_PATH_REFRESH', $null, 'User') +` diff --git a/packages/desktop/src/main/service/cli-stages.test.ts b/packages/desktop/src/main/service/cli-stages.test.ts index 06c63e082fd..f6716317f66 100644 --- a/packages/desktop/src/main/service/cli-stages.test.ts +++ b/packages/desktop/src/main/service/cli-stages.test.ts @@ -14,23 +14,23 @@ describe("cleanStages", () => { { name: "prerelease", staged: ["2.0.20", "2.1.0-beta.1", "local"], current: "2.1.0-beta.1" }, { name: "only current", staged: ["2.0.20"], current: "2.0.20" }, ])("keeps only the current staged CLI after $name", async (input) => { - const root = mkdtempSync(path.join(tmpdir(), "opencode-cli-stages-")) + const root = mkdtempSync(path.join(tmpdir(), "opencode-stages-")) try { input.staged.forEach((version) => { mkdirSync(path.join(root, version)) - writeFileSync(path.join(root, version, "opencode-cli"), version) + writeFileSync(path.join(root, version, "opencode"), version) }) writeFileSync(path.join(root, "unrelated"), "") await Effect.runPromise( - cleanStages(path.join(root, input.current, "opencode-cli")).pipe( + cleanStages(path.join(root, input.current, "opencode")).pipe( Effect.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)), ), ) expect(readdirSync(root).sort()).toEqual([input.current, "unrelated"]) - expect(readdirSync(path.join(root, input.current))).toEqual(["opencode-cli"]) + expect(readdirSync(path.join(root, input.current))).toEqual(["opencode"]) } finally { rmSync(root, { recursive: true, force: true }) } diff --git a/packages/desktop/src/main/service/desktop-cli.ts b/packages/desktop/src/main/service/desktop-cli.ts index d7397e90b5b..73fb99c6f0b 100644 --- a/packages/desktop/src/main/service/desktop-cli.ts +++ b/packages/desktop/src/main/service/desktop-cli.ts @@ -101,7 +101,7 @@ const bundledVersion = Effect.fn("DesktopCli.bundledVersion")(function* (bundled // async read waits behind everything else the main thread is doing at that moment. const shipped = yield* Effect.sync(() => { try { - return readFileSync(path.join(path.dirname(bundled), "opencode-cli.version"), "utf8").trim() + return readFileSync(path.join(path.dirname(bundled), "opencode.version"), "utf8").trim() } catch { return "" } @@ -209,9 +209,9 @@ const runInstaller = Effect.fn("DesktopCli.installForUser")(function* (binary: s }) function executableName() { - return process.platform === "win32" ? "opencode-cli.exe" : "opencode-cli" + return process.platform === "win32" ? "opencode.exe" : "opencode" } function developmentExecutableName() { - return process.platform === "win32" ? "opencode-cli-dev.exe" : "opencode-cli-dev" + return process.platform === "win32" ? "opencode-dev.exe" : "opencode-dev" } diff --git a/packages/desktop/src/main/service/sidecar-probe.ts b/packages/desktop/src/main/service/sidecar-probe.ts index 66b608d5c9e..a82999362dc 100644 --- a/packages/desktop/src/main/service/sidecar-probe.ts +++ b/packages/desktop/src/main/service/sidecar-probe.ts @@ -26,7 +26,7 @@ export function sidecarProbe() { function bundledVersion() { try { - return readFileSync(path.join(process.resourcesPath, "opencode-cli.version"), "utf8").trim() + return readFileSync(path.join(process.resourcesPath, "opencode.version"), "utf8").trim() } catch { return "" }