Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(windows): patch node-pty's ConPTY baton/HPCON leak the session host already relies on
enes19b35a2d64f3
diff --git a/CLAUDE.md b/CLAUDE.mdindex d55f2e114..cd4adee9b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -53,16 +53,33 @@ npm run rebuild # re-run electron-rebuild for node-pty if you hit ABI/native```**`rebuild` and `postinstall` both run `scripts/patch-node-pty.mjs` first, and that is not-optional.** node-pty 1.1.0's darwin `pty_posix_spawn` leaks a ptmx device on every SUCCESSFUL spawn-(an off-by-one in the low-fd cleanup) and master+slave on every FAILED one; on this app's spawn-churn that exhausts `kern.tty.ptmx_max` within hours, and terminals then simply stop opening. The-script rewrites `node_modules/node-pty/src/unix/pty.cc` before electron-rebuild compiles it.--`src/main/node-pty-patch.test.ts` asserts the marker is present in those sources, so a node-pty-upgrade that silently drops the patch fails loudly. **If that test is red, your `node_modules` is-unpatched, not your code** — run `npm run rebuild`. It deliberately does not measure descriptors-(that is environment-dependent); it checks the source the native module is built from. Upstream:-microsoft/node-pty#950 — if the fix lands there, delete the script, its wiring and that test.+optional.** It carries TWO version-pinned native patches for node-pty 1.1.0, one per platform leg:+- **darwin** — `pty_posix_spawn` leaks a ptmx device on every SUCCESSFUL spawn (an off-by-one in+ the low-fd cleanup) and master+slave on every FAILED one; on this app's spawn churn that+ exhausts `kern.tty.ptmx_max` within hours, and terminals then simply stop opening+ (microsoft/node-pty#950). Rewrites `node_modules/node-pty/src/unix/pty.cc`.+- **Windows** — the native exit thread deletes its `pty_baton` without closing the HPCON the baton+ owns, so the session host's taskkill-first kill path (src/session-host/host.ts) leaves a+ host-parented conhost alive for the life of the long-lived session-host process, one per killed+ session, and `conpty.kill(id)` reports nothing. The patch serializes baton access, closes the+ exact HPCON before every baton deletion, and makes `kill(id)` return `true` only as positive+ proof — the contract `src/session-host/windows-conpty.ts` was ALREADY written against (it+ shipped with #305 expecting a patched node-pty that did not exist until this patch; do not+ wire `closeExactWindowsConpty` into the ordinary kill path — after taskkill the exit thread+ usually wins the race, has already closed the HPCON itself under the patch, and the primitive+ would then report `false`; it exists for a pre-first-output teardown that bypasses the exit+ thread). Rewrites `node_modules/node-pty/src/win/conpty.cc` on every host — the file only+ compiles for the win32 native target, so patching on mac/Linux is harmless and keeps packaged+ rebuilds honest.++Both patches run before electron-rebuild compiles the module.++`src/main/node-pty-patch.test.ts` asserts both markers are present in those sources, so a node-pty+upgrade that silently drops either patch fails loudly. **If that test is red, your `node_modules`+is unpatched, not your code** — run `npm run rebuild`. It deliberately does not measure descriptors+or handles (that is environment-dependent); it checks the source the native module is built from.+Upstream: the darwin leg tracks microsoft/node-pty#950; the Windows leg has no upstream issue yet.+When a leg's fix lands upstream, delete that leg (and the whole script + test once both are gone).``````diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e63c9a0a3..fa31a07a0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -21,8 +21,10 @@ npm test # vitest, unit + integration**If `src/main/node-pty-patch.test.ts` is red, your `node_modules` is unpatched — not your code.**Run `npm run rebuild`. node-pty 1.1.0 leaks a pty device per spawn on macOS-([node-pty#950](https://github.com/microsoft/node-pty/issues/950)); we patch its source before-`electron-rebuild` compiles it, and that test guards the patch surviving upgrades.+([node-pty#950](https://github.com/microsoft/node-pty/issues/950)) and, on Windows, leaves a+conhost alive per killed session (its exit thread deletes the ConPTY baton without closing the+HPCON); we patch both sources before `electron-rebuild` compiles them, and that test guards the+patches surviving upgrades.## Where code goesdiff --git a/scripts/patch-node-pty.mjs b/scripts/patch-node-pty.mjsindex 25eb19366..ee4ddf459 100644--- a/scripts/patch-node-pty.mjs+++ b/scripts/patch-node-pty.mjs@@ -1,29 +1,47 @@#!/usr/bin/env node/**- * patch-node-pty.mjs — local fix for a file-descriptor leak in node-pty's macOS- * spawn path (`pty_posix_spawn` in node_modules/node-pty/src/unix/pty.cc).+ * patch-node-pty.mjs — version-pinned local fixes for node-pty 1.1.0, applied to+ * node_modules before electron-rebuild compiles the native module:*- * WHAT IT FIXES — upstream issue: https://github.com/microsoft/node-pty/issues/950- * (filed by us against node-pty 1.1.0)+ * 1. DARWIN — a file-descriptor leak in the macOS spawn path (`pty_posix_spawn`+ * in src/unix/pty.cc). Upstream issue: https://github.com/microsoft/node-pty/issues/950+ * (filed by us against node-pty 1.1.0)*- * (a) FAILED spawns leak the master + slave descriptors. None of the early- * returns after `posix_openpt()` succeeds close the master, and the slave- * is never closed in the parent on any path. Each failure burns 2 ptmx- * devices + 1 /dev/ttysNNN descriptor.+ * (a) FAILED spawns leak the master + slave descriptors. None of the early+ * returns after `posix_openpt()` succeeds close the master, and the slave+ * is never closed in the parent on any path. Each failure burns 2 ptmx+ * devices + 1 /dev/ttysNNN descriptor.*- * (b) SUCCESSFUL spawns leak exactly one ptmx device via the "low fd"- * prologue's off-by-one cleanup:- * for (; count > 0; count--) close(low_fds[count]);- * The loop stops at count == 0, so low_fds[0] — the descriptor opened- * first, and the only one opened in the common case where the very first- * posix_openpt() already returns an fd >= STDERR_FILENO — is never- * closed. It also skips index 0 whenever count > 0, and reads low_fds[3]- * out of bounds if the loop above ever runs to completion.+ * (b) SUCCESSFUL spawns leak exactly one ptmx device via the "low fd"+ * prologue's off-by-one cleanup:+ * for (; count > 0; count--) close(low_fds[count]);+ * The loop stops at count == 0, so low_fds[0] — the descriptor opened+ * first, and the only one opened in the common case where the very first+ * posix_openpt() already returns an fd >= STDERR_FILENO — is never+ * closed. It also skips index 0 whenever count > 0, and reads low_fds[3]+ * out of bounds if the loop above ever runs to completion.*- * Field impact on macOS: ~16 successful spawns/min of normal park/offscreen/- * reap + reattach churn x 1 leaked ptmx device each walks straight into- * `kern.tty.ptmx_max` (511 on this machine) within hours, after which every- * further pty spawn fails with "posix_spawnp failed.".+ * Field impact on macOS: ~16 successful spawns/min of normal park/offscreen/+ * reap + reattach churn x 1 leaked ptmx device each walks straight into+ * `kern.tty.ptmx_max` (511 on this machine) within hours, after which every+ * further pty spawn fails with "posix_spawnp failed.".+ *+ * 2. WINDOWS — the ConPTY baton/HPCON race in src/win/conpty.cc. node-pty's+ * native exit thread deletes its `pty_baton` as soon as the shell process+ * handle signals, WITHOUT closing the HPCON the baton owns (pty_baton has no+ * destructor that closes it). When a caller terminates the process tree+ * first — exactly what the session host's kill path does via `taskkill /T /F`+ * (src/session-host/host.ts) — the exit thread wins the race, a later+ * `conpty.kill(id)` silently finds no baton, and the host-parented conhost+ * stays alive until the whole session-host process exits. The session host is+ * a long-lived daemon by design, so leaked conhosts accumulate per kill.+ * The patch serializes baton access behind a mutex, closes the exact HPCON+ * before every baton deletion (the exit thread's included), and makes+ * `kill(id)` return `true` only when it found and closed that exact handle —+ * the positive proof `src/session-host/windows-conpty.ts` requires.+ * (Adapted from the material-nodeterm fork's PR #448 branch; anchors verified+ * against the pristine 1.1.0 sources, native behavior not yet re-measured on+ * a Windows device by us — see the PR's device checklist.)** WHY A SCRIPT AND NOT patch-package: patch-package is not a dependency of this* repo and adding one would require an `npm install` against a node_modules@@ -33,20 +51,22 @@* patched sources.** PROPERTIES- * - Idempotent: re-running is a no-op (detected via the PATCH_MARKER below).+ * - Idempotent: re-running is a no-op (detected via the per-file patch markers).* - Verifiable: if any anchor is missing (e.g. after a node-pty upgrade that- * reshapes this function) the script exits non-zero and explains what to do+ * reshapes these functions) the script exits non-zero and explains what to do* rather than silently producing an unpatched build.- * - Cross-platform safe: pty.cc ships in every install; the patched block is- * inside `#if defined(__APPLE__)`, so patching on Linux/CI is harmless.+ * - Cross-platform safe: both source files ship in every install; the unix+ * block is inside `#if defined(__APPLE__)` and conpty.cc only compiles for+ * the win32 native target, so patching on Linux/CI is harmless and keeps+ * packaged rebuilds honest on every host.** REMOVAL CONDITION- * Delete this script, its postinstall/rebuild wiring, and- * src/main/node-pty-patch.test.ts as soon as we upgrade to a node-pty- * release that carries the upstream fix for issue #950. The guard test in- * src/main/node-pty-patch.test.ts will fail loudly if a node-pty upgrade- * silently drops this patch, which is the signal to check whether the fix- * landed upstream.+ * Delete each leg (its EDITS block, marker and test assertions) as soon as we+ * upgrade to a node-pty release that carries the corresponding fix upstream —+ * the darwin leg tracks microsoft/node-pty#950; the Windows leg has no upstream+ * issue yet. The guard test in src/main/node-pty-patch.test.ts will fail loudly+ * if a node-pty upgrade silently drops either patch, which is the signal to+ * check whether the fix landed upstream.*/import fs from 'node:fs';@@ -57,8 +77,10 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));const repoRoot = path.resolve(__dirname, '..');const ptyDir = path.join(repoRoot, 'node_modules', 'node-pty');const ptyCc = path.join(ptyDir, 'src', 'unix', 'pty.cc');+const conptyCc = path.join(ptyDir, 'src', 'win', 'conpty.cc');export const PATCH_MARKER = 'NODETERM-PATCH(node-pty#950)';+export const WINDOWS_CONPTY_PATCH_MARKER = 'NODETERM-PATCH(node-pty-conpty-exact-close)';const ISSUE_URL = 'https://github.com/microsoft/node-pty/issues/950';const EXPECTED_VERSION = '1.1.0';@@ -194,20 +216,326 @@ const EDITS = [}];+/** Anchor -> replacement for src/win/conpty.cc. Every anchor must match exactly once. */+export const WINDOWS_EDITS = [+ {+ name: 'ConPTY baton lifetime, exact close, and synchronization',+ find: `#include <sstream>+#include <iostream>+#include <string>+#include <thread>+#include <vector>+#include <Windows.h>+#include <strsafe.h>+#include "path_util.h"+#include "conpty.h"++// Taken from the RS5 Windows SDK, but redefined here in case we're targeting <= 17134+#ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE+#define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE \\+ ProcThreadAttributeValue(22, FALSE, TRUE, FALSE)++typedef VOID* HPCON;+typedef HRESULT (__stdcall *PFNCREATEPSEUDOCONSOLE)(COORD c, HANDLE hIn, HANDLE hOut, DWORD dwFlags, HPCON* phpcon);+typedef HRESULT (__stdcall *PFNRESIZEPSEUDOCONSOLE)(HPCON hpc, COORD newSize);+typedef HRESULT (__stdcall *PFNCLEARPSEUDOCONSOLE)(HPCON hpc);+typedef void (__stdcall *PFNCLOSEPSEUDOCONSOLE)(HPCON hpc);+typedef void (__stdcall *PFNRELEASEPSEUDOCONSOLE)(HPCON hpc);++#endif++struct pty_baton {+ int id;+ HANDLE hIn;+ HANDLE hOut;+ HPCON hpc;++ HANDLE hShell;++ pty_baton(int _id, HANDLE _hIn, HANDLE _hOut, HPCON _hpc) : id(_id), hIn(_hIn), hOut(_hOut), hpc(_hpc) {};+};++static std::vector<std::unique_ptr<pty_baton>> ptyHandles;+static volatile LONG ptyCounter;++static pty_baton* get_pty_baton(int id) {+ auto it = std::find_if(ptyHandles.begin(), ptyHandles.end(), [id](const auto& ptyHandle) {+ return ptyHandle->id == id;+ });+ if (it != ptyHandles.end()) {+ return it->get();+ }+ return nullptr;+}++static bool remove_pty_baton(int id) {+ auto it = std::remove_if(ptyHandles.begin(), ptyHandles.end(), [id](const auto& ptyHandle) {+ return ptyHandle->id == id;+ });+ if (it != ptyHandles.end()) {+ ptyHandles.erase(it);+ return true;+ }+ return false;+}`,+ replace: `#include <sstream>+#include <iostream>+#include <string>+#include <thread>+#include <vector>+#include <mutex>+#include <Windows.h>+#include <strsafe.h>+#include "path_util.h"+#include "conpty.h"++// Taken from the RS5 Windows SDK, but redefined here in case we're targeting <= 17134+#ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE+#define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE \\+ ProcThreadAttributeValue(22, FALSE, TRUE, FALSE)++typedef VOID* HPCON;+typedef HRESULT (__stdcall *PFNCREATEPSEUDOCONSOLE)(COORD c, HANDLE hIn, HANDLE hOut, DWORD dwFlags, HPCON* phpcon);+typedef HRESULT (__stdcall *PFNRESIZEPSEUDOCONSOLE)(HPCON hpc, COORD newSize);+typedef HRESULT (__stdcall *PFNCLEARPSEUDOCONSOLE)(HPCON hpc);+typedef void (__stdcall *PFNCLOSEPSEUDOCONSOLE)(HPCON hpc);+typedef void (__stdcall *PFNRELEASEPSEUDOCONSOLE)(HPCON hpc);++#endif++struct pty_baton {+ int id;+ HANDLE hIn;+ HANDLE hOut;+ HPCON hpc;+ PFNCLOSEPSEUDOCONSOLE closePseudoConsole;++ HANDLE hShell = nullptr;++ pty_baton(int _id, HANDLE _hIn, HANDLE _hOut, HPCON _hpc, PFNCLOSEPSEUDOCONSOLE _closePseudoConsole) :+ id(_id), hIn(_hIn), hOut(_hOut), hpc(_hpc), closePseudoConsole(_closePseudoConsole) {};++ // ${WINDOWS_CONPTY_PATCH_MARKER}: callers hold g_ptyHandlesMutex. Exchange the handle before+ // ClosePseudoConsole can signal hShell, so the exit callback can never double-close it.+ bool closeExactPseudoConsole() {+ if (hpc == nullptr || closePseudoConsole == nullptr) {+ return false;+ }+ HPCON exact = hpc;+ hpc = nullptr;+ closePseudoConsole(exact);+ return true;+ }+};++static std::vector<std::unique_ptr<pty_baton>> ptyHandles;+static std::mutex g_ptyHandlesMutex;+static volatile LONG ptyCounter;++// The scoped-lock parameter makes the ownership precondition impossible to omit accidentally.+static pty_baton* get_pty_baton(const std::lock_guard<std::mutex>&, int id) {+ auto it = std::find_if(ptyHandles.begin(), ptyHandles.end(), [id](const auto& ptyHandle) {+ return ptyHandle->id == id;+ });+ if (it != ptyHandles.end()) {+ return it->get();+ }+ return nullptr;+}++static bool remove_pty_baton(const std::lock_guard<std::mutex>&, int id) {+ auto it = std::remove_if(ptyHandles.begin(), ptyHandles.end(), [id](const auto& ptyHandle) {+ return ptyHandle->id == id;+ });+ if (it != ptyHandles.end()) {+ ptyHandles.erase(it);+ return true;+ }+ return false;+}`+ },+ {+ name: 'close exact HPCON before shell-exit baton deletion',+ find: ` // Wait for process to complete.+ WaitForSingleObject(baton->hShell, INFINITE);+ // Get process exit code.+ GetExitCodeProcess(baton->hShell, (LPDWORD)(&exit_event->exit_code));+ // Clean up handles+ CloseHandle(baton->hShell);+ assert(remove_pty_baton(baton->id));`,+ replace: ` // Wait for process to complete.+ WaitForSingleObject(baton->hShell, INFINITE);+ {+ std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);+ // ${WINDOWS_CONPTY_PATCH_MARKER}: a taskkill-first teardown reaches this thread before JS can+ // call kill(id). Close the exact HPCON while its baton still exists, then delete the baton.+ baton->closeExactPseudoConsole();+ // Get process exit code.+ GetExitCodeProcess(baton->hShell, (LPDWORD)(&exit_event->exit_code));+ // Clean up handles+ CloseHandle(baton->hShell);+ assert(remove_pty_baton(lock, baton->id));+ }`+ },+ {+ name: 'resolve exact close primitive before ConPTY creation',+ find: ` HPCON hpc;+ HRESULT hr = CreateNamedPipesAndPseudoConsole(info, {cols, rows}, inheritCursor ? 1/*PSEUDOCONSOLE_INHERIT_CURSOR*/ : 0, &hIn, &hOut, &hpc, inName, outName, pipeName, useConptyDll);`,+ replace: ` HANDLE closeLibrary = LoadConptyDll(info, useConptyDll);+ PFNCLOSEPSEUDOCONSOLE const closePseudoConsole = closeLibrary == nullptr ? nullptr :+ (PFNCLOSEPSEUDOCONSOLE)GetProcAddress(+ (HMODULE)closeLibrary,+ useConptyDll ? "ConptyClosePseudoConsole" : "ClosePseudoConsole");+ if (closePseudoConsole == nullptr) {+ throw errorWithCode(info, "Cannot resolve exact pseudoconsole close primitive");+ }++ HPCON hpc;+ HRESULT hr = CreateNamedPipesAndPseudoConsole(info, {cols, rows}, inheritCursor ? 1/*PSEUDOCONSOLE_INHERIT_CURSOR*/ : 0, &hIn, &hOut, &hpc, inName, outName, pipeName, useConptyDll);`+ },+ {+ name: 'synchronize new ConPTY baton insertion',+ find: ` ptyHandles.emplace_back(+ std::make_unique<pty_baton>(ptyId, hIn, hOut, hpc));`,+ replace: ` std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);+ ptyHandles.emplace_back(+ std::make_unique<pty_baton>(ptyId, hIn, hOut, hpc, closePseudoConsole));`+ },+ {+ name: 'synchronize ConPTY connect lookup',+ find: ` // Fetch pty handle from ID and start process+ pty_baton* handle = get_pty_baton(id);+ if (!handle) {+ throw Napi::Error::New(env, "Invalid pty handle");+ }`,+ replace: ` // Fetch pty handle from ID and start process. This baton has no exit callback yet,+ // so it remains alive after the lookup lock is released.+ pty_baton* handle;+ {+ std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);+ handle = get_pty_baton(lock, id);+ if (!handle) {+ throw Napi::Error::New(env, "Invalid pty handle");+ }+ }`+ },+ {+ name: 'synchronize ConPTY resize',+ find: ` SHORT rows = static_cast<SHORT>(info[2].As<Napi::Number>().Uint32Value());+ const bool useConptyDll = info[3].As<Napi::Boolean>().Value();++ const pty_baton* handle = get_pty_baton(id);++ if (handle != nullptr) {+ HANDLE hLibrary = LoadConptyDll(info, useConptyDll);`,+ replace: ` SHORT rows = static_cast<SHORT>(info[2].As<Napi::Number>().Uint32Value());+ const bool useConptyDll = info[3].As<Napi::Boolean>().Value();++ std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);+ const pty_baton* handle = get_pty_baton(lock, id);++ if (handle != nullptr && handle->hpc != nullptr) {+ HANDLE hLibrary = LoadConptyDll(info, useConptyDll);`+ },+ {+ name: 'synchronize ConPTY clear',+ find: ` if (!useConptyDll) {+ return env.Undefined();+ }++ const pty_baton* handle = get_pty_baton(id);++ if (handle != nullptr) {+ HANDLE hLibrary = LoadConptyDll(info, useConptyDll);`,+ replace: ` if (!useConptyDll) {+ return env.Undefined();+ }++ std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);+ const pty_baton* handle = get_pty_baton(lock, id);++ if (handle != nullptr && handle->hpc != nullptr) {+ HANDLE hLibrary = LoadConptyDll(info, useConptyDll);`+ },+ {+ name: 'make ConPTY kill exact and positively acknowledged',+ find: ` const pty_baton* handle = get_pty_baton(id);++ if (handle != nullptr) {+ HANDLE hLibrary = LoadConptyDll(info, useConptyDll);+ bool fLoadedDll = hLibrary != nullptr;+ if (fLoadedDll)+ {+ PFNCLOSEPSEUDOCONSOLE const pfnClosePseudoConsole = (PFNCLOSEPSEUDOCONSOLE)GetProcAddress(+ (HMODULE)hLibrary,+ useConptyDll ? "ConptyClosePseudoConsole" : "ClosePseudoConsole");+ if (pfnClosePseudoConsole)+ {+ pfnClosePseudoConsole(handle->hpc);+ }+ }+ if (useConptyDll) {+ TerminateProcess(handle->hShell, 1);+ }+ }++ return env.Undefined();`,+ replace: ` bool closed = false;+ {+ std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);+ pty_baton* handle = get_pty_baton(lock, id);++ if (handle != nullptr) {+ // ${WINDOWS_CONPTY_PATCH_MARKER}: unlike stock 1.1.0's void result, true is positive proof+ // that this exact baton existed and its one HPCON was synchronously closed.+ closed = handle->closeExactPseudoConsole();+ if (useConptyDll && handle->hShell != nullptr) {+ TerminateProcess(handle->hShell, 1);+ }+ }+ }++ return Napi::Boolean::New(env, closed);`+ }+];+function fail(msg) {console.error(`\n[patch-node-pty] ERROR: ${msg}\n`);console.error(` Patch script : scripts/patch-node-pty.mjs`);- console.error(` Upstream bug : ${ISSUE_URL}`);+ console.error(` Darwin bug : ${ISSUE_URL}`);+ console.error(` Windows bug : node-pty 1.1.0 ConPTY baton deletion before HPCON close`);console.error(- ` If node-pty was upgraded: check whether the fix landed upstream. If it did,\n` +- ` delete this script, its postinstall/rebuild wiring and src/main/node-pty-patch.test.ts.\n` +- ` If it did not, re-derive the anchors in EDITS against the new pty.cc.\n`+ ` If node-pty was upgraded: check whether the corresponding fix landed upstream. If it did,\n` ++ ` delete that leg (its EDITS block, marker and test assertions) — and the whole script once\n` ++ ` both legs are upstream. If it did not, re-derive the anchors against the new sources.\n`);process.exit(1);}+/** Apply one file's edits; returns false when the marker shows they are already applied. */+function patchOne(file, marker, edits) {+ if (!fs.existsSync(file)) {+ fail(`required node-pty source is missing:\n ${file}`);+ }+ const original = fs.readFileSync(file, 'utf8');+ if (original.includes(marker)) {+ return false;+ }++ let patched = original;+ for (const edit of edits) {+ const occurrences = patched.split(edit.find).length - 1;+ if (occurrences !== 1) {+ fail(`anchor "${edit.name}" matched ${occurrences} times (expected exactly 1) in\n ${file}`);+ }+ patched = patched.replace(edit.find, edit.replace);+ }+ fs.writeFileSync(file, patched, 'utf8');+ return true;+}+function main() {- if (!fs.existsSync(ptyCc)) {+ if (!fs.existsSync(ptyDir)) {// node-pty is optional in some install shapes (e.g. docs-only CI installs).console.log('[patch-node-pty] node-pty sources not present, nothing to patch.');return;@@ -222,13 +550,6 @@ function main() {/* fall through — the anchor check below is the real guard */}- const original = fs.readFileSync(ptyCc, 'utf8');-- if (original.includes(PATCH_MARKER)) {- console.log(`[patch-node-pty] already applied (node-pty ${installedVersion}), skipping.`);- return;- }-if (installedVersion !== EXPECTED_VERSION) {console.warn(`[patch-node-pty] note: expected node-pty ${EXPECTED_VERSION}, found ${installedVersion}. ` +@@ -236,23 +557,16 @@ function main() {);}- let patched = original;- for (const edit of EDITS) {- const occurrences = patched.split(edit.find).length - 1;- if (occurrences !== 1) {- fail(- `anchor "${edit.name}" matched ${occurrences} times (expected exactly 1) in\n ${ptyCc}\n` +- ` node-pty version: ${installedVersion}`- );- }- patched = patched.replace(edit.find, edit.replace);+ const applied = [];+ if (patchOne(ptyCc, PATCH_MARKER, EDITS)) applied.push('darwin fd-leak (src/unix/pty.cc)');+ if (patchOne(conptyCc, WINDOWS_CONPTY_PATCH_MARKER, WINDOWS_EDITS)) {+ applied.push('Windows exact ConPTY close (src/win/conpty.cc)');+ }+ if (applied.length === 0) {+ console.log(`[patch-node-pty] already applied (node-pty ${installedVersion}), skipping.`);+ } else {+ console.log(`[patch-node-pty] applied to node-pty ${installedVersion}: ${applied.join('; ')}`);}-- fs.writeFileSync(ptyCc, patched, 'utf8');- console.log(- `[patch-node-pty] applied fd-leak patch to node-pty ${installedVersion} ` +- `(src/unix/pty.cc) — ${ISSUE_URL}`- );}// Only patch when executed directly (`node scripts/patch-node-pty.mjs`), never asdiff --git a/src/main/node-pty-patch.test.ts b/src/main/node-pty-patch.test.tsindex 7f4cc53b9..95fe5f49d 100644--- a/src/main/node-pty-patch.test.ts+++ b/src/main/node-pty-patch.test.ts@@ -3,21 +3,32 @@ import fs from 'fs'import path from 'path'/**- * Guard for our local node-pty fd-leak patch (microsoft/node-pty#950).+ * Guard for our local node-pty native patches (scripts/patch-node-pty.mjs).*- * node-pty 1.1.0's darwin `pty_posix_spawn` leaks one ptmx device per SUCCESSFUL- * spawn (off-by-one in the low-fd cleanup) and master+slave on every FAILED one.- * On this app's spawn churn that exhausts `kern.tty.ptmx_max` within hours.- * scripts/patch-node-pty.mjs rewrites node_modules/node-pty/src/unix/pty.cc- * before electron-rebuild compiles it.+ * Darwin: node-pty 1.1.0's `pty_posix_spawn` leaks one ptmx device per SUCCESSFUL+ * spawn (off-by-one in the low-fd cleanup) and master+slave on every FAILED one+ * (microsoft/node-pty#950). On this app's spawn churn that exhausts+ * `kern.tty.ptmx_max` within hours.*- * This test does NOT measure descriptors (that is environment-dependent); it- * asserts the patch is present in the sources the native module is built from,- * so a node-pty upgrade that silently drops it fails loudly here.+ * Windows: node-pty 1.1.0's native exit thread deletes its `pty_baton` without+ * closing the HPCON the baton owns, so a taskkill-first teardown — the session+ * host's kill path — leaves a host-parented conhost alive for the life of the+ * long-lived session-host process, and `conpty.kill(id)` reports nothing. The+ * patch serializes baton access, closes the exact HPCON before every baton+ * deletion, and makes `kill(id)` return positive proof — the contract+ * src/session-host/windows-conpty.ts requires.+ *+ * These tests do NOT measure descriptors or handles (that is environment-+ * dependent); they assert the patches are present in the sources the native+ * module is built from, so a node-pty upgrade that silently drops either one+ * fails loudly here.*/const PTY_CC = path.resolve(__dirname, '../../node_modules/node-pty/src/unix/pty.cc')+const CONPTY_CC = path.resolve(__dirname, '../../node_modules/node-pty/src/win/conpty.cc')/** Must stay in sync with PATCH_MARKER in scripts/patch-node-pty.mjs. */const PATCH_MARKER = 'NODETERM-PATCH(node-pty#950)'+/** Must stay in sync with WINDOWS_CONPTY_PATCH_MARKER in scripts/patch-node-pty.mjs. */+const WINDOWS_CONPTY_PATCH_MARKER = 'NODETERM-PATCH(node-pty-conpty-exact-close)'const HOWTO ='Run `node scripts/patch-node-pty.mjs && npm run rebuild`. ' +@@ -48,3 +59,32 @@ describe('node-pty fd-leak patch (microsoft/node-pty#950)', () => {expect(source).toContain('size_t opened = count < 3 ? count + 1 : 3;')})})++describe('node-pty exact Windows ConPTY close patch', () => {+ const exists = fs.existsSync(CONPTY_CC)+ const source = exists ? fs.readFileSync(CONPTY_CC, 'utf8') : ''++ it.skipIf(!exists)('is applied to node_modules/node-pty/src/win/conpty.cc', () => {+ expect(+ source.includes(WINDOWS_CONPTY_PATCH_MARKER),+ `node-pty Windows ConPTY patch is MISSING. ${HOWTO}`+ ).toBe(true)+ })++ it.skipIf(!exists)('closes the exact HPCON before deleting its shell-exit baton', () => {+ // The exit thread is where the stock leak lives: it deleted the baton without ever+ // closing the HPCON. The close must come first, and both under the baton mutex.+ const closeIndex = source.indexOf('baton->closeExactPseudoConsole();')+ const removeIndex = source.indexOf('remove_pty_baton(lock, baton->id)')+ expect(closeIndex).toBeGreaterThan(0)+ expect(removeIndex).toBeGreaterThan(closeIndex)+ expect(source).toContain('std::lock_guard<std::mutex> lock(g_ptyHandlesMutex);')+ })++ it.skipIf(!exists)('returns positive proof instead of the stock void kill result', () => {+ // src/session-host/windows-conpty.ts refuses anything but `true` from conpty.kill —+ // this is the source-level half of that contract.+ expect(source).toContain('closed = handle->closeExactPseudoConsole();')+ expect(source).toContain('return Napi::Boolean::New(env, closed);')+ })+})diff --git a/src/session-host/windows-conpty.test.ts b/src/session-host/windows-conpty.test.tsnew file mode 100644index 000000000..dd9c22c8c--- /dev/null+++ b/src/session-host/windows-conpty.test.ts@@ -0,0 +1,197 @@+/**+ * Behavior pins for the exact ConPTY close adapter (./windows-conpty.ts), against a fake of+ * node-pty 1.1.0's private Windows shape. The adapter shipped with the session-host extraction+ * (#305) but had no test until the ConPTY native patch landed; these pins came with that patch+ * (adapted from the material-nodeterm fork's PR #448 branch, which wrote them against the+ * byte-identical module). The load-bearing claims:+ *+ * - the close path calls ONLY the native `kill(id)` primitive — never the broad JS+ * `WindowsPtyAgent.kill()` and never console-process enumeration;+ * - anything but a literal `true` from the native binding fails CLOSED (stock 1.1.0 returns+ * void, and void cannot distinguish a close from the shell-exit race that already deleted+ * the baton);+ * - a drifted private shape refuses before touching any kill primitive;+ * - the error that crosses the session-host protocol never carries private process details;+ * - transport release tears down input handle → conout worker → output socket IN THAT ORDER,+ * because the output socket's close event is node-pty's public `onExit`.+ */+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { IPty } from 'node-pty'+import {+ closeExactWindowsConpty,+ releaseExactWindowsConpty,+ SUPPORTED_WINDOWS_CONPTY_NODE_PTY_VERSION+} from './windows-conpty'++class ConoutConnection {+ _worker = { terminate: vi.fn(async () => 1) }+ _drainTimeout: ReturnType<typeof setTimeout> | undefined+ _isDisposed = false+}++class FakeSocket {+ destroyed = false+ private readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>()++ once(event: string, listener: (...args: unknown[]) => void): this {+ const wrapped = (...args: unknown[]): void => {+ this.removeListener(event, wrapped)+ listener(...args)+ }+ const current = this.listeners.get(event) ?? new Set()+ current.add(wrapped)+ this.listeners.set(event, current)+ return this+ }++ removeListener(event: string, listener: (...args: unknown[]) => void): this {+ this.listeners.get(event)?.delete(listener)+ return this+ }++ destroy(): this {+ this.destroyed = true+ queueMicrotask(() => {+ for (const listener of [...(this.listeners.get('close') ?? [])]) listener()+ })+ return this+ }+}++class WindowsPtyAgent {+ _useConpty = true+ _useConptyDll = false+ _pty = 41+ _inSocket = new FakeSocket()+ _outSocket = new FakeSocket()+ _conoutSocketWorker = new ConoutConnection()+ _getConsoleProcessList = vi.fn(() => {+ throw new Error('exact close must not enumerate console processes')+ })+ kill = vi.fn(() => {+ throw new Error('exact close must not call the broad JS agent kill')+ })+ _ptyNative = {+ startProcess: vi.fn(),+ connect: vi.fn(),+ resize: vi.fn(),+ clear: vi.fn(),+ kill: vi.fn((): unknown => true)+ }+}++class WindowsTerminal {+ _pty = 41+ _isReady = false+ _deferreds: unknown[] = []+ _agent = new WindowsPtyAgent()+ _close = vi.fn()+}++function terminal(): WindowsTerminal & IPty {+ return new WindowsTerminal() as WindowsTerminal & IPty+}++describe('exact Windows ConPTY close adapter', () => {+ afterEach(() => vi.restoreAllMocks())++ it('is pinned to the installed node-pty lifecycle contract', () => {+ expect(SUPPORTED_WINDOWS_CONPTY_NODE_PTY_VERSION).toBe('1.1.0')+ })++ it('closes only the exact native PTY id before first output without process enumeration', () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')+ const target = terminal()++ closeExactWindowsConpty(target)++ expect(target._agent._ptyNative.kill).toHaveBeenCalledOnce()+ expect(target._agent._ptyNative.kill).toHaveBeenCalledWith(41, false)+ expect(target._agent.kill).not.toHaveBeenCalled()+ expect(target._agent._getConsoleProcessList).not.toHaveBeenCalled()+ expect(target._isReady).toBe(false)+ })++ it.each([undefined, false, 0, null])(+ 'fails closed when the native binding cannot prove the exact HPCON close (%s)',+ (result) => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')+ const target = terminal()+ target._agent._ptyNative.kill.mockReturnValue(result)++ expect(() => closeExactWindowsConpty(target)).toThrow(+ 'session-host could not safely close the Windows terminal'+ )+ }+ )++ it('fails closed on a drifted private shape without invoking any kill primitive', () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')+ const target = terminal()+ target._agent._useConpty = false++ expect(() => closeExactWindowsConpty(target)).toThrow(+ 'session-host could not safely close the Windows terminal'+ )+ expect(target._agent._ptyNative.kill).not.toHaveBeenCalled()+ expect(target._agent.kill).not.toHaveBeenCalled()+ })++ it('does not expose private process details when native close throws', () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')+ const target = terminal()+ target._agent._ptyNative.kill.mockImplementation(() => {+ throw new Error('C:\\private cwd\\shell.exe --secret PID 12345')+ })++ expect(() => closeExactWindowsConpty(target)).toThrow(+ 'session-host could not safely close the Windows terminal'+ )+ try {+ closeExactWindowsConpty(target)+ } catch (error) {+ expect(String(error)).not.toContain('private cwd')+ expect(String(error)).not.toContain('12345')+ }+ })++ it('awaits the exact worker and input handle before emitting the output close/onExit', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')+ const target = terminal()+ const order: string[] = []+ target._agent._inSocket.destroy = vi.fn(() => {+ order.push('input')+ return FakeSocket.prototype.destroy.call(target._agent._inSocket)+ })+ target._agent._conoutSocketWorker._worker.terminate = vi.fn(async () => {+ order.push('worker-start')+ await Promise.resolve()+ order.push('worker-done')+ return 1+ })+ target._agent._outSocket.destroy = vi.fn(() => {+ order.push('output')+ return FakeSocket.prototype.destroy.call(target._agent._outSocket)+ })++ closeExactWindowsConpty(target)+ await releaseExactWindowsConpty(target)++ expect(order).toEqual(['input', 'worker-start', 'worker-done', 'output'])+ expect(target._close).toHaveBeenCalledOnce()+ expect(target._agent._conoutSocketWorker._isDisposed).toBe(true)+ expect(target._agent.kill).not.toHaveBeenCalled()+ expect(target._agent._getConsoleProcessList).not.toHaveBeenCalled()+ })++ it('refuses transport release before an exact native close', async () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')+ const target = terminal()++ await expect(releaseExactWindowsConpty(target)).rejects.toThrow(+ 'session-host could not safely close the Windows terminal'+ )+ expect(target._agent._conoutSocketWorker._worker.terminate).not.toHaveBeenCalled()+ expect(target._agent._outSocket.destroyed).toBe(false)+ })+})