Repository navigation
fix(daemon): relocate daemon host image out of the install-dir kill zone - #7473
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThis PR adds a standalone Windows 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (4)
src/main/daemon/daemon-host-relocation.ts (1)
40-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider testing the one-shot
installedguard.
installedis set unconditionally before the platform/env checks, so a second call is always a no-op regardless of outcome. This contract isn't directly asserted by the test suite (each test resets modules instead). A quick test callinginstallRelocatedDaemonHost()twice and asserting only one relocation occurs would lock in this behavior.config/daemon-host-node-runtime.cjs (2)
10-39: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider enforcing the Node-version invariant instead of only documenting it.
The doc comment asserts the staged
node.exeis "version-correct by construction" becauseengines.nodepins the build to Node 24.x. But nothing in the code actually verifiesprocess.versionagainst that pin — it only checks the binary is namednode.exeand exists. If packaging is ever run under a different local/CI Node version (e.g., a manualelectron-builderinvocation outside the pinnedrelease-cut.ymlworkflow, which usesnode-version-file: package.jsonto enforce this), this would silently stage anode.exewith a mismatched NAPI ABI, breaking the daemon at runtime in a way that's hard to diagnose after the fact.Consider reading
engines.nodefrompackage.jsonand assertingprocess.versionsatisfies it, failing the build loudly if not.🛡️ Proposed defensive check
+const { readFileSync } = require('node:fs') +const semver = require('semver') + +function assertExecPathVersionPinned() { + const packageJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf8')) + const requiredRange = packageJson.engines && packageJson.engines.node + if (requiredRange && !semver.satisfies(process.version, requiredRange)) { + throw new Error( + `[daemon-host] build host Node ${process.version} does not satisfy engines.node "${requiredRange}"` + ) + } +} + function ensurePackagedDaemonHostNode(resourcesDir, electronPlatformName) { if (electronPlatformName !== 'win32') { return } + assertExecPathVersionPinned() const nodeExePath = process.execPath
4-8: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShare the daemon-host path constants
src/main/daemon/daemon-host-relocation.tsstill hardcodes'daemon-host'and'node.exe', duplicatingconfig/daemon-host-node-runtime.cjs. Pull both values from one shared constant module so the packaged and relocated paths can’t drift..github/workflows/release-cut.yml (1)
881-888: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: fold into the existing
$requiredFilesloop for consistency.The new daemon-host check duplicates the existing
Test-Path/throwpattern as a standalone block rather than joining$requiredFiles, so the verification logic now exists in two slightly different shapes in the same step.♻️ Optional consolidation
$runtimeDir = 'dist/win-unpacked/resources/node_modules/node-pty/build/Release' + # The standalone node.exe that hosts the terminal daemon outside the + # install-dir kill zone the NSIS updater sweeps. See + # src/main/daemon/daemon-host-relocation.ts. $requiredFiles = @( "$runtimeDir/conpty.node", "$runtimeDir/conpty/conpty.dll", - "$runtimeDir/conpty/OpenConsole.exe" + "$runtimeDir/conpty/OpenConsole.exe", + 'dist/win-unpacked/resources/daemon-host/node.exe' ) foreach ($file in $requiredFiles) { if (-not (Test-Path -LiteralPath $file -PathType Leaf)) { throw "Missing Windows node-pty runtime file: $file" } Get-Item -LiteralPath $file } - # The standalone node.exe that hosts the terminal daemon outside the - # install-dir kill zone the NSIS updater sweeps. See - # src/main/daemon/daemon-host-relocation.ts. - $daemonHostNode = 'dist/win-unpacked/resources/daemon-host/node.exe' - if (-not (Test-Path -LiteralPath $daemonHostNode -PathType Leaf)) { - throw "Missing Windows daemon-host runtime file: $daemonHostNode" - } - Get-Item -LiteralPath $daemonHostNode
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 68440ae6-99bb-4963-8902-4d667d9a834e
📒 Files selected for processing (13)
.github/workflows/release-cut.ymlconfig/daemon-host-node-runtime.cjsconfig/electron-builder.config.cjsconfig/scripts/electron-builder-config.test.mjsconfig/scripts/package-electron-runtime-contract.test.mjssrc/main/daemon/daemon-host-relocation.test.tssrc/main/daemon/daemon-host-relocation.tssrc/main/daemon/daemon-init.tssrc/main/index.tssrc/main/pty/install-dir-runtime-relocation.test.tssrc/main/pty/install-dir-runtime-relocation.tssrc/main/pty/node-pty-runtime-relocation.test.tssrc/main/pty/node-pty-runtime-relocation.ts
Jinwoo-H
left a comment
There was a problem hiding this comment.
Reviewed with the context of the original installer-sweep investigation (I wrote #7421 and the harness evidence on it). This is the right fix — it's precisely the "phase 2: daemon image relocation" follow-up #7421's description called for, and it removes our dependence on the installer's single-match .Count blind spot, which was the one remaining accidental protection. I verified the load-bearing assumptions independently rather than taking the description's word:
Verified — ABI. node-pty 1.1.0 is pure N-API (node-addon-api, node_api.h, Napi:: throughout its C++ sources) — no V8-ABI coupling to Electron. And empirically: during the input-freeze investigation I ran the real daemon-entry under a standalone node.exe with the repo's conpty binding, spawning live ConPTY PowerShell sessions, for hours on a Windows machine. The core concept of this PR is field-tested. The engines.node: "24" + node-version-file: package.json wiring in release-cut means the staged binary genuinely version-matches Electron 42's embedded Node.
Verified — GC pinning is safe on main today. All win32 pid files on main currently have startedAtMs: null (the CIM start-time self-report isn't on main yet), so pinning rests on startTimeMatches(pid, null) → fails open → live daemons pin their dirs. Adoption never rewrites the pid file (only the fresh-fork ready handler writes it), so a surviving daemon's pin can't silently shift to the new app version. And the module correctly encodes the .stale.stale lesson: no rename heuristics, pid-file pinning only.
Verified — identity/adoption unaffected. killStaleDaemon/health checks match on command line (daemon-entry + socket/token) and recorded entryPath, never the image name.
Two small requests before/right after merge:
- Move the ~70 MB copy off the pre-window startup path.
installRelocatedDaemonHost()runs synchronously in thehasSingleInstanceLockblock, so the first launch after every update pays a ~70 MB sync copy (plus AV scan of a fresh signed exe) before anything paints — colliding with the Windows startup-latency work (#7266 et al.). Its only consumer is the daemon fork; the function is latched/idempotent, so calling it frominitDaemonPtyProvider(or the launcher) instead preserves the ordering guarantee at zero risk. - Include the host-decision breadcrumb now rather than as a follow-up. Known-risk #2 says nothing logs which host the fork used. We just spent a full field investigation blind because
main.trace.ndjsoncarries zero daemon lifecycle logging — one breadcrumb at the fork site (relocatedvsfallback+ path) is ~5 lines and would have saved hours.
One correction for the handoff record: the #7456 framing ("discovery map missed the legacy session, so keystrokes dispatched to the wrong daemon") is stated more confidently than the evidence supports. My instrumented cross-version harness showed discovery populating the router map correctly and writes landing on the v18 daemon at the router layer; the field freeze is more plausibly the ptyOwnership gate in ipc/pty.ts (writes silently rejected for ids missing from that registry, while resize uses a lenient fallback — matching the field observation that resize reflowed the TUI while typing was dead). #7456 is still worth having as hardening, but the frozen-input root cause should be treated as open until the DevTools writeAccepted probe is run on an affected machine.
Also noting: the platform (windows/mac/linux) CI jobs skipped on this PR — verify and both native-smoke legs passed. Given the risk surface is Windows-packaging-specific and unit-testable parts are covered, the real validation is the planned RC exercise: note it takes TWO fixed builds to see the benefit (the update to the first fixed build still sweeps the old daemon; only fixed→fixed survives).
|
Spec note for the host-decision logging request: emit it through the observability tracer ( |
- Move installRelocatedDaemonHost() from app startup into the daemon launcher: the ~70MB node.exe copy no longer sits on the first-paint path, and launches that adopt a live daemon (no fork) skip it entirely. The ordering guarantee is unchanged - the launcher stages the host immediately before computing the fork execPath. - Emit daemon.fork / daemon.adopt spans through the observability tracer so field trace files (userData/logs/main.trace.ndjson, also collected by diagnostic bundles) show which host image the daemon runs from and whether a launch adopted or forked. A silent fallback to the install-dir host was previously indistinguishable from the fixed path; the update-survival investigations had zero daemon lifecycle records to work with. - Fail-open hardening: installRelocatedDaemonHost() no longer throws when process.resourcesPath is unset (tests, node-hosted tooling). Verified: 79 daemon/relocation/tracer tests + 21 builder-config tests pass; typecheck clean; end-to-end smoke on Windows forked the BUILT daemon-entry.js bundle from a standalone node.exe (execPath swap, empty execArgv, no ELECTRON_RUN_AS_NODE) and drove a live ConPTY session through it with working input and output.
Since #7473 the terminal daemon runs under a standalone node.exe. Electron's bundled Node defaults windowsHide to true; plain node.exe defaults it to false, so every child_process call in the daemon that does not pass the flag - the periodic PowerShell CIM process probes, node-pty's kill-path conpty_console_list_agent fork - now allocates a visible console, which opens and closes a Windows Terminal window on the user's screen every few seconds. Fix: daemon-entry installs a child_process shim (first import, before any module captures bindings like promisify(execFile)) that defaults windowsHide: true across spawn/exec/execFile/fork and their sync variants, restoring the Electron default the daemon has always relied on. Explicit windowsHide from a caller still wins. Also adds windowsHide to node-pty's console-list agent fork in the existing patch as defense in depth. Verified on Windows: reproduced the flash with the rc.5 production daemon (WindowsTerminal windows, ~3s cadence matching the CIM probe interval, conhost spawned visible-capable "0x4"); with the shim, a node.exe-hosted daemon's children (OpenConsole, powershell, node helpers) all run without a visible-capable console and session kill still works end to end.
Since #7473 the terminal daemon runs under a standalone node.exe. Electron's bundled Node defaults windowsHide to true; plain node.exe defaults it to false, so every child_process call in the daemon that does not pass the flag - the periodic PowerShell CIM process probes, node-pty's kill-path conpty_console_list_agent fork - now allocates a visible console, which opens and closes a Windows Terminal window on the user's screen every few seconds. Fix: daemon-entry installs a child_process shim (first import, before any module captures bindings like promisify(execFile)) that defaults windowsHide: true across spawn/exec/execFile/fork and their sync variants, restoring the Electron default the daemon has always relied on. Explicit windowsHide from a caller still wins. Also adds windowsHide to node-pty's console-list agent fork in the existing patch as defense in depth. Verified on Windows: reproduced the flash with the rc.5 production daemon (WindowsTerminal windows, ~3s cadence matching the CIM probe interval, conhost spawned visible-capable "0x4"); with the shim, a node.exe-hosted daemon's children (OpenConsole, powershell, node helpers) all run without a visible-capable console and session kill still works end to end.
) (#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.
… to survive updates Phase 1 of Windows terminal update-survival. On win32 packaged, the terminal daemon is now forked from a copy of the Electron runtime staged under userData/daemon-host/<version> (run as node, ELECTRON_RUN_AS_NODE), so its process image and all loaded modules live outside the install dir the NSIS updater deletes and force-closes. Keeping the Electron binary (not stock node.exe) means run-as-node behavior is byte-identical — no console flashing, asar-correct — which the reverted #7473 attempt broke. Proven on CI by tools/daemon-relocation-spike: a copied Orca.exe boots the daemon, drives a real ConPTY session, and holds zero loaded-module handles into the install dir, on the minimal file set. - daemon-host-relocation.ts: materialize (atomic staging + marker-last + fail-open), version-keyed dir, PID-pinned GC of old versions. - daemon-init.ts: fork from the relocated exe/entry when available; byte-identical in-dir fork otherwise (non-win32, dev, or fail-open). - Adoption-neutral: protocol/pipe unchanged; a new app still adopts an old in-dir daemon. - win-update-survival-e2e.yml: builds a branch installer and runs the harness with --expect survival to prove sessions survive an update.
…one (stablyai#7473) Co-authored-by: Neil <[email protected]> Co-authored-by: Jinwoo Hong <[email protected]>
…lyai#7486) Since stablyai#7473 the terminal daemon runs under a standalone node.exe. Electron's bundled Node defaults windowsHide to true; plain node.exe defaults it to false, so every child_process call in the daemon that does not pass the flag - the periodic PowerShell CIM process probes, node-pty's kill-path conpty_console_list_agent fork - now allocates a visible console, which opens and closes a Windows Terminal window on the user's screen every few seconds. Fix: daemon-entry installs a child_process shim (first import, before any module captures bindings like promisify(execFile)) that defaults windowsHide: true across spawn/exec/execFile/fork and their sync variants, restoring the Electron default the daemon has always relied on. Explicit windowsHide from a caller still wins. Also adds windowsHide to node-pty's console-list agent fork in the existing patch as defense in depth. Verified on Windows: reproduced the flash with the rc.5 production daemon (WindowsTerminal windows, ~3s cadence matching the CIM probe interval, conhost spawned visible-capable "0x4"); with the shim, a node.exe-hosted daemon's children (OpenConsole, powershell, node helpers) all run without a visible-capable console and session kill still works end to end.
…#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.
Problem
On Windows, terminal daemon sessions don't survive app updates. The terminal daemon was
fork()ed with no explicitexecPath, so its process image was the install-dirOrca.exerunning underELECTRON_RUN_AS_NODE=1. The NSIS installer'sCHECK_APP_RUNNINGsweep force-kills any process whose image lives under the install directory — so an update killed the live daemon and every terminal it hosted (including a running Claude process).Fix
Relocate the daemon's host image out of the install dir. A standalone, version-correct
node.exeis staged under%APPDATA%\orca\daemon-host\<appVersion>\, and the daemon is forked from that (execPath= relocatednode.exe,execArgv: [], noELECTRON_RUN_AS_NODE). Its image now lives in userData, outside the installer's kill zone, so it survives updates.afterPack, win32-only): copies the build host's ownprocess.execPath— the official OpenJS-signed Node 24.xnode.exe— intoresources/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 NAPIconpty.node. Shipping the OpenJS-signed binary means it is validly signed regardless of whether SignPath re-signs nested PEs.install-dir-runtime-relocation.tsand reused it for the host. GC only reclaims version dirs that no live daemon pins (viadaemon-v<N>.pidappVersion), so a surviving daemon's host is never deleted.daemon-entry/socket/token args and the unchangedentryPath— never the host image name. Verified end-to-end indaemon-health.ts.Fallback behavior
If no relocated
node.exeis present (dev, non-win32, pre-relocation builds), the daemon forks from the currentOrca.exe+ELECTRON_RUN_AS_NODEhost. This is a "this environment has no install-dir kill zone" path — mac/Linux and dev builds have no NSIS sweep and nothing staged, so they keep launching the daemon the way they always have. It is not a Windows degradation path (see risk #1 for the present-but-unusable case).Context & handoff — how this differs from the frozen-input work (#7456)
This PR came out of the same production investigation as the frozen-input bug, but fixes a different, more severe failure mode. For an agent picking up either thread:
Original symptom → PR fix(daemon): self-heal write routing for undiscovered legacy sessions #7456 (open): "frozen input with live output." After a protocol-bumping update (
v1.4.124-rc.1protocol v18 →rc.2.perfprotocol v19) an old daemon survived holding live sessions;DaemonPtyRouterfanned reads out to all daemons but routed writes through a discovery map that had missed the legacy session, so keystrokes were dispatched to the wrong (new) daemon and dropped. fix(daemon): self-heal write routing for undiscovered legacy sessions #7456 self-heals that routing. fix(daemon): self-heal write routing for undiscovered legacy sessions #7456 is the frozen-input fix — this PR (fix(daemon): relocate daemon host image out of the install-dir kill zone #7473) is not.The frozen-input symptom can only occur when an old daemon survives an update. Investigating that precondition exposed that daemon-survival-across-Windows-updates is broken in three independent ways:
conptybinaries yanked → spawns failConnective tissue: the same dual-daemon-during-update condition that triggers fix(daemon): self-heal write routing for undiscovered legacy sessions #7456's routing bug is also what made the NSIS sweep count ≥2 install-dir processes and force-kill them all. Relocating the host (this PR) removes daemons from the sweep's view entirely, so surviving daemons become the norm — which makes fix(daemon): self-heal write routing for undiscovered legacy sessions #7456's correct-routing-to-survivors more necessary, not less. fix(daemon): self-heal write routing for undiscovered legacy sessions #7456 + fix(pty): keep runtime dirs a surviving daemon still uses #7463 + fix(daemon): relocate daemon host image out of the install-dir kill zone #7473 together = "update the app without losing or freezing your terminals."
This PR in one line: stop the Windows updater from killing the daemon process. It does not touch write/resize routing (that's fix(daemon): self-heal write routing for undiscovered legacy sessions #7456) or change runtime-dir GC semantics beyond reusing fix(pty): keep runtime dirs a surviving daemon still uses #7463's version-keyed cleanup.
Tests
install-dir-runtime-relocation.test.ts,node-pty-runtime-relocation.test.ts), 3 daemon-host tests, plus contract + electron-builder-config tests covering the staging and the "must be a realnode.exe" guard.resources/daemon-host/node.exeis staged.node/cli/webtypecheck clean; oxlint + oxfmt clean.Known risks & accepted limitations
An adversarial audit surfaced these. We are deliberately shipping without a fork-failure fallback — rationale under #1.
node.exeexists; it does not retry onOrca.exeif that fork fails. Three present-but-unusable cases therefore degrade to the non-persistent in-processLocalPtyProvider(terminals still work — you can type and see output — just no cross-update persistence): (a) AppLocker/WDAC default rules blocking%APPDATA%execution; (b) the stagednode.exequarantined by AV/EDR after the.relocation-completemarker is written (ENOENTat fork); (c) an ABI-incompatiblenode.exe(daemon starts, thenpty.spawnfails). We considered a retry-on-Orca.exefallback and chose not to add it: it could only prevent a regression for locked-down shops, and it cannot give those environments kill-zone escape anyway — for a non-admin under AppLocker default rules, no path is both execution-allowed and outside the install dir. Terminals stay functional in all three cases.Orca.exe) is still killed on the upgrade that ships the fix. Only fixed→fixed updates benefit. Worth a release note.node.exein user-writable%APPDATA%, forked without an integrity re-check, is a tamper/persistence target and may trip EDR living-off-the-land / publisher-allowlist heuristics. Relocate node-pty ConPTY runtime outside the Windows install dir (fixes update-time terminal loss) #7421 already placed executable native code (conpty.node) in userData, so this is incremental, not novel.Minor: the ~70 MB copy is synchronous on the first launch after each update (one-time, marker-guarded); downgrade to a pre-fix build leaks
daemon-host/<version>dirs (self-heals on the next re-upgrade).Validation plan
E2E on the next rc: packaged build → install → trigger an update → confirm the daemon + terminals survive. Unit tests can't exercise the NSIS sweep.