CodeNomad/scripts/test-electron-owner-close.mjs
Pascal André 78a734cb6b
perf(electron): run the backend with Electron's Node (#1304)
## Summary

Electron already ships the Node runtime the backend needs. The Electron
package now launches the CodeNomad server through `process.execPath`
with `ELECTRON_RUN_AS_NODE=1` and keeps only npm (from the pinned
`.node-version` archive), dropping the redundant standalone `node.exe`
(~89 MiB on Windows). Tauri keeps its full bundled runtime unchanged.

## Changes

- **Launch**: `process-manager.ts` runs the backend with Electron's own
executable in run-as-Node mode; `managed-node.ts` is removed.
- **Resources**: `prepare-node-runtime.cjs` gains an npm-only layout
requested by `electron-app/scripts/prepare-resources.js`; Tauri keeps
the full Node + npm layout.
- **npm discovery**: `bundledNpm()` (`npm-runtime.ts`) finds npm in
Electron resources (Windows, Linux, macOS `.app/Contents/Resources`)
while preserving Node/Tauri layouts.
- **npm lifecycle scripts**: `@opencode/cli` runs `node
./postinstall.mjs`; installation (`shared-installation.ts`) and native
upgrades (`native-upgrade.ts`) get a private, scoped `node` command
pointing at the Electron executable, removed afterwards. The shared
OpenCode daemon never inherits `ELECTRON_RUN_AS_NODE`.
- **Checks/CI**: packaged-resource smoke, `verify-bundled-node`,
`build.js` and `build-and-upload.yml` separate the Electron (npm-only)
and Tauri contracts; `test-opencode-*-native.mjs` and the desktop setup
qualification can target the packaged Electron runtime without a system
Node on PATH.
- **Docs**: `dev-docs/RUNTIME_MAINTENANCE.md` (the Electron package
follows Electron's Node version), `dev-docs/OPENCODE_RUNTIME_SETUP.md`,
and `server.md` / `updates.md` help pages in all ten locales.

## Validation

- Electron 39.0.0 → Node 22.20.0; npm 11.19.0 (engines `^20.17.0 ||
>=22.9.0`).
- Packaged Windows ZIP and Linux (`linux-unpacked` + extracted DEB,
Ubuntu 24.04 VM): backend reaches ready, API answers 200, both backend
processes run as the app executable with `ELECTRON_RUN_AS_NODE=1`, no
Node in resources or on PATH, clean exit with no orphan and the
executable released.
- `test-opencode-install-native` (2.2.3), `test-opencode-upgrade-native`
(→ 2.2.5, isolated service PID kept) and
`test-opencode-legacy-replacement-native` (1.18.10 → 2.2.5) pass on
Windows and Linux with the packaged Electron runtime.
- Typechecks (server, Electron), resource tests 11/11, `opencode-update`
tests (Windows 66 pass / 1 POSIX skip; Linux 62 pass / 5 Windows skips),
help validation.
- The full Electron suite on Windows shows intermittent failures in
`process-stop.test.ts` and `native-service-start.test.ts` (PowerShell
capture timeout of 1.5 s); they reproduce identically on `dev`
(30527e58d) and the files are unchanged here.

## Size (same machine and options)

| | Before | After | Delta |
|---|---:|---:|---:|
| Windows `resources` | 344 274 218 B | 250 740 778 B | −89.20 MiB |
| Windows ZIP | 221 737 165 B | 188 286 779 B | −31.90 MiB |
| Linux `resources` | 377 016 175 B | 250 408 680 B | −120.74 MiB |
| Linux DEB | 138 393 810 B | 107 123 634 B | −29.82 MiB |

macOS was not exercised at runtime (path handling is covered by unit
tests; arm64/x64 builds run in CI).
2026-11-06 06:35:53 +01:00

80 lines
4 KiB
JavaScript

import assert from "node:assert/strict"
import { spawn } from "node:child_process"
import { createRequire } from "node:module"
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { fileURLToPath } from "node:url"
import { build } from "esbuild"
// Real native destruction order, isolated from the desktop profile and backend.
const root = fileURLToPath(new URL("../", import.meta.url))
const require = createRequire(new URL("../packages/electron-app/package.json", import.meta.url))
const directory = await mkdtemp(join(tmpdir(), "codenomad-owner-close-"))
try {
const entry = join(directory, "fixture.mjs")
await build({
stdin: { resolveDir: root, sourcefile: "owner-close-fixture.ts", loader: "ts", contents: `
import assert from "node:assert/strict"
import { app, BrowserWindow } from "electron"
import { BrowserController } from "./packages/electron-app/electron/main/browser-controller"
import { MultiwindowLifecycle } from "./packages/electron-app/electron/main/multiwindow-lifecycle"
process.on("uncaughtException", error => { console.error(error); app.exit(1) })
process.on("unhandledRejection", error => { console.error(error); app.exit(1) })
void app.whenReady().then(async () => {
const controller = new BrowserController(() => {})
let closed = 0
const makeWindow = () => {
const window = new BrowserWindow({ show: false })
controller.observeOwner(window)
window.on("closed", () => {
assert.equal(window.isDestroyed(), true)
// Demonstrates why reading this getter inside the old callback failed.
assert.throws(() => window.webContents, /Object has been destroyed/)
closed++
})
return window
}
const last = makeWindow()
const destroyed = makeWindow()
destroyed.destroy()
const ordinary = makeWindow()
const ordinaryClosed = new Promise(resolve => ordinary.once("closed", resolve))
ordinary.close()
await ordinaryClosed
assert.equal(closed, 2)
const lifecycle = new MultiwindowLifecycle({
app, getLocalWindows: () => [], getAllWindows: () => BrowserWindow.getAllWindows(),
clientStateManager: { isPrimary: false, flush: async () => {}, drainAndReleasePrimary: async () => {} },
cliManager: { shutdown: async () => {} }, removeWindowState: async () => true,
getAllowedRendererOrigins: () => [], isTrustedRendererOrigin: () => false,
})
lifecycle.attachRemote(last)
lifecycle.registerAppEvents()
app.on("quit", () => {
assert.equal(closed, 3)
console.log("PASS: destroy, ordinary close and final lifecycle exit")
})
last.close()
})
` },
outfile: entry, bundle: true, platform: "node", format: "esm", external: ["electron"], logLevel: "silent",
})
const env = { ...process.env }
delete env.ELECTRON_RUN_AS_NODE
delete env.ELECTRON_NO_ASAR
// Some Linux test hosts disable unprivileged user namespaces. This opt-in
// only affects this empty-window fixture, which loads no page or backend.
const sandboxArgs = process.platform === "linux" && process.argv.includes("--no-sandbox") ? ["--no-sandbox"] : []
const child = spawn(require("electron"), [entry, `--user-data-dir=${join(directory, "profile")}`, ...sandboxArgs], { env, stdio: ["ignore", "pipe", "pipe"] })
let output = ""
child.stdout.on("data", data => { output += data })
child.stderr.on("data", data => { output += data })
const timeout = setTimeout(() => child.kill(), 30_000)
const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("exit", resolve) }).finally(() => clearTimeout(timeout))
assert.equal(code, 0, output)
assert.match(output, /PASS: destroy, ordinary close and final lifecycle exit/)
console.log("Real Electron owner-close regression passed.")
} finally {
await rm(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
}