Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(desktop): ship node-pty with the app so terminals can spawn (#393)

Yaowei Zheng069d77bd95c1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 18b75bdf..d09cdecd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -62,11 +62,13 @@ jobs:
# macOS: the same build/typecheck/test gates on macos-latest (arm64). This is the only job
# where the terminal's pty suites run on darwin — node-pty compiles against the runner's
- # toolchain and its darwin-only spawn-helper actually executes — and the standalone
- # terminal smoke script then re-runs node-pty under Electron's own Node
- # (ELECTRON_RUN_AS_NODE), the runtime the packaged app's server really uses. A macOS
- # terminal regression that once shipped as a silently empty panel fails here instead.
- # No format:check (same files as ubuntu) and no live-LLM e2e (ubuntu-only budget).
+ # toolchain and its darwin-only spawn-helper actually executes — and the terminal smoke
+ # script then re-runs node-pty under Electron's own Node (ELECTRON_RUN_AS_NODE), resolved
+ # from the built desktop bundle: the same module lookup, on the same runtime, that the
+ # packaged app's server performs. It runs after the build because that staged copy is a
+ # build output. A macOS terminal regression that once shipped as a silently empty panel
+ # fails here instead. No format:check (same files as ubuntu) and no live-LLM e2e
+ # (ubuntu-only budget).
ci-macos:
runs-on: macos-latest
steps:
diff --git a/changelog/unreleased/2026-08-21-desktop-terminal-node-pty.md b/changelog/unreleased/2026-08-21-desktop-terminal-node-pty.md
new file mode 100644
index 00000000..e0a394b8
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-desktop-terminal-node-pty.md
@@ -0,0 +1,38 @@
+# Desktop terminals: node-pty ships with the app again
+
+- **Date:** 2026-08-21
+- **Type:** fix
+- **Scope:** `desktop`, `ci`
+- **PR:** [#393](https://github.com/Prism-Shadow/penguin-harness/pull/393)
+
+[中文版](2026-08-21-desktop-terminal-node-pty.zh.md)
+
+Opening a terminal in the desktop app failed with `POST /api/terminals` → 500
+`terminal_spawn_failed`, reporting `Cannot find module 'node-pty'` from
+`packages/desktop/dist/server.js`. node-pty is a native module and the only dependency the
+bundler cannot absorb: the server reaches it through a runtime `require`, and node-pty's own
+loader then resolves its binary relative to its package directory. `pnpm build` now stages a
+node-pty package directory into `packages/desktop/dist/node_modules`, which both a source run
+and a packaged app resolve, and `electron-builder.yml` ships it.
+
+## Details
+
+- `src/pty-payload.ts` selects and copies node-pty's shipping subset — its manifest, its own MIT
+ license and vendored winpty's, `lib/`, the `build/Release` binding compiled at install time,
+ and the `prebuilds/` binaries — dropping sourcemaps, node-pty's own tests, its TypeScript
+ sources, node-gyp inputs, the vendored winpty sources and 44 MB of Windows `.pdb` debug
+ symbols. The staged copy is 5.4 MB and covers darwin arm64/x64 and win32 x64/arm64 alongside
+ the host build.
+- The staging step restores the exec bit on every `spawn-helper` it copies. node-pty publishes
+ that darwin side binary as `0644`, which makes `posix_spawnp` refuse it; fixing the mode
+ before the app is packed keeps a signed `.app` under `/Applications`, where the server's
+ runtime repair cannot write, out of that failure.
+- `scripts/build-assets.mjs` resolves node-pty from `packages/server`, where pnpm installs it,
+ and fails the build when the staged copy carries no `pty.node` the build host can load.
+ node-pty prebuilds darwin and win32 but not Linux, so a Linux install whose node-gyp step
+ never ran still stages three bindings, none of which that app could load.
+- The `pnpm desktop` preflight checks the staged package, so a stale build says so at launch
+ instead of at the first terminal.
+- `scripts/terminal-smoke.mjs` now loads node-pty the way the server bundle does — a bare
+ `require("node-pty")` anchored at `dist/server.js` — under Electron's own Node, so CI's macOS
+ job covers module resolution as well as the ABI and the spawn.
diff --git a/changelog/unreleased/2026-08-21-desktop-terminal-node-pty.zh.md b/changelog/unreleased/2026-08-21-desktop-terminal-node-pty.zh.md
new file mode 100644
index 00000000..33d19b6b
--- /dev/null
+++ b/changelog/unreleased/2026-08-21-desktop-terminal-node-pty.zh.md
@@ -0,0 +1,30 @@
+# 桌面终端:node-pty 重新随应用分发
+
+- **Date:** 2026-08-21
+- **Type:** fix
+- **Scope:** `desktop`, `ci`
+- **PR:** [#393](https://github.com/Prism-Shadow/penguin-harness/pull/393)
+
+[English](2026-08-21-desktop-terminal-node-pty.md)
+
+在桌面应用中打开终端会失败:`POST /api/terminals` 返回 500 `terminal_spawn_failed`,并报告
+`packages/desktop/dist/server.js` 处 `Cannot find module 'node-pty'`。node-pty 是原生模块,也是打包器唯一无法吸收的
+依赖:服务端通过运行时 `require` 取用它,而 node-pty 自己的加载器再按包相对路径解析二进制文件。`pnpm build` 现在会把一份
+node-pty 包目录落到 `packages/desktop/dist/node_modules`,源码运行与打包后的应用都能解析到它,`electron-builder.yml`
+则负责把它装进安装包。
+
+## 细节
+
+- `src/pty-payload.ts` 挑选并复制 node-pty 中真正需要分发的部分——清单文件、它自身的 MIT 许可证与内置 winpty 的许可证、
+ `lib/`、安装时编译出的 `build/Release` binding,以及 `prebuilds/` 下的预编译二进制——丢弃 source map、node-pty
+ 自带的测试、其 TypeScript 源码、node-gyp 输入、内置的 winpty 源码,以及 44 MB 的 Windows `.pdb` 调试符号。落盘副本为
+ 5.4 MB,除宿主机自身的构建产物外,还覆盖 darwin arm64/x64 与 win32 x64/arm64。
+- 落盘时会为复制到的每个 `spawn-helper` 补回可执行位。node-pty 发布的这个 darwin 辅助二进制权限为 `0644`,会导致
+ `posix_spawnp` 拒绝执行;在打包前修正权限,可以避免签名后位于 `/Applications` 下、服务端运行时无法写入修复的 `.app`
+ 落入该故障。
+- `scripts/build-assets.mjs` 从 pnpm 实际安装它的 `packages/server` 解析 node-pty,若落盘副本中没有构建宿主机能加载的
+ `pty.node` 则直接构建失败。node-pty 只为 darwin 与 win32 提供预编译产物、不含 Linux,因此在 Linux 上即使 node-gyp
+ 步骤未执行,落盘副本里仍会有三份该应用无法加载的 binding。
+- `pnpm desktop` 的预检会检查这份落盘的包,构建产物过期时在启动阶段就报出,而不是等到第一次打开终端。
+- `scripts/terminal-smoke.mjs` 改为按服务端产物的方式加载 node-pty——以 `dist/server.js` 为锚点的裸
+ `require("node-pty")`——并在 Electron 自带的 Node 下运行,因此 CI 的 macOS 任务除 ABI 与 spawn 之外,也覆盖了模块解析。
diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.yml
index 39a58279..9f435863 100644
--- a/packages/desktop/electron-builder.yml
+++ b/packages/desktop/electron-builder.yml
@@ -1,9 +1,9 @@
# electron-builder config for the desktop shell installers.
#
# The app directory is this package itself: `pnpm build` emits self-contained bundles of
-# the shell, the server and the CLI into dist/ (see tsup.config.ts), so the app has no
-# runtime dependencies and electron-builder ships no node_modules — `files` below is the
-# complete description of what goes inside an installer.
+# the shell, the server and the CLI into dist/ (see tsup.config.ts), so the app carries no
+# dependency tree for electron-builder to collect — `files` below is the complete
+# description of what goes inside an installer.
#
# asar is off on purpose: the shell forks the server as a child process, the skill
# library reads its .md files from disk, and agent commands spawn real shells — plain
@@ -34,6 +34,12 @@ directories:
files:
- dist/**/*
- "!dist/**/*.map"
+ # The staged node-pty package (scripts/build-assets.mjs, src/pty-payload.ts). electron-builder
+ # adds a `!**/node_modules/**` of its own: at the head of this list when no non-negated
+ # pattern names node_modules, or immediately BEFORE the first one that does. Naming it here
+ # is what moves that exclusion behind `dist/**/*` — last match wins, so this one node_modules
+ # ships and any other that appears under dist/ does not.
+ - dist/node_modules/**/*
- bin/**/*
- skills/**/*
- package.json
@@ -47,7 +53,10 @@ extraMetadata:
name: penguin-harness-desktop
homepage: https://github.com/Prism-Shadow/penguin-harness
asar: false
-# Nothing to rebuild: the app ships no node_modules and no native modules.
+# Nothing to rebuild: the only native module is node-pty, staged into dist/node_modules as
+# the binaries its npm tarball prebuilds (darwin, win32) or as the binding pnpm's install
+# already compiled on this host (Linux). Both are N-API, so Electron's Node loads them as
+# published — scripts/terminal-smoke.mjs is what proves it.
npmRebuild: false
nodeGypRebuild: false
diff --git a/packages/desktop/scripts/build-assets.mjs b/packages/desktop/scripts/build-assets.mjs
index 7ad11fa2..9eb37cab 100644
--- a/packages/desktop/scripts/build-assets.mjs
+++ b/packages/desktop/scripts/build-assets.mjs
@@ -10,6 +10,9 @@
* copy lands where that same package-relative lookup finds it. (The server's web-dist
* lookup works the same way and is satisfied by electron-builder's file mapping when
* packaging; a source run falls back to packages/web/dist on its own.)
+ * - `dist/node_modules/node-pty` — the one dependency the bundler cannot absorb, because the
+ * server loads it as a native module through a runtime `require` and node-pty's own loader
+ * then resolves its binary package-relative. See src/pty-payload.ts.
* - `dist/icon.png` — the runtime window icon, read app-path-relative (see src/app-icon.ts).
* build/ is electron-builder's buildResources directory and does not ship inside the app.
* - `bin/penguin`, `bin/penguin.cmd` — the CLI launchers, whose script text lives in
@@ -18,6 +21,7 @@
* Run from anywhere (after tsup); all paths derive from this file's location.
*/
import fs from "node:fs";
+import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -25,9 +29,13 @@ const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const distDir = path.join(pkgDir, "dist");
const launcherModule = path.join(distDir, "launcher.js");
-if (!fs.existsSync(launcherModule)) {
- console.error("[build-assets] dist/launcher.js is missing — run `tsup` first.");
- process.exit(1);
+for (const required of [launcherModule, path.join(distDir, "pty-payload.js")]) {
+ if (!fs.existsSync(required)) {
+ console.error(
+ `[build-assets] dist/${path.basename(required)} is missing — run \`tsup\` first.`,
+ );
+ process.exit(1);
+ }
}
const skillsSrc = path.resolve(pkgDir, "..", "skills", "skills");
@@ -42,6 +50,31 @@ if (!fs.existsSync(iconSrc)) {
}
fs.copyFileSync(iconSrc, path.join(distDir, "icon.png"));
+// node-pty, resolved from the package that depends on it: under pnpm it is installed into
+// packages/server/node_modules, out of reach of any lookup anchored in this package.
+const serverRequire = createRequire(path.resolve(pkgDir, "..", "server", "package.json"));
+let ptySrc;
+try {
+ ptySrc = path.dirname(serverRequire.resolve("node-pty/package.json"));
+} catch {
+ console.error("[build-assets] node-pty is not installed — run `pnpm install` at the repo root.");
+ process.exit(1);
+}
+const { stageNodePty, nativeBindings, hostBinding, NODE_PTY_RELDIR } = await import(
+ pathToFileURL(path.join(distDir, "pty-payload.js")).href
+);
+const ptyFiles = stageNodePty(ptySrc, path.join(pkgDir, ...NODE_PTY_RELDIR));
+const bindings = nativeBindings(ptyFiles);
+// A pty.node for some other platform is not a payload: node-pty prebuilds darwin and win32,
+// so a Linux install whose node-gyp step was skipped still stages three of them.
+if (hostBinding(ptyFiles) === undefined) {
+ const carried = bindings.length === 0 ? "none at all" : `only ${bindings.join(", ")}`;
+ console.error(
+ `[build-assets] the node-pty install at ${ptySrc} has no pty.node for ${process.platform}-${process.arch} (${carried}) — reinstall it so its build script runs (pnpm-workspace.yaml allows it).`,
+ );
+ process.exit(1);
+}
+
const { posixLauncherScript, windowsLauncherScript } = await import(
pathToFileURL(launcherModule).href
);
@@ -52,4 +85,6 @@ fs.writeFileSync(path.join(binDir, "penguin"), posixLauncherScript(), { mode: 0o
fs.chmodSync(path.join(binDir, "penguin"), 0o755);
fs.writeFileSync(path.join(binDir, "penguin.cmd"), windowsLauncherScript());
-console.log("[build-assets] done: skills/, dist/icon.png, bin/");
+console.log(
+ `[build-assets] done: skills/, dist/icon.png, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,
+);
diff --git a/packages/desktop/scripts/preflight.mjs b/packages/desktop/scripts/preflight.mjs
index df615412..84e2ae11 100644
--- a/packages/desktop/scripts/preflight.mjs
+++ b/packages/desktop/scripts/preflight.mjs
@@ -17,6 +17,9 @@ const problems = [];
for (const [what, rel] of [
["the desktop shell build", "dist/main.js"],
["the embedded server bundle", "dist/server.js"],
+ // Where the server bundle's `require("node-pty")` lands; without it every terminal
+ // session fails to spawn, and only once the user opens a terminal panel.
+ ["the staged node-pty package", "dist/node_modules/node-pty/package.json"],
["the skill library copy", "skills"],
["the web frontend build", "../web/dist/index.html"],
]) {
diff --git a/packages/desktop/scripts/terminal-smoke.mjs b/packages/desktop/scripts/terminal-smoke.mjs
index d971d940..5752386c 100644
--- a/packages/desktop/scripts/terminal-smoke.mjs
+++ b/packages/desktop/scripts/terminal-smoke.mjs
@@ -3,27 +3,33 @@
* the server as an Electron utilityProcess, so node-pty's native binding — and, on macOS,
* its `spawn-helper` side binary — must work under Electron's Node, not the Node that
* compiled the tree. ELECTRON_RUN_AS_NODE is that same runtime, so this loads node-pty
- * the way the server resolves it, spawns a real shell and waits for one byte of output.
+ * exactly as the server bundle does — a bare `require("node-pty")` anchored at
+ * dist/server.js, which reaches the copy scripts/build-assets.mjs stages into
+ * dist/node_modules — then spawns a real shell and waits for one byte of output.
*
- * A platform where the pty cannot load or spawn fails here with the real error, instead
- * of shipping a desktop app whose terminal panel silently stays empty (the macOS bug
- * this guards against). Run standalone (CI's ci-macos job) after `pnpm install`; it needs
- * no build outputs and does not touch the staging tree.
+ * A platform where the pty cannot be resolved, loaded or spawned fails here with the real
+ * error, instead of shipping a desktop app whose terminal panel silently stays empty (the
+ * macOS bug this guards against). Run after `pnpm build` (CI's ci-macos job); the staged
+ * copy is a build output, so an unbuilt tree fails with that, not with a pty error.
*/
import { execFileSync } from "node:child_process";
-import { createRequire } from "node:module";
+import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
-const repoRoot = path.resolve(pkgDir, "..", "..");
+const serverBundle = path.join(pkgDir, "dist", "server.js");
-// Resolve node-pty exactly the way the server package does.
-const serverRequire = createRequire(path.join(repoRoot, "packages", "server", "package.json"));
-const ptyPath = path.dirname(serverRequire.resolve("node-pty/package.json"));
+if (!fs.existsSync(serverBundle)) {
+ console.error(`[terminal-smoke] ${serverBundle} is missing — run \`pnpm -r build\` first.`);
+ process.exit(1);
+}
const smoke = `
- const pty = require(${JSON.stringify(ptyPath)});
+ const { createRequire } = require("node:module");
+ const { pathToFileURL } = require("node:url");
+ // The server bundle's own line: packages/server/src/platform/terminal/pty-module.ts.
+ const pty = createRequire(pathToFileURL(${JSON.stringify(serverBundle)}).href)("node-pty");
const shell = process.platform === "win32" ? "cmd.exe" : "/bin/sh";
const term = pty.spawn(shell, [], { name: "xterm-256color", cols: 40, rows: 10, cwd: process.cwd(), env: process.env });
const timer = setTimeout(() => { console.error("no pty output within 15s"); process.exit(1); }, 15000);
diff --git a/packages/desktop/src/pty-payload.ts b/packages/desktop/src/pty-payload.ts
new file mode 100644
index 00000000..0e57fc1c
--- /dev/null
+++ b/packages/desktop/src/pty-payload.ts
@@ -0,0 +1,125 @@
+/**
+ * Staging node-pty into the app directory — pure filesystem logic, no Electron imports
+ * (unit-tested).
+ *
+ * node-pty is the one native module the embedded server needs, and the only dependency the
+ * bundler cannot absorb. The server reaches it through `createRequire(import.meta.url)
+ * ("node-pty")` (packages/server/src/platform/terminal/pty-module.ts), and node-pty's own
+ * loader then resolves `../build/Release/pty.node` or `../prebuilds/<platform>-<arch>/pty.node`
+ * relative to its lib/ directory — on darwin also `../<that dir>/spawn-helper`, a side binary
+ * it execs. All of that needs a real package directory on disk, so scripts/build-assets.mjs
+ * writes one to `dist/node_modules/node-pty`: the first node_modules the resolver meets walking
+ * up from dist/server.js, in a source run and inside a packaged app alike.
+ *
+ * Not the whole npm install. node-pty's prebuilds carry ~44 MB of Windows .pdb debug symbols,
+ * and its TypeScript sources, node-gyp inputs and vendored winpty sources are build-time only —
+ * out of that vendored tree only the license ships, alongside the winpty binaries built from it.
+ * scripts/deploy.mjs selects the same way for the copy an HMR push carries as an asset, but not
+ * over the same set: that rule is looser, keeping the sourcemaps and node-pty's own tests and
+ * shipping no license. Same shape, different destination and transport — and separate, so
+ * changing one leaves the other exactly as it was.
+ */
+import fs from "node:fs";
+import path from "node:path";
+
+/** Where the bundled server resolves node-pty, relative to the app directory. */
+export const NODE_PTY_RELDIR = ["dist", "node_modules", "node-pty"];
+
+/**
+ * Individual files that ship at their own path: the manifest whose `main` the require lands on,
+ * node-pty's MIT license, and winpty's — node-pty's license does not cover that vendored
+ * project, whose winpty.dll and winpty-agent.exe ship in the win32 prebuilds below.
+ */
+const SHIPPED_FILES = ["package.json", "LICENSE", "deps/winpty/LICENSE"];
+
+/**
+ * Package-root directories whose contents ship: the JavaScript, the binding node-gyp builds
+ * where no prebuild exists (Linux), and the prebuilt binaries for every other platform.
+ */
+const SHIPPED_DIRS = ["lib", "build/Release", "prebuilds"];
+
+/**
+ * Never shipped, wherever they appear: sourcemaps, node-pty's own test build, and the Windows
+ * debug symbols and link-time import libraries nothing loads at runtime.
+ */
+const DROPPED_SUFFIXES = [".map", ".test.js", ".pdb", ".lib"];
+
+/** node-pty's darwin side binary, which its npm tarball ships without the exec bit. */
+const SPAWN_HELPER = "spawn-helper";
+
+/** Package-relative, POSIX-separated path of an entry inside a node-pty install. */
+function toRelPosix(...segments: string[]): string {
+ return segments.join("/");
+}
+
+/** Whether a file at this package-relative path belongs in the staged copy. */
+export function shipsNodePtyFile(relPath: string): boolean {
+ const rel = relPath.split(path.sep).join("/");
+ if (DROPPED_SUFFIXES.some((suffix) => rel.endsWith(suffix))) return false;
+ if (SHIPPED_FILES.includes(rel)) return true;
+ return SHIPPED_DIRS.some((dir) => rel.startsWith(`${dir}/`));
+}
+
+/** Whether a directory can still contain a shipped file — everything else is pruned unvisited. */
+function descendsInto(relPath: string): boolean {
+ const rel = relPath.split(path.sep).join("/");
+ return (
+ SHIPPED_DIRS.some(
+ (dir) => dir === rel || dir.startsWith(`${rel}/`) || rel.startsWith(`${dir}/`),
+ ) || SHIPPED_FILES.some((file) => file.startsWith(`${rel}/`))
+ );
+}
+
+function copyInto(srcDir: string, destDir: string, relBase: string, copied: string[]): void {
+ for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
+ const rel = relBase === "" ? entry.name : toRelPosix(relBase, entry.name);
+ const from = path.join(srcDir, entry.name);
+ if (entry.isDirectory()) {
+ if (descendsInto(rel)) copyInto(from, path.join(destDir, entry.name), rel, copied);
+ continue;
+ }
+ if (!shipsNodePtyFile(rel)) continue;
+ const to = path.join(destDir, entry.name);
+ fs.mkdirSync(destDir, { recursive: true });
+ // copyFileSync follows the symlink pnpm's store uses and lands real bytes.
+ fs.copyFileSync(from, to);
+ // node-pty publishes spawn-helper as 0644, which makes posix_spawnp refuse it and every
+ // macOS terminal fail to start. The runtime repair in the server cannot reach a signed
+ // .app under /Applications, so the mode is fixed here, before the app is packed.
+ if (entry.name === SPAWN_HELPER) fs.chmodSync(to, 0o755);
+ copied.push(rel);
+ }
+}
+
+/**
+ * Replaces `destDir` with the shipping subset of the node-pty install at `srcDir`. Returns the
+ * package-relative paths copied, in walk order.
+ */
+export function stageNodePty(srcDir: string, destDir: string): string[] {
+ fs.rmSync(destDir, { recursive: true, force: true });
+ const copied: string[] = [];
+ copyInto(srcDir, destDir, "", copied);
+ return copied;
+}
+
+/** The native bindings among a staged file list — an empty result means the copy ships no pty. */
+export function nativeBindings(relPaths: string[]): string[] {
+ return relPaths.filter((rel) => rel.endsWith("/pty.node"));
+}
+
+/**
+ * The staged binding node-pty's loader will actually find here, in its own search order
+ * (lib/utils.js: build/Release, then prebuilds/<platform>-<arch>). Undefined means the copy
+ * carries bindings for other platforms only: node-pty prebuilds darwin and win32 but not
+ * Linux, so an install whose node-gyp step never ran still looks populated to a check that
+ * only asks whether some pty.node exists.
+ */
+export function hostBinding(
+ relPaths: string[],
+ platform: string = process.platform,
+ arch: string = process.arch,
+): string | undefined {
+ return ["build/Release/pty.node", `prebuilds/${platform}-${arch}/pty.node`].find((rel) =>
+ relPaths.includes(rel),
+ );
+}
diff --git a/packages/desktop/test/pty-payload.test.ts b/packages/desktop/test/pty-payload.test.ts
new file mode 100644
index 00000000..e0ea4bea
--- /dev/null
+++ b/packages/desktop/test/pty-payload.test.ts
@@ -0,0 +1,201 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ NODE_PTY_RELDIR,
+ hostBinding,
+ nativeBindings,
+ shipsNodePtyFile,
+ stageNodePty,
+} from "../src/pty-payload.js";
+
+const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+
+/** Tests whose assertion reads a POSIX file mode, which Windows does not carry. */
+const itPosix = it.skipIf(process.platform === "win32");
+
+/** A node-pty install with one of everything its npm tarball and node-gyp actually produce. */
+function fakeNodePty(root: string): void {
+ const write = (rel: string, mode?: number) => {
+ const file = path.join(root, ...rel.split("/"));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, rel);
+ if (mode !== undefined) fs.chmodSync(file, mode);
+ };
+ write("package.json");
+ write("LICENSE");
+ write("README.md");
+ write("binding.gyp");
+ write("lib/index.js");
+ write("lib/index.js.map");
+ write("lib/unixTerminal.test.js");
+ write("lib/worker/conoutSocketWorker.js");
+ write("build/Release/pty.node");
+ write("build/Release/spawn-helper", 0o644);
+ write("build/Debug/pty.node");
+ write("prebuilds/darwin-arm64/pty.node");
+ write("prebuilds/darwin-arm64/spawn-helper", 0o644);
+ write("prebuilds/win32-x64/pty.node");
+ write("prebuilds/win32-x64/pty.pdb");
+ write("prebuilds/win32-x64/winpty.lib");
+ write("prebuilds/win32-x64/conpty/OpenConsole.exe");
+ write("src/unixTerminal.ts");
+ write("deps/winpty/LICENSE");
+ write("deps/winpty/README.md");
+ write("scripts/post-install.js");
+ write("third_party/notice.txt");
+ write("typings/node-pty.d.ts");
+}
+
+describe("shipsNodePtyFile", () => {
+ it("keeps the manifest the require lands on, both licenses, the JavaScript and the binaries", () => {
+ for (const rel of [
+ "package.json",
+ "LICENSE",
+ "lib/index.js",
+ "lib/worker/conoutSocketWorker.js",
+ "build/Release/pty.node",
+ "build/Release/spawn-helper",
+ "prebuilds/darwin-arm64/pty.node",
+ "prebuilds/win32-x64/conpty/OpenConsole.exe",
+ "deps/winpty/LICENSE",
+ ]) {
+ expect(shipsNodePtyFile(rel), rel).toBe(true);
+ }
+ });
+
+ it("drops build inputs, sourcemaps, node-pty's own tests and Windows debug symbols", () => {
+ for (const rel of [
+ "README.md",
+ "binding.gyp",
+ "lib/index.js.map",
+ "lib/unixTerminal.test.js",
+ "prebuilds/win32-x64/pty.pdb",
+ "prebuilds/win32-x64/winpty.lib",
+ "src/unixTerminal.ts",
+ "deps/winpty/README.md",
+ "scripts/post-install.js",
+ "third_party/notice.txt",
+ "typings/node-pty.d.ts",
+ ]) {
+ expect(shipsNodePtyFile(rel), rel).toBe(false);
+ }
+ });
+});
+
+describe("stageNodePty", () => {
+ const tmps: string[] = [];
+ const tmpdir = () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-pty-payload-"));
+ tmps.push(dir);
+ return dir;
+ };
+ afterEach(() => {
+ for (const dir of tmps.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("copies exactly the shipping subset, keeping node-pty's package-relative layout", () => {
+ const src = tmpdir();
+ const dest = path.join(tmpdir(), "node-pty");
+ fakeNodePty(src);
+
+ const copied = stageNodePty(src, dest).sort();
+
+ expect(copied).toEqual([
+ "LICENSE",
+ "build/Release/pty.node",
+ "build/Release/spawn-helper",
+ "deps/winpty/LICENSE",
+ "lib/index.js",
+ "lib/worker/conoutSocketWorker.js",
+ "package.json",
+ "prebuilds/darwin-arm64/pty.node",
+ "prebuilds/darwin-arm64/spawn-helper",
+ "prebuilds/win32-x64/conpty/OpenConsole.exe",
+ "prebuilds/win32-x64/pty.node",
+ ]);
+ for (const rel of copied) {
+ expect(fs.existsSync(path.join(dest, ...rel.split("/"))), rel).toBe(true);
+ }
+ expect(fs.existsSync(path.join(dest, "src"))).toBe(false);
+ expect(fs.existsSync(path.join(dest, "deps", "winpty", "README.md"))).toBe(false);
+ expect(fs.existsSync(path.join(dest, "build", "Debug"))).toBe(false);
+ });
+
+ // Windows has no POSIX exec bit: chmod there drives the read-only attribute alone, so
+ // stat().mode & 0o111 always reads back 0. The staging call still runs on win32 (a
+ // harmless no-op) and spawn-helper is a darwin-only side binary, so what is skipped here
+ // is the assertion's platform, not the behaviour it guards.
+ itPosix("restores the exec bit node-pty's tarball leaves off spawn-helper", () => {
+ const src = tmpdir();
+ const dest = path.join(tmpdir(), "node-pty");
+ fakeNodePty(src);
+
+ stageNodePty(src, dest);
+
+ for (const rel of ["build/Release/spawn-helper", "prebuilds/darwin-arm64/spawn-helper"]) {
+ const mode = fs.statSync(path.join(dest, ...rel.split("/"))).mode;
+ expect(mode & 0o111, rel).not.toBe(0);
+ }
+ });
+
+ it("replaces a previous staging instead of merging into it", () => {
+ const src = tmpdir();
+ const dest = path.join(tmpdir(), "node-pty");
+ fakeNodePty(src);
+ fs.mkdirSync(path.join(dest, "prebuilds", "linux-x64"), { recursive: true });
+ fs.writeFileSync(path.join(dest, "prebuilds", "linux-x64", "pty.node"), "stale");
+
+ stageNodePty(src, dest);
+
+ expect(fs.existsSync(path.join(dest, "prebuilds", "linux-x64"))).toBe(false);
+ });
+
+ it("reports the native bindings, so a copy that ships no pty fails the build", () => {
+ const src = tmpdir();
+ const dest = path.join(tmpdir(), "node-pty");
+ fakeNodePty(src);
+
+ expect(nativeBindings(stageNodePty(src, dest)).sort()).toEqual([
+ "build/Release/pty.node",
+ "prebuilds/darwin-arm64/pty.node",
+ "prebuilds/win32-x64/pty.node",
+ ]);
+ expect(nativeBindings(["package.json", "lib/index.js"])).toEqual([]);
+ });
+});
+
+describe("hostBinding", () => {
+ const staged = [
+ "build/Release/pty.node",
+ "prebuilds/darwin-arm64/pty.node",
+ "prebuilds/win32-x64/pty.node",
+ ];
+
+ it("prefers the node-gyp build, then the platform prebuild — node-pty's own order", () => {
+ expect(hostBinding(staged, "linux", "x64")).toBe("build/Release/pty.node");
+ expect(hostBinding(staged.slice(1), "darwin", "arm64")).toBe("prebuilds/darwin-arm64/pty.node");
+ expect(hostBinding(staged.slice(1), "win32", "x64")).toBe("prebuilds/win32-x64/pty.node");
+ });
+
+ it("rejects a copy carrying only other platforms' bindings, which the count alone accepts", () => {
+ const prebuiltOnly = staged.slice(1);
+
+ expect(nativeBindings(prebuiltOnly)).toHaveLength(2);
+ expect(hostBinding(prebuiltOnly, "linux", "x64")).toBeUndefined();
+ expect(hostBinding(prebuiltOnly, "darwin", "x64")).toBeUndefined();
+ });
+});
+
+describe("packaged layout", () => {
+ it("stages into the first node_modules above the server bundle", () => {
+ expect(NODE_PTY_RELDIR).toEqual(["dist", "node_modules", "node-pty"]);
+ });
+
+ it("is listed in electron-builder's files, which otherwise excludes every node_modules", () => {
+ const builderConfig = fs.readFileSync(path.join(pkgDir, "electron-builder.yml"), "utf8");
+ expect(builderConfig).toContain("- dist/node_modules/**/*");
+ });
+});
diff --git a/packages/desktop/tsup.config.ts b/packages/desktop/tsup.config.ts
index 2e9c9555..68ded027 100644
--- a/packages/desktop/tsup.config.ts
+++ b/packages/desktop/tsup.config.ts
@@ -1,19 +1,25 @@
import { defineConfig } from "tsup";
/**
- * Four self-contained bundles, no shared chunks: the shell itself, the server it forks as a
- * utilityProcess, the CLI its bin/ launchers start on the app's Electron runtime, and
- * launcher.ts, which scripts/build-assets.mjs imports (plain node, no Electron) to write
- * those launcher scripts. Because everything is bundled, the packaged app has no runtime
- * dependencies and ships no node_modules at all.
+ * Five self-contained bundles, no shared chunks: the shell itself, the server it forks as a
+ * utilityProcess, the CLI its bin/ launchers start on the app's Electron runtime, and the two
+ * modules scripts/build-assets.mjs imports (plain node, no Electron) to produce the rest of
+ * the build — launcher.ts writes the launcher scripts, pty-payload.ts stages node-pty.
*
* The server and the CLI are bundled from their own packages' build output, so the app runs
* exactly what an `npm install` of those packages would, linked into one file each.
+ *
+ * Bundling absorbs every JavaScript dependency, so the app carries no dependency tree. node-pty
+ * is the one exception and cannot be one: it is a native module the server reaches through a
+ * runtime `require`, and its loader resolves the binary relative to its own package directory.
+ * build-assets.mjs stages a package directory for it at dist/node_modules/node-pty — the only
+ * node_modules the app ships (see src/pty-payload.ts).
*/
export default defineConfig({
entry: {
main: "src/main.ts",
launcher: "src/launcher.ts",
+ "pty-payload": "src/pty-payload.ts",
server: "../server/dist/index.js",
penguin: "../cli/dist/penguin.js",
},