π OpenHands: AI-Driven Development
feat(desktop): universal macOS DMG with per-arch bundled runtimes (#17225)
Harsh Batheja431393cc047f
diff --git a/.github/workflows/desktop-linux.yml b/.github/workflows/desktop-linux.ymlindex d6aa26329c..c0470f5af2 100644--- a/.github/workflows/desktop-linux.yml+++ b/.github/workflows/desktop-linux.yml@@ -23,6 +23,7 @@ on:- .github/workflows/desktop-linux.yml- electron/**- electron-builder.config.mjs+ - scripts/download-arch-utils.mjs- scripts/download-uv.mjs- scripts/download-node.mjsrelease:diff --git a/.github/workflows/desktop-macos.yml b/.github/workflows/desktop-macos.ymlindex 55897c619e..54bc395c86 100644--- a/.github/workflows/desktop-macos.yml+++ b/.github/workflows/desktop-macos.yml@@ -1,17 +1,30 @@name: Desktop (macOS)-# Builds the Agent Canvas macOS DMG (Apple Silicon).-# pull_request: paths-filtered smoke build β the uploaded artifact is-# what a tester downloads to verify a PR on macOS.-# release published: rebuilds from the release tag and attaches the .dmg-# to the GitHub Release created by release-please.-# workflow_dispatch: manual escape hatch for any ref.+# Builds the Agent Canvas macOS DMG.+# pull_request: paths-filtered smoke build on BOTH native arches β+# arm64 on macos-latest (Apple Silicon) and Intel x64 on+# macos-15-intel (GitHub's last Intel macOS runner). Each+# leg runs npm run build:desktop natively, so the per-arch+# uv/node download + electron-builder path is exercised+# for the runner's CPU on every PR, and testers on either+# Mac architecture get a native artifact to download.+# release published: rebuilds from the release tag as a UNIVERSAL build+# (arm64 + x64, with per-arch bundled uv/node runtimes+# selected at runtime by process.arch) and attaches the+# .dmg to the GitHub Release created by release-please.+# Intel Macs are supported by the release DMG.+# workflow_dispatch: manual escape hatch for any ref β the native per-arch+# builds above AND the universal build, so the universal+# merge can be validated from a branch before a release+# (the first release build is the worst time to find a+# merger failure).# The app is only ad-hoc signed (no signing certs exist for any platform);# a downloaded DMG is quarantined by Gatekeeper, which reports the app as# "damaged" until the attribute is cleared:# xattr -d com.apple.quarantine "/Applications/OpenHands Agent Canvas.app"-# Intel DMGs are not produced β the bundled uv/node runtimes are host-arch-# only, so Intel users build from source.+#+# Intel-leg removal date: macos-15-intel is available until August 2027, after+# which GitHub drops x86_64 macOS support entirely and this leg must go.on:workflow_dispatch:pull_request:@@ -19,6 +32,7 @@ on:- .github/workflows/desktop-macos.yml- electron/**- electron-builder.config.mjs+ - scripts/download-arch-utils.mjs- scripts/download-uv.mjs- scripts/download-node.mjsrelease:@@ -34,10 +48,26 @@ permissions:contents: writejobs:+ # PR / manual smoke builds: one native DMG per CPU arch, in parallel.build-dmg:- name: Build macOS DMG- runs-on: macos-latest- timeout-minutes: 30+ name: Build macOS DMG (${{ matrix.arch }})+ if: github.event_name != 'release'+ runs-on: ${{ matrix.runner }}+ strategy:+ fail-fast: false+ matrix:+ include:+ - arch: arm64+ runner: macos-latest+ # Intel x64: the last Intel GitHub runner (macos-15-intel) is+ # available until August 2027; after that GitHub drops x86_64 macOS+ # support and this leg must be removed (see header comment).+ - arch: x64+ runner: macos-15-intel+ # Universal release builds download two Electron zips + two Node dists and+ # lipo-merge them; single-arch native builds are much faster. 40 min leaves+ # headroom for the slowest leg (Intel runners are slower than arm64).+ timeout-minutes: 40steps:- name: Check out repository@@ -52,19 +82,21 @@ jobs:- name: Install dependenciesrun: npm ci- - name: Build macOS DMG+ - name: Build macOS DMG (${{ matrix.arch }})env:- # Production analytics key only for release builds (same split as- # docker.yml); PR/manual runs get the staging key. Both are public- # client-side keys stored as repo vars β empty on fork PRs, which- # simply disables analytics in the built app.- VITE_POSTHOG_API_KEY: ${{ github.event_name == 'release' && vars.POSTHOG_PROD_KEY || vars.POSTHOG_STAGING_KEY }}+ # PR/manual runs get the staging key (same split as docker.yml).+ # Both are public client-side keys stored as repo vars β empty on+ # fork PRs, which simply disables analytics in the built app.+ VITE_POSTHOG_API_KEY: ${{ vars.POSTHOG_STAGING_KEY }}# Authenticates download-uv.mjs's GitHub API version lookup so it# doesn't hit the unauthenticated per-IP rate limit on shared runners.GITHUB_TOKEN: ${{ github.token }}+ # Native single-arch build: download-uv/node resolve to the runner's+ # CPU arch and electron-builder packages that arch (fast, and proves+ # the per-arch runtime download path for the runner's CPU).run: npm run build:desktop- - name: Verify DMG output+ - name: Verify DMG output (${{ matrix.arch }})run: |ls -la dist-electrondmg_count=$(find dist-electron -maxdepth 1 -name '*.dmg' | wc -l | tr -d ' ')@@ -72,18 +104,96 @@ jobs:echo "::error::Expected exactly one DMG in dist-electron/, found $dmg_count"exit 1fi+ dmg_path=$(find dist-electron -maxdepth 1 -name '*.dmg' | head -n 1)+ # electron-builder names the DMG OpenHands-Agent-Canvas-<ver>-<arch>.dmg.+ if ! echo "$dmg_path" | grep -q -- "-${{ matrix.arch }}.dmg$"; then+ echo "::error::Expected ${{ matrix.arch }} DMG, got: $dmg_path"+ exit 1+ fi+ # The filename suffix reflects electron-builder's target arch, but+ # assert the actual Mach-O arch of the packaged binary too β the+ # point of the Intel leg is catching an accidentally-arm64 artifact.+ app_dir=$(find dist-electron -maxdepth 2 -name '*.app' | head -n 1)+ if [ -n "$app_dir" ]; then+ binary=$(find "$app_dir/Contents/MacOS" -maxdepth 1 -type f | head -n 1)+ if [ -n "$binary" ]; then+ file "$binary"+ expected=$([ "${{ matrix.arch }}" = "arm64" ] && echo "arm64" || echo "x86_64")+ if ! file "$binary" | grep -q "$expected"; then+ echo "::error::Expected ${{ matrix.arch }} binary, got: $(file "$binary")"+ exit 1+ fi+ fi+ fi- - name: Upload DMG artifact+ - name: Upload DMG artifact (${{ matrix.arch }})uses: actions/upload-artifact@v7with:- name: agent-canvas-macos-dmg+ name: agent-canvas-macos-dmg-${{ matrix.arch }}path: dist-electron/*.dmgif-no-files-found: error# The DMG is large (~175 MB); keep PR artifacts long enough for# manual QA without hoarding storage.retention-days: 14+ # Universal builds: one merged (arm64+x64) DMG on an arm64 runner.+ build-universal-dmg:+ name: Build universal macOS DMG+ # Not on pull_request: the two-leg native matrix already proves the+ # per-arch download/packaging path cheaply, and a full universal merge+ # (two Electron zips + Node dists + lipo) is too heavy for every PR.+ # Keeping it off pull_request also lets a maintainer run the universal+ # build from a branch via workflow_dispatch, so the merger gets CI+ # evidence before the first release exercises it.+ if: github.event_name != 'pull_request'+ runs-on: macos-latest+ # Two Electron zips + two Node dists + lipo merge; 40 min leaves headroom+ # over the observed ~25 min.+ timeout-minutes: 40++ steps:+ - name: Check out repository+ uses: actions/checkout@v7++ - name: Set up Node.js with npm cache+ uses: actions/setup-node@v7+ with:+ node-version: '24'+ cache: npm++ - name: Install dependencies+ run: npm ci++ - name: Build universal macOS DMG+ env:+ # Production analytics key only for release builds (same split as+ # docker.yml); workflow_dispatch runs get the staging key. Both are+ # public client-side keys stored as repo vars.+ VITE_POSTHOG_API_KEY: ${{ github.event_name == 'release' && vars.POSTHOG_PROD_KEY || vars.POSTHOG_STAGING_KEY }}+ # Authenticates download-uv.mjs's GitHub API version lookup so it+ # doesn't hit the unauthenticated per-IP rate limit on shared runners.+ GITHUB_TOKEN: ${{ github.token }}+ # Universal build: downloads BOTH runtime arches into per-arch dirs+ # (resources/{bin,node}-{arm64,x64}/) and merges two Electron binaries.+ run: npm run build:desktop:universal++ - name: Verify DMG output+ run: |+ ls -la dist-electron+ dmg_count=$(find dist-electron -maxdepth 1 -name '*.dmg' | wc -l | tr -d ' ')+ if [ "$dmg_count" -ne 1 ]; then+ echo "::error::Expected exactly one DMG in dist-electron/, found $dmg_count"+ exit 1+ fi+ dmg_path=$(find dist-electron -maxdepth 1 -name '*.dmg' | head -n 1)+ if ! echo "$dmg_path" | grep -q -- "-universal.dmg$"; then+ echo "::error::Expected universal DMG, got: $dmg_path"+ exit 1+ fi+- name: Attach DMG to GitHub release+ # Only release events have a tag to attach to; workflow_dispatch+ # runs only build and verify the universal DMG.if: github.event_name == 'release'env:GH_TOKEN: ${{ github.token }}diff --git a/.github/workflows/desktop-windows.yml b/.github/workflows/desktop-windows.ymlindex adb905b555..bdbccd6c9f 100644--- a/.github/workflows/desktop-windows.yml+++ b/.github/workflows/desktop-windows.yml@@ -17,6 +17,7 @@ on:- .github/workflows/desktop-windows.yml- electron/**- electron-builder.config.mjs+ - scripts/download-arch-utils.mjs- scripts/download-uv.mjs- scripts/download-node.mjsrelease:diff --git a/.gitignore b/.gitignoreindex 40ca897911..c92d99baf6 100644--- a/.gitignore+++ b/.gitignore@@ -43,3 +43,6 @@ build-fresh//resources/bin/# Downloaded Node.js distribution (populated by `npm run download-node` before packaging)/resources/node/+# Per-arch runtime downloads for macOS universal builds (ELECTRON_ARCH=universal)+/resources/bin-*/+/resources/node-*/diff --git a/.pr/desktop-universal-boot.png b/.pr/desktop-universal-boot.pngnew file mode 100644index 0000000000..8133b40554Binary files /dev/null and b/.pr/desktop-universal-boot.png differdiff --git a/AGENTS.md b/AGENTS.mdindex f4ea1ac5ea..c4dee0a349 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -723,6 +723,8 @@ When adding code that needs a new string, decide up front which rule it falls un- Electron desktop packaging β `electron-builder.config.mjs` uses `directories.app: "electron"` so electron/package.json is the app manifest. Even though electron/package.json has zero `dependencies`, app-builder-lib's `collectNodeModulesWithLogging` walks UP from the app dir looking for the first npm workspace that resolves modules. The next dir in line is the project root, where `npm list --json` reports the full hoisted tree (~342 dirs, ~600 MB of Vite/React/Monaco/HeroUI), and electron-builder copies all of it into `Resources/app/node_modules/`. The walk is hardcoded in `app-builder-lib/out/util/appFileCopier.js::collectNodeModulesWithLogging` β there is no config knob to disable it. Creating an empty `electron/node_modules/` does NOT help because the collector falls through to project root when it sees zero deps. **The fix is the `afterPack` hook** (`stripBundledNodeModules` in `electron-builder.config.mjs`): after electron-builder copies everything, the hook `rm -rf`s `Resources/app/node_modules/` (handling macOS `.app` bundle layout and Linux/Windows flat resources/ layout), then copies back the dependency closure of `RUNTIME_PACKAGES` (`sirv` for static-server.mjs, `httpxy` for proxy-utils.mjs/ingress.mjs β ~200 KB total). Effect: `resources/app/` drops from ~598 MB to ~7 MB; total `linux-unpacked/` from ~1 GB to ~365 MB (the rest is Electron + Chromium + the bundled `uv` binary). If a spawned backend script gains a new bare npm import, add the package to `RUNTIME_PACKAGES` β otherwise that service crashes with `ERR_MODULE_NOT_FOUND` only in the installed app. **Testing trap:** an app launched from `dist-electron/` inside the repo resolves bare specifiers against the repo's own `node_modules` (Node ESM resolution walks up from the script file), so a missing runtime package is invisible there β verify packaged builds from a copy outside the repo tree (e.g. `/Applications`). Don't add real deps to electron/package.json β any real dep would survive the strip and would also have to be hand-installed inside electron/ since the project root is npm-hoisted. `build:desktop:universal` and `--linux/--win/--mac` variants all run the same hook.+- Electron desktop universal (multi-arch) builds β `ELECTRON_ARCH=universal npm run build:desktop:universal` produces one fat arm64+x64 DMG. The bundled uv/node runtimes are per-arch: the download scripts (arch resolution in `scripts/download-arch-utils.mjs::resolveDownloadArches()`; any `ELECTRON_ARCH` value other than unset or `universal` fails fast) populate `resources/{bin,node}-{arm64,x64}/` in universal mode (legacy flat `resources/{bin,node}/` otherwise), `mac.extraResources` ships all four dirs into BOTH packaging passes, and `mac.x64ArchFiles` whitelists them through the `@electron/universal` merge β the merger requires both pass trees to carry the same Mach-O file list and rejects byte-identical thin Mach-O files unless whitelisted, so bundling only the pass's own arch (e.g. via the `${arch}` macro) fails the merge. `electron/lib/bundled-runtime-dir.mjs::resolveBundledRuntimeDir()` (used by `injectBundledUv`/`injectBundledNode`) prefers `<Resources>/{bin,node}-<process.arch>` β under a universal Electron binary `process.arch` reports the executing slice (arm64 native, x64 under Rosetta) β and falls back to the flat dirs. Release CI (`desktop-macos.yml`) builds universal; PR/manual smoke builds run a two-leg matrix β native arm64 on `macos-latest` and native Intel x64 on `macos-15-intel` (GitHub's last Intel macOS runner, available until Aug 2027) β so the per-arch download + packaging path is exercised on the runner's own CPU. On `macos-15-intel` (which reports `process.arch === "x64"`), `npm run build:desktop` resolves the Intel runtimes into the legacy flat dirs, so that leg also guards the single-arch x64 fallback path.+- Electron desktop app name in dev (macOS) β `npm run desktop` shows the app as "Electron" in the Dock unless `scripts/brand-dev-electron.mjs` (wired as the `predesktop` hook) has run. There are **three independent name sources** and they must all be set; getting one wrong looks like the fix silently not working. (1) `app.name` β Electron-internal, drives the menu bar, About panel and `app.getPath("userData")`. It comes from `productName` in `electron/package.json`, read by Electron's `default_app` in dev and `lib/browser/init` when packaged. Note `default_app` only reads `<arg>/package.json`, so `npm run desktop` must point electron at the `electron/` **directory** β `electron electron/main.mjs` makes it probe `electron/main.mjs/package.json`, miss, and leave `app.name` at the host bundle default. (2) `CFBundleDisplayName` / `CFBundleName` in the running bundle's Info.plist β what `lsappinfo` and `NSRunningApplication.localizedName` report. (3) **The `.app` directory name β this is what the Dock tooltip actually shows.** macOS prefers the bundle's filesystem name over the plist keys; `/Applications/DBeaver.app` displays as "DBeaver" despite `CFBundleName = "DBeaver Community"`. So patching only the plist is NOT enough β the script also renames `node_modules/electron/dist/Electron.app` β `<productName>.app` and rewrites `node_modules/electron/path.txt` to match (`getElectronPath()` in `node_modules/electron/index.js` joins path.txt onto `dist/` and silently re-downloads Electron ~100 MB if it doesn't resolve, so the two must move together). `CFBundleExecutable` is deliberately left as `Electron` β `/Applications/Antigravity.app` ships that exact value and still displays correctly, so it only affects `ps`/Activity Monitor. Editing the plist does not break code signing: Electron's dist is ad-hoc *linker-signed* (`Info.plist=not bound`, `Sealed Resources=none`), so the signature covers only the Mach-O. `npm run build:desktop` is unaffected by the rename β electron-builder packages from `~/Library/Caches/electron/electron-v*.zip`, never from `node_modules/electron/dist`. The packaged app never had the problem: electron-builder emits `<productName>.app` with matching plist keys. Already-running instances keep the name they launched with, so quit and relaunch when verifying.- Electron desktop `node` / `npm` / `npx` PATH bridging β when the packaged `.app` is launched from Finder/Spotlight on macOS, the OS gives it a minimal PATH (`/usr/bin:/bin`). Homebrew, nvm, asdf installs of Node.js are invisible to spawned subprocesses. Two breakages flow from that: (1) backend launcher scripts that do `spawn("node", ...)` can't find Node; (2) most stdio MCP marketplace entries (Slack, GitHub, Figma, etc.) use `command: "npx"`, and when the agent-server tries to spawn them the missing `npx` makes the spawn fail with ENOENT β the SDK reports it as an `error_kind: "connection"` MCP test failure, which the install modal renders as `MCP$TEST_ERROR_CONNECTION` ("Could not reach the server. Check the URL and server type."), a misleading error since no URL is involved. **First fix attempt β DOES NOT WORK for stdio MCPs:** wrap `node`/`npm`/`npx` with thin shell scripts that run Electron with `ELECTRON_RUN_AS_NODE=1` against the package's CLI JS. That bridges the ENOENT but stdio JSON-RPC servers spawned through the wrapper exit with `McpError: Connection closed` before completing the MCP handshake β Electron-as-Node has subtly different stdin/stdout pipe semantics from a vanilla `node` binary when used as a stdio child of a windowed process. **Working fix:** bundle the real Node.js distribution. `scripts/download-node.mjs` downloads the official `node-v<ver>-<platform>-<arch>` tarball from `https://nodejs.org/dist/v<ver>/` into `resources/node/` (gitignored), prunes `include/`, `share/`, docs, and `node_modules/corepack` to keep the size down (~130 MB on Linux x64, dominated by the Node binary itself). Default pin: `NODE_BUNDLE_VERSION = "22.12.0"` (the volta pin in `package.json`; every 22.x build shares the Electron 42 ABI β the `engines.node` floor is now `>=24`, so it is no longer the rationale); override with `NODE_VERSION=`. `electron-builder.config.mjs` ships `resources/node/` as an extraResource β `<Resources>/node/`. `electron/main.mjs::injectBundledNode()` prepends the platform-appropriate bin dir to `PATH` (POSIX: `<Resources>/node/bin`; Windows: `<Resources>/node/`) so subsequent spawns of `node`/`npm`/`npx` resolve to real binaries with full stdio fidelity. It also `chmod +x`'s the binaries on POSIX because electron-builder doesn't always preserve the bit. `injectBundledNode()` is a no-op when `!app.isPackaged` (dev `npm run desktop` uses the developer's system node). `build:desktop` and `build:desktop:universal` both run `download-node.mjs` after `download-uv.mjs`. If the bundled dir is missing at runtime, `injectBundledNode()` logs a loud `[desktop]` warning instead of silently leaving PATH bare. **extraResources will not copy the distribution's root `node_modules`:** `app-builder-lib/src/util/filter.ts::createFilter` returns `false` for any entry whose path relative to the copy root is exactly `node_modules`, *before* the `filter` patterns are consulted, so no `filter` value can opt back in. The Windows Node zip puts npm at `<root>/node_modules/npm` and hits this exactly; POSIX tarballs put it at `<root>/lib/node_modules/npm` and are unaffected β which is why this only broke Windows. Shipped result: a working `node.exe` beside `npm.cmd`/`npx.cmd` shims pointing at a missing `node_modules\npm\bin\npx-cli.js`, so every `npx -y <pkg>` spawn dies with `MODULE_NOT_FOUND` *and* shadows the user's own npm, since the dir is PREPENDED to PATH. The `afterPack` hook (`restoreBundledNodeNpm`) copies that directory into the packed output and then hard-fails the build if `npm-cli.js` still isn't there, mirroring the check `download-node.mjs` already runs on the source tree.diff --git a/__tests__/electron/lib/bundled-runtime-dir.test.ts b/__tests__/electron/lib/bundled-runtime-dir.test.tsnew file mode 100644index 0000000000..d29bf07831--- /dev/null+++ b/__tests__/electron/lib/bundled-runtime-dir.test.ts@@ -0,0 +1,61 @@+// @vitest-environment node+// Resolve the bundled runtime dir (uv `bin`, Node `node`) inside a packaged+// Electron app: universal macOS builds ship arch-tagged `<base>-<arch>`+// dirs (picked via process.arch β the executing slice of the universal+// binary), single-arch builds ship the legacy flat `<base>` dir. These+// tests build throwaway <resourcesPath> fixtures to pin the candidate+// order: arch-tagged first, legacy flat second, null when neither exists.+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { resolveBundledRuntimeDir } from "../../../electron/lib/bundled-runtime-dir.mjs";++let resourcesPath: string;++beforeEach(() => {+ resourcesPath = mkdtempSync(join(tmpdir(), "bundled-runtime-dir-"));+});++afterEach(() => {+ rmSync(resourcesPath, { recursive: true, force: true });+});++describe("resolveBundledRuntimeDir", () => {+ it.each(["arm64", "x64"])(+ "returns the arch-tagged dir when only it exists (arch=%s)",+ (arch) => {+ const tagged = join(resourcesPath, `node-${arch}`);+ mkdirSync(tagged);++ expect(resolveBundledRuntimeDir(resourcesPath, "node", arch)).toBe(+ tagged,+ );+ },+ );++ it("prefers the arch-tagged dir when both candidates exist", () => {+ const tagged = join(resourcesPath, "bin-arm64");+ const legacy = join(resourcesPath, "bin");+ mkdirSync(tagged);+ mkdirSync(legacy);++ expect(resolveBundledRuntimeDir(resourcesPath, "bin", "arm64")).toBe(+ tagged,+ );+ });++ it("falls back to the legacy flat dir for single-arch builds", () => {+ const legacy = join(resourcesPath, "bin");+ mkdirSync(legacy);++ expect(resolveBundledRuntimeDir(resourcesPath, "bin", "x64")).toBe(legacy);+ });++ it("returns null when neither candidate exists", () => {+ expect(+ resolveBundledRuntimeDir(resourcesPath, "node", "arm64"),+ ).toBeNull();+ });+});diff --git a/__tests__/scripts/download-arch-utils.test.ts b/__tests__/scripts/download-arch-utils.test.tsnew file mode 100644index 0000000000..bf45f81891--- /dev/null+++ b/__tests__/scripts/download-arch-utils.test.ts@@ -0,0 +1,86 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import {+ resolveDownloadArches,+ resourceDirName,+} from "../../scripts/download-arch-utils.mjs";++describe("resolveDownloadArches", () => {+ it("returns only the host arch when ELECTRON_ARCH is unset", () => {+ expect(+ resolveDownloadArches({ platform: "darwin", hostArch: "arm64" }),+ ).toEqual(["arm64"]);+ expect(+ resolveDownloadArches({+ platform: "linux",+ hostArch: "x64",+ electronArch: undefined,+ }),+ ).toEqual(["x64"]);+ });++ it("returns both darwin arches for ELECTRON_ARCH=universal on darwin", () => {+ // Order is load-bearing (maps onto resources/{node,bin}-<arch> dirs).+ expect(+ resolveDownloadArches({+ platform: "darwin",+ hostArch: "arm64",+ electronArch: "universal",+ }),+ ).toEqual(["arm64", "x64"]);+ });++ it("throws for ELECTRON_ARCH=universal on linux", () => {+ expect(() =>+ resolveDownloadArches({+ platform: "linux",+ hostArch: "x64",+ electronArch: "universal",+ }),+ ).toThrow(/universal.*darwin|darwin.*universal/i);+ });++ it("throws for ELECTRON_ARCH=universal on win32", () => {+ expect(() =>+ resolveDownloadArches({+ platform: "win32",+ hostArch: "x64",+ electronArch: "universal",+ }),+ ).toThrow(/universal.*darwin|darwin.*universal/i);+ });++ it("throws for an explicit single arch value like x64 β fail loud instead of bundling a silently-wrong cross-arch runtime", () => {+ expect(() =>+ resolveDownloadArches({+ platform: "darwin",+ hostArch: "arm64",+ electronArch: "x64",+ }),+ ).toThrow(/ELECTRON_ARCH/i);+ });++ it("throws for garbage ELECTRON_ARCH values", () => {+ expect(() =>+ resolveDownloadArches({+ platform: "darwin",+ hostArch: "arm64",+ electronArch: "bogus",+ }),+ ).toThrow(/ELECTRON_ARCH/i);+ });+});++describe("resourceDirName", () => {+ it("suffixed the arch onto the base in multi-arch (universal) mode", () => {+ expect(resourceDirName("node", "arm64", true)).toBe("node-arm64");+ expect(resourceDirName("node", "x64", true)).toBe("node-x64");+ expect(resourceDirName("bin", "arm64", true)).toBe("bin-arm64");+ expect(resourceDirName("bin", "x64", true)).toBe("bin-x64");+ });++ it("keeps the legacy single-arch base directory name", () => {+ expect(resourceDirName("node", "arm64", false)).toBe("node");+ expect(resourceDirName("bin", "x64", false)).toBe("bin");+ });+});diff --git a/__tests__/scripts/download-node.test.ts b/__tests__/scripts/download-node.test.tsnew file mode 100644index 0000000000..932ed944b2--- /dev/null+++ b/__tests__/scripts/download-node.test.ts@@ -0,0 +1,52 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { getPlatformSpec } from "../../scripts/download-node.mjs";++describe("download-node getPlatformSpec", () => {+ it("maps explicit darwin arches to the matching distribution", () => {+ expect(getPlatformSpec("22.12.0", "darwin", "x64")).toEqual({+ name: "node-v22.12.0-darwin-x64",+ ext: "tar.gz",+ });+ expect(getPlatformSpec("22.12.0", "darwin", "arm64")).toEqual({+ name: "node-v22.12.0-darwin-arm64",+ ext: "tar.gz",+ });+ });++ it("maps linux arches to the matching distribution", () => {+ expect(getPlatformSpec("22.12.0", "linux", "x64")).toEqual({+ name: "node-v22.12.0-linux-x64",+ ext: "tar.gz",+ });+ expect(getPlatformSpec("22.12.0", "linux", "arm64")).toEqual({+ name: "node-v22.12.0-linux-arm64",+ ext: "tar.gz",+ });+ });++ it("maps win32 arches to the zip distribution", () => {+ expect(getPlatformSpec("22.12.0", "win32", "x64")).toEqual({+ name: "node-v22.12.0-win-x64",+ ext: "zip",+ });+ expect(getPlatformSpec("22.12.0", "win32", "arm64")).toEqual({+ name: "node-v22.12.0-win-arm64",+ ext: "zip",+ });+ });++ it("defaults platform/arch to the host values", () => {+ const spec = getPlatformSpec("22.12.0");+ expect(spec.name.startsWith("node-v22.12.0-")).toBe(true);+ expect(["darwin", "linux", "win32"]).toContain(+ spec.name.replace("node-v22.12.0-", "").split("-")[0],+ );+ });++ it("throws for an unsupported platform", () => {+ expect(() => getPlatformSpec("22.12.0", "freebsd", "x64")).toThrow(+ /Unsupported platform for Node download: freebsd\/x64/,+ );+ });+});diff --git a/__tests__/scripts/download-uv.test.ts b/__tests__/scripts/download-uv.test.tsnew file mode 100644index 0000000000..7f8bce3464--- /dev/null+++ b/__tests__/scripts/download-uv.test.ts@@ -0,0 +1,50 @@+// @vitest-environment node+// Importing the module must not trigger a download: main() only runs when+// the script is executed directly (`node scripts/download-uv.mjs`). If that+// main-guard regressed, this import would hit the GitHub API (and its+// failure handler calls process.exit(1)), killing the worker loudly.+import { describe, expect, it } from "vitest";+import { getPlatformSpec } from "../../scripts/download-uv.mjs";++describe("download-uv module import", () => {+ it("imports as a module without starting a download", () => {+ expect(typeof getPlatformSpec).toBe("function");+ });+});++describe("download-uv getPlatformSpec", () => {+ it("maps darwin arches to uv's Rust-style triplets", () => {+ expect(getPlatformSpec("arm64", "darwin")).toEqual({+ target: "uv-aarch64-apple-darwin",+ ext: "tar.gz",+ binaries: ["uv", "uvx"],+ });+ expect(getPlatformSpec("x64", "darwin")).toEqual({+ target: "uv-x86_64-apple-darwin",+ ext: "tar.gz",+ binaries: ["uv", "uvx"],+ });+ });++ it("maps linux to the x86_64 gnu target", () => {+ expect(getPlatformSpec("x64", "linux")).toEqual({+ target: "uv-x86_64-unknown-linux-gnu",+ ext: "tar.gz",+ binaries: ["uv", "uvx"],+ });+ });++ it("maps win32 to the msvc zip with .exe binaries", () => {+ expect(getPlatformSpec("x64", "win32")).toEqual({+ target: "uv-x86_64-pc-windows-msvc",+ ext: "zip",+ binaries: ["uv.exe", "uvx.exe"],+ });+ });++ it("throws for an unsupported platform", () => {+ expect(() => getPlatformSpec("arm64", "sunos")).toThrow(+ /Unsupported platform for uv download: sunos/,+ );+ });+});diff --git a/__tests__/scripts/electron-builder-config.test.ts b/__tests__/scripts/electron-builder-config.test.tsindex 60b0f1ac98..27999e592f 100644--- a/__tests__/scripts/electron-builder-config.test.ts+++ b/__tests__/scripts/electron-builder-config.test.ts@@ -9,8 +9,8 @@import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, describe, expect, it } from "vitest";+import { dirname, join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import config from "../../electron-builder.config.mjs";const afterPack = config.afterPack as (ctx: unknown) => Promise<void>;@@ -25,11 +25,16 @@ function makeContext(platform: string, appOutDir: string) {};}+/** Resolve the packaged Resources dir for a platform, mirroring the bundle layout. */+function resourcesDirFor(platform: string, appOutDir: string) {+ return platform === "darwin"+ ? join(appOutDir, `${PRODUCT_FILENAME}.app`, "Contents", "Resources")+ : join(appOutDir, "resources");+}+/** Resolve the packaged app dir for a platform, mirroring the bundle layout. */function appDirFor(platform: string, appOutDir: string) {- return platform === "darwin"- ? join(appOutDir, `${PRODUCT_FILENAME}.app`, "Contents", "Resources", "app")- : join(appOutDir, "resources", "app");+ return join(resourcesDirFor(platform, appOutDir), "app");}/**@@ -45,6 +50,16 @@ function resolveRuntimeImports(appDir: string) {);}+/**+ * Write a fake POSIX-layout bundled Node dir (npm at lib/node_modules) with+ * its npm-cli.js marker, as download-node.mjs produces on macOS/Linux.+ */+function writeFakeNpmCli(resourcesDir: string, nodeDirName: string) {+ const npmCli = join(resourcesDir, nodeDirName, "lib", "node_modules", "npm", "bin", "npm-cli.js");+ mkdirSync(dirname(npmCli), { recursive: true });+ writeFileSync(npmCli, "// fake npm-cli.js\n");+}+describe("electron-builder afterPack hook", () => {let tmp: string | null = null;@@ -95,6 +110,92 @@ describe("electron-builder afterPack hook", () => {expect(existsSync(join(appDir, "node_modules", "sirv", "package.json"))).toBe(true);expect(existsSync(join(appDir, "node_modules", "httpxy", "package.json"))).toBe(true);});++ it("verifies npm in every per-arch node dir of a universal bundle", async () => {+ tmp = mkdtempSync(join(tmpdir(), "eb-afterpack-"));+ const resourcesDir = resourcesDirFor("darwin", tmp);+ mkdirSync(join(resourcesDir, "app"), { recursive: true });+ writeFakeNpmCli(resourcesDir, "node-arm64");+ writeFakeNpmCli(resourcesDir, "node-x64");++ await expect(afterPack(makeContext("darwin", tmp))).resolves.toBeUndefined();+ });++ it("fails the build when one per-arch node dir of a universal bundle is missing npm", async () => {+ tmp = mkdtempSync(join(tmpdir(), "eb-afterpack-"));+ const resourcesDir = resourcesDirFor("darwin", tmp);+ mkdirSync(join(resourcesDir, "app"), { recursive: true });+ writeFakeNpmCli(resourcesDir, "node-arm64");+ // x64 slice gutted: the dir exists but its npm-cli.js does not β the+ // hook must verify BOTH slices, not just the first one it finds.+ mkdirSync(join(resourcesDir, "node-x64"), { recursive: true });++ await expect(afterPack(makeContext("darwin", tmp))).rejects.toThrow(+ /missing npm-cli\.js at .*node-x64/,+ );+ });++ it("still verifies the legacy flat node dir (single-arch back-compat)", async () => {+ tmp = mkdtempSync(join(tmpdir(), "eb-afterpack-"));+ const resourcesDir = resourcesDirFor("darwin", tmp);+ mkdirSync(join(resourcesDir, "app"), { recursive: true });+ writeFakeNpmCli(resourcesDir, "node");++ await expect(afterPack(makeContext("darwin", tmp))).resolves.toBeUndefined();+ });+});++// The config is a .mjs module whose extraResources is computed at evaluation+// time from ELECTRON_ARCH (build:desktop:universal sets it before invoking+// electron-builder). Each case therefore re-imports the module fresh, with+// the env var scrubbed in beforeEach and restored in afterEach.+const ELECTRON_ARCH_ENV = "ELECTRON_ARCH";++describe("extraResources mode switch", () => {+ let savedArch: string | undefined;++ async function importConfig() {+ vi.resetModules();+ return (await import("../../electron-builder.config.mjs")).default;+ }++ beforeEach(() => {+ savedArch = process.env[ELECTRON_ARCH_ENV];+ delete process.env[ELECTRON_ARCH_ENV];+ });++ afterEach(() => {+ if (savedArch === undefined) delete process.env[ELECTRON_ARCH_ENV];+ else process.env[ELECTRON_ARCH_ENV] = savedArch;+ });++ it("ships the legacy flat runtime dirs when ELECTRON_ARCH is unset", async () => {+ const cfg = await importConfig();++ expect(cfg.extraResources).toEqual([+ { from: "resources/bin/", to: "bin/", filter: ["**/*"] },+ { from: "resources/node/", to: "node/", filter: ["**/*"] },+ ]);+ });++ it("ships both per-arch runtime dirs into every universal pass, whitelisted for the merger", async () => {+ process.env[ELECTRON_ARCH_ENV] = "universal";+ const cfg = await importConfig();++ // Both per-arch dirs go into BOTH packaging passes: @electron/universal+ // requires the x64 and arm64 pass trees to carry the same Mach-O file+ // list, and mac.x64ArchFiles whitelists our intentionally identical+ // per-arch runtime binaries through the merge. Full rationale in+ // electron-builder.config.mjs.+ expect(cfg.extraResources).toEqual([+ { from: "resources/bin-arm64/", to: "bin-arm64/", filter: ["**/*"] },+ { from: "resources/bin-x64/", to: "bin-x64/", filter: ["**/*"] },+ { from: "resources/node-arm64/", to: "node-arm64/", filter: ["**/*"] },+ { from: "resources/node-x64/", to: "node-x64/", filter: ["**/*"] },+ ]);+ expect(cfg.mac).toBeDefined();+ expect(cfg.mac!.x64ArchFiles).toBe("**/{bin,node}-{arm64,x64}/**");+ });});// The app's display name is set in two places that must agree:diff --git a/electron-builder.config.mjs b/electron-builder.config.mjsindex 333bd3294b..2327d5ae78 100644--- a/electron-builder.config.mjs+++ b/electron-builder.config.mjs@@ -42,13 +42,18 @@* config/ β defaults.json* build/ β static frontend (npm run build:app output)*- * The bundled uv binary (resources/bin/) lands in <Resources>/bin/ via- * extraResources so Electron can inject it into PATH on startup.+ * The bundled uv / Node.js runtimes land in <Resources>/ via extraResources+ * so Electron can inject them into PATH on startup. The per-arch repo layout+ * (single-arch resources/{bin,node}/ vs universal+ * resources/{bin,node}-{arm64,x64}/) is canonical in+ * scripts/download-arch-utils.mjs; electron/main.mjs selects+ * <Resources>/{bin,node}-<process.arch> at runtime (falling back to the flat+ * dirs).*- * The bundled Node.js distribution (resources/node/) lands in- * <Resources>/node/ via extraResources β except for its root-level- * node_modules (npm itself), which electron-builder refuses to copy and the- * afterPack hook restores; see restoreBundledNodeNpm below.+ * The bundled Node distribution's root-level node_modules (npm itself) is+ * dropped by electron-builder's copy filter in both layouts; the afterPack+ * hook restores and verifies it per node dir; see restoreBundledNodeNpm+ * below.** Electron prepends its bin dir to PATH at startup so backend scripts (`node* scripts/ingress.mjs` etc.) and stdio MCP servers spawned via `npx -y β¦`@@ -58,9 +63,15 @@import { cp, rm } from "node:fs/promises";import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";-import { dirname, join, relative } from "node:path";+import { basename, dirname, join, relative } from "node:path";import { fileURLToPath } from "node:url";+// Arch the desktop runtimes are bundled for β "universal" (macOS) or a+// single arch. The per-arch layouts live in scripts/download-arch-utils.mjs;+// extraResources below maps them onto <Resources>/.+const ELECTRON_ARCH = process.env.ELECTRON_ARCH;+const isUniversal = ELECTRON_ARCH === "universal";+// npm packages the packaged app's child-process scripts import at runtime:// scripts/static-server.mjs β sirv// scripts/proxy-utils.mjs β httpxy (imported by ingress.mjs)@@ -188,7 +199,13 @@ async function restoreRuntimeNodeModules(appDir) {/*** Restore the bundled Node distribution's root-level `node_modules` (npm* itself), which electron-builder silently refuses to copy, then verify the- * packed result.+ * packed result β for every node dir the bundle ships: the per-arch+ * node-arm64/ + node-x64/ dirs of a universal build and/or the legacy flat+ * node/ dir of a single-arch build.+ *+ * electron-builder's afterPack fires once per arch pass on universal builds,+ * so each dir's restore keeps the `!existsSync(destNodeModules)` guard to+ * stay idempotent; the npm-cli.js verification is read-only.** WHY THIS IS NEEDED β app-builder-lib's copy filter drops a `node_modules`* directory sitting at the ROOT of a `from` dir, before any `filter` pattern@@ -218,36 +235,49 @@ async function restoreRuntimeNodeModules(appDir) {*/async function restoreBundledNodeNpm(context) {const isWin = context.electronPlatformName === "win32";- const nodeDir = join(packagedResourcesDir(context), "node");++ // Universal builds ship one Node distribution per arch (node-arm64/,+ // node-x64/); single-arch builds ship the legacy flat node/. Handle+ // whichever of them made it into the packed output.+ const nodeDirs = ["node-arm64", "node-x64", "node"]+ .map((name) => join(packagedResourcesDir(context), name))+ .filter((dir) => existsSync(dir));// No bundled Node at all β `npm run download-node` was skipped. That is a// different (and already loudly reported) situation; main.mjs warns at// startup. Don't turn it into a build failure here.- if (!existsSync(nodeDir)) return;-- const srcNodeModules = join(repoRoot, "resources", "node", "node_modules");- const destNodeModules = join(nodeDir, "node_modules");- if (!existsSync(destNodeModules) && existsSync(srcNodeModules)) {- await cp(srcNodeModules, destNodeModules, { recursive: true });- const rel = relative(process.cwd(), destNodeModules);- // eslint-disable-next-line no-console -- electron-builder build log- console.log(- `[electron-builder] restored bundled Node node_modules: ${rel}`,+ if (nodeDirs.length === 0) return;++ for (const nodeDir of nodeDirs) {+ const srcNodeModules = join(+ repoRoot,+ "resources",+ basename(nodeDir),+ "node_modules",);- }+ const destNodeModules = join(nodeDir, "node_modules");+ if (!existsSync(destNodeModules) && existsSync(srcNodeModules)) {+ await cp(srcNodeModules, destNodeModules, { recursive: true });+ const rel = relative(process.cwd(), destNodeModules);+ // eslint-disable-next-line no-console -- electron-builder build log+ console.log(+ `[electron-builder] restored bundled Node node_modules: ${rel}`,+ );+ }- // Mirror the check scripts/download-node.mjs runs on the source tree, but- // against the packed output β the last point where a broken npm is still a- // build failure instead of a broken install.- const npmCli = isWin- ? join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js")- : join(nodeDir, "lib", "node_modules", "npm", "bin", "npm-cli.js");- if (!existsSync(npmCli)) {- throw new Error(- `[electron-builder] packaged Node is missing npm-cli.js at ${npmCli} β ` +- "npm/npx would fail with MODULE_NOT_FOUND in the installed app. " +- "Run `npm run download-node` and rebuild.",- );+ // Mirror the check scripts/download-node.mjs runs on the source tree, but+ // against the packed output β the last point where a broken npm is still a+ // build failure instead of a broken install.+ const npmCli = isWin+ ? join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js")+ : join(nodeDir, "lib", "node_modules", "npm", "bin", "npm-cli.js");+ if (!existsSync(npmCli)) {+ throw new Error(+ `[electron-builder] packaged Node is missing npm-cli.js at ${npmCli} β ` ++ "npm/npx would fail with MODULE_NOT_FOUND in the installed app. " ++ "Run `npm run download-node` and rebuild.",+ );+ }}}@@ -353,10 +383,29 @@ const config = {// `npm run download-node`)// `from` is relative to the project root (not directories.app).// build:desktop calls both download scripts before invoking electron-builder.- extraResources: [- { from: "resources/bin/", to: "bin/", filter: ["**/*"] },- { from: "resources/node/", to: "node/", filter: ["**/*"] },- ],+ //+ // Universal (ELECTRON_ARCH=universal): both runtime arches (per-arch+ // layout canonical in scripts/download-arch-utils.mjs) ship in BOTH+ // packaging passes. @electron/universal then merges the x64 and arm64 pass+ // trees: it lipos files that differ (the Electron framework) and rejects+ // thin Mach-O files that are byte-identical in both trees unless they+ // match mac.x64ArchFiles below β which is exactly what our per-arch runtime+ // binaries are (identical arm64/x64 binaries copied into both passes).+ // Bundling only the pass's own arch (e.g. via the ${arch} macro) does NOT+ // work: the merger requires both trees to carry the same Mach-O file list.+ // Missing `from` dirs fail the build, so each mode lists exactly the dirs+ // its download scripts populate.+ extraResources: isUniversal+ ? [+ { from: "resources/bin-arm64/", to: "bin-arm64/", filter: ["**/*"] },+ { from: "resources/bin-x64/", to: "bin-x64/", filter: ["**/*"] },+ { from: "resources/node-arm64/", to: "node-arm64/", filter: ["**/*"] },+ { from: "resources/node-x64/", to: "node-x64/", filter: ["**/*"] },+ ]+ : [+ { from: "resources/bin/", to: "bin/", filter: ["**/*"] },+ { from: "resources/node/", to: "node/", filter: ["**/*"] },+ ],// ββ macOS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ//@@ -369,11 +418,9 @@ const config = {// Or use the dedicated script:// npm run build:desktop:universal//- // CAUTION: the bundled uv/node extraResources are downloaded for the- // BUILD HOST's architecture only (scripts/download-uv.mjs and- // download-node.mjs have no arch override), so a "universal" build still- // ships single-arch runtimes and breaks on the other architecture. Don't- // distribute universal DMGs until the download scripts support multi-arch.+ // Universal builds download both runtime arches (layout canonical in+ // scripts/download-arch-utils.mjs) which the conditional extraResources+ // above packages side by side.//mac: {category: "public.app-category.developer-tools",@@ -381,11 +428,18 @@ const config = {{target: "dmg",arch: [- process.env.ELECTRON_ARCH ??- (process.arch === "arm64" ? "arm64" : "x64"),+ ELECTRON_ARCH ?? (process.arch === "arm64" ? "arm64" : "x64"),],},],+ // Universal merge whitelist: the per-arch uv/node runtime binaries are+ // thin single-arch Mach-O files that are intentionally byte-identical in+ // both packaging passes (each pass bundles all four per-arch dirs β see+ // extraResources above). Without this rule @electron/universal fails the+ // merge with "same in both x64 and arm64 builds". Scoped to exactly our+ // per-arch runtime dirs so any accidental duplicate elsewhere still+ // fails the build loudly.+ x64ArchFiles: "**/{bin,node}-{arm64,x64}/**",// Icon auto-discovered from directories.buildResources/icon.icns// (committed; regenerate with `npm run generate-icons`).},diff --git a/electron/lib/bundled-runtime-dir.mjs b/electron/lib/bundled-runtime-dir.mjsnew file mode 100644index 0000000000..fa849a9311--- /dev/null+++ b/electron/lib/bundled-runtime-dir.mjs@@ -0,0 +1,37 @@+/**+ * Resolve the bundled-runtime directory (uv `bin`, Node `node`) for the+ * running Electron process, arch-aware for macOS universal builds.+ *+ * Under a universal Electron binary, `process.arch` reports the slice the+ * OS actually executed β arm64 on Apple Silicon, x64 on Intel hardware or+ * when running under Rosetta (`arch -x86_64`). Universal builds download+ * one runtime tree per arch into `resources/{bin,node}-<arch>`, so the+ * arch-tagged directory is correct by construction: the executing slice+ * can only use runtimes built for that same arch. Single-arch builds keep+ * shipping the legacy flat `resources/{bin,node}` directory, which is the+ * fallback. Returns null when neither candidate exists so callers can emit+ * their own loud missing-runtime warning.+ */+import { existsSync } from "node:fs";+import { join } from "node:path";++/**+ * @param {string} resourcesPath Electron's process.resourcesPath.+ * @param {string} baseName Runtime dir base name ("bin" for uv, "node" for+ * the bundled Node.js distribution).+ * @param {string} arch CPU arch tag; defaults to the executing process's+ * arch (overridable so tests can pin arm64/x64).+ * @returns {string | null} The first existing candidate dir, or null when+ * neither the arch-tagged nor the legacy flat dir exists.+ */+export function resolveBundledRuntimeDir(+ resourcesPath,+ baseName,+ arch = process.arch,+) {+ const candidates = [+ join(resourcesPath, `${baseName}-${arch}`),+ join(resourcesPath, baseName),+ ];+ return candidates.find((dir) => existsSync(dir)) ?? null;+}diff --git a/electron/main.mjs b/electron/main.mjsindex 3445cae1f6..ce59667cde 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -14,8 +14,14 @@* scripts/ β copied from repo scripts/* config/ β copied from repo config/* build/ β static frontend- * Contents/Resources/bin/ β process.resourcesPath/bin- * uv uvx β bundled via extraResources+ * Contents/Resources/bin-<arch>/ β process.resourcesPath/bin-<arch>+ * uv uvx β bundled via extraResources+ * Contents/Resources/bin/ β legacy flat dir (single-arch builds)+ *+ * Bundled runtimes (uv `bin`, Node `node`) prefer the arch-tagged dir+ * matching process.arch β under a universal binary that's the executing+ * slice (arm64 on Apple Silicon, x64 on Intel/Rosetta) β and fall back+ * to the legacy flat dir (see lib/bundled-runtime-dir.mjs).** Dev (npm run desktop β electron electron):* electron/main.mjs β __dirname = <repo>/electron/@@ -48,6 +54,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";import { spawnSync } from "node:child_process";import { isExternalBrowsableUrl, isLoopbackAppUrl } from "./lib/window-url-policy.mjs";+import { resolveBundledRuntimeDir } from "./lib/bundled-runtime-dir.mjs";const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -99,7 +106,16 @@ function injectBundledUv() {const isWin = process.platform === "win32";const uvName = isWin ? "uv.exe" : "uv";const uvxName = isWin ? "uvx.exe" : "uvx";- const binDir = join(process.resourcesPath, "bin");+ const binDir = resolveBundledRuntimeDir(process.resourcesPath, "bin");+ if (!binDir) {+ console.warn(+ "[desktop] Bundled uv not found β looked in",+ join(process.resourcesPath, `bin-${process.arch}`),+ "and",+ join(process.resourcesPath, "bin"),+ );+ return;+ }const uvPath = join(binDir, uvName);// We only probe for `uv` here β `uv` and `uvx` ship together in the@@ -173,7 +189,16 @@ function injectBundledNode() {if (!app.isPackaged) return;const isWin = process.platform === "win32";- const nodeRoot = join(process.resourcesPath, "node");+ const nodeRoot = resolveBundledRuntimeDir(process.resourcesPath, "node");+ if (!nodeRoot) {+ console.warn(+ "[desktop] Bundled Node.js not found β looked in " ++ `${join(process.resourcesPath, `node-${process.arch}`)} and ` ++ `${join(process.resourcesPath, "node")} β backend scripts and stdio ` ++ "MCP servers will fail. Run `npm run download-node` and rebuild.",+ );+ return;+ }// POSIX Node distributions put binaries in bin/; Windows zips put node.exe// and the npm.cmd / npx.cmd wrappers at the distribution root.const binDir = isWin ? nodeRoot : join(nodeRoot, "bin");diff --git a/package.json b/package.jsonindex 8e48bc9344..dc0e433e73 100644--- a/package.json+++ b/package.json@@ -108,7 +108,7 @@"predesktop": "node scripts/brand-dev-electron.mjs","desktop": "npm run build:app && electron electron","build:desktop": "npm run build:app && node scripts/download-uv.mjs && node scripts/download-node.mjs && electron-builder --config electron-builder.config.mjs --publish never",- "build:desktop:universal": "npm run build:app && node scripts/download-uv.mjs && node scripts/download-node.mjs && cross-env ELECTRON_ARCH=universal electron-builder --config electron-builder.config.mjs --publish never",+ "build:desktop:universal": "npm run build:app && cross-env ELECTRON_ARCH=universal node scripts/download-uv.mjs && cross-env ELECTRON_ARCH=universal node scripts/download-node.mjs && cross-env ELECTRON_ARCH=universal electron-builder --config electron-builder.config.mjs --publish never","download-uv": "node scripts/download-uv.mjs","download-node": "node scripts/download-node.mjs","generate-icons": "node scripts/generate-icons.mjs"diff --git a/scripts/download-arch-utils.mjs b/scripts/download-arch-utils.mjsnew file mode 100644index 0000000000..42e8283105--- /dev/null+++ b/scripts/download-arch-utils.mjs@@ -0,0 +1,77 @@+/**+ * Shared multi-arch resolution for the runtime download scripts+ * (download-node.mjs / download-uv.mjs).+ *+ * macOS universal Electron builds (`npm run build:desktop:universal` with+ * ELECTRON_ARCH=universal) need a per-arch Node.js and uv runtime for BOTH+ * darwin slices β a universal .app that carries only the host-arch runtime+ * silently breaks npx/uvx spawns on the other arch. These helpers decide+ * which arches to download and which resources/<dir> name each one lands in:+ *+ * single-arch (default): resources/node/ and resources/bin/+ * universal (macOS only): resources/node-{arm64,x64}/ and resources/bin-{arm64,x64}/+ *+ * The env-var semantics and directory names are pinned together with+ * electron-builder.config.mjs and electron/main.mjs β change one, change all.+ */++/** ELECTRON_ARCH value that selects a macOS universal (dual-arch) download. */+const UNIVERSAL_ARCH = "universal";++/**+ * The two darwin slices a macOS universal build bundles, in the order the+ * download scripts iterate them. macOS is the only platform Electron+ * supports universal binaries for.+ */+const DARWIN_UNIVERSAL_ARCHES = ["arm64", "x64"];++/**+ * Resolve the list of runtime architectures to download.+ *+ * - ELECTRON_ARCH unset β `[hostArch]` (today's single-arch behavior,+ * writes to the legacy resources/{node,bin} directories).+ * - ELECTRON_ARCH=universal + darwin β both slices in+ * DARWIN_UNIVERSAL_ARCHES order.+ * - ELECTRON_ARCH=universal + non-darwin β throws: there is no universal+ * build for this platform, so downloading two runtimes would be wasted+ * work at best and a mis-bundled app at worst.+ * - Any other value (including a concrete arch like "x64") β throws.+ * Explicit single-arch pinning is deliberately unsupported: a host-arm64+ * machine downloading an x64-only runtime looks like a typo, and a+ * silently-wrong cross-arch bundle is much harder to diagnose than a+ * failed download step.+ */+export function resolveDownloadArches({+ platform = process.platform,+ hostArch = process.arch,+ electronArch = process.env.ELECTRON_ARCH,+} = {}) {+ if (electronArch === undefined) {+ return [hostArch];+ }+ if (electronArch === UNIVERSAL_ARCH) {+ if (platform === "darwin") {+ return [...DARWIN_UNIVERSAL_ARCHES];+ }+ throw new Error(+ `ELECTRON_ARCH=universal is only supported for macOS (darwin) builds; ` ++ `current platform is "${platform}". Remove ELECTRON_ARCH to download ` ++ `the host-arch runtime instead.`,+ );+ }+ throw new Error(+ `Unsupported ELECTRON_ARCH value: "${electronArch}". Leave it unset to ` ++ `download for the host arch (${hostArch}) or set it to ` ++ `"${UNIVERSAL_ARCH}" for a macOS universal build.`,+ );+}++/**+ * Name of the resources subdirectory for a runtime download.+ * `base` is "node" or "bin". Multi-arch (universal) downloads get per-arch+ * suffixed directories so both slices can coexist; single-arch downloads+ * keep the legacy unsuffixed name.+ */+export function resourceDirName(base, arch, multi) {+ return multi ? `${base}-${arch}` : base;+}diff --git a/scripts/download-node.mjs b/scripts/download-node.mjsindex 6826ef602b..b68b8b5dbe 100644--- a/scripts/download-node.mjs+++ b/scripts/download-node.mjs@@ -27,12 +27,17 @@* earlier download-npm.mjs).** Usage:- * node scripts/download-node.mjs # uses NODE_BUNDLE_VERSION below+ * node scripts/download-node.mjs # host arch β resources/node/* NODE_VERSION=22.10.0 node scripts/download-node.mjs+ * ELECTRON_ARCH=universal node scripts/download-node.mjs # macOS only** Output (per platform):* POSIX: resources/node/bin/{node,npm,npx} + resources/node/lib/node_modules/npm/...* Windows: resources/node/{node.exe,npm.cmd,npx.cmd} + resources/node/node_modules/npm/...+ *+ * With ELECTRON_ARCH=universal on macOS, both darwin slices are downloaded+ * into per-arch directories β the multi-arch layout is canonical in+ * scripts/download-arch-utils.mjs.*/import {@@ -50,12 +55,12 @@ import {import { get } from "node:https";import { tmpdir } from "node:os";import { dirname, join } from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { execFileSync } from "node:child_process";+import { resolveDownloadArches, resourceDirName } from "./download-arch-utils.mjs";const __dirname = dirname(fileURLToPath(import.meta.url));const projectRoot = join(__dirname, "..");-const outDir = join(projectRoot, "resources", "node");// Pinned Node version. Electron 42 ships Node 22, so we bundle a 22.x// LTS release to match the embedded runtime's ABI/native-module surface.@@ -85,21 +90,21 @@ const ARCH = process.arch; // 'x64' | 'arm64' | 'ia32'* win32 x64 β node-v<ver>-win-x64.zip* win32 arm64 β node-v<ver>-win-arm64.zip*/-function getPlatformSpec(version) {+export function getPlatformSpec(version, platform = PLATFORM, arch = ARCH) {const base = `node-v${version}`;- if (PLATFORM === "darwin") {- const arch = ARCH === "arm64" ? "arm64" : "x64";- return { name: `${base}-darwin-${arch}`, ext: "tar.gz" };+ if (platform === "darwin") {+ const distArch = arch === "arm64" ? "arm64" : "x64";+ return { name: `${base}-darwin-${distArch}`, ext: "tar.gz" };}- if (PLATFORM === "linux") {- const arch = ARCH === "arm64" ? "arm64" : "x64";- return { name: `${base}-linux-${arch}`, ext: "tar.gz" };+ if (platform === "linux") {+ const distArch = arch === "arm64" ? "arm64" : "x64";+ return { name: `${base}-linux-${distArch}`, ext: "tar.gz" };}- if (PLATFORM === "win32") {- const arch = ARCH === "arm64" ? "arm64" : "x64";- return { name: `${base}-win-${arch}`, ext: "zip" };+ if (platform === "win32") {+ const distArch = arch === "arm64" ? "arm64" : "x64";+ return { name: `${base}-win-${distArch}`, ext: "zip" };}- throw new Error(`Unsupported platform for Node download: ${PLATFORM}/${ARCH}`);+ throw new Error(`Unsupported platform for Node download: ${platform}/${arch}`);}// ββ Version resolution βββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -164,13 +169,13 @@ function ensureExecutable(p) {* Confirm the extracted tree has the binaries we depend on.* On Unix Node puts them in bin/; on Windows they live at the root.*/-function verifyLayout() {- const isWin = PLATFORM === "win32";+function verifyLayout(dir, platform) {+ const isWin = platform === "win32";const required = isWin? ["node.exe", "npm.cmd", "npx.cmd"]: ["bin/node", "bin/npm", "bin/npx"];for (const rel of required) {- const p = join(outDir, rel);+ const p = join(dir, rel);if (!existsSync(p)) {throw new Error(`Expected ${rel} in extracted Node distribution but it is missing ` +@@ -184,8 +189,8 @@ function verifyLayout() {// points; verify the targets exist too so a packaged build doesn't ship// a half-broken installation.const npmCli = isWin- ? join(outDir, "node_modules", "npm", "bin", "npm-cli.js")- : join(outDir, "lib", "node_modules", "npm", "bin", "npm-cli.js");+ ? join(dir, "node_modules", "npm", "bin", "npm-cli.js")+ : join(dir, "lib", "node_modules", "npm", "bin", "npm-cli.js");if (!existsSync(npmCli)) {throw new Error(`Bundled Node is missing npm-cli.js at ${npmCli}`);}@@ -204,7 +209,7 @@ function verifyLayout() {* lib/node_modules/{npm,corepack} β npm itself* LICENSE β required by the BSD-style Node license*/-function pruneUnusedFiles() {+function pruneUnusedFiles(dir, platform) {// IMPORTANT: every entry that points into a directory we delete must also// delete any symlink/shim that targets into it, otherwise electron-builder// hits ENOENT trying to stat() the dangling symlink while copying the@@ -215,7 +220,7 @@ function pruneUnusedFiles() {// module under lib/ but leave the symlink, `electron-builder` fails with// ENOENT: ... Resources/node/bin/corepackconst candidates =- PLATFORM === "win32"+ platform === "win32"? [// Windows Node zip lays out npm directly under node_modules/, not lib/.// Strip docs, headers, and node_modules/corepack (the npm runtime@@ -239,7 +244,7 @@ function pruneUnusedFiles() {"bin/corepack",];for (const rel of candidates) {- const p = join(outDir, rel);+ const p = join(dir, rel);// `rmSync(force: true)` resolves the path through symlinks, so once the// corepack target directory is deleted the now-dangling `bin/corepack`// link reads as "already gone" and silently survives β the exact ENOENT@@ -268,9 +273,9 @@ function pruneUnusedFiles() {* ENOENT β fail at download time instead, with a message that says which* pruned directory the symlink was reaching into.*/-function failOnDanglingSymlinks() {+function failOnDanglingSymlinks(dir) {const broken = [];- const stack = [outDir];+ const stack = [dir];while (stack.length) {const next = stack.pop();let entries;@@ -306,7 +311,7 @@ function failOnDanglingSymlinks() {"(or its target) to pruneUnusedFiles() in this script:",);for (const entry of broken) console.error(" β’", entry);- throw new Error(`${broken.length} dangling symlink(s) in resources/node/`);+ throw new Error(`${broken.length} dangling symlink(s) in ${dir}`);}}@@ -340,43 +345,71 @@ function dirSizeBytes(dir) {// ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync function main() {+ // Resolve both up front: the version must be identical for every arch+ // (one source of truth, no per-arch drift), and the arch list is decided+ // once by ELECTRON_ARCH (see download-arch-utils.mjs).const version = resolveVersion();- const spec = getPlatformSpec(version);- const archiveName = `${spec.name}.${spec.ext}`;- const url = `https://nodejs.org/dist/v${version}/${archiveName}`;- const tmpFile = join(tmpdir(), `node-download-${Date.now()}.${spec.ext}`);+ const arches = resolveDownloadArches();+ const multi = arches.length > 1;+ if (multi) {+ console.log(+ `[download-node] macOS universal build: downloading per-arch Node runtimes for ${arches.join(", ")}`,+ );+ }- console.log(- `[download-node] Downloading Node v${version} for ${PLATFORM}/${ARCH}`,- );- console.log(`[download-node] URL: ${url}`);+ for (const arch of arches) {+ const outDir = join(+ projectRoot,+ "resources",+ resourceDirName("node", arch, multi),+ );+ const spec = getPlatformSpec(version, PLATFORM, arch);+ const archiveName = `${spec.name}.${spec.ext}`;+ const url = `https://nodejs.org/dist/v${version}/${archiveName}`;+ const tmpFile = join(+ tmpdir(),+ `node-download-${arch}-${Date.now()}.${spec.ext}`,+ );- try {- // Clear any previous output so stale files (different Node version, or- // a stale resources/npm/ from the previous wrapper approach) don't- // linger in the bundle.- if (existsSync(outDir)) rmSync(outDir, { recursive: true, force: true });- mkdirSync(outDir, { recursive: true });+ console.log(+ `[download-node] Downloading Node v${version} for ${PLATFORM}/${arch}`,+ );+ console.log(`[download-node] URL: ${url}`);++ try {+ // Clear any previous output so stale files (different Node version, or+ // a stale resources/npm/ from the previous wrapper approach) don't+ // linger in the bundle.+ if (existsSync(outDir)) rmSync(outDir, { recursive: true, force: true });+ mkdirSync(outDir, { recursive: true });- console.log(`[download-node] Downloading to ${tmpFile}`);- await downloadFile(url, tmpFile);- console.log(`[download-node] Extracting to ${outDir}`);- extract(tmpFile, outDir, spec.ext);+ console.log(`[download-node] Downloading to ${tmpFile}`);+ await downloadFile(url, tmpFile);+ console.log(`[download-node] Extracting to ${outDir}`);+ extract(tmpFile, outDir, spec.ext);- verifyLayout();- pruneUnusedFiles();- failOnDanglingSymlinks();+ verifyLayout(outDir, PLATFORM);+ pruneUnusedFiles(outDir, PLATFORM);+ failOnDanglingSymlinks(outDir);- const mb = Math.round(dirSizeBytes(outDir) / (1024 * 1024));- console.log(`[download-node] β Node v${version} ready at ${outDir} (~${mb} MB)`);- } finally {- try {- rmSync(tmpFile, { force: true });- } catch {}+ const mb = Math.round(dirSizeBytes(outDir) / (1024 * 1024));+ console.log(`[download-node] β Node v${version} ready at ${outDir} (~${mb} MB)`);+ } finally {+ try {+ rmSync(tmpFile, { force: true });+ } catch {}+ }}}-main().catch((err) => {- console.error("[download-node] Error:", err.message);- process.exit(1);-});+// Run only when executed directly (`node scripts/download-node.mjs`), not+// when imported β __tests__/scripts/download-node.test.ts imports this+// module to exercise getPlatformSpec with zero network I/O.+// process.argv[1] is undefined when the module is plain-imported (vitest),+// and pathToFileURL(undefined) would throw, so guard on it first.+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((err) => {+ console.error("[download-node] Error:", err.message);+ process.exit(1);+ });+}diff --git a/scripts/download-uv.mjs b/scripts/download-uv.mjsindex c8fda754fc..4f99b0138f 100644--- a/scripts/download-uv.mjs+++ b/scripts/download-uv.mjs@@ -9,10 +9,15 @@* Usage:* node scripts/download-uv.mjs # uses latest GitHub release* UV_VERSION=0.7.0 node scripts/download-uv.mjs+ * ELECTRON_ARCH=universal node scripts/download-uv.mjs # macOS only** Output (per platform):* resources/bin/uv + resources/bin/uvx (macOS / Linux)* resources/bin/uv.exe + resources/bin/uvx.exe (Windows)+ *+ * With ELECTRON_ARCH=universal on macOS, both darwin slices are downloaded+ * into per-arch directories β the multi-arch layout is canonical in+ * scripts/download-arch-utils.mjs.*/import {@@ -26,28 +31,33 @@ import {import { get } from "node:https";import { tmpdir } from "node:os";import { dirname, join } from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { execFileSync } from "node:child_process";+import { resolveDownloadArches, resourceDirName } from "./download-arch-utils.mjs";const __dirname = dirname(fileURLToPath(import.meta.url));const projectRoot = join(__dirname, "..");-const outDir = join(projectRoot, "resources", "bin");// ββ Platform detection βββββββββββββββββββββββββββββββββββββββββββββββββββββββββconst PLATFORM = process.platform; // 'darwin' | 'linux' | 'win32'const ARCH = process.arch; // 'x64' | 'arm64'-function getPlatformSpec() {- if (PLATFORM === "darwin") {- const uvArch = ARCH === "arm64" ? "aarch64" : "x86_64";+/**+ * Map arch β uv's published release target for the given platform.+ * `arch` is a Node-style arch ("arm64" | "x64"); uv's Rust-style triplets+ * use "aarch64" / "x86_64".+ */+export function getPlatformSpec(arch = ARCH, platform = PLATFORM) {+ if (platform === "darwin") {+ const uvArch = arch === "arm64" ? "aarch64" : "x86_64";return {target: `uv-${uvArch}-apple-darwin`,ext: "tar.gz",binaries: ["uv", "uvx"],};}- if (PLATFORM === "linux") {+ if (platform === "linux") {// Only x64 is officially supported by uv for desktop buildsreturn {target: "uv-x86_64-unknown-linux-gnu",@@ -55,14 +65,14 @@ function getPlatformSpec() {binaries: ["uv", "uvx"],};}- if (PLATFORM === "win32") {+ if (platform === "win32") {return {target: "uv-x86_64-pc-windows-msvc",ext: "zip",binaries: ["uv.exe", "uvx.exe"],};}- throw new Error(`Unsupported platform for uv download: ${PLATFORM}`);+ throw new Error(`Unsupported platform for uv download: ${platform}`);}// ββ Version resolution ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -152,53 +162,76 @@ function extract(archivePath, targetDir, ext) {// ββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync function main() {- const spec = getPlatformSpec();+ // Resolve the version once (one GitHub API call / one UV_VERSION read)+ // so every arch in a universal build downloads the exact same release.const version = await resolveVersion();+ const arches = resolveDownloadArches();+ const multi = arches.length > 1;+ if (multi) {+ console.log(+ `[download-uv] macOS universal build: downloading per-arch uv runtimes for ${arches.join(", ")}`,+ );+ }- console.log(`[download-uv] Downloading uv v${version} for ${PLATFORM}/${ARCH}`);-- const filename = `${spec.target}.${spec.ext}`;- const url = `https://github.com/astral-sh/uv/releases/download/${version}/${filename}`;- const tmpFile = join(tmpdir(), `uv-download-${Date.now()}.${spec.ext}`);- const extractDir = join(tmpdir(), `uv-extract-${Date.now()}`);-- try {- mkdirSync(outDir, { recursive: true });- mkdirSync(extractDir, { recursive: true });-- console.log(`[download-uv] URL: ${url}`);- await downloadFile(url, tmpFile);- console.log(`[download-uv] Extracting to ${outDir}...`);- extract(tmpFile, extractDir, spec.ext);-- // Copy the required binaries to outDir- for (const bin of spec.binaries) {- const src = join(extractDir, bin);- const dest = join(outDir, bin);+ for (const arch of arches) {+ const spec = getPlatformSpec(arch);+ const outDir = join(+ projectRoot,+ "resources",+ resourceDirName("bin", arch, multi),+ );+ const filename = `${spec.target}.${spec.ext}`;+ const url = `https://github.com/astral-sh/uv/releases/download/${version}/${filename}`;+ const tmpFile = join(tmpdir(), `uv-download-${arch}-${Date.now()}.${spec.ext}`);+ const extractDir = join(tmpdir(), `uv-extract-${arch}-${Date.now()}`);++ console.log(`[download-uv] Downloading uv v${version} for ${PLATFORM}/${arch}`);++ try {+ mkdirSync(outDir, { recursive: true });+ mkdirSync(extractDir, { recursive: true });++ console.log(`[download-uv] URL: ${url}`);+ await downloadFile(url, tmpFile);+ console.log(`[download-uv] Extracting to ${outDir}...`);+ extract(tmpFile, extractDir, spec.ext);++ // Copy the required binaries to outDir+ for (const bin of spec.binaries) {+ const src = join(extractDir, bin);+ const dest = join(outDir, bin);++ if (!existsSync(src)) {+ throw new Error(`Expected binary not found after extraction: ${src}`);+ }- if (!existsSync(src)) {- throw new Error(`Expected binary not found after extraction: ${src}`);- }+ // copyFileSync works across filesystems (unlike renameSync with EXDEV)+ copyFileSync(src, dest);- // copyFileSync works across filesystems (unlike renameSync with EXDEV)- copyFileSync(src, dest);+ if (process.platform !== "win32") {+ chmodSync(dest, 0o755);+ }- if (process.platform !== "win32") {- chmodSync(dest, 0o755);+ console.log(`[download-uv] β ${dest}`);}-- console.log(`[download-uv] β ${dest}`);+ } finally {+ // Clean up temp files (best-effort)+ try { rmSync(tmpFile, { force: true }); } catch {}+ try { rmSync(extractDir, { recursive: true, force: true }); } catch {}}-- console.log("[download-uv] Done. Binaries are ready for bundling.");- } finally {- // Clean up temp files (best-effort)- try { rmSync(tmpFile, { force: true }); } catch {}- try { rmSync(extractDir, { recursive: true, force: true }); } catch {}}++ console.log("[download-uv] Done. Binaries are ready for bundling.");}-main().catch((err) => {- console.error("[download-uv] Error:", err.message);- process.exit(1);-});+// Run only when executed directly (`node scripts/download-uv.mjs`), not+// when imported β __tests__/scripts/download-uv.test.ts imports this module+// to exercise getPlatformSpec with zero network I/O. process.argv[1] is+// undefined when the module is plain-imported (vitest), and+// pathToFileURL(undefined) would throw, so guard on it first.+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((err) => {+ console.error("[download-uv] Error:", err.message);+ process.exit(1);+ });+}