From 854b3bb9d7d889f9c6e8c4627405b84d45bbc631 Mon Sep 17 00:00:00 2001 From: Max Weinbach Date: Mon, 12 Oct 2026 01:27:39 -0400 Subject: [PATCH] fix(desktop): bundle arm64 binaries for windows arm (#54689) Co-authored-by: Luke Parker <10430890+Hona@users.noreply.github.com> --- .github/workflows/publish.yml | 3 + bun.lock | 4 +- packages/core/package.json | 2 +- .../desktop/electron-builder.config.test.ts | 51 ++-- packages/desktop/electron-builder.config.ts | 225 ++++++++++-------- packages/desktop/electron.vite.config.test.ts | 108 +++++---- packages/desktop/electron.vite.config.ts | 168 ++++++------- packages/desktop/scripts/utils.ts | 26 +- 8 files changed, 338 insertions(+), 249 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 92691055656..eb6e1c3b2b3 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -369,6 +369,7 @@ jobs: - host: "windows-2025" target: aarch64-pc-windows-msvc platform_flag: --win --arm64 + bun_install_flags: --cpu=* - host: "blacksmith-4vcpu-windows-2025" target: x86_64-pc-windows-msvc platform_flag: --win @@ -471,6 +472,7 @@ jobs: timeout-minutes: 60 env: OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }} + OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} GH_TOKEN: ${{ steps.committer.outputs.token }} CSC_KEYCHAIN: build.keychain APPLE_API_KEY: ${{ runner.temp }}/apple-api-key.p8 @@ -484,6 +486,7 @@ jobs: timeout-minutes: 60 env: OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }} + OPENCODE_CLI_TARGET: ${{ matrix.settings.target }} - name: Create macOS .app.tar.gz if: runner.os == 'macOS' && needs.version.outputs.release diff --git a/bun.lock b/bun.lock index 3824e25487c..4e689630519 100644 --- a/bun.lock +++ b/bun.lock @@ -365,7 +365,7 @@ "@parcel/watcher": "2.5.1", "@silvia-odwyer/photon-node": "0.3.4", "@standard-schema/spec": "catalog:", - "bun-pty": "0.4.9", + "bun-pty": "0.4.11", "diff": "catalog:", "drizzle-orm": "catalog:", "effect": "catalog:", @@ -3528,7 +3528,7 @@ "bun-ffi-structs": ["bun-ffi-structs@0.3.1", "", { "peerDependencies": { "typescript": "^5" } }, "sha512-3gM7PpVWLyrwxWjcilSiGuhWanhZivvo6l0u573NziPH6f/gwk6McbaYgn7oJWov6pKGRTDbrg94W5DcJsKTtQ=="], - "bun-pty": ["bun-pty@0.4.9", "", {}, "sha512-IUF/B3FANo8vIQ775Zt7Er7lphMpYMhLkes45am2WE8FaVI7KRYtj1rQwliZ18b6GpNzBNWcl7sz9QT5wDFBeQ=="], + "bun-pty": ["bun-pty@0.4.11", "", {}, "sha512-DpBfXCoWbcDziqL4gT3sFw/O6vfe2Gm1LmsnjfGjpqNhmsPjBcVorTrRv7OVATsy88PiXfn486vp0w4x3/Q84g=="], "bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="], diff --git a/packages/core/package.json b/packages/core/package.json index a74bf1add6d..f59afaa0013 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -116,7 +116,7 @@ "@parcel/watcher": "2.5.1", "@silvia-odwyer/photon-node": "0.3.4", "@standard-schema/spec": "catalog:", - "bun-pty": "0.4.9", + "bun-pty": "0.4.11", "diff": "catalog:", "drizzle-orm": "catalog:", "effect": "catalog:", diff --git a/packages/desktop/electron-builder.config.test.ts b/packages/desktop/electron-builder.config.test.ts index 4a39ac2918f..f9e62d80333 100644 --- a/packages/desktop/electron-builder.config.test.ts +++ b/packages/desktop/electron-builder.config.test.ts @@ -6,6 +6,8 @@ import os from "node:os" import path from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" import type { Configuration } from "electron-builder" +import { getConfig } from "./electron-builder.config" +import { CLI_BINARIES, nodePtyPackage } from "./scripts/utils" // Use electron-builder's matcher so the tests also cover its glob and directory traversal semantics. const { FileMatcher } = createRequire(import.meta.resolve("electron-builder"))("app-builder-lib/out/fileMatcher") @@ -16,30 +18,37 @@ const channels = [ { channel: "prod", appId: "ai.opencode.desktop" }, ] as const -async function load(channel: string) { +function load(channel: string, target?: string): Configuration { const previous = process.env.OPENCODE_CHANNEL + const previousTarget = process.env.OPENCODE_CLI_TARGET process.env.OPENCODE_CHANNEL = channel + if (target !== undefined) process.env.OPENCODE_CLI_TARGET = target + else delete process.env.OPENCODE_CLI_TARGET + try { - return (await import(`./electron-builder.config.ts?${channel}`)).default as Configuration + return getConfig() } finally { delete process.env.OPENCODE_CHANNEL + delete process.env.OPENCODE_CLI_TARGET if (previous !== undefined) process.env.OPENCODE_CHANNEL = previous + + if (previousTarget !== undefined) process.env.OPENCODE_CLI_TARGET = previousTarget } } function trimFilter(dir: string, config: Configuration) { + const patterns = Array.isArray(config.files) ? config.files.flatMap((value) => (value ? [String(value)] : [])) : [] + return new FileMatcher(dir, "", (value: string) => value, [ "**/*", - ...(Array.isArray(config.files) ? config.files : []).filter( - (value): value is string => typeof value === "string" && value.startsWith("!"), - ), + ...patterns.filter((value) => value.startsWith("!")), ]).createFilter() } -test.each(channels)("channel identity for $channel", async ({ channel, appId }) => { - const config = await load(channel) +test.each(channels)("channel identity for $channel", ({ channel, appId }) => { + const config = load(channel) expect(config.appId).toBe(appId) expect(config.extraMetadata?.desktopName).toBe(`${appId}.desktop`) expect(config.linux?.executableName).toBe(appId) @@ -62,7 +71,7 @@ test("legacy Linux launcher stays hidden", async () => { }) test("shared packaging defaults", async () => { - const config = await load("dev") + const config = load("dev") expect(config.mac?.sign).toBeFunction() expect(config.dmg?.sign).not.toBe(true) expect(config.mac?.extendInfo?.NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac).toBe(true) @@ -75,12 +84,13 @@ test("shared packaging defaults", async () => { ]) }) -test("trims external dependencies without excluding runtime files", async () => { - const filter = trimFilter(import.meta.dirname, await load("dev")) +test("trims external dependencies without excluding runtime files", () => { + const fileStats = statSync(import.meta.filename) + const dirStats = statSync(import.meta.dirname) + const filter = trimFilter(import.meta.dirname, load("dev")) for (const prefix of ["node_modules/", "node_modules/parent/node_modules/"]) { - const included = (file: string, stats = statSync(import.meta.filename)) => - filter(path.join(import.meta.dirname, prefix, file), stats) + const included = (file: string, stats = fileStats) => filter(path.join(import.meta.dirname, prefix, file), stats) // One file for each excluded pattern, including each brace alternative. for (const file of [ @@ -125,13 +135,24 @@ test("trims external dependencies without excluding runtime files", async () => expect(included(file)).toBe(true) } - expect(included("@zip.js/zip.js/dist", statSync(import.meta.dirname))).toBe(false) - expect(included("@zip.js/zip.js/lib", statSync(import.meta.dirname))).toBe(true) + expect(included("@zip.js/zip.js/dist", dirStats)).toBe(false) + expect(included("@zip.js/zip.js/lib", dirStats)).toBe(true) + } + + for (const item of CLI_BINARIES) { + const targetFilter = trimFilter(import.meta.dirname, load("prod", item.target)) + const active = nodePtyPackage(item.target) + + for (const candidate of CLI_BINARIES) { + const pkg = nodePtyPackage(candidate.target) + const included = targetFilter(path.join(import.meta.dirname, "node_modules", pkg, "lib/index.js"), fileStats) + expect(included).toBe(pkg === active) + } } }) test("the trimmed Zip.js package can still export compressed logs", async () => { - const config = (await import("./electron-builder.config.ts")).default + const config = load("dev") const dir = await mkdtemp(path.join(os.tmpdir(), "opencode-zip-package-")) const source = path.dirname(fileURLToPath(import.meta.resolve("@zip.js/zip.js/package.json"))) const filter = trimFilter(dir, config) diff --git a/packages/desktop/electron-builder.config.ts b/packages/desktop/electron-builder.config.ts index d46134ac49c..9e5f17ade1f 100644 --- a/packages/desktop/electron-builder.config.ts +++ b/packages/desktop/electron-builder.config.ts @@ -6,6 +6,7 @@ import { promisify } from "node:util" import type { CustomMacSignOptions } from "app-builder-lib" import type { Configuration } from "electron-builder" +import { CLI_BINARIES, getCurrentCli, nodePtyPackage } from "./scripts/utils" const execFileAsync = promisify(execFile) @@ -51,7 +52,7 @@ function macSignOptions(options: CustomMacSignOptions): CustomMacSignOptions { } } -const channel = (() => { +function resolveChannel() { const raw = process.env.OPENCODE_CHANNEL if (raw === "dev" || raw === "beta" || raw === "prod") return raw @@ -59,7 +60,7 @@ const channel = (() => { if (raw === "latest") return "prod" return "dev" -})() +} const APP_IDS = { dev: "ai.opencode.desktop.dev", @@ -67,111 +68,131 @@ const APP_IDS = { prod: "ai.opencode.desktop", } as const -const getBase = (appId: string): Configuration => ({ - artifactName: "opencode-desktop-${os}-${arch}.${ext}", - directories: { - output: "dist", - buildResources: "resources", - }, - // Linux launchers are .desktop files, so this is the desktop file name, - // not just the app id. For prod, app id "ai.opencode.desktop" becomes - // "ai.opencode.desktop.desktop". - // https://developer.gnome.org/documentation/guidelines/maintainer/integrating.html - // https://www.electron.build/docs/linux/ - extraMetadata: { - desktopName: `${appId}.desktop`, - }, - files: [ - "out/**/*", - "resources/**/*", - "!resources/opencode-cli*", - // Log export imports Zip.js as ESM. Keep index.js and lib, including its inline worker. - "!**/node_modules/@zip.js/zip.js/dist{,/**/*}", - "!**/node_modules/@zip.js/zip.js/{index.cjs,index.min.js,index-fflate.js,deno.json,eslint.config.mjs}", - // Nothing executes type declarations or source maps, and every entry costs startup time: the - // main process parses the whole asar header before it runs any JavaScript. - "!**/node_modules/**/*.d.{ts,cts,mts}", - "!**/node_modules/**/*.d.{ts,cts,mts}.map", - "!**/node_modules/**/*.{js,cjs,mjs}.map", - // These packages execute compiled JavaScript, not their sources. - "!**/node_modules/ajv/lib{,/**/*}", - "!**/node_modules/ajv-formats/src{,/**/*}", - // Keep js-yaml's CommonJS sources and dist/js-yaml.mjs ESM entry, not browser bundles or its CLI. - "!**/node_modules/js-yaml/dist/{js-yaml.js,js-yaml.min.js,*.map}", - "!**/node_modules/js-yaml/bin{,/**/*}", - ], - extraResources: [ - { - from: "resources/", - to: "", - filter: ["opencode-cli", "opencode-cli.exe", "opencode-cli.version"], - }, - ], - afterPack: async (context) => { - const cli = path.join( - context.packager.getResourcesDir(context.appOutDir), - context.electronPlatformName === "win32" ? "opencode-cli.exe" : "opencode-cli", - ) +const getBase = (appId: string): Configuration => { + const target = getCurrentCli() - const file = await stat(cli) - - if (!file.isFile() || file.size === 0) throw new Error(`Bundled CLI must be a non-empty file: ${cli}`) - const version = path.join(path.dirname(cli), "opencode-cli.version") - - if ((await stat(version)).size === 0) throw new Error(`Bundled CLI version must be a non-empty file: ${version}`) - }, - mac: { - category: "public.app-category.developer-tools", - icon: `resources/icons/icon.icns`, - extendInfo: { - NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac: true, + return { + artifactName: "opencode-desktop-${os}-${arch}.${ext}", + directories: { + output: "dist", + buildResources: "resources", }, - hardenedRuntime: true, - gatekeeperAssess: false, - entitlements: "resources/entitlements.plist", - entitlementsInherit: "resources/entitlements.plist", - sign: async (options) => { - const { sign } = await import("app-builder-lib/out/codeSign/macCodeSign") - await sign(macSignOptions(options)) + // Linux launchers are .desktop files, so this is the desktop file name, + // not just the app id. For prod, app id "ai.opencode.desktop" becomes + // "ai.opencode.desktop.desktop". + // https://developer.gnome.org/documentation/guidelines/maintainer/integrating.html + // https://www.electron.build/docs/linux/ + extraMetadata: { + desktopName: `${appId}.desktop`, }, - notarize: true, - target: ["dmg", "zip"], - }, - protocols: { - name: "OpenCode", - schemes: ["opencode"], - }, - win: { - icon: `resources/icons/icon.ico`, - signtoolOptions: { - sign: signWindows, - }, - target: ["nsis"], - verifyUpdateCodeSignature: false, - }, - nsis: { - include: path.join(packageDir, "resources", "windows", "installer.nsh"), - oneClick: true, - perMachine: false, - installerIcon: `resources/icons/icon.ico`, - installerHeaderIcon: `resources/icons/icon.ico`, - }, - linux: { - icon: `resources/icons`, - category: "Development", - executableName: appId, - desktop: { - entry: { - // Match the installed .desktop file and hicolor icon basename so - // Linux shells can associate the running Electron window with its launcher. - StartupWMClass: appId, + files: [ + "out/**/*", + "resources/**/*", + "!resources/opencode-cli*", + // 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}{,/**/*}`, + ), + // Log export imports Zip.js as ESM. Keep index.js and lib, including its inline worker. + "!**/node_modules/@zip.js/zip.js/dist{,/**/*}", + "!**/node_modules/@zip.js/zip.js/{index.cjs,index.min.js,index-fflate.js,deno.json,eslint.config.mjs}", + // Nothing executes type declarations or source maps, and every entry costs startup time: the + // main process parses the whole asar header before it runs any JavaScript. + "!**/node_modules/**/*.d.{ts,cts,mts}", + "!**/node_modules/**/*.d.{ts,cts,mts}.map", + "!**/node_modules/**/*.{js,cjs,mjs}.map", + // These packages execute compiled JavaScript, not their sources. + "!**/node_modules/ajv/lib{,/**/*}", + "!**/node_modules/ajv-formats/src{,/**/*}", + // Keep js-yaml's CommonJS sources and dist/js-yaml.mjs ESM entry, not browser bundles or its CLI. + "!**/node_modules/js-yaml/dist/{js-yaml.js,js-yaml.min.js,*.map}", + "!**/node_modules/js-yaml/bin{,/**/*}", + ], + extraResources: [ + { + from: "resources/", + to: "", + filter: ["opencode-cli", "opencode-cli.exe", "opencode-cli.version"], }, - }, - target: ["AppImage", "deb", "rpm"], - }, -}) + ], + afterPack: async (context) => { + const resources = context.packager.getResourcesDir(context.appOutDir) + const cli = path.join(resources, context.electronPlatformName === "win32" ? "opencode-cli.exe" : "opencode-cli") -function getConfig() { + const file = await stat(cli) + + if (!file.isFile() || file.size === 0) throw new Error(`Bundled CLI must be a non-empty file: ${cli}`) + const version = path.join(path.dirname(cli), "opencode-cli.version") + + if ((await stat(version)).size === 0) throw new Error(`Bundled CLI version must be a non-empty file: ${version}`) + + if (context.electronPlatformName !== "win32") return + + const addon = path.join( + resources, + "app.asar.unpacked/node_modules", + nodePtyPackage(target.target), + "prebuilds", + `${target.os}-${target.cpu}`, + "conpty.node", + ) + + if ((await stat(addon)).size === 0) throw new Error(`Bundled node-pty must be a non-empty file: ${addon}`) + }, + mac: { + category: "public.app-category.developer-tools", + icon: `resources/icons/icon.icns`, + extendInfo: { + NSAutoFillRequiresTextContentTypeForOneTimeCodeOnMac: true, + }, + hardenedRuntime: true, + gatekeeperAssess: false, + entitlements: "resources/entitlements.plist", + entitlementsInherit: "resources/entitlements.plist", + sign: async (options) => { + const { sign } = await import("app-builder-lib/out/codeSign/macCodeSign") + await sign(macSignOptions(options)) + }, + notarize: true, + target: ["dmg", "zip"], + }, + protocols: { + name: "OpenCode", + schemes: ["opencode"], + }, + win: { + icon: `resources/icons/icon.ico`, + signtoolOptions: { + sign: signWindows, + }, + target: ["nsis"], + verifyUpdateCodeSignature: false, + }, + nsis: { + include: path.join(packageDir, "resources", "windows", "installer.nsh"), + oneClick: true, + perMachine: false, + installerIcon: `resources/icons/icon.ico`, + installerHeaderIcon: `resources/icons/icon.ico`, + }, + linux: { + icon: `resources/icons`, + category: "Development", + executableName: appId, + desktop: { + entry: { + // Match the installed .desktop file and hicolor icon basename so + // Linux shells can associate the running Electron window with its launcher. + StartupWMClass: appId, + }, + }, + target: ["AppImage", "deb", "rpm"], + }, + } +} + +export function getConfig() { + const channel = resolveChannel() const appId = APP_IDS[channel] const base = getBase(appId) diff --git a/packages/desktop/electron.vite.config.test.ts b/packages/desktop/electron.vite.config.test.ts index a6f4c6a89f5..bde20523324 100644 --- a/packages/desktop/electron.vite.config.test.ts +++ b/packages/desktop/electron.vite.config.test.ts @@ -1,21 +1,22 @@ import { expect, test } from "bun:test" import { existsSync } from "node:fs" import path from "node:path" -import { loadConfigFromFile, MainConfigFactory } from "electron-vite" +import { MainConfigFactory } from "electron-vite" import { build } from "vite" +import createConfig from "./electron.vite.config" import pkg from "./package.json" +import { CLI_BINARIES, nodePtyPackage } from "./scripts/utils" -const load = (command: "build" | "serve") => - loadConfigFromFile( - { command, mode: command === "build" ? "production" : "development" }, - `${import.meta.dirname}/electron.vite.config.ts`, - ) +const load = async (command: "build" | "serve") => ({ + config: await createConfig({ command, mode: command === "build" ? "production" : "development" }), +}) // Bundled into the main process, so the manifest must not also ship them as external packages. const bundled = ["effect", "@effect/platform-node", "@effect/platform-node-shared", "drizzle-orm"] test("minifies only builds, previews onboarding only in development, and ships sourcemaps and public assets", async () => { const previous = process.env.OPENCODE_TEST_ONBOARDING + const previousTarget = process.env.OPENCODE_CLI_TARGET try { process.env.OPENCODE_TEST_ONBOARDING = "1" @@ -33,10 +34,22 @@ test("minifies only builds, previews onboarding only in development, and ships s delete process.env.OPENCODE_TEST_ONBOARDING const serve = await load("serve") expect(serve.config.renderer?.define?.["import.meta.env.OPENCODE_TEST_ONBOARDING"]).toBe("false") + + for (const item of CLI_BINARIES) { + process.env.OPENCODE_CLI_TARGET = item.target + const main = (await load("build")).config.main + expect(main?.build?.externalizeDeps).toEqual({ + exclude: bundled, + include: [nodePtyPackage(item.target)], + }) + } } finally { delete process.env.OPENCODE_TEST_ONBOARDING + delete process.env.OPENCODE_CLI_TARGET if (previous !== undefined) process.env.OPENCODE_TEST_ONBOARDING = previous + + if (previousTarget !== undefined) process.env.OPENCODE_CLI_TARGET = previousTarget } const renderer = (await load("build")).config.renderer @@ -44,10 +57,9 @@ test("minifies only builds, previews onboarding only in development, and ships s expect(renderer?.build?.sourcemap).toBe(true) // Vite resolves publicDir from the renderer root, not from the config file. - if (!renderer?.root || typeof renderer.publicDir !== "string") throw new Error("Missing renderer root or publicDir") - expect(existsSync(path.resolve(import.meta.dirname, renderer.root, renderer.publicDir, "oc-theme-preload.js"))).toBe( - true, - ) + const root = renderer?.root ?? "" + const publicDir = renderer?.publicDir || "" + expect(existsSync(path.resolve(import.meta.dirname, root, publicDir, "oc-theme-preload.js"))).toBe(true) }) test("bundles one Effect runtime and Drizzle while keeping native dependencies external", async () => { @@ -64,42 +76,56 @@ test("bundles one Effect runtime and Drizzle while keeping native dependencies e "@lydell/node-pty-win32-arm64", "@lydell/node-pty-win32-x64", ]) - const result = await load("build") - if (!result.config.main) throw new Error("Missing main-process build configuration") + const previousTarget = process.env.OPENCODE_CLI_TARGET + // Build against the opposite architecture to prove cross-packaging resolves the target's native package, not the host's. + const crossTarget = process.arch === "arm64" ? "x86_64-pc-windows-msvc" : "aarch64-pc-windows-msvc" + const crossNodePty = nodePtyPackage(crossTarget) - const config = await new MainConfigFactory( - result.config.main, - { configFile: false, mode: "production" }, - { root: import.meta.dirname }, - ).build() + try { + process.env.OPENCODE_CLI_TARGET = crossTarget + const result = await load("build") - config.build = { ...config.build, write: false } - config.logLevel = "silent" - const output = await build(config) + if (!result.config.main) throw new Error("Missing main-process build configuration") - const chunks = (Array.isArray(output) ? output : [output]).flatMap((result) => - "output" in result ? result.output.filter((item) => item.type === "chunk") : [], - ) + const config = await new MainConfigFactory( + result.config.main, + { configFile: false, mode: "production" }, + { root: import.meta.dirname }, + ).build() - expect(chunks.length).toBeGreaterThan(0) - // Resource resolution must not depend on which lazy entry owns DesktopPaths. - expect(chunks.every((chunk) => !chunk.fileName.includes("/"))).toBe(true) - const imports = chunks.flatMap((chunk) => [...chunk.imports, ...chunk.dynamicImports]) - const modules = chunks.flatMap((chunk) => Object.keys(chunk.modules)) + config.build = { ...config.build, minify: false, write: false } + config.logLevel = "silent" + const output = await build(config) - for (const name of bundled) { - expect(imports.filter((id) => id === name || id.startsWith(`${name}/`))).toEqual([]) - expect(modules.some((id) => id.includes(`/node_modules/${name}/`))).toBe(true) + const chunks = (Array.isArray(output) ? output : [output]).flatMap((item) => + "output" in item ? item.output.filter((entry) => entry.type === "chunk") : [], + ) + + expect(chunks.length).toBeGreaterThan(0) + // Resource resolution must not depend on which lazy entry owns DesktopPaths. + expect(chunks.every((chunk) => !chunk.fileName.includes("/"))).toBe(true) + const imports = chunks.flatMap((chunk) => [...chunk.imports, ...chunk.dynamicImports]) + const modules = chunks.flatMap((chunk) => Object.keys(chunk.modules)) + + for (const name of bundled) { + expect(imports.filter((id) => id === name || id.startsWith(`${name}/`))).toEqual([]) + expect(modules.some((id) => id.includes(`/node_modules/${name}/`))).toBe(true) + } + + const effect = modules.filter((id) => id.includes("/node_modules/effect/")) + expect(new Set(effect.map((id) => id.split("/node_modules/effect/")[0])).size).toBe(1) + expect(new Set(effect).size).toBe(effect.length) + expect(imports).toContain("electron") + expect(imports).toContain("node:sqlite") + expect(chunks.some((chunk) => chunk.dynamicImports.includes("@zip.js/zip.js"))).toBe(true) + expect(imports).toContain(crossNodePty) + expect(imports).not.toContain(`@lydell/node-pty-${process.platform}-${process.arch}`) + expect(modules.some((id) => id.includes("/node_modules/msgpackr"))).toBe(false) + expect(chunks.some((chunk) => chunk.code.includes("msgpackr"))).toBe(false) + } finally { + delete process.env.OPENCODE_CLI_TARGET + + if (previousTarget !== undefined) process.env.OPENCODE_CLI_TARGET = previousTarget } - - const effect = modules.filter((id) => id.includes("/node_modules/effect/")) - expect(new Set(effect.map((id) => id.split("/node_modules/effect/")[0])).size).toBe(1) - expect(new Set(effect).size).toBe(effect.length) - expect(imports).toContain("electron") - expect(imports).toContain("node:sqlite") - expect(chunks.some((chunk) => chunk.dynamicImports.includes("@zip.js/zip.js"))).toBe(true) - expect(imports).toContain(`@lydell/node-pty-${process.platform}-${process.arch}`) - expect(modules.some((id) => id.includes("/node_modules/msgpackr"))).toBe(false) - expect(chunks.some((chunk) => chunk.code.includes("msgpackr"))).toBe(false) }, 30_000) diff --git a/packages/desktop/electron.vite.config.ts b/packages/desktop/electron.vite.config.ts index e1ea24c36ac..d2384112838 100644 --- a/packages/desktop/electron.vite.config.ts +++ b/packages/desktop/electron.vite.config.ts @@ -1,18 +1,17 @@ import { defineConfig } from "electron-vite" import type { Plugin } from "vite" import { pickerPlugin } from "./scripts/picker" +import { nodePtyPackage } from "./scripts/utils" -const channel = (() => { +function resolveChannel() { const raw = process.env.OPENCODE_CHANNEL if (raw === "local" || raw === "dev" || raw === "beta" || raw === "prod") return raw - if (process.env.OPENCODE_CHANNEL === "latest") return "prod" + if (raw === "latest") return "prod" return "dev" -})() - -const nodePtyPkg = `@lydell/node-pty-${process.platform}-${process.arch}` +} const appPlugin = (await import("@opencode/app/vite")).default @@ -51,95 +50,100 @@ const initialChunk: Plugin = { }, } -export default defineConfig(({ command }) => ({ - main: { - resolve: { - dedupe: ["effect"], - }, - define: { - // Local renderer/server mode still uses the dev application identity and updater policy. - "import.meta.env.OPENCODE_CHANNEL": JSON.stringify(channel === "local" ? "dev" : channel), - }, - build: { - minify: command === "build", - rolldownOptions: { - input: { index: "src/main/index.ts" }, - // Keep this identical to electron-vite's Node 20.11+ shim. Its regex insertion can - // corrupt bundled TypeScript, while an output banner places the shim safely. - output: { - format: "es", - // DesktopPaths resolves resources from the main output directory, - // including when the lazy desktop entry shares it with other chunks. - chunkFileNames: "[name]-[hash].js", - banner: ` +export default defineConfig(({ command }) => { + const channel = resolveChannel() + const nodePtyPkg = nodePtyPackage() + + return { + main: { + resolve: { + dedupe: ["effect"], + }, + define: { + // Local renderer/server mode still uses the dev application identity and updater policy. + "import.meta.env.OPENCODE_CHANNEL": JSON.stringify(channel === "local" ? "dev" : channel), + }, + build: { + minify: command === "build", + rolldownOptions: { + input: { index: "src/main/index.ts" }, + // Keep this identical to electron-vite's Node 20.11+ shim. Its regex insertion can + // corrupt bundled TypeScript, while an output banner places the shim safely. + output: { + format: "es", + // DesktopPaths resolves resources from the main output directory, + // including when the lazy desktop entry shares it with other chunks. + chunkFileNames: "[name]-[hash].js", + banner: ` // -- CommonJS Shims -- import __cjs_mod__ from 'node:module'; const __filename = import.meta.filename; const __dirname = import.meta.dirname; const require = __cjs_mod__.createRequire(import.meta.url); `, + }, + }, + externalizeDeps: { + // Bundle the Effect family together. + exclude: ["effect", "@effect/platform-node", "@effect/platform-node-shared", "drizzle-orm"], + include: [nodePtyPkg], }, }, - externalizeDeps: { - // Bundle the Effect family together. - exclude: ["effect", "@effect/platform-node", "@effect/platform-node-shared", "drizzle-orm"], - include: [nodePtyPkg], - }, - }, - plugins: [ - { - name: "opencode:node-pty-narrower", - enforce: "pre", - resolveId(s) { - if (s === "@lydell/node-pty") return nodePtyPkg + plugins: [ + { + name: "opencode:node-pty-narrower", + enforce: "pre", + resolveId(s) { + if (s === "@lydell/node-pty") return nodePtyPkg - return undefined + return undefined + }, }, - }, - ], - }, - preload: { - build: { - minify: command === "build", - rolldownOptions: { - input: { index: "src/preload/index.ts" }, - output: { - format: "cjs", - // The package is "type": "module". Under --no-sandbox Electron loads the preload - // through Node's module loader, which treats a .js file as ESM and fails on - // require("electron"). The sandboxed path ignores the extension. - entryFileNames: "[name].cjs", - }, - }, + ], }, - }, - renderer: { - experimental: { - bundledDev: true, - }, - define: { - "import.meta.env.OPENCODE_VERSION": JSON.stringify(process.env.OPENCODE_VERSION), - "import.meta.env.VITE_OPENCODE_CHANNEL": JSON.stringify(channel), - "import.meta.env.OPENCODE_TEST_ONBOARDING": JSON.stringify( - command === "serve" && process.env.OPENCODE_TEST_ONBOARDING === "1", - ), - }, - plugins: [pickerPlugin(), appPlugin, initialChunk, sentry], - publicDir: "../../../app/public", - root: "src/renderer", - build: { - minify: command === "build", - sourcemap: true, - rolldownOptions: { - input: { - main: "src/renderer/index.html", - }, - output: { - codeSplitting: { - groups: [{ name: (id) => (initialGraph.has(id) ? "app" : null), priority: 10 }], + preload: { + build: { + minify: command === "build", + rolldownOptions: { + input: { index: "src/preload/index.ts" }, + output: { + format: "cjs", + // The package is "type": "module". Under --no-sandbox Electron loads the preload + // through Node's module loader, which treats a .js file as ESM and fails on + // require("electron"). The sandboxed path ignores the extension. + entryFileNames: "[name].cjs", }, }, }, }, - }, -})) + renderer: { + experimental: { + bundledDev: true, + }, + define: { + "import.meta.env.OPENCODE_VERSION": JSON.stringify(process.env.OPENCODE_VERSION), + "import.meta.env.VITE_OPENCODE_CHANNEL": JSON.stringify(channel), + "import.meta.env.OPENCODE_TEST_ONBOARDING": JSON.stringify( + command === "serve" && process.env.OPENCODE_TEST_ONBOARDING === "1", + ), + }, + plugins: [pickerPlugin(), appPlugin, initialChunk, sentry], + publicDir: "../../../app/public", + root: "src/renderer", + build: { + minify: command === "build", + sourcemap: true, + rolldownOptions: { + input: { + main: "src/renderer/index.html", + }, + output: { + codeSplitting: { + groups: [{ name: (id) => (initialGraph.has(id) ? "app" : null), priority: 10 }], + }, + }, + }, + }, + }, + } +}) diff --git a/packages/desktop/scripts/utils.ts b/packages/desktop/scripts/utils.ts index 3c119286676..fdde2a440cb 100644 --- a/packages/desktop/scripts/utils.ts +++ b/packages/desktop/scripts/utils.ts @@ -1,14 +1,16 @@ -import { $ } from "bun" import { chmod, copyFile, mkdtemp, rm } from "node:fs/promises" import { tmpdir } from "node:os" import { dirname, join } from "node:path" +import { Option, Schema } from "effect" const CLI_VERSION = "dev" +const Manifest = Schema.fromJsonString(Schema.Struct({ version: Schema.NonEmptyString })) + export type Channel = "dev" | "beta" | "prod" export function resolveChannel(): Channel { - const raw = Bun.env.OPENCODE_CHANNEL + const raw = process.env.OPENCODE_CHANNEL if (raw === "dev" || raw === "beta" || raw === "prod") return raw @@ -56,7 +58,7 @@ export const CLI_BINARIES: Array<{ target: string; package: string; os: string; }, ] -export const CLI_TARGET = Bun.env.OPENCODE_CLI_TARGET +export const CLI_TARGET = process.env.OPENCODE_CLI_TARGET function nativeTarget() { const { platform, arch } = process @@ -69,7 +71,7 @@ function nativeTarget() { throw new Error(`Unsupported platform: ${platform}/${arch}`) } -export function getCurrentCli(target = CLI_TARGET ?? nativeTarget()) { +export function getCurrentCli(target = process.env.OPENCODE_CLI_TARGET ?? nativeTarget()) { const binaryConfig = CLI_BINARIES.find((item) => item.target === target) if (!binaryConfig) throw new Error(`CLI configuration not available for target '${target}'`) @@ -77,7 +79,14 @@ export function getCurrentCli(target = CLI_TARGET ?? nativeTarget()) { return binaryConfig } +export function nodePtyPackage(target?: string) { + const cli = getCurrentCli(target) + + return `@lydell/node-pty-${cli.os}-${cli.cpu}` +} + export async function downloadCliToResources(version = CLI_VERSION, dest = windowsify("resources/opencode-cli")) { + const { $ } = await import("bun") const cli = getCurrentCli() const directory = await mkdtemp(join(tmpdir(), "opencode-cli-")) @@ -104,9 +113,12 @@ async function copyCliToResources(pkg: string, dest: string) { const cli = getCurrentCli() await copyFile(join(pkg, "bin", cli.os === "win32" ? "opencode.exe" : "opencode"), dest) await prepareCli(dest) - const manifest = (await Bun.file(join(pkg, "package.json")).json()) as { version?: string } - if (!manifest.version) throw new Error(`Bundled CLI package has no version: ${pkg}`) + const manifest = Option.getOrUndefined( + Schema.decodeUnknownOption(Manifest)(await Bun.file(join(pkg, "package.json")).text()), + ) + + if (!manifest) throw new Error(`Bundled CLI package has no version: ${pkg}`) await Bun.write(versionFile(dest), manifest.version) } @@ -115,6 +127,8 @@ export function versionFile(cli: string) { } async function prepareCli(dest: string) { + const { $ } = await import("bun") + if (process.platform !== "win32") await chmod(dest, 0o755) if (process.platform === "win32" && process.env.GITHUB_ACTIONS === "true") {