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
feat(windows): run the session host from a staged runtime outside the install dir (#829)
reviewf51a3dba32ce
diff --git a/CLAUDE.md b/CLAUDE.mdindex 35ed39d83..54656b3e9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8573,6 +8573,35 @@ verify and stop any remaining host. Never recommend **End session** (it deletesresume depends on supported, saved conversation history; it does not preserve running tasks.See `docs/windows-session-host.md` for the user-controlled preparation/recovery steps and limits.+**Staged host runtime (#829 step 3).** The host used to run as a hard link of `nodeterm.exe` INSIDE+the install dir, so it mapped the installed exe/DLLs/`resources.pak` and every update stopped until+the user ended it (and every session). Packaged Windows builds now copy what the host needs into+`%LOCALAPPDATA%\nodeterm\session-host\<version>-<fingerprint>\` and launch+`nodeterm-sessionhost-v2.exe` from there (`core/session-host-runtime.ts`, wired in+`session-host-backend.ts`; the client waits at most `STAGED_RUNTIME_WAIT_MS` for the first staging+of a version). Rules a refactor must not undo:+- **Only a published, verified copy is launched.** Files are copied into `.staging-<uuid>`, each+ re-read and compared by SHA-256, the copy is smoke-run once (`ELECTRON_RUN_AS_NODE`, requires its+ node-pty, must exit `SMOKE_OK`), the marker is written LAST, and the dir is published by one+ `renameAtomic`. A dir without a valid marker (sizes checked on reuse) is moved aside, never run.+- **A new image name.** Old uninstallers match `nodeterm.exe`/`nodeterm-session-host.exe` by NAME+ machine-wide; the staged host must never answer to either. The preflight deliberately does not+ match it by name (path test still applies).+- **Fail-safe, not fail-open.** Any staging failure, or a staged host that dies within 10 s with a+ code other than the host's own 0/1 (`stagedExitWantsFallback` — a missing DLL, a policy block),+ falls back to the legacy hard-link launch for the rest of the run. That host still blocks the+ installer through the unchanged read-only preflight.+- **GC is fail-closed.** An old version dir is deleted only when a successful Win32_Process query+ shows nothing running under it, no staged-host process has an unreadable path, it is older than+ 10 min, AND a rename aside succeeds (Windows refuses while an image inside is mapped). The+ uninstaller leaves the staged runtimes alone (never kills a host); `docs/uninstall.md` lists them.+- **The file set is not measured yet** (written on Linux): exe, top-level `*.dll`, `icudtl.dat`+ (required), `resources.pak`, snapshot blobs, `locales/`, `resources/session-host/**`. The smoke+ run is what proves it per machine; device checklist in docs/windows-session-host.md.+- **Protocol is additive-only across versions.** A newer app keeps using an older staged host+ (protocol v1/v2 + `hello` features); an unsupported one is left running and reported+ (`SessionHostProtocolCompatibilityError`), never killed. ~250 MB of disk per staged version.+**Follow-ups, in order:** code signing, then Windows auto-update wiring (electron-updater NSIS leg+ `latest.yml` on the nodeterm.dev feed — blocked on signing: an unsigned auto-update is adowngrade in trust), and the fork's PE-identity polish (electron-builder leaves `OriginalFilename`diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex cafbf9fdc..384ab0dfd 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -93,6 +93,17 @@ verify and stop any remaining host. Never recommend **End session** (it deletesresume depends on supported, saved conversation history; it does not preserve running tasks.See `docs/windows-session-host.md` for the user-controlled preparation/recovery steps and limits.+Staged host runtime (#829 step 3): a packaged Windows build launches the host from a private+copy, `%LOCALAPPDATA%\nodeterm\session-host\<version>-<fingerprint>\nodeterm-sessionhost-v2.exe`+(`src/core/session-host-runtime.ts`), so it maps no installed file and no longer blocks updates.+Rules: a copy is launched only after it was published by one rename of a hash-verified,+smoke-tested temp dir (marker written last); the image name must stay unlike `nodeterm.exe` /+`nodeterm-session-host.exe` (old uninstallers match those by name machine-wide); every staging+failure falls back to the legacy in-install-dir launch, which the preflight still blocks on; old+copies are deleted only after a SUCCESSFUL process query shows nothing runs from them and the+directory can be renamed aside. The host protocol stays additive-only — an older host is kept and+used, an incompatible one is left running and reported, never killed.+## Three surfacesA feature is not done until you have decided how it behaves on each — even if the decision is "notdiff --git a/docs/uninstall.md b/docs/uninstall.mdindex ff58e2cdc..c5886acfd 100644--- a/docs/uninstall.md+++ b/docs/uninstall.md@@ -123,3 +123,8 @@ So the honest design is:Windows note: the desktop build ships as an NSIS installer with its own uninstaller(Add/Remove Programs); after running it, delete `%APPDATA%\node-terminal` and`%USERPROFILE%\.nodeterm`. The POSIX script does not run there.+The uninstaller also leaves `%LOCALAPPDATA%\nodeterm\session-host` — the session host's private+runtime copies (about 250 MB per app version, issue #829) — because a host may still be running+from one and the uninstaller never stops it. Delete that folder after any+`nodeterm-sessionhost-v2.exe` process has exited (Task Manager → Details); Windows refuses while it+is running, which is safe.diff --git a/docs/windows-session-host.md b/docs/windows-session-host.mdindex d8fe9cdba..4bd559c43 100644--- a/docs/windows-session-host.md+++ b/docs/windows-session-host.md@@ -398,11 +398,91 @@ confirmed `{ok:true}` host responses, while a transport/request rejection remainpropagated. That propagation is what lets the periodic snapshot keep its dirty bit for a retry andwhat prevents a delete from claiming a persistent process is gone when the host never confirmed it.+## Staged host runtime (issue #829, step 3)++A host launched as a hard link of `nodeterm.exe` inside the install directory maps the installed+executable, its DLLs and `resources.pak`, so the installer cannot replace them while it runs. On+macOS/Linux the sessions live in tmux, a separate binary, and survive an update; the staged runtime+gives Windows the same property.++**What happens.** In a packaged Windows build, before the app spawns a host it stages+(`src/core/session-host-runtime.ts`) a private copy of the runtime into++ %LOCALAPPDATA%\nodeterm\session-host\<app version>-<fingerprint>\+ nodeterm-sessionhost-v2.exe (nodeterm.exe, renamed)+ *.dll, icudtl.dat, resources.pak, snapshot_blob.bin, v8_context_snapshot.bin, locales\+ resources\session-host\host.cjs + node_modules\node-pty\…+ nodeterm-runtime.json (marker: file list, sizes, SHA-256)++and launches the host from there. The fingerprint hashes every source file's path, size and mtime,+so a reinstall of the same version with different bytes gets its own directory. `app.asar` is not+copied (the host never reads it).++**The file set is not measured.** It was written on Linux and is the conservative set an+`ELECTRON_RUN_AS_NODE` process can plausibly touch: `icudtl.dat` is required (Node's ICU data);+`resources.pak` was measured open by a running host in #829; the DLLs cover load-time and delayed+imports; `locales\` covers resource-bundle initialisation. The per-machine proof is the smoke run+below. Device checklist item 1 measures the real set so it can be pruned.++**Never a half-staged directory.** Files are copied into `.staging-<uuid>` beside the target, each+copy is re-read and compared by SHA-256 to what was read from the install directory, and the copy is+smoke-run once: `nodeterm-sessionhost-v2.exe -e …` with `ELECTRON_RUN_AS_NODE=1` must load,+`require` its own node-pty and exit `42`. Only then is the marker written, and the directory is+published by one `renameAtomic`. A directory without a valid marker (or whose files no longer have+their recorded sizes) is moved aside and restaged, never launched. Two app processes staging the+same version at once both succeed: the second rename loses and adopts the first one's directory.++**A new image name.** Uninstallers already in the field match `nodeterm.exe` and+`nodeterm-session-host.exe` machine-wide by name; the staged host runs as+`nodeterm-sessionhost-v2.exe` so none of them mistakes it for something that blocks them.++**Fail-safe.** Every staging failure (no `%LOCALAPPDATA%`, a missing required file, disk full, a+failed hash, a smoke run that does not answer 42 within 60 s — STATUS_DLL_NOT_FOUND, an AppLocker or+WDAC policy blocking executables under the profile) falls back to the legacy launch: the hard link+in the install directory, then `nodeterm.exe` itself. A staged host that dies within 10 s with an+exit code other than the host's own `0`/`1` also falls back, and staging is not offered again for+the rest of the app run. The legacy host still blocks the installer, so the preflight below still+protects the install. The first launch of a new version waits at most 45 s for staging (copy,+hashing, smoke run; usually a few seconds, longer behind an antivirus scan); past that the host is+launched the legacy way and the finished copy serves the next launch. Staging progress and failures+are appended to `<userData>\session-host.log` with an `[app]` tag.++**Old copies.** After staging, copies other than the current one are collected — fail-closed: only+when a Win32_Process query SUCCEEDS, no `nodeterm-sessionhost-v2.exe` process has an unreadable+path, nothing runs from under that directory, the directory is older than 10 minutes, and renaming+it aside succeeds (Windows refuses while an image inside is mapped). A failed query deletes nothing.+A host started by an older version therefore keeps its copy for as long as it runs; once it exits+(30 s after its last session), the next app launch removes that copy. Disk use: about 250 MB per+version, normally one or two versions.++**Versions talk to each other.** There is one host per user-data directory, whichever runtime+started it. A newer app connects to a host started by an older staged runtime through the existing+negotiation: the state file's protocol version (v1 or v2 accepted) and the `hello` feature list+(`SESSION_HOST_FEATURES`, e.g. `geometry`). New sessions go to that host as long as it is+compatible; it exits by itself once it empties, and the next host is launched from the current+version's copy. The rule for every future change: **the host protocol is additive-only** — a new+command or push frame is negotiated at `hello`, never assumed. An operation an older host cannot+perform is refused with `SessionHostProtocolCompatibilityError`, which tells the user why. A host+whose protocol version the app does not accept at all is left running and the connect fails with+that reason — an app never kills a host to replace it.++**Not covered.** A dev checkout (`electron-vite dev`) and an asar-resolved bundle keep the legacy+launch. Server Edition and macOS/Linux are unaffected (tmux).+## Windows updates and uninstalls-A running host maps the installed Electron executable and its DLLs. Its separate hard-link name-makes it identifiable; it does **not** make the install directory safe to replace. Closing the app-alone deliberately leaves the host and its sessions running (#829).+A host launched the legacy way (a hard link inside the install directory, or `nodeterm.exe` itself)+maps the installed Electron executable and its DLLs. Its separate hard-link name makes it+identifiable; it does **not** make the install directory safe to replace. Closing the app alone+deliberately leaves the host and its sessions running (#829). A host running from its staged+runtime (above) maps nothing in the install directory and does not block an update or an+uninstall: the preflight matches it neither by name nor by path, and the old version's uninstaller+does not know its name. Updating from a version that predates the staged runtime still meets that+version's legacy host once.++The uninstaller leaves `%LOCALAPPDATA%\nodeterm\session-host` in place, because a staged host may+still be running from it and the uninstaller never stops a host. `docs/uninstall.md` says how to+remove it afterwards.The NSIS install/uninstall preflight now refuses to proceed while the app or host is running fromany installation, or a process runs under the installation path prefix. It replaces electron-builder's@@ -464,6 +544,9 @@ Mirrors tmux's server lifetime rule as closely as a different OS allows:- **Spawned detached, unref'd, `stdio: 'ignore'`, `windowsHide: true`**(`session-host-launcher.ts`) — survives the spawning app process exiting entirely.+- In a packaged Windows build the binary is the **staged runtime's**+ `nodeterm-sessionhost-v2.exe` outside the install directory (see "Staged host runtime"), so a+ host also outlives an update of the app; the legacy hard link is the fallback.- In a **packaged** app, `process.execPath` is the Electron binary itself (there is no separate`node` executable to shell out to), so the child is spawned with `ELECTRON_RUN_AS_NODE=1`,which tells Electron to run as a plain Node process with no Chromium/BrowserWindow machinery.@@ -696,6 +779,44 @@ injected sharing violations. That source/runtime evidence does not replace the p## Packaged verification still owed+### Staged host runtime (#829 step 3) — device checklist++Written and unit-tested on Linux; nothing below has run on Windows yet.++1. **Measure the file set.** On a packaged build, run Process Monitor filtered to+ `nodeterm-sessionhost-v2.exe` during host start and an attach; record every file opened under+ the staged directory. Prune `RUNTIME_*` in `session-host-runtime.ts` to that set (expect+ `locales\` and most DLLs to be unnecessary) and re-run the smoke check.+2. **Smoke run passes.** Fresh install of the new build, open a terminal: `session-host.log`+ shows `[app] staged runtime: published <key>`, and Task Manager → Details shows+ `nodeterm-sessionhost-v2.exe` with a path under `%LOCALAPPDATA%\nodeterm\session-host`.+3. **Update 0.3.x → new build with live sessions.** On a release with the legacy host, the first+ update still meets the legacy host (expected: prepare as before). Then, with the new build's+ staged host holding live shells/agents, install the NEXT build with the app closed: the installer+ must not prompt, must complete, and after reopening every session re-attaches **warm** (log:+ `attach (warm)`, same host pid as before the update).+4. **Same, with the app open** during the install: the preflight prompts for the app only; after+ closing it the install completes and sessions stay warm.+5. **Old uninstaller during update.** Confirm the previous version's uninstaller (both a pre-#868+ stock one and a #868 one) completes with the staged host running.+6. **Compatibility.** With a staged host from build N running, launch build N+1: new terminals go+ to the old host; after the last session closes and 30 s pass, the next terminal starts a host+ from N+1's copy and N's directory is removed on the following launch.+7. **GC fail-closed.** With a staged host of an old version running, launch the new app: that old+ directory is kept. With PowerShell blocked by policy: nothing is removed.+8. **Defender / AV.** First staging with real-time protection on: time it (log timestamps), check+ for quarantine or SmartScreen prompts, and that a scan holding the new exe does not fail the+ publish rename. Repeat with a third-party AV and with AppLocker/WDAC denying executables in the+ profile (expected: smoke run fails, legacy launch, installer still protects the install).+9. **Disk usage.** Size of one staged version directory; confirm only the current (plus running)+ versions remain after a few updates.+10. **Uninstall** with a staged host running: completes, host and sessions keep running, the+ staged folder remains; after the host exits the folder can be deleted.+11. **Two users / all-users install.** Each user stages their own copy; one user's host does not+ block another user's update.++### Earlier items+The real Windows x64 installer must still be exercised through the required cheap headless route:create every available profile, verify input/output/resize/Unicode/copy/cwd and labels, relauncharound a long-running process, switch a node through the destructive profile warning, and recorddiff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex be562dc3e..9abb45a43 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -36,7 +36,8 @@# with a warning — they are harmless: the installed hook command is self-guarded and becomes# a silent no-op once the script it points to is deleted.# - macOS and Linux. On Windows use the NSIS uninstaller (Add/Remove Programs), then delete-# %APPDATA%\node-terminal and %USERPROFILE%\.nodeterm.+# %APPDATA%\node-terminal, %USERPROFILE%\.nodeterm and (once no nodeterm-sessionhost-v2.exe+# runs) %LOCALAPPDATA%\nodeterm\session-host.set -uDRY_RUN=0diff --git a/scripts/windows-update-preflight.ps1 b/scripts/windows-update-preflight.ps1index c63925ce8..34fdf5c8d 100644--- a/scripts/windows-update-preflight.ps1+++ b/scripts/windows-update-preflight.ps1@@ -10,6 +10,10 @@ try {# Old uninstallers can use a machine-wide NAME match, or a PATH PREFIX match without a# directory boundary. We must cover both before handing control to that old executable.# This deliberately blocks another installation too; it never terminates its processes.+ # The STAGED host (nodeterm-sessionhost-v2.exe, run from a private copy under+ # %LOCALAPPDATA%\nodeterm\session-host, issue #829) is deliberately NOT matched by name:+ # it maps none of this installation's files, so the install may replace them while it+ # keeps its sessions. It is still caught by the path test below if it ever ran from here.if ($process.Name -ieq 'nodeterm.exe' -or $process.Name -ieq 'nodeterm-session-host.exe') {if ([string]::IsNullOrWhiteSpace($process.ExecutablePath)) { exit 20 }exit 10diff --git a/scripts/windows-update-preflight.test.ts b/scripts/windows-update-preflight.test.tsindex 0a9d44e89..05b9f2772 100644--- a/scripts/windows-update-preflight.test.ts+++ b/scripts/windows-update-preflight.test.ts@@ -18,6 +18,10 @@ const host: Process = {Name: 'nodeterm-session-host.exe',ExecutablePath: 'C:\\Apps\\nodeterm\\nodeterm-session-host.exe'}+const staged: Process = {+ Name: 'nodeterm-sessionhost-v2.exe',+ ExecutablePath: 'C:\\Users\\me\\AppData\\Local\\nodeterm\\session-host\\0.4.0-0123456789abcdef\\nodeterm-sessionhost-v2.exe'+}function probe(processes: Process[], fail = false, directory = 'C:\\Apps\\nodeterm'): number | null {// Override only the query, in a fresh PowerShell process. Never enumerate or stop real sessions.const fixture = path.join(temp, 'processes.json')@@ -44,7 +48,15 @@ describe.skipIf(!available)('installer preflight with disposable process-query f['unknown app owner/path', [{ ...app, ExecutablePath: '' }], 20],['uninstaller copied to temp is clear', [{ Name: 'Uninstall nodeterm.exe', ExecutablePath: 'C:\\Temp\\Uninstall nodeterm.exe' }], 0],['legacy prefix-matched process blocks', [{ Name: 'helper.exe', ExecutablePath: 'C:\\Apps\\nodeterm-other\\helper.exe' }], 10],- ['unrelated process outside installation is clear', [{ Name: 'helper.exe', ExecutablePath: 'C:\\Other\\helper.exe' }], 0]+ ['unrelated process outside installation is clear', [{ Name: 'helper.exe', ExecutablePath: 'C:\\Other\\helper.exe' }], 0],+ // Issue #829 step 3: a host running from its staged runtime outside the install directory+ // maps none of the installed files and must not block the update.+ ['staged host outside the installation is clear', [staged], 0],+ ['app closed / staged host live / legacy host gone is clear', [staged, { Name: 'svchost.exe', ExecutablePath: null }], 0],+ ['staged host plus the legacy host still blocks', [staged, host], 10],+ ['staged host plus the app still blocks', [staged, app], 10],+ ['staged image name inside the installation blocks by path', [{ ...staged, ExecutablePath: 'C:\\Apps\\nodeterm\\nodeterm-sessionhost-v2.exe' }], 10],+ ["another user's staged host with an unreadable path is clear", [{ ...staged, ExecutablePath: null }], 0]] as const)('%s', (_name, processes, result) => {expect(probe([...processes])).toBe(result)})diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.tsindex aa80eedeb..8eeb8ba15 100644--- a/src/core/session-host-backend.ts+++ b/src/core/session-host-backend.ts@@ -5,12 +5,15 @@ import type { TextDeliveryResult } from '../shared/text-delivery'// sites need a session-host equivalent for. Nothing here is tmux-specific or Electron-specific;// see docs/windows-session-host.md for how each of these maps onto the underlying protocol.+import fs from 'fs'+import path from 'path'import { platform } from './platform'import {SessionHostClient,SessionHostProtocolCompatibilityError} from './session-host-client'import { SessionHostPty } from './session-host-pty'+import { ensureStagedHostRuntime } from './session-host-runtime'import type { ExecuteLaunchResult, SessionHostSpawnOptions } from '../session-host/protocol'import type { PreparedAgentLaunch } from './agent-launch'import type { PaneOwner } from '../shared/agents/pane-owner-predicate'@@ -42,7 +45,31 @@ function getClient(): SessionHostClient {appPath: platform().appPath,// Dev-mode fallback, mirroring `findTmux`'s own `process.cwd()` use: under `electron-vite// dev` the cwd is the repo root, which is where `npm run host:build` writes its bundle.- repoRoot: process.cwd()+ repoRoot: process.cwd(),+ // Windows: run the host from a private copy of its runtime under %LOCALAPPDATA%, so the+ // installer can replace the install directory while sessions keep running (issue #829).+ // Packaged builds only — a dev checkout's host runs from the repo as before.+ stageRuntime:+ process.platform === 'win32' && platform().isPackaged+ ? (script) =>+ ensureStagedHostRuntime({+ platform: process.platform,+ execPath: process.execPath,+ resourcesPath: platform().resourcesPath,+ script,+ appVersion: platform().appVersion,+ localAppData: process.env.LOCALAPPDATA,+ // Into the host's own log, so a device report carries why a host ran from where.+ log: (line) => {+ void fs.promises+ .appendFile(+ path.join(platform().userDataDir, 'session-host.log'),+ `${new Date().toISOString()} [app] ${line}\n`+ )+ .catch(() => undefined)+ }+ })+ : undefined})}return clientdiff --git a/src/core/session-host-client-staged.test.ts b/src/core/session-host-client-staged.test.tsnew file mode 100644index 000000000..9a1c06eee--- /dev/null+++ b/src/core/session-host-client-staged.test.ts@@ -0,0 +1,63 @@+// Issue #829 step 3: the client hands the launcher a staged runtime (outside the install+// directory) when one is available, and the legacy launch (null) whenever staging fails.+import { describe, it, expect, beforeEach, vi } from 'vitest'++const launcherMocks = vi.hoisted(() => ({+ resolveSessionHostScript: vi.fn(() => 'fake-session-host.cjs'),+ spawnSessionHost: vi.fn()+}))+const identityMocks = vi.hoisted(() => ({+ readExistingSessionHostIdentity: vi.fn(() => ({ kind: 'absent' })),+ startupLockState: vi.fn(() => 'other' as string),+ LISTEN_RETRY_BUDGET_MS: 120_000,+ EMPTY_LOCK_STALE_MS: 15_000+}))+vi.mock('./session-host-launcher', () => launcherMocks)+vi.mock('../session-host/existing-host-state', () => identityMocks)++import { SessionHostClient } from './session-host-client'+import { testTmpDir } from './test-tmp'++beforeEach(() => {+ vi.clearAllMocks()+ identityMocks.readExistingSessionHostIdentity.mockReturnValue({ kind: 'absent' })+})++const staged = { exe: 'C:\\L\\nodeterm\\session-host\\v\\nodeterm-sessionhost-v2.exe', script: 'C:\\L\\h.cjs' }++describe('SessionHostClient launches from a staged runtime when one is available', () => {+ it('passes the staged runtime to the launcher', async () => {+ const stageRuntime = vi.fn(async () => staged)+ const client = new SessionHostClient({ userDataDir: testTmpDir('nt-staged-'), stageRuntime })+ await expect(client.listSessions()).rejects.toThrow()+ expect(stageRuntime).toHaveBeenCalledWith('fake-session-host.cjs')+ expect(launcherMocks.spawnSessionHost).toHaveBeenCalledTimes(1)+ expect(launcherMocks.spawnSessionHost.mock.calls[0][2]).toEqual(staged)+ }, 30_000)++ it('falls back to the legacy launch when staging rejects', async () => {+ const stageRuntime = vi.fn(async () => {+ throw new Error('disk full')+ })+ const client = new SessionHostClient({ userDataDir: testTmpDir('nt-staged-'), stageRuntime })+ await expect(client.listSessions()).rejects.toThrow()+ expect(launcherMocks.spawnSessionHost.mock.calls[0][2]).toBeNull()+ }, 30_000)++ it('stops offering the staged runtime after it failed to start once', async () => {+ const stageRuntime = vi.fn(async () => staged)+ const client = new SessionHostClient({ userDataDir: testTmpDir('nt-staged-'), stageRuntime })+ await expect(client.listSessions()).rejects.toThrow()+ const onStagedFailure = launcherMocks.spawnSessionHost.mock.calls[0][3] as () => void+ onStagedFailure()+ await expect(client.listSessions()).rejects.toThrow()+ const last = launcherMocks.spawnSessionHost.mock.calls.at(-1)!+ expect(last[2]).toBeNull()+ }, 30_000)++ it('without a stager behaves exactly as before (no staged argument)', async () => {+ const client = new SessionHostClient({ userDataDir: testTmpDir('nt-staged-') })+ await expect(client.listSessions()).rejects.toThrow()+ expect(launcherMocks.spawnSessionHost.mock.calls[0][2]).toBeNull()+ }, 30_000)+})diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsindex 6aeb2d7fd..6d3379326 100644--- a/src/core/session-host-client.ts+++ b/src/core/session-host-client.ts@@ -36,6 +36,10 @@ import {type ListSessionsResult} from '../session-host/protocol'import { resolveSessionHostScript, spawnSessionHost } from './session-host-launcher'++/** How long a host launch waits for the first staging of a new version (copy + hash + smoke run)+ * before launching from the installed binary instead. */+export const STAGED_RUNTIME_WAIT_MS = 45_000import { latestClaimSize, type SizeClaim } from './pty-size'import { isTerminalReport } from './terminal-reports'import type { PreparedAgentLaunch } from './agent-launch'@@ -271,9 +275,33 @@ export class SessionHostClient {resourcesPath?: string | nullappPath?: string | nullrepoRoot?: string | null+ /** Stage (or reuse) a host runtime outside the install directory. Absent = legacy launch. */+ stageRuntime?: (script: string) => Promise<{ exe: string; script: string } | null>}) {}+ /** A staged host crashed on start this app run: launch from the installed binary from now on. */+ private stagedRuntimeDisabled = false++ /** The relocated runtime to launch the host from (Windows; `session-host-runtime.ts`), or null+ * for the legacy launch. Bounded: a staging that has not finished in time is not waited for —+ * it keeps running and serves the next launch. */+ private async stagedRuntimeFor(script: string): Promise<{ exe: string; script: string } | null> {+ const stage = this.deps.stageRuntime+ if (!stage || this.stagedRuntimeDisabled) return null+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ stage(script).catch(() => null),+ new Promise<null>((resolve) => {+ timer = setTimeout(() => resolve(null), STAGED_RUNTIME_WAIT_MS)+ })+ ])+ } finally {+ if (timer) clearTimeout(timer)+ }+ }+bundleAvailable(): boolean {return (resolveSessionHostScript({@@ -418,7 +446,16 @@ export class SessionHostClient {// A host that is ALREADY starting needs no second one. Spawning anyway is not harmful (it// exits on the exclusive-create lock), but it is a process per create during the window this// wait exists for — see `hostIsStarting`.- if (!this.hostIsStarting()) spawnSessionHost(script, this.deps.userDataDir)+ if (!this.hostIsStarting()) {+ const staged = await this.stagedRuntimeFor(script)+ // Staging can take seconds on the first launch of a new version; re-ask so a host another+ // process started meanwhile is not doubled.+ if (!staged || !this.hostIsStarting()) {+ spawnSessionHost(script, this.deps.userDataDir, staged, () => {+ this.stagedRuntimeDisabled = true+ })+ }+ }let lastPublicationError: Error | null = nullconst waitStartedAt = Date.now()for (let attempt = 0; ; attempt++) {diff --git a/src/core/session-host-launcher.test.ts b/src/core/session-host-launcher.test.tsindex e11406d79..3d267e07f 100644--- a/src/core/session-host-launcher.test.ts+++ b/src/core/session-host-launcher.test.ts@@ -1,6 +1,12 @@import { describe, it, expect } from 'vitest'import path from 'path'-import { hostLauncherPath, resolveSessionHostScript, WINDOWS_HOST_EXE } from './session-host-launcher'+import {+ hostLaunchPlan,+ hostLauncherPath,+ resolveSessionHostScript,+ stagedExitWantsFallback,+ WINDOWS_HOST_EXE+} from './session-host-launcher'import type { HostLinkFs } from './session-host-launcher'const asar = path.join('/app', 'resources', 'app.asar')@@ -172,3 +178,45 @@ describe('hostLauncherPath', () => {expect(hostLauncherPath(exe, 'win32', fs)).toBe(exe)})})++describe('hostLaunchPlan (issue #829 step 3)', () => {+ const exe = 'C:\\Program Files\\nodeterm\\nodeterm.exe'+ const script = 'C:\\Program Files\\nodeterm\\resources\\session-host\\host.cjs'+ const staged = { exe: 'C:\\L\\nodeterm\\session-host\\0.4.0-x\\nodeterm-sessionhost-v2.exe', script: 'C:\\L\\h.cjs' }+ const noLink: HostLinkFs = {+ statSync: () => {+ throw new Error('ENOENT')+ },+ unlinkSync: () => {},+ linkSync: () => {+ throw new Error('EPERM')+ }+ }++ it('tries the staged runtime first, then the installed binary', () => {+ expect(hostLaunchPlan(script, exe, 'win32', staged, noLink)).toEqual([+ { bin: staged.exe, script: staged.script, staged: true },+ { bin: exe, script }+ ])+ })++ it('without a staged runtime the plan is exactly the legacy one', () => {+ expect(hostLaunchPlan(script, exe, 'win32', null, noLink)).toEqual([{ bin: exe, script }])+ })++ it('never uses a staged runtime off Windows', () => {+ expect(hostLaunchPlan('/x/host.cjs', '/usr/bin/node', 'linux', staged)).toEqual([+ { bin: '/usr/bin/node', script: '/x/host.cjs' }+ ])+ })+})++describe('stagedExitWantsFallback', () => {+ it("treats the host's own controlled exits as answers, anything else as a broken copy", () => {+ expect(stagedExitWantsFallback(0, null)).toBe(false)+ expect(stagedExitWantsFallback(1, null)).toBe(false)+ expect(stagedExitWantsFallback(3221225781, null)).toBe(true) // STATUS_DLL_NOT_FOUND+ expect(stagedExitWantsFallback(null, 'SIGTERM')).toBe(true)+ expect(stagedExitWantsFallback(null, null)).toBe(false)+ })+})diff --git a/src/core/session-host-launcher.ts b/src/core/session-host-launcher.tsindex 0358d4096..93953f976 100644--- a/src/core/session-host-launcher.ts+++ b/src/core/session-host-launcher.ts@@ -83,6 +83,10 @@ export interface HostLinkFs {* The binary to spawn the host with — `execPath` everywhere, except on Windows, where it is a hard* link beside it named `nodeterm-session-host.exe`.*+ * Since issue #829 step 3 this is the FALLBACK: a packaged Windows build launches the host from a+ * staged copy outside the install directory (`session-host-runtime.ts`), and only lands here when+ * staging failed or the staged copy could not start.+ ** The separate image name makes the background host identifiable, but does NOT isolate it from* updates: it still maps the installed Electron image and DLLs. NSIS can find processes by path* as well as name. The installer preflight must refuse while this host (or the app) is running;@@ -125,10 +129,68 @@ export function hostLauncherPath(}}-export function spawnSessionHost(scriptPath: string, userDataDir: string): void {- const launch = (bin: string, onError?: () => void): void => {+/** A host's own controlled failures exit 0 (lost the startup race) or 1 (refused a state it could+ * not judge). Any other code from a staged host — 0xC0000135 STATUS_DLL_NOT_FOUND, an access+ * violation, a policy block — means the staged COPY could not run, and is worth one launch from the+ * installed binary instead. Exported for tests. */+export function stagedExitWantsFallback(code: number | null, signal: NodeJS.Signals | null): boolean {+ if (signal) return true+ return code !== null && code !== 0 && code !== 1+}++/** How long after spawn an exit still counts as "the staged copy could not start". */+export const STAGED_EARLY_EXIT_MS = 10_000++/** A launch target: the binary and the host script it runs. */+export interface HostLaunchTarget {+ bin: string+ script: string+ /** A staged runtime, which gets the early-exit fallback. */+ staged?: boolean+}++/**+ * The ordered launch attempts. A staged runtime (outside the install directory — see+ * `session-host-runtime.ts`) goes first; the legacy pair (`hostLauncherPath`, then the plain+ * `execPath`) is what every staged failure falls back to. Exported for tests.+ */+export function hostLaunchPlan(+ scriptPath: string,+ execPath: string,+ platformName: NodeJS.Platform | string,+ staged?: { exe: string; script: string } | null,+ fsLike?: HostLinkFs+): HostLaunchTarget[] {+ const plan: HostLaunchTarget[] = []+ if (staged && platformName === 'win32') plan.push({ bin: staged.exe, script: staged.script, staged: true })+ const legacy = hostLauncherPath(execPath, platformName, fsLike)+ plan.push({ bin: legacy, script: scriptPath })+ if (legacy !== execPath) plan.push({ bin: execPath, script: scriptPath })+ return plan+}++export function spawnSessionHost(+ scriptPath: string,+ userDataDir: string,+ staged?: { exe: string; script: string } | null,+ onStagedFailure?: () => void+): void {+ let plan: HostLaunchTarget[] | null = null+ const legacyPlan = (): HostLaunchTarget[] => {+ // The legacy alias is created lazily: a staged host that starts never needs the hard link in+ // the install directory at all.+ if (!plan) plan = hostLaunchPlan(scriptPath, process.execPath, os.platform(), null)+ return plan+ }+ const launch = (target: HostLaunchTarget, next: () => void): void => {+ let failedOver = false+ const failOver = (): void => {+ if (failedOver) return+ failedOver = true+ next()+ }try {- const child = spawn(bin, [scriptPath, userDataDir], {+ const child = spawn(target.bin, [target.script, userDataDir], {detached: true,stdio: 'ignore',windowsHide: true,@@ -139,15 +201,33 @@ export function spawnSessionHost(scriptPath: string, userDataDir: string): void// two app processes can race on the alias, and the loser can unlink the link between the// winner creating it and spawning through it (ENOENT). The listener is what makes the// fallback below real rather than theoretical.- child.on('error', () => onError?.())+ child.on('error', () => {+ if (target.staged) onStagedFailure?.()+ failOver()+ })+ if (target.staged) {+ const startedAt = Date.now()+ child.once('exit', (code, signal) => {+ if (Date.now() - startedAt > STAGED_EARLY_EXIT_MS) return+ if (!stagedExitWantsFallback(code, signal)) return+ onStagedFailure?.()+ failOver()+ })+ }child.unref()} catch {- onError?.()+ if (target.staged) onStagedFailure?.()+ failOver()}}- const bin = hostLauncherPath(process.execPath, os.platform())- // One retry, and only when the alias was actually used: `execPath` is the path that has always- // worked, so the retry can have no listener of its own beyond swallowing.- if (bin === process.execPath) launch(bin)- else launch(bin, () => launch(process.execPath))+ const runLegacy = (index: number): void => {+ const targets = legacyPlan()+ if (index >= targets.length) return+ launch(targets[index], () => runLegacy(index + 1))+ }+ if (staged && os.platform() === 'win32') {+ launch({ bin: staged.exe, script: staged.script, staged: true }, () => runLegacy(0))+ } else {+ runLegacy(0)+ }}diff --git a/src/core/session-host-runtime.test.ts b/src/core/session-host-runtime.test.tsnew file mode 100644index 000000000..13d28413c--- /dev/null+++ b/src/core/session-host-runtime.test.ts@@ -0,0 +1,278 @@+// Issue #829 step 3. Pure staging/GC logic: runs on every platform against a fake install tree;+// the Windows-only parts (process query, real Electron smoke) are injected.+import { describe, it, expect, beforeEach } from 'vitest'+import fs from 'fs'+import path from 'path'+import {+ STAGED_HOST_EXE,+ RUNTIME_MARKER,+ SMOKE_OK,+ collectStagedRuntimes,+ ensureStagedHostRuntime,+ parseProcessJson,+ planRuntimeFiles,+ resetStagedHostRuntimeForTests,+ runtimeKey,+ stageHostRuntime,+ stagedRuntimeRoot,+ validStagedRuntime,+ type ProcessInfo+} from './session-host-runtime'+import { testTmpDir } from './test-tmp'++function write(p: string, body: string): void {+ fs.mkdirSync(path.dirname(p), { recursive: true })+ fs.writeFileSync(p, body)+}++function fakeInstall(): { root: string; execPath: string; resourcesPath: string; script: string; local: string } {+ const root = testTmpDir('nt-runtime-')+ const inst = path.join(root, 'Programs', 'nodeterm')+ const execPath = path.join(inst, 'nodeterm.exe')+ write(execPath, 'MZ electron')+ write(path.join(inst, 'ffmpeg.dll'), 'ffmpeg')+ write(path.join(inst, 'libEGL.dll'), 'egl')+ write(path.join(inst, 'icudtl.dat'), 'icu')+ write(path.join(inst, 'resources.pak'), 'pak')+ write(path.join(inst, 'v8_context_snapshot.bin'), 'snap')+ write(path.join(inst, 'LICENSE.electron.txt'), 'license')+ write(path.join(inst, 'Uninstall nodeterm.exe'), 'uninstaller')+ write(path.join(inst, 'locales', 'en-US.pak'), 'en')+ const resourcesPath = path.join(inst, 'resources')+ write(path.join(resourcesPath, 'app.asar'), 'asar')+ const script = path.join(resourcesPath, 'session-host', 'host.cjs')+ write(script, '// host')+ write(path.join(resourcesPath, 'session-host', 'node_modules', 'node-pty', 'package.json'), '{}')+ write(path.join(resourcesPath, 'session-host', 'node_modules', 'node-pty', 'build', 'Release', 'conpty.node'), 'n')+ return { root, execPath, resourcesPath, script, local: path.join(root, 'Local') }+}++const okSmoke = async (): Promise<number> => SMOKE_OK++function opts(f: ReturnType<typeof fakeInstall>, extra: Record<string, unknown> = {}) {+ return {+ platform: 'win32',+ execPath: f.execPath,+ resourcesPath: f.resourcesPath,+ script: f.script,+ appVersion: '0.4.0',+ localAppData: f.local,+ smoke: okSmoke,+ ...extra+ }+}++const tree = (dir: string): string[] => {+ const out: string[] = []+ const walk = (d: string, rel: string): void => {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ const r = rel ? rel + '/' + e.name : e.name+ if (e.isDirectory()) walk(path.join(d, e.name), r)+ else out.push(r)+ }+ }+ walk(dir, '')+ return out.sort()+}++beforeEach(() => resetStagedHostRuntimeForTests())++describe('planRuntimeFiles', () => {+ it('takes the exe (renamed), DLLs, runtime data, locales and the host bundle — nothing else', async () => {+ const f = fakeInstall()+ const plan = await planRuntimeFiles(f.execPath, f.resourcesPath)+ expect(plan!.map((p) => p.rel)).toEqual([+ STAGED_HOST_EXE,+ 'ffmpeg.dll',+ 'icudtl.dat',+ 'libEGL.dll',+ 'locales/en-US.pak',+ 'resources.pak',+ 'resources/session-host/host.cjs',+ 'resources/session-host/node_modules/node-pty/build/Release/conpty.node',+ 'resources/session-host/node_modules/node-pty/package.json',+ 'v8_context_snapshot.bin'+ ].sort())+ })++ it('refuses without ICU data or without the node-pty copy', async () => {+ const f = fakeInstall()+ fs.rmSync(path.join(path.dirname(f.execPath), 'icudtl.dat'))+ expect(await planRuntimeFiles(f.execPath, f.resourcesPath)).toBeNull()+ const g = fakeInstall()+ fs.rmSync(path.join(g.resourcesPath, 'session-host', 'node_modules'), { recursive: true })+ expect(await planRuntimeFiles(g.execPath, g.resourcesPath)).toBeNull()+ })+})++describe('runtimeKey', () => {+ it('is version-prefixed and changes when any source file changes', async () => {+ const f = fakeInstall()+ const plan = (await planRuntimeFiles(f.execPath, f.resourcesPath))!+ const a = runtimeKey('0.4.0', plan)+ expect(a).toMatch(/^0\.4\.0-[0-9a-f]{16}$/)+ expect(runtimeKey('0.4.0', [...plan.slice(1), { ...plan[0], size: plan[0].size + 1 }])).not.toBe(a)+ expect(runtimeKey('../../evil', plan)).not.toContain('/')+ })+})++describe('stageHostRuntime', () => {+ it('stages a verified copy outside the install directory and reuses it', async () => {+ const f = fakeInstall()+ const rt = await stageHostRuntime(opts(f))+ expect(rt).not.toBeNull()+ expect(rt!.dir.startsWith(stagedRuntimeRoot(f.local))).toBe(true)+ expect(rt!.dir.startsWith(path.dirname(f.execPath))).toBe(false)+ expect(fs.readFileSync(rt!.exe, 'utf8')).toBe('MZ electron')+ expect(fs.existsSync(rt!.script)).toBe(true)+ expect(tree(rt!.dir)).toContain(RUNTIME_MARKER)+ expect(tree(rt!.dir)).not.toContain('Uninstall nodeterm.exe')+ expect(tree(rt!.dir)).not.toContain('resources/app.asar')+ // No staging litter is left behind.+ expect(fs.readdirSync(stagedRuntimeRoot(f.local))).toEqual([path.basename(rt!.dir)])++ let smokes = 0+ const again = await stageHostRuntime(opts(f, { smoke: async () => (smokes++, SMOKE_OK) }))+ expect(again).toEqual(rt)+ expect(smokes).toBe(0)+ })++ it('never publishes a copy whose smoke run failed, and falls back (null)', async () => {+ const f = fakeInstall()+ for (const code of [null, 0, 1, 3221225781]) {+ expect(await stageHostRuntime(opts(f, { smoke: async () => code }))).toBeNull()+ const root = stagedRuntimeRoot(f.local)+ expect(fs.existsSync(root) ? fs.readdirSync(root) : []).toEqual([])+ }+ })++ it('does not stage off Windows, without LOCALAPPDATA, or for a non-packaged script', async () => {+ const f = fakeInstall()+ expect(await stageHostRuntime(opts(f, { platform: 'linux' }))).toBeNull()+ expect(await stageHostRuntime(opts(f, { localAppData: undefined }))).toBeNull()+ expect(await stageHostRuntime(opts(f, { script: path.join(f.root, 'out', 'host.cjs') }))).toBeNull()+ })++ it('never launches a half-staged directory: an invalid one is moved aside and restaged', async () => {+ const f = fakeInstall()+ const plan = (await planRuntimeFiles(f.execPath, f.resourcesPath))!+ const dir = path.join(stagedRuntimeRoot(f.local), runtimeKey('0.4.0', plan))+ // An interrupted copy: the exe exists, no marker.+ write(path.join(dir, STAGED_HOST_EXE), 'MZ')+ expect(await validStagedRuntime(dir, runtimeKey('0.4.0', plan))).toBe(false)+ const rt = await stageHostRuntime(opts(f))+ expect(rt!.dir).toBe(dir)+ expect(await validStagedRuntime(dir, runtimeKey('0.4.0', plan))).toBe(true)+ })++ it('rejects a staged copy whose file sizes no longer match its marker', async () => {+ const f = fakeInstall()+ const rt = (await stageHostRuntime(opts(f)))!+ const key = path.basename(rt.dir)+ fs.writeFileSync(rt.exe, 'truncated')+ expect(await validStagedRuntime(rt.dir, key)).toBe(false)+ fs.rmSync(rt.exe)+ expect(await validStagedRuntime(rt.dir, key)).toBe(false)+ })++ it('a reinstall of the same version with different bytes gets its own directory', async () => {+ const f = fakeInstall()+ const a = (await stageHostRuntime(opts(f)))!+ fs.writeFileSync(f.execPath, 'MZ electron, rebuilt')+ const b = (await stageHostRuntime(opts(f)))!+ expect(b.dir).not.toBe(a.dir)+ expect(fs.readFileSync(b.exe, 'utf8')).toBe('MZ electron, rebuilt')+ })++ it('ensureStagedHostRuntime memoizes per app run', async () => {+ const f = fakeInstall()+ let smokes = 0+ const o = { ...opts(f, { smoke: async () => (smokes++, SMOKE_OK) }), collect: false }+ const [a, b] = await Promise.all([ensureStagedHostRuntime(o), ensureStagedHostRuntime(o)])+ expect(a).toEqual(b)+ expect(smokes).toBe(1)+ })+})++describe('collectStagedRuntimes', () => {+ const old = 60 * 60_000+ function setup(): { root: string; dirs: string[] } {+ const root = testTmpDir('nt-runtime-gc-')+ const dirs = ['0.3.20-aaaa', '0.3.21-bbbb', '0.4.0-cccc']+ for (const d of dirs) write(path.join(root, d, STAGED_HOST_EXE), 'MZ')+ return { root, dirs }+ }+ const later = Date.now() + 2 * old+ const procs = (list: ProcessInfo[]) => async () => list++ it('deletes only old runtimes nothing runs from, keeping the current one', async () => {+ const { root } = setup()+ const r = await collectStagedRuntimes({+ root,+ keep: ['0.4.0-cccc'],+ now: later,+ query: procs([+ { name: STAGED_HOST_EXE, path: path.join(root, '0.3.21-bbbb', STAGED_HOST_EXE).toUpperCase() },+ { name: 'explorer.exe', path: 'C:\\Windows\\explorer.exe' },+ { name: 'System', path: null }+ ])+ })+ expect(r.removed).toEqual(['0.3.20-aaaa'])+ expect(fs.readdirSync(root).sort()).toEqual(['0.3.21-bbbb', '0.4.0-cccc'])+ })++ it('fails closed: a failed query deletes nothing', async () => {+ const { root, dirs } = setup()+ for (const query of [async () => null, async () => { throw new Error('denied') }]) {+ const r = await collectStagedRuntimes({ root, keep: [], now: later, query })+ expect(r.refused).toBe('query-failed')+ expect(fs.readdirSync(root).sort()).toEqual(dirs)+ }+ })++ it('fails closed: a staged host whose path cannot be read deletes nothing', async () => {+ const { root, dirs } = setup()+ const r = await collectStagedRuntimes({+ root,+ keep: [],+ now: later,+ query: procs([{ name: STAGED_HOST_EXE.toUpperCase(), path: null }])+ })+ expect(r.refused).toBe('unknown-host-path')+ expect(fs.readdirSync(root).sort()).toEqual(dirs)+ })++ it('leaves recently created directories alone and sweeps old staging litter', async () => {+ const { root } = setup()+ write(path.join(root, '.staging-1234', 'x'), 'x')+ const fresh = await collectStagedRuntimes({ root, keep: [], query: procs([]) })+ expect(fresh.removed).toEqual([])+ const r = await collectStagedRuntimes({ root, keep: ['0.4.0-cccc'], now: later, query: procs([{ name: 'a.exe', path: 'C:\\a.exe' }]) })+ expect(r.removed.sort()).toEqual(['.staging-1234', '0.3.20-aaaa', '0.3.21-bbbb'])+ expect(fs.readdirSync(root)).toEqual(['0.4.0-cccc'])+ })++ it('does not match a sibling whose name only starts with the same characters', async () => {+ const { root } = setup()+ const r = await collectStagedRuntimes({+ root,+ keep: ['0.4.0-cccc', '0.3.21-bbbb'],+ now: later,+ query: procs([{ name: 'x.exe', path: path.join(root, '0.3.20-aaaa-other', 'x.exe') }])+ })+ expect(r.removed).toEqual(['0.3.20-aaaa'])+ })+})++describe('parseProcessJson', () => {+ it('reads PowerShell ConvertTo-Json output, single object or array', () => {+ expect(parseProcessJson('{"Name":"a.exe","ExecutablePath":"C:\\\\a.exe"}')).toEqual([{ name: 'a.exe', path: 'C:\\a.exe' }])+ expect(parseProcessJson('[{"Name":"System","ExecutablePath":null},{"Name":"b","ExecutablePath":""}]')).toEqual([+ { name: 'System', path: null },+ { name: 'b', path: null }+ ])+ })+ it('anything unexpected is a failed query', () => {+ for (const t of ['', 'not json', '[]', '[1]', '[{"ExecutablePath":"x"}]']) expect(parseProcessJson(t)).toBeNull()+ })+})diff --git a/src/core/session-host-runtime.ts b/src/core/session-host-runtime.tsnew file mode 100644index 000000000..3a6eb13e4--- /dev/null+++ b/src/core/session-host-runtime.ts@@ -0,0 +1,578 @@+// A private copy of the Windows session host's runtime, OUTSIDE the install directory (issue #829).+//+// The persistent host used to run as a hard link of `nodeterm.exe` inside the install directory.+// A running host therefore mapped the installed executable, its DLLs and `resources.pak`, and the+// installer could not replace them: every update stopped until the user ended the host, and with+// it every live session. On macOS/Linux the sessions live in tmux, a separate binary, and survive+// an update. This module gives Windows the same property: before a host is spawned, the files it+// needs are copied ("staged") into a per-version directory under `%LOCALAPPDATA%`, and the host+// runs from there under its own image name. The installer then replaces the install directory+// freely while the old host keeps running from its own copy.+//+// Rules, each a refusal (docs/windows-session-host.md, "Staged host runtime"):+// - A staged directory is published by ONE rename of a fully written, hash-verified and+// smoke-tested temp directory, and only a directory carrying a marker is ever launched. A+// half-staged directory is never run.+// - The host's image name is NEW (`nodeterm-sessionhost-v2.exe`): uninstallers already in the+// field match `nodeterm.exe` / `nodeterm-session-host.exe` machine-wide by NAME, and must not+// match a host that does not block them.+// - Every failure answers `null`, and the caller then launches the host exactly as before+// (`hostLauncherPath`). The installer preflight still protects the install in that case.+// - Old staged versions are deleted only when a successful process query shows nothing running+// from them AND the directory can be renamed aside. A failed query deletes nothing.++import { createHash, randomUUID } from 'crypto'+import { execFile, spawn } from 'child_process'+import { createReadStream, createWriteStream, promises as fsp } from 'fs'+import path from 'path'+import { renameAtomic } from './fs-atomic'++/** The relocated host's image name. Deliberately unlike every name an existing uninstaller or+ * installer preflight matches (`nodeterm.exe`, `nodeterm-session-host.exe`). */+export const STAGED_HOST_EXE = 'nodeterm-sessionhost-v2.exe'+/** Written last, inside the temp directory, after verification and the smoke run. */+export const RUNTIME_MARKER = 'nodeterm-runtime.json'+const MARKER_VERSION = 1+/** Directory names this module creates under the root and owns. */+const STAGING_PREFIX = '.staging-'+const TRASH_PREFIX = '.trash-'++/**+ * What the host needs from the install directory. NOT measured on a device yet (this was written on+ * Linux) — it is the conservative set an `ELECTRON_RUN_AS_NODE` process can plausibly touch, and the+ * smoke run below is what proves it on the machine that will use it. Device checklist item 1 in+ * docs/windows-session-host.md measures the real set (Process Monitor) so it can be pruned.+ *+ * - the Electron executable itself, renamed to STAGED_HOST_EXE;+ * - every top-level `*.dll` (ffmpeg.dll is a load-time import; the rest are small and cover+ * delay-loads);+ * - icudtl.dat (Node's ICU data — REQUIRED), resources.pak (measured open by a running host in+ * #829), the V8 snapshot blobs, and `locales/` (in case resource-bundle init wants a locale pak);+ * - `resources/session-host/**`: the host bundle and its own node-pty copy (package.json+ * `build.win.extraResources`). NOT `app.asar`: the host never reads it.+ */+const REQUIRED_TOP_FILES = ['icudtl.dat']+const OPTIONAL_TOP_FILES = ['resources.pak', 'snapshot_blob.bin', 'v8_context_snapshot.bin']+const OPTIONAL_TOP_DIRS = ['locales']++export interface StagedHostRuntime {+ /** The published version directory. */+ dir: string+ /** `<dir>/STAGED_HOST_EXE`. */+ exe: string+ /** `<dir>/resources/session-host/host.cjs`. */+ script: string+}++interface PlannedFile {+ /** Source path. */+ src: string+ /** Path relative to the staged directory, always with `/` separators. */+ rel: string+ size: number+ mtimeMs: number+}++interface MarkerFile {+ rel: string+ size: number+ sha256: string+}+interface Marker {+ v: number+ appVersion: string+ key: string+ files: MarkerFile[]+}++/** Runs the staged executable once with `ELECTRON_RUN_AS_NODE=1` and answers its exit code (null on+ * timeout or spawn failure). Injected so tests need no Electron binary. */+export type RuntimeSmoke = (exe: string, nodePtyDir: string) => Promise<number | null>++/** The exit code the smoke script uses for "loaded, and node-pty resolved". Any other answer —+ * STATUS_DLL_NOT_FOUND, a missing ICU file, a policy block — rejects the staged copy. */+export const SMOKE_OK = 42+const SMOKE_SCRIPT =+ "require(process.env.NODETERM_RUNTIME_PROBE_PTY);process.exit(" + String(SMOKE_OK) + ')'++export const defaultRuntimeSmoke: RuntimeSmoke = (exe, nodePtyDir) =>+ new Promise((resolve) => {+ let done = false+ const finish = (code: number | null): void => {+ if (done) return+ done = true+ clearTimeout(timer)+ resolve(code)+ }+ let child: ReturnType<typeof spawn>+ try {+ child = spawn(exe, ['-e', SMOKE_SCRIPT], {+ stdio: 'ignore',+ windowsHide: true,+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', NODETERM_RUNTIME_PROBE_PTY: nodePtyDir }+ })+ } catch {+ resolve(null)+ return+ }+ // A first run of a freshly written executable can sit behind an antivirus scan.+ const timer = setTimeout(() => {+ try {+ child.kill()+ } catch {+ /* gone */+ }+ finish(null)+ }, 60_000)+ child.once('error', () => finish(null))+ child.once('exit', (code) => finish(code))+ })++export interface StageOptions {+ platform: NodeJS.Platform | string+ /** `process.execPath` of the running app (the installed Electron binary). */+ execPath: string+ resourcesPath?: string | null+ /** The host script the legacy launcher would use. Staging applies only when it is the packaged+ * `<resourcesPath>/session-host/host.cjs` — a dev checkout or an asar-resolved bundle is left+ * on the legacy path. */+ script: string+ appVersion: string+ /** `%LOCALAPPDATA%`. Absent ⇒ no staging. */+ localAppData?: string | null+ smoke?: RuntimeSmoke+ log?: (line: string) => void+}++/** `%LOCALAPPDATA%\nodeterm\session-host`. Outside every install directory: a per-user install+ * lives in `%LOCALAPPDATA%\Programs\nodeterm`, an all-users one under Program Files. */+export function stagedRuntimeRoot(localAppData: string): string {+ return path.join(localAppData, 'nodeterm', 'session-host')+}++async function statOrNull(p: string): Promise<import('fs').Stats | null> {+ try {+ return await fsp.stat(p)+ } catch {+ return null+ }+}++async function walk(dir: string, relBase: string, out: PlannedFile[]): Promise<void> {+ for (const entry of await fsp.readdir(dir, { withFileTypes: true })) {+ const src = path.join(dir, entry.name)+ const rel = relBase + '/' + entry.name+ if (entry.isDirectory()) await walk(src, rel, out)+ else if (entry.isFile()) {+ const st = await fsp.stat(src)+ out.push({ src, rel, size: st.size, mtimeMs: st.mtimeMs })+ }+ // Links and anything else are not part of an installed Electron tree; skip them.+ }+}++/** The files to stage, or null when something required is missing. Exported for tests. */+export async function planRuntimeFiles(+ execPath: string,+ resourcesPath: string+): Promise<PlannedFile[] | null> {+ const installDir = path.dirname(execPath)+ const out: PlannedFile[] = []+ const exe = await statOrNull(execPath)+ if (!exe?.isFile()) return null+ out.push({ src: execPath, rel: STAGED_HOST_EXE, size: exe.size, mtimeMs: exe.mtimeMs })+ let entries: import('fs').Dirent[]+ try {+ entries = await fsp.readdir(installDir, { withFileTypes: true })+ } catch {+ return null+ }+ const wanted = new Set([...REQUIRED_TOP_FILES, ...OPTIONAL_TOP_FILES].map((n) => n.toLowerCase()))+ for (const entry of entries) {+ if (!entry.isFile()) continue+ const lower = entry.name.toLowerCase()+ if (!lower.endsWith('.dll') && !wanted.has(lower)) continue+ const src = path.join(installDir, entry.name)+ const st = await fsp.stat(src)+ out.push({ src, rel: entry.name, size: st.size, mtimeMs: st.mtimeMs })+ }+ for (const required of REQUIRED_TOP_FILES) {+ if (!out.some((f) => f.rel.toLowerCase() === required)) return null+ }+ for (const dirName of OPTIONAL_TOP_DIRS) {+ const src = path.join(installDir, dirName)+ if ((await statOrNull(src))?.isDirectory()) await walk(src, dirName, out)+ }+ const hostDir = path.join(resourcesPath, 'session-host')+ if (!(await statOrNull(path.join(hostDir, 'host.cjs')))?.isFile()) return null+ if (!(await statOrNull(path.join(hostDir, 'node_modules', 'node-pty')))?.isDirectory()) return null+ await walk(hostDir, 'resources/session-host', out)+ out.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))+ return out+}++/** `<app version>-<fingerprint>`. The fingerprint covers every source file's path, size and mtime,+ * so a reinstall of the same version with different bytes gets its own directory; the bytes+ * themselves are verified by SHA-256 at staging time. Exported for tests. */+export function runtimeKey(appVersion: string, files: readonly PlannedFile[]): string {+ const h = createHash('sha256')+ for (const f of files) h.update(`${f.rel}\0${f.size}\0${Math.trunc(f.mtimeMs)}\n`)+ const version = appVersion.replace(/[^0-9A-Za-z.+-]/g, '_').slice(0, 40) || 'unknown'+ return `${version}-${h.digest('hex').slice(0, 16)}`+}++function hashFile(p: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const h = createHash('sha256')+ const s = createReadStream(p)+ s.on('error', reject)+ s.on('data', (c) => h.update(c))+ s.on('end', () => resolve(h.digest('hex')))+ })+}++/** Copy `src` to `dest`, answering the SHA-256 of the bytes READ. */+function copyHashing(src: string, dest: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const h = createHash('sha256')+ const input = createReadStream(src)+ const output = createWriteStream(dest, { flags: 'wx' })+ let failed = false+ const fail = (e: unknown): void => {+ if (failed) return+ failed = true+ input.destroy()+ output.destroy()+ reject(e)+ }+ input.on('error', fail)+ output.on('error', fail)+ input.on('data', (c) => h.update(c))+ output.on('finish', () => {+ if (!failed) resolve(h.digest('hex'))+ })+ input.pipe(output)+ })+}++function runtimeOf(dir: string): StagedHostRuntime {+ return {+ dir,+ exe: path.join(dir, STAGED_HOST_EXE),+ script: path.join(dir, 'resources', 'session-host', 'host.cjs')+ }+}++function fromRel(dir: string, rel: string): string {+ return path.join(dir, ...rel.split('/'))+}++/**+ * Is `dir` a complete, published runtime for `key`? A cheap check (marker + every file present at+ * its recorded size): the bytes were hashed when the directory was staged, and nothing but this+ * module writes there. Exported for tests.+ */+export async function validStagedRuntime(dir: string, key: string): Promise<boolean> {+ let marker: Marker+ try {+ marker = JSON.parse(await fsp.readFile(path.join(dir, RUNTIME_MARKER), 'utf8')) as Marker+ } catch {+ return false+ }+ if (!marker || marker.v !== MARKER_VERSION || marker.key !== key || !Array.isArray(marker.files)) {+ return false+ }+ if (!marker.files.some((f) => f && f.rel === STAGED_HOST_EXE)) return false+ for (const f of marker.files) {+ if (!f || typeof f.rel !== 'string' || f.rel.includes('..') || typeof f.size !== 'number') {+ return false+ }+ const st = await statOrNull(fromRel(dir, f.rel))+ if (!st?.isFile() || st.size !== f.size) return false+ }+ return true+}++async function moveAside(root: string, dir: string): Promise<boolean> {+ try {+ await renameAtomic(dir, path.join(root, TRASH_PREFIX + randomUUID()))+ return true+ } catch {+ return false+ }+}++/** Publish `tmp` as `dir`. Windows may hold a just-written executable open for a scan; give the+ * rename a few rounds of the atomic helper's own bounded retry. */+async function publish(tmp: string, dir: string): Promise<void> {+ let last: unknown+ for (let round = 0; round < 4; round++) {+ try {+ await renameAtomic(tmp, dir)+ return+ } catch (e) {+ last = e+ const code = (e as NodeJS.ErrnoException)?.code+ if (code === 'EEXIST' || code === 'ENOTEMPTY') throw e+ await new Promise((r) => setTimeout(r, 500))+ }+ }+ throw last+}++/**+ * Stage (or reuse) the host runtime for this app version. Never throws; null = launch the legacy+ * way. Exported for tests — production goes through `ensureStagedHostRuntime`, which memoizes.+ */+export async function stageHostRuntime(opts: StageOptions): Promise<StagedHostRuntime | null> {+ const log = opts.log ?? (() => {})+ try {+ if (opts.platform !== 'win32' || !opts.localAppData || !opts.resourcesPath) return null+ const expectedScript = path.join(opts.resourcesPath, 'session-host', 'host.cjs')+ if (path.resolve(opts.script) !== path.resolve(expectedScript)) return null+ const files = await planRuntimeFiles(opts.execPath, opts.resourcesPath)+ if (!files) {+ log('staged runtime: required files missing; using the installed binary')+ return null+ }+ const key = runtimeKey(opts.appVersion, files)+ const root = stagedRuntimeRoot(opts.localAppData)+ const dir = path.join(root, key)+ if (await statOrNull(dir)) {+ if (await validStagedRuntime(dir, key)) return runtimeOf(dir)+ // Incomplete or tampered with. Never launch it; move it aside if nothing holds it.+ if (!(await moveAside(root, dir))) {+ log(`staged runtime: ${key} is invalid and cannot be moved aside`)+ return null+ }+ }+ await fsp.mkdir(root, { recursive: true })+ const tmp = path.join(root, STAGING_PREFIX + randomUUID())+ try {+ await fsp.mkdir(tmp)+ const marker: Marker = { v: MARKER_VERSION, appVersion: opts.appVersion, key, files: [] }+ for (const f of files) {+ const dest = fromRel(tmp, f.rel)+ await fsp.mkdir(path.dirname(dest), { recursive: true })+ const read = await copyHashing(f.src, dest)+ // Verify what landed, not what we meant to write: size AND content.+ const st = await fsp.stat(dest)+ if (st.size !== f.size) throw new Error(`size mismatch for ${f.rel}`)+ if ((await hashFile(dest)) !== read) throw new Error(`hash mismatch for ${f.rel}`)+ marker.files.push({ rel: f.rel, size: f.size, sha256: read })+ }+ const staged = runtimeOf(tmp)+ const smoke = opts.smoke ?? defaultRuntimeSmoke+ const code = await smoke(+ staged.exe,+ path.join(tmp, 'resources', 'session-host', 'node_modules', 'node-pty')+ )+ if (code !== SMOKE_OK) throw new Error(`smoke run answered ${String(code)}`)+ // The marker is the "this directory may be launched" bit, so it is written last.+ await fsp.writeFile(path.join(tmp, RUNTIME_MARKER), JSON.stringify(marker))+ try {+ await publish(tmp, dir)+ } catch (e) {+ const code2 = (e as NodeJS.ErrnoException)?.code+ // Another app process published the same key first: theirs is as good as ours.+ if ((code2 === 'EEXIST' || code2 === 'ENOTEMPTY') && (await validStagedRuntime(dir, key))) {+ await fsp.rm(tmp, { recursive: true, force: true }).catch(() => undefined)+ return runtimeOf(dir)+ }+ throw e+ }+ log(`staged runtime: published ${key}`)+ return runtimeOf(dir)+ } catch (e) {+ log(`staged runtime: staging failed (${String((e as Error)?.message ?? e)}); using the installed binary`)+ await fsp.rm(tmp, { recursive: true, force: true }).catch(() => undefined)+ return null+ }+ } catch (e) {+ log(`staged runtime: ${String((e as Error)?.message ?? e)}; using the installed binary`)+ return null+ }+}++/** A running process as Win32_Process reports it. `path` null = unknown (another user, access). */+export interface ProcessInfo {+ name: string+ path: string | null+}+/** Answers every process, or null when the query failed. */+export type ProcessQuery = () => Promise<ProcessInfo[] | null>++export const defaultProcessQuery: ProcessQuery = () =>+ new Promise((resolve) => {+ const systemRoot = process.env.SystemRoot || 'C:\\Windows'+ const ps = path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')+ execFile(+ ps,+ [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ "$ErrorActionPreference='Stop'; @(Get-CimInstance -ClassName Win32_Process | Select-Object Name, ExecutablePath) | ConvertTo-Json -Compress"+ ],+ { windowsHide: true, timeout: 20_000, maxBuffer: 16 * 1024 * 1024 },+ (err, stdout) => {+ if (err) return resolve(null)+ resolve(parseProcessJson(String(stdout)))+ }+ )+ })++/** Parse ConvertTo-Json output. Anything unexpected is a failed query (null). Exported for tests. */+export function parseProcessJson(text: string): ProcessInfo[] | null {+ let raw: unknown+ try {+ raw = JSON.parse(text.trim())+ } catch {+ return null+ }+ const list = Array.isArray(raw) ? raw : [raw]+ if (list.length === 0) return null // Windows always has processes; an empty answer is not one.+ const out: ProcessInfo[] = []+ for (const p of list) {+ if (!p || typeof p !== 'object') return null+ const { Name, ExecutablePath } = p as { Name?: unknown; ExecutablePath?: unknown }+ if (typeof Name !== 'string') return null+ out.push({+ name: Name,+ path: typeof ExecutablePath === 'string' && ExecutablePath.trim() ? ExecutablePath : null+ })+ }+ return out+}++const norm = (p: string): string => p.replace(/\//g, '\\').replace(/\\+$/, '').toLowerCase()++export interface CollectOptions {+ root: string+ /** Directory names (keys) never deleted. */+ keep: readonly string[]+ query?: ProcessQuery+ now?: number+ /** A directory younger than this is left alone: another app process may be about to launch it. */+ minAgeMs?: number+ /** Abandoned `.staging-*` / `.trash-*` older than this are swept. */+ litterAgeMs?: number+}++export interface CollectReport {+ removed: string[]+ kept: string[]+ /** Set when the process query failed or could not prove a host's path — nothing was removed. */+ refused?: 'query-failed' | 'unknown-host-path'+}++/**+ * Delete staged runtimes nothing runs from. Fail-closed: a failed process query, or a staged-host+ * process whose path cannot be read, deletes nothing. A directory is first RENAMED aside, which+ * Windows refuses while any file inside is mapped — a second, independent in-use check — and only+ * then removed. Never throws.+ */+export async function collectStagedRuntimes(opts: CollectOptions): Promise<CollectReport> {+ const report: CollectReport = { removed: [], kept: [] }+ const now = opts.now ?? Date.now()+ const minAge = opts.minAgeMs ?? 10 * 60_000+ const litterAge = opts.litterAgeMs ?? 60 * 60_000+ let entries: import('fs').Dirent[]+ try {+ entries = await fsp.readdir(opts.root, { withFileTypes: true })+ } catch {+ return report+ }+ const candidates: string[] = []+ for (const e of entries) {+ if (!e.isDirectory()) continue+ const full = path.join(opts.root, e.name)+ if (e.name.startsWith(STAGING_PREFIX) || e.name.startsWith(TRASH_PREFIX)) {+ // Litter from a crashed staging or a removal that could not finish.+ const st = await statOrNull(full)+ if (st && now - st.mtimeMs >= litterAge) candidates.push(e.name)+ else report.kept.push(e.name)+ continue+ }+ if (opts.keep.includes(e.name)) {+ report.kept.push(e.name)+ continue+ }+ const st = await statOrNull(full)+ if (!st || now - st.mtimeMs < minAge) {+ report.kept.push(e.name)+ continue+ }+ candidates.push(e.name)+ }+ if (candidates.length === 0) return report+ const processes = await (opts.query ?? defaultProcessQuery)().catch(() => null)+ if (!processes) {+ report.refused = 'query-failed'+ report.kept.push(...candidates)+ return report+ }+ if (processes.some((p) => p.path === null && p.name.toLowerCase() === STAGED_HOST_EXE)) {+ report.refused = 'unknown-host-path'+ report.kept.push(...candidates)+ return report+ }+ const running = processes.filter((p) => p.path !== null).map((p) => norm(p.path as string))+ for (const name of candidates) {+ const full = path.join(opts.root, name)+ const prefix = norm(full) + '\\'+ if (running.some((p) => p.startsWith(prefix))) {+ report.kept.push(name)+ continue+ }+ let target = full+ if (!name.startsWith(TRASH_PREFIX)) {+ target = path.join(opts.root, TRASH_PREFIX + randomUUID())+ try {+ await renameAtomic(full, target)+ } catch {+ report.kept.push(name)+ continue+ }+ }+ try {+ await fsp.rm(target, { recursive: true, force: true })+ report.removed.push(name)+ } catch {+ // Left as `.trash-*`; the next sweep tries again.+ report.kept.push(name)+ }+ }+ return report+}++let memo: { key: string; promise: Promise<StagedHostRuntime | null> } | null = null++/**+ * The process-wide entry point: stage once per (execPath, script, version), then collect older+ * runtimes in the background. A null answer is remembered for the app run too — staging is not+ * retried on every host launch.+ */+export function ensureStagedHostRuntime(+ opts: StageOptions & { collect?: boolean }+): Promise<StagedHostRuntime | null> {+ const key = `${opts.execPath}\0${opts.script}\0${opts.appVersion}`+ if (memo && memo.key === key) return memo.promise+ const promise = stageHostRuntime(opts).then((runtime) => {+ if (runtime && opts.collect !== false && opts.localAppData) {+ void collectStagedRuntimes({+ root: stagedRuntimeRoot(opts.localAppData),+ keep: [path.basename(runtime.dir)]+ }).catch(() => undefined)+ }+ return runtime+ })+ memo = { key, promise }+ return promise+}++/** Tests only. */+export function resetStagedHostRuntimeForTests(): void {+ memo = null+}