Skip to content

The agent that grows with you

fix(desktop): prepare the locked Electron runtime explicitly before use

ahrazzlea9376424e51d
diff --git a/.github/workflows/e2e-desktop-core.yml b/.github/workflows/e2e-desktop-core.yml
index 0edc1802da9..06eeb153d27 100644
--- a/.github/workflows/e2e-desktop-core.yml
+++ b/.github/workflows/e2e-desktop-core.yml
@@ -53,20 +53,23 @@ jobs:
extras: '[]'
test-environment: 'true'
- # Full npm ci (not --ignore-scripts): electron's postinstall downloads
- # the binary we launch.
+ # Native addons still need lifecycle scripts. Electron 42 requires
+ # explicit binary preparation before the native fixtures launch.
- uses: ./.github/actions/retry
with:
command: npm ci
+ - name: Prepare locked Electron runtime
+ run: node scripts/build/electron-runtime.mjs --source .
+
- name: Build the desktop app
working-directory: apps/desktop
# The generator uses the runtime's Pillow + resvg-py, not a build-only venv.
run: npm run build
# Package the Linux app the way users get it (electron-builder --dir; no
- # installer formats, no publish). Reuses the npm-installed Electron dist,
- # so no download. packaged-smoke.spec.ts asserts the asarUnpack contract
+ # installer formats, no publish). The packaging preparer acquires its
+ # pinned archive separately. packaged-smoke.spec.ts asserts the asarUnpack contract
# on this output (#121097) and boots the packaged binary to a first chat.
- name: Package the desktop app (electron-builder --dir)
working-directory: apps/desktop
diff --git a/.github/workflows/e2e-desktop.yml b/.github/workflows/e2e-desktop.yml
index d24eeb2ffff..a3e6bb4123e 100644
--- a/.github/workflows/e2e-desktop.yml
+++ b/.github/workflows/e2e-desktop.yml
@@ -55,13 +55,16 @@ jobs:
test-environment: 'true'
prune-python-cache: true
- # Full npm ci (not --ignore-scripts): electron's postinstall
- # downloads the binary we launch, and node-pty's native build is
- # needed for the terminal pane.
+ # Full npm ci (not --ignore-scripts): native addons need lifecycle scripts;
+ # Electron's binary is prepared explicitly below.
+ # node-pty's native build is needed for the terminal pane.
- uses: ./.github/actions/retry
with:
command: npm ci
+ - name: Prepare locked Electron runtime
+ run: node scripts/build/electron-runtime.mjs --source .
+
# ── Build desktop app ─────────────────────────────────────────────
# The Playwright step below runs `npm run build` before testing so
# dist/ is always fresh — no separate build step needed here.
diff --git a/.github/workflows/js-tests.yml b/.github/workflows/js-tests.yml
index 19e1b4bf536..7efccf2c655 100644
--- a/.github/workflows/js-tests.yml
+++ b/.github/workflows/js-tests.yml
@@ -45,15 +45,14 @@ jobs:
# setup-pm caches npm downloads, not the installed workspace tree.
# The job then extracts the full workspace node_modules
- # again and runs the postinstalls again, which includes the Electron
- # binary fetch. This caches the installed tree itself, keyed on the
+ # again and runs the native postinstalls again. Electron's binary is
+ # prepared explicitly below. This caches the installed tree itself, keyed on the
# lockfile, and skips ``npm ci`` on an exact hit. There are no
# restore-keys: a partial hit leaves a stale tree, so anything other
# than an exact lockfile match reinstalls from the start.
#
- # This install runs WITH scripts, so the tree holds the postinstall
- # artifacts. The postinstall of electron unpacks its binary into
- # node_modules/electron/dist, which is inside the cached tree.
+ # This install runs WITH scripts, so the tree holds native lifecycle
+ # artifacts and the explicitly prepared Electron dist, both inside the cached tree.
#
# The ~/.cache/electron download cache stays out of the key on purpose.
# ``npm ci`` is skipped on a hit, so nothing reads that cache. It only
@@ -76,6 +75,9 @@ jobs:
with:
command: npm ci
+ - name: Prepare locked Electron runtime before parallel checks
+ run: node scripts/build/electron-runtime.mjs --source .
+
# Every check runs at the same time. The step fails only after all of
# them finish. There are two reasons this is not ``npm run --ws check``.
#
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index 2326a395b90..537a84f0057 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -1769,6 +1769,7 @@ def cmd_gui(args: argparse.Namespace):
raise FileNotFoundError(executable)
except OSError as exc:
print(f"✗ Prepared Electron runtime is missing: {exc}")
+ print(" From the project root, run: node scripts/build/electron-runtime.mjs --source .")
raise SystemExit(1) from exc
launch_command = [str(executable), "."]
else:
diff --git a/scripts/build/electron-runtime.mjs b/scripts/build/electron-runtime.mjs
new file mode 100644
index 00000000000..7eb8e9db010
--- /dev/null
+++ b/scripts/build/electron-runtime.mjs
@@ -0,0 +1,56 @@
+#!/usr/bin/env node
+import { execFileSync } from 'node:child_process'
+import { existsSync, readFileSync, statSync } from 'node:fs'
+import { dirname, join, relative, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { parseArgs } from 'node:util'
+
+// Do not require('electron'): Electron 42's entry point can acquire a binary.
+// Only this explicit preparation phase may execute the installed installer.
+/** @param {{ source: string, install?: boolean, env?: NodeJS.ProcessEnv }} options @returns {string} */
+export function prepareElectronRuntime({ source, install = true, env = process.env }) {
+ source = resolve(source)
+ const manifest = [join(source, 'apps/desktop/node_modules/electron/package.json'),
+ join(source, 'node_modules/electron/package.json')].find(existsSync)
+ if (!manifest) throw new Error('Missing prepared Electron dependency; install the locked desktop workspace first')
+ const packageRoot = dirname(manifest)
+ const { version } = JSON.parse(readFileSync(manifest, 'utf8'))
+ const desktop = JSON.parse(readFileSync(join(source, 'apps/desktop/package.json'), 'utf8'))
+ const lock = JSON.parse(readFileSync(join(source, 'package-lock.json'), 'utf8'))
+ const entry = lock.packages?.[relative(source, packageRoot).split('\\').join('/')]
+ const lockedVersion = entry?.link ? lock.packages[entry.resolved]?.version : entry?.version
+ if (version !== desktop.devDependencies?.electron || version !== lockedVersion) {
+ throw new Error('Installed Electron is not the desktop lock-pinned version')
+ }
+ const binaryName = process.platform === 'darwin' ? 'Electron.app/Contents/MacOS/Electron'
+ : process.platform === 'win32' ? 'electron.exe' : 'electron'
+ const executable = join(packageRoot, 'dist', binaryName)
+ const prepared = () => {
+ try {
+ return readFileSync(join(packageRoot, 'path.txt'), 'utf8').trim() === binaryName
+ && readFileSync(join(packageRoot, 'dist/version'), 'utf8').trim().replace(/^v/, '') === version
+ && statSync(executable).isFile()
+ } catch {
+ return false
+ }
+ }
+ if (prepared()) return executable
+ if (!install) throw new Error('Electron binary is missing or stale and lazy installs are disabled; run an explicit desktop build/update')
+ const excluded = new Set(['electron_skip_binary_download', 'electron_override_dist_path',
+ 'electron_install_arch', 'electron_install_platform', 'npm_config_arch', 'npm_config_platform'])
+ const installerEnv = Object.fromEntries(Object.entries(env).filter(([key]) => !excluded.has(key.toLowerCase())))
+ Object.assign(installerEnv, { ELECTRON_INSTALL_PLATFORM: process.platform, ELECTRON_INSTALL_ARCH: process.arch,
+ npm_config_platform: process.platform, npm_config_arch: process.arch })
+ console.log(`electron-runtime: preparing locked Electron ${version} (${process.platform}-${process.arch})...`)
+ execFileSync(process.execPath, [join(packageRoot, 'install.js')], { cwd: source, env: installerEnv, stdio: 'inherit' })
+ if (!prepared()) throw new Error('Electron installer did not produce the prepared host runtime')
+ return executable
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const { values } = parseArgs({ options: {
+ source: { type: 'string' }, 'no-install': { type: 'boolean', default: false },
+ } })
+ if (!values.source) throw new Error('--source is required')
+ prepareElectronRuntime({ source: values.source, install: !values['no-install'] })
+}
diff --git a/scripts/build/node-deps.mjs b/scripts/build/node-deps.mjs
index df2bbd9adec..8b0596a5b0f 100644
--- a/scripts/build/node-deps.mjs
+++ b/scripts/build/node-deps.mjs
@@ -8,6 +8,8 @@ import { delimiter, dirname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { parseArgs } from 'node:util'
+import { prepareElectronRuntime } from './electron-runtime.mjs'
+
// npm.cmd needs a shell. Use npm's JS entrypoint so paths remain argv on Windows.
export function npmCommand({ env = process.env } = {}) {
const names = process.platform === 'win32' ? ['npm.cmd', 'npm'] : ['npm']
@@ -106,6 +108,8 @@ export function prepareNodeDependencies({ source, workspaces, env = process.env,
}
return path
}))].sort()
+ const prepareElectron = selected.includes('apps/desktop')
+ && Boolean(JSON.parse(readFileSync(join(source, 'apps/desktop/package.json'), 'utf8')).devDependencies?.electron)
const [node, npm] = npmCommand({ env })
const npmVersion = npmManifestVersion(npm) ?? execFileSync(
node, [npm, '--version'], { cwd: source, env, encoding: 'utf8' }).trim()
@@ -141,6 +145,7 @@ export function prepareNodeDependencies({ source, workspaces, env = process.env,
}
const key = inputs.digest('hex')
if (reuse && completedInstallMatches({ source, receipt, hiddenLock, key, nativeKey })) {
+ if (prepareElectron) prepareElectronRuntime({ source, install, env })
console.log(`node-deps: reusing completed install (${selected.join(', ')})`)
return { source, workspaces: selected }
}
@@ -150,6 +155,7 @@ export function prepareNodeDependencies({ source, workspaces, env = process.env,
rmSync(nativeReceipt, { force: true })
console.log(`node-deps: installing workspace dependencies with npm ci (${selected.join(', ')})...`)
runNpmCi(node, npm, args, { source, env })
+ if (prepareElectron) prepareElectronRuntime({ source, install, env })
if (reuse) {
const completed = `${key}\n${createHash('sha256').update(readFileSync(hiddenLock)).digest('hex')}\n`
writeFileSync(receipt, completed)
diff --git a/scripts/ci/desktop_build_cache.py b/scripts/ci/desktop_build_cache.py
index 0432a090dba..a483fe06190 100644
--- a/scripts/ci/desktop_build_cache.py
+++ b/scripts/ci/desktop_build_cache.py
@@ -28,7 +28,7 @@ _INPUT_FILES = (
"scripts/bundles/desktop_prepare.py", "scripts/bundles/desktop_toolchain.py",
"scripts/bundles/desktop_inputs.py", "scripts/bundles/native.py", "scripts/bundles/native_prepared.py",
"scripts/bundles/native_build.py",
- "scripts/build/node-deps.mjs", "scripts/build/icon_environment.py",
+ "scripts/build/node-deps.mjs", "scripts/build/electron-runtime.mjs", "scripts/build/icon_environment.py",
"pm/native_build.py", "scripts/windows-build-deps.ps1",
"apps/desktop/scripts/stage-native-deps.mjs", "apps/desktop/scripts/prepare-packaging-tools.mjs",
"apps/desktop/scripts/build-command-screenshot-monitor.mjs",
diff --git a/tests-js/electron-runtime.test.mjs b/tests-js/electron-runtime.test.mjs
new file mode 100644
index 00000000000..49e914c5b4b
--- /dev/null
+++ b/tests-js/electron-runtime.test.mjs
@@ -0,0 +1,83 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+
+import { afterEach, expect, test } from 'vitest'
+
+import { prepareElectronRuntime } from '../scripts/build/electron-runtime.mjs'
+
+const roots = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+function json(file, value) {
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, JSON.stringify(value))
+}
+
+function fixture(layout = 'apps/desktop/node_modules/electron') {
+ const source = mkdtempSync(join(tmpdir(), 'electron preparation with spaces-'))
+ roots.push(source)
+ const packageRoot = join(source, layout)
+ json(join(source, 'apps/desktop/package.json'), { devDependencies: { electron: '42.11.12' } })
+ json(join(source, 'package-lock.json'), { packages: { [layout]: { version: '42.11.12' } } })
+ json(join(packageRoot, 'package.json'), { name: 'electron', version: '42.11.12', main: 'index.js' })
+ // Electron 42's lazy package entry point must never execute during validation.
+ writeFileSync(join(packageRoot, 'index.js'), `require('node:fs').writeFileSync(__dirname + '/lazy-entry-executed', 'yes'); throw new Error('unexpected lazy entry')`)
+ const binaryName = process.platform === 'darwin' ? 'Electron.app/Contents/MacOS/Electron'
+ : process.platform === 'win32' ? 'electron.exe' : 'electron'
+ writeFileSync(join(packageRoot, 'install.js'), `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ if (process.env.ELECTRON_SKIP_BINARY_DOWNLOAD || process.env.ELECTRON_OVERRIDE_DIST_PATH) throw new Error('unexpected installer override');
+ if (process.env.ELECTRON_INSTALL_PLATFORM !== process.platform || process.env.ELECTRON_INSTALL_ARCH !== process.arch) throw new Error('wrong host');
+ fs.appendFileSync(path.join(__dirname, 'installer-calls'), 'install\\n');
+ const binary = path.join(__dirname, 'dist', ${JSON.stringify(binaryName)});
+ fs.mkdirSync(path.dirname(binary), { recursive: true });
+ fs.writeFileSync(binary, 'synthetic executable');
+ fs.writeFileSync(path.join(__dirname, 'dist/version'), 'v42.11.12');
+ fs.writeFileSync(path.join(__dirname, 'path.txt'), ${JSON.stringify(binaryName)});
+ `)
+ return { source, packageRoot, executable: join(packageRoot, 'dist', binaryName) }
+}
+
+test.each(['apps/desktop/node_modules/electron', 'node_modules/electron'])('explicitly prepares a fresh locked %s runtime once', layout => {
+ const { source, packageRoot, executable } = fixture(layout)
+ const env = { ...process.env, ELECTRON_SKIP_BINARY_DOWNLOAD: '1', ELECTRON_OVERRIDE_DIST_PATH: 'foreign',
+ ELECTRON_INSTALL_PLATFORM: 'foreign', ELECTRON_INSTALL_ARCH: 'foreign' }
+ expect(prepareElectronRuntime({ source, env })).toBe(executable)
+ expect(readFileSync(join(packageRoot, 'installer-calls'), 'utf8')).toBe('install\n')
+ expect(prepareElectronRuntime({ source, install: false })).toBe(executable)
+ expect(prepareElectronRuntime({ source })).toBe(executable)
+ expect(readFileSync(join(packageRoot, 'installer-calls'), 'utf8')).toBe('install\n')
+ expect(existsSync(join(packageRoot, 'lazy-entry-executed'))).toBe(false)
+})
+
+test('read-only validation refuses missing or stale binaries without executing either entry point', () => {
+ const { source, packageRoot, executable } = fixture()
+ expect(() => prepareElectronRuntime({ source, install: false })).toThrow(/disabled/)
+ expect(existsSync(join(packageRoot, 'installer-calls'))).toBe(false)
+ prepareElectronRuntime({ source })
+ rmSync(executable)
+ expect(() => prepareElectronRuntime({ source, install: false })).toThrow(/disabled/)
+ prepareElectronRuntime({ source })
+ writeFileSync(join(packageRoot, 'dist/version'), 'v40.10.2')
+ expect(() => prepareElectronRuntime({ source, install: false })).toThrow(/disabled/)
+ expect(readFileSync(join(packageRoot, 'installer-calls'), 'utf8')).toBe('install\ninstall\n')
+ expect(existsSync(join(packageRoot, 'lazy-entry-executed'))).toBe(false)
+})
+
+test('propagates installer failure and rejects success without a complete runtime', () => {
+ const { source, packageRoot } = fixture()
+ writeFileSync(join(packageRoot, 'install.js'), 'process.exit(13)')
+ expect(() => prepareElectronRuntime({ source })).toThrow()
+ writeFileSync(join(packageRoot, 'install.js'), '')
+ expect(() => prepareElectronRuntime({ source })).toThrow(/did not produce/)
+ expect(() => prepareElectronRuntime({ source, install: false })).toThrow(/disabled/)
+})
+
+test('refuses a foreign installed version before running its installer', () => {
+ const { source, packageRoot } = fixture()
+ json(join(packageRoot, 'package.json'), { version: '41.10.6' })
+ expect(() => prepareElectronRuntime({ source })).toThrow(/lock-pinned/)
+ expect(existsSync(join(packageRoot, 'installer-calls'))).toBe(false)
+})
diff --git a/tests/hermes_cli/test_source_build.py b/tests/hermes_cli/test_source_build.py
index 23fdd980946..e34d2d63a9b 100644
--- a/tests/hermes_cli/test_source_build.py
+++ b/tests/hermes_cli/test_source_build.py
@@ -145,7 +145,7 @@ def source_checkout(tmp_path, monkeypatch):
scripts = root / "scripts" / "build"
scripts.mkdir(parents=True)
repository = Path(__file__).resolve().parents[2]
- for name in ("node-deps.mjs", "freshness.mjs", "frontend-common.mjs"):
+ for name in ("node-deps.mjs", "electron-runtime.mjs", "freshness.mjs", "frontend-common.mjs"):
shutil.copy2(repository / "scripts/build" / name, scripts / name)
(root / ".gitignore").write_text("node_modules/\n**/dist/\n", encoding="utf-8")
return root, acquired