Skip to content

Relocate node-pty ConPTY runtime outside the Windows install dir (fixes update-time terminal loss) - #7421

Merged
Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/relocate-conpty-runtime-main
Jul 5, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
Jinwoo-H/relocate-conpty-runtime-main

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Summary

Windows terminal sessions die on every app update since June 30 because the NSIS update installer force-closes every process running from the install directory — and #6968 moved the ConPTY console hosts into it. This PR relocates node-pty's native runtime (conpty.node, conpty.dll, OpenConsole.exe, winpty binaries) to userData/node-pty-runtime/<version>/, taking terminal infrastructure out of the installer's kill zone. Verified end-to-end against the installer's verbatim kill commands.

Root cause (reproduction-harness verified, not inferred)

electron-builder's NSIS template (allowOnlyOneInstallerInstance.nsh, unchanged in this repo since the initial commit) runs CHECK_APP_RUNNING during every update install:

# FIND: is anything running from the install dir?
if ((Get-CimInstance Win32_Process | ? {$_.Path -and $_.Path.StartsWith('$INSTDIR', 'CurrentCultureIgnoreCase')}).Count -gt 0) { exit 0 } else { exit 1 }
# KILL: Stop-Process each match, then a -Force retry loop

Three facts, each demonstrated by running these commands verbatim against disposable process topologies (harness output in the PR comments):

  1. A latent single-match blind spot protected the daemon until June 30. In Windows PowerShell 5.1, a pipeline that matches exactly ONE process returns a bare CimInstance whose .Count is $null, so -gt 0 is false and the installer concludes "nothing running" and kills nothing. Pre-Fix Windows bundled ConPTY packaging #6968, terminals used the System32 console host, so the detached daemon was the only install-dir process → single match → spared on every update. Same-process daemon survival across updates was real — and an accident.
  2. Fix Windows bundled ConPTY packaging #6968 (June 30) unmasked the sweep. With OpenConsole.exe instances now under resources/, there are 2+ matches, .Count works, and the sweep kills the daemon and every console host mid-install. Killing a console host kills its attached shell (reproduced; matches the GetConsoleScreenBufferInfo console-loss crashes Windows Error Reporting captured during the July 4 and July 5 update windows on the incident machine — and at no June update).
  3. Relocated topology survives. With the native runtime outside the install dir, OpenConsole.exe spawns from userData, FIND reports nothing (the daemon is again the sole install-dir process, back under the single-match umbrella), and daemon + shell + console host all survive the sweep.

This also corrects the earlier working theory: the update-relaunch wedge-kill path fixed in #7340 is real and reproducible, but the installer sweep — not that path — is what killed sessions in the July incidents.

Fix

  • node-pty patch (config/patches/[email protected]): loadNativeModule honors ORCA_NODE_PTY_NATIVE_DIR before its stock search paths, falling through on any failure. The native side already resolves conpty.dll (and spawns OpenConsole.exe) from conpty/ beside the loaded binding, so relocating the binding relocates the console hosts.
  • src/main/pty/node-pty-runtime-relocation.ts: at startup (win32 + packaged only), copy the binding dir (rebuilt build/Release, fallback platform prebuilds; .pdb excluded) to userData/node-pty-runtime/<appVersion>/ and set the env var. Crash-safe via a completion marker (partial copies redone). The forked daemon inherits the env, covering daemon-owned PTYs.
  • Stale version cleanup uses a rename probe: renaming a directory fails on Windows while anything inside is open, so only provably-unused version dirs are deleted — an adopted previous-version daemon keeps its runtime.
  • Fail-open everywhere: any error leaves the env unset and node-pty loads from the install dir exactly as today.

Verification

  • End-to-end sweep test (this machine): daemon-analog + patched node-pty package under a fake install dir, ORCA_NODE_PTY_NATIVE_DIR pointing at a relocated runtime; real ConPTY session with a live powershell.exe. OpenConsole.exe verified running from the relocated dir; the verbatim installer FIND/KILL sequence found nothing and daemon, shell, and console host all survived. Control legs: pre-fix (July) topology → all killed; pre-Fix Windows bundled ConPTY packaging #6968 (June) topology → all spared via the single-match blind spot.
  • Unit tests (node-pty-runtime-relocation.test.ts): source-dir resolution order, tree copy without symbols, marker idempotency, interrupted-copy recovery, stale-version cleanup keeping the current version, fail-open on missing source — plus a win32 integration test loading the real conpty binding through the patched loader from a relocated dir.
  • Typecheck clean; pty suites green (one pre-existing symlink-privilege failure in terminal-cwd-realpath.test.ts, untouched by this change and identical on the base branch).

Follow-ups (not in this PR)

  1. Daemon image relocation — the daemon binary is still INSTDIR\Orca.exe; today it survives via the single-match blind spot. Moving its image out of the install dir makes survival principled instead of accidental (and is the fix that remains correct if electron-builder ever repairs the .Count check upstream).
  2. Upstream report to electron-builder — the single-match .Count bug means the sweep silently skips exactly-one-process cases for every Electron app; conversely apps with detached helpers under the install dir lose them whenever there are 2+.
  3. The periodic resume-record capture from Fix Windows update-relaunch killing the live terminal daemon (session loss on update) #7340 remains the safety net for any path that still loses processes.

Root cause of update-time terminal loss (verified with a reproduction
harness running the installer sweep commands verbatim): the NSIS update
installer force-closes every process whose image path is under the
install directory. Since #6968 started bundling conpty.dll and
OpenConsole.exe under resources/, every live terminal's console host -
and with 2+ matches the daemon too - is killed mid-update. Before #6968
the daemon was the only install-dir process and survived only by luck:
the sweep's find step does (...).Count -gt 0, and in Windows PowerShell
5.1 a single-instance CIM result has null Count, so one match reads as
"nothing running".

Fix: copy the node-pty native runtime (conpty binding + conpty.dll +
OpenConsole.exe + winpty) to userData/node-pty-runtime/<version>/ at
startup and point the node-pty loader at it via ORCA_NODE_PTY_NATIVE_DIR
(loader override added to the existing node-pty patch; falls through to
the stock search paths on any failure). The daemon inherits the env var,
so console hosts for both main- and daemon-owned PTYs run outside the
installer kill zone. Stale version dirs are removed only when a rename
probe proves nothing inside is still running.

Verified end-to-end against the verbatim sweep: with the relocated
runtime, OpenConsole spawns from userData, the sweep finds nothing to
kill, and daemon + shell + console host all survive.
@Jinwoo-H

Jinwoo-H commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

Reproduction harness evidence (installer sweep commands run verbatim against disposable topologies)

Topology legs (sweep-repro.mjs)

=== LEG JULY (conpty mode=dll, runtime INSIDE instdir) ===
[repro +5.5s] daemon-analog pid 55472 (image INSTDIR\Orca.exe), shell pid 35372, console host(s): OpenConsole.exe:27824
[repro +7.9s] sweep: FIND -> FOUND (exit 0)
[repro +10.9s] sweep outcome: cleared-after-graceful
[repro +12.4s] --- JULY RESULT ---
[repro +12.4s]     daemon-analog         (pid 55472): DEAD
[repro +12.4s]     shell (powershell)    (pid 35372): DEAD
[repro +12.4s]     console host OpenConsole.exe (pid 27824): DEAD
[repro +12.4s]     outside control       (pid 41588): ALIVE
=== LEG JUNE (conpty mode=system, runtime INSIDE instdir) ===
[repro +14.6s] daemon-analog pid 47516 (image INSTDIR\Orca.exe), shell pid 14776, console host(s): conhost.exe:21100
[repro +16.5s] sweep: FIND -> nothing (exit 1)
[repro +16.5s] sweep outcome: nothing-found
[repro +18.0s] --- JUNE RESULT ---
[repro +18.0s]     daemon-analog         (pid 47516): ALIVE
[repro +18.0s]     shell (powershell)    (pid 14776): ALIVE
[repro +18.0s]     console host conhost.exe (pid 21100): ALIVE
[repro +18.0s]     outside control       (pid 27124): ALIVE
=== LEG FIX (conpty mode=dll, runtime OUTSIDE instdir) ===
[repro +22.9s] daemon-analog pid 39732 (image runtime\Orca.exe), shell pid 25252, console host(s): OpenConsole.exe:13464
[repro +24.8s] sweep: FIND -> nothing (exit 1)
[repro +24.8s] sweep outcome: nothing-found
[repro +26.3s] --- FIX RESULT ---
[repro +26.3s]     daemon-analog         (pid 39732): ALIVE
[repro +26.3s]     shell (powershell)    (pid 25252): ALIVE
[repro +26.3s]     console host OpenConsole.exe (pid 13464): ALIVE
[repro +26.3s]     outside control       (pid 43388): ALIVE
=== LEG CONSOLE-LOSS (kill only OpenConsole; is the shell a collateral victim?) ===
[repro +31.3s] killing ONLY OpenConsole pid 48832 (daemon-analog and shell untouched)
[repro +31.4s] host 42944: SHELL EXITED ({"event":"shell-exit"})
[repro +34.4s] --- CONSOLE-LOSS RESULT ---
[repro +34.4s]     daemon-analog      (pid 42944): ALIVE
[repro +34.4s]     shell (powershell) (pid 1432): ALIVE
JULY|daemon-analog|DEAD
JULY|shell (powershell)|DEAD
JULY|console host OpenConsole.exe|DEAD
JULY|outside control|DEAD
JUNE|daemon-analog|DEAD
JUNE|shell (powershell)|ALIVE
JUNE|console host conhost.exe|ALIVE
JUNE|outside control|DEAD
FIX|daemon-analog|DEAD
FIX|shell (powershell)|ALIVE
FIX|console host OpenConsole.exe|ALIVE
FIX|outside control|DEAD

Single-match .Count blind spot (Windows PowerShell 5.1)

single-match .Count = [] -gt 0 -> False   # one process running from INSTDIR reads as nothing-running
two-match    .Count = [2] -gt 0 -> True

Post-fix end-to-end (fix-verify.mjs: patched loader + relocated runtime + verbatim sweep)

daemon-analog pid 44412 (image under INSTDIR), shell pid 32676
OpenConsole: 43592 | C:\Users\jinwo\AppData\Local\Temp\claude\C--Users-jinwo-orca-workspaces-orca-barramundi\9650c256-5c60-414b-a8d7-7c1bf6bc3f39\scratchpad\sweep-repro\legs\fix-verify\relocated-runtime\1.0.0\conpty\OpenConsole.exe
OpenConsole image under relocated runtime (NOT instdir): YES
sweep FIND -> nothing running (installer proceeds, kills NOTHING)

=== POST-SWEEP RESULT (post-fix topology) ===
daemon-analog: ALIVE
shell:         ALIVE
OpenConsole:   ALIVE
verdict: FIX VERIFIED — sessions survive the installer sweep

@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

This PR adds Windows-only relocation of node-pty native binaries into a versioned user-data directory, then points node-pty at that directory through an environment variable before the first PTY load. It also patches node-pty’s native loader to try the relocated path first, and adds tests for source resolution, copy and cleanup behavior, and the override path. Separately, the patch updates some Windows build settings, hardens native helper path rewriting, and makes console-list and spawn error handling more resilient.

Related issues: None provided
Related PRs: None provided
Suggested labels: pty, windows, native-module, main-process
Suggested reviewers: None provided

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change, root cause, fix, and verification, but it omits several required template sections and checklist items. Add the missing template sections: Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: relocating the node-pty ConPTY runtime outside the Windows install directory to prevent update-time terminal loss.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1de08489-4548-4d9b-917c-f2d8b200476b

📥 Commits

Reviewing files that changed from the base of the PR and between 9981c3b and 74052e6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • config/patches/[email protected]
  • src/main/index.ts
  • src/main/pty/node-pty-runtime-relocation.test.ts
  • src/main/pty/node-pty-runtime-relocation.ts

Comment thread config/patches/[email protected] Resolved
Comment thread src/main/index.ts Resolved
The update relaunch chain (old app -> installer -> new app) inherits
ORCA_NODE_PTY_NATIVE_DIR from the previous version, so honoring a
pre-set value would pin the new process to stale binaries and skip
copying the current version. Also restore any pre-existing override in
the loader integration test instead of unconditionally deleting it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/pty/node-pty-runtime-relocation.ts (1)

134-136: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clear an inherited stale override when relocation fails.

The comment on Lines 114-117 states a pre-set ORCA_NODE_PTY_NATIVE_DIR (inherited from the previous version via the update relaunch chain) must not pin the new process to stale binaries. That guarantee only holds on the success path. When ensureRelocatedNodePtyNativeRuntime returns null, the env var is left untouched, so the inherited stale value survives in process.env and is honored by the patched loader (and by the forked daemon). This breaks the documented fail-open behavior of loading from the install directory and can pin the new process to a previous version's runtime dir.

🛡️ Proposed fix
   if (destDir) {
     process.env[NODE_PTY_NATIVE_DIR_ENV_VAR] = destDir
+  } else {
+    // Relocation failed: drop any inherited stale override so node-pty
+    // falls back to the install-dir runtime instead of a previous version's dir.
+    delete process.env[NODE_PTY_NATIVE_DIR_ENV_VAR]
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 816c7b70-47ac-4e69-9927-2f0c6a2cd929

📥 Commits

Reviewing files that changed from the base of the PR and between 74052e6 and 2aff843.

📒 Files selected for processing (2)
  • src/main/pty/node-pty-runtime-relocation.test.ts
  • src/main/pty/node-pty-runtime-relocation.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/pty/node-pty-runtime-relocation.test.ts

@Jinwoo-H
Jinwoo-H merged commit 509c41e into main Jul 5, 2026
1 check passed
Jinwoo-H added a commit that referenced this pull request Jul 5, 2026
Re-based onto the current shared remote tip (4110c29, which already
carried an older main sync + windows-update-daemon-adoption); this brings
in the 18 newer main commits through v1.4.124-rc.1. MERGE, not rebase.

Conflict resolutions (our structure wins; main's semantics graft in):

- update-check feature (update-check-click-options.ts + test,
  GeneralUpdateSettingsSection.tsx, SidebarSettingsHelpMenu.tsx + test,
  updater.ts + test): took main's shape — getUpdateCheckHint() centralizes
  the RC/perf hint, pointerdown modifier-capture handler, and the refined
  `checkVariant === 'prerelease'` guard so a perf check never permanently
  opts background retries into the RC channel. getUpdateCheckClickOptions
  (the actual behavior) was byte-identical on both sides.

- Ctrl+K clear vs producer flow control (pty-subprocess.ts, session.ts,
  session.test.ts): kept BOTH — our pause()/resume() flow-control methods
  AND main's clear() ConPTY screen-state resync (#7413). Orthogonal.

- orca-runtime.ts: took main's public visibility on
  clearHeadlessTerminalBuffer (ipc/pty.ts Ctrl+K path calls it); dropped
  main's createHeadlessEmulator factory — our Phase-5 query-authority
  emulator construction is restructured and has no caller for it.

Incoming (auto-merged, off the byte-delivery path): #6277 agent cold-
restore fallback (pty-connection.ts), node-pty ConPTY relocation (#7421),
MiniMax rate limits, translations.

Gates: typecheck 0 errors; ipc+daemon+terminal-pane+pane-manager 4204
passed; both fuzz suites pass; hand-resolved renderer files pass. No
delivery/restore/flow-control/ACK/batching/scheduler bytes changed, so no
10MB bench required.

Co-authored-by: Orca <[email protected]>
brennanb2025 pushed a commit that referenced this pull request Jul 6, 2026
The terminal daemon was fork()ed with no explicit execPath, so its process
image was the install-dir Orca.exe run via ELECTRON_RUN_AS_NODE. On Windows,
the NSIS installer's CHECK_APP_RUNNING sweep force-kills processes whose image
lives under the install directory, so an app update killed the live daemon and
every terminal it hosted (including the user's running Claude process).

Relocate the daemon host image out of the install dir: stage a standalone,
version-correct node.exe under %APPDATA%\orca\daemon-host\<appVersion>\ and fork
the daemon from it. The daemon's image now lives in userData, outside the
installer's kill zone, so it survives updates.

Fail-open: if no relocated node.exe is present, fall back to the current
Orca.exe + ELECTRON_RUN_AS_NODE path (zero regression). Adoption and stale-kill
are unaffected — process identification matches on daemon-entry/socket/token
args and the unchanged entryPath, never the host image name.

Build: afterPack stages the build host's own official (OpenJS-signed) Node 24.x
node.exe into resources/daemon-host/node.exe. engines.node="24" pins the build
host to the ABI Electron 42 embeds (Node 24.15, NAPI 10) so the relocated host
loads node-pty's NAPI conpty.node addon. Shipping the OpenJS-signed binary means
it is validly signed regardless of whether SignPath re-signs nested PEs.

Extract the version-keyed copy + daemon-pinned GC shared by the node-pty native
relocation (#7421) into install-dir-runtime-relocation.ts and reuse it for the
host relocation. CI verify step + contract/config tests guard the staging.
Jinwoo-H added a commit that referenced this pull request Jul 6, 2026
) (#7505)

* Revert "Preload the daemon windowsHide shim via --require; wrap promisify custom (#7499)"

This reverts commit 8f396ba.

* Revert "Hide console windows for children of the node.exe-hosted daemon (#7486)"

This reverts commit f0fdd3a.

* Revert "fix(daemon): relocate daemon host image out of the install-dir kill zone (#7473)"

This reverts commit f4faafa.

* Revert "fix(pty): keep runtime dirs a surviving daemon still uses (#7463)"

This reverts commit 3cd23a1.

* Revert "Relocate node-pty ConPTY runtime outside the Windows install dir (fixes update-time terminal loss) (#7421)"

This reverts commit 509c41e.
Jinwoo-H added a commit that referenced this pull request Jul 6, 2026
Records why the #7421->#7499 chain was reverted in #7505 (failure
mechanisms, why verification missed them, non-negotiables), and lays out
the from-scratch plan: proof harness first, relocate the daemon file
closure out of the install dir while keeping the exact Electron runtime,
fix adoption interactivity, and gate every phase on a packaged-artifact
update test.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…#7421→stablyai#7499) (stablyai#7505)

* Revert "Preload the daemon windowsHide shim via --require; wrap promisify custom (stablyai#7499)"

This reverts commit b5710ee.

* Revert "Hide console windows for children of the node.exe-hosted daemon (stablyai#7486)"

This reverts commit 081cf2f.

* Revert "fix(daemon): relocate daemon host image out of the install-dir kill zone (stablyai#7473)"

This reverts commit 38c2e2e.

* Revert "fix(pty): keep runtime dirs a surviving daemon still uses (stablyai#7463)"

This reverts commit 01ad86a.

* Revert "Relocate node-pty ConPTY runtime outside the Windows install dir (fixes update-time terminal loss) (stablyai#7421)"

This reverts commit 24d599f.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant