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): session-host subsystem for tmux-less terminal persistence
enes4889adcda3bc
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.mdnew file mode 100644index 000000000..3ebb82400--- /dev/null+++ b/docs/windows-session-host.md@@ -0,0 +1,529 @@+# Windows session host++**What this is:** a tmux-equivalent session-persistence backend for Windows (and any other+platform where a real `tmux` cannot be found), so closing the app — or the app crashing — no+longer kills every running terminal and every agent CLI mid-task. It is a standalone,+long-lived Node process that owns the real PTYs and outlives the Electron app.++This document describes the Windows desktop implementation. It does not embed Microsoft Windows+Terminal, and it does not change the Server Edition or mobile companion.++Selected automatically, per session, in this order:++```+real tmux found on this machine → tmux (unchanged, every platform)+no tmux found, tmuxEnabled → session host (this document)+neither → plain shell (no persistence, as before)+```++Stock Windows provides no native tmux, so the session host is the normal persistence backend+there. On macOS/Linux nothing changes: if tmux is installed, it is still preferred every time.++## Why not just port tmux's approach++tmux does not exist on Windows, full stop — there is no binary to bundle. The session host is a+from-scratch analogue built out of three pieces this codebase (or the wider Node ecosystem)+already has good building blocks for:++1. A **real PTY** per session — `node-pty`, the same dependency the rest of the app already uses.+2. A **server-side terminal emulator** per session — `@xterm/headless` + `@xterm/addon-serialize`,+ so the host can answer "what does this screen currently look like" without a human ever having+ looked at it. This is the piece tmux gets from its own C implementation; here it's the same+ xterm.js core the renderer itself uses, just running headless in Node.+3. A **tiny bespoke IPC protocol** (newline-delimited JSON over a local named pipe / unix socket)+ instead of tmux's binary control-mode protocol, because there is no existing "attach to a named+ session and stream its output" primitive to reuse on Windows.++## Architecture++```+Electron main process Session-host process (standalone, detached)+┌─────────────────────┐ ┌──────────────────────────────────────────┐+│ PtyManager │ │ net.Server (named pipe / unix socket) │+│ spawnSession() │ local IPC │ ── per-connection: hello + dispatch │+│ └ SessionHostPty ──┼─── (JSON lines) ─┼─→ Map<name, HostSession> │+│ (IPty-shim) │ │ ├─ node-pty IPty (the real process) │+│ │ │ ├─ TerminalEmulator (headless xterm) │+│ session-host-client │ │ └─ subscriber sockets (co-attach) │+│ (one connection, │ │ │+│ auto-spawns host) │ │ exits when its last session is killed, │+└─────────────────────┘ │ plus a grace window (see "Lifetime") │+ └──────────────────────────────────────────┘+```++- `src/session-host/` — the standalone process. Pure Node, no Electron dependency anywhere in+ this directory (verified: it does not even import `../core` or `../main`). Bundled with esbuild+ (`npm run host:build`, mirroring the existing `server:build` script) to+ `out/session-host/host.cjs`, with `node-pty` kept external (native module — the same reason+ `server:build` externalizes it).+- `src/core/session-host-client.ts` / `session-host-launcher.ts` / `session-host-backend.ts` /+ `session-host-pty.ts` — the Electron-main-side client. `src/core` stays Electron-free+ (`no-electron.test.ts`); these files import only `net`/`fs`/`crypto` and the pure protocol/paths+ modules.+- `src/core/pty-manager.ts` — the integration seam: `Session.sessionHost?: boolean`+ marks a session-host-backed `Session`, and every call site that reaches past `session.proc` to+ run a tmux CLI command directly (`sendText`, `paneCommand`, `captureSession`, `captureSnapshot`,+ `snapshotScrollback`, `captureForResync`, the final kill in `destroySession`,+ `listNodetermSessions`) gained one `else if (!this.tmuxPath) { … session-host equivalent … }`+ branch, in the same shape the existing `sshRemote` branch already used. `spawnSession()` selects+ this backend between the tmux branch and the plain-shell fallback, and constructs a+ `SessionHostPty` instead of calling `pty.spawn` directly.++## Windows profile resolution++The profile catalog is a trusted desktop service. Its public API returns only a stable `id`,+display label, kind, availability, and an optional unavailable reason. Executable paths and argv+remain private. `PtyCreateOptions.profileId` crosses the desktop bridge; the trusted core validates+and resolves it immediately before either `node-pty` or the session host spawns a process.++Stable ids are `auto`, `pwsh`, `windows-powershell`, `cmd`, `git-bash`, `custom`, and one+`wsl:<distribution>` per installed WSL distribution. `auto` is the only profile allowed to search+down a precedence list: PowerShell 7, then Windows PowerShell, then `%COMSPEC%`/`cmd.exe`. An+explicit unavailable or malformed profile fails; it never becomes a different shell.++For WSL, distribution discovery parses the UTF-16/NUL-padded output of+`wsl.exe --list --quiet`. The selected distribution's own `wslpath` translates the Windows project+directory, after which launch keeps the structured `wsl.exe -d <distribution> --cd <linux-path>`+prefix and runs a trusted distro-side cwd guard before replacing it with the configured default+shell. The guard independently changes to the positional Linux path so a directory removed after+translation cannot silently open in `/`. Enumeration,+translation, and launch failures keep their real reason and perform no fallback spawn. A+distribution name containing spaces remains one argv element.++The profile id is a machine-local snapshot, not project content. `terminalProfileId`, legacy+custom `shell`, and advanced SSH execution values are removed from shared project files, portable+exports, and inbound canvas traffic. A shared file or peer can therefore neither inject argv nor+select a local executable. See+[`features/terminals/windows-shell-profiles.md`](features/terminals/windows-shell-profiles.md).++### The IPty-shim (why the integration is this small)++`PtyManager`'s entire co-attach / flow-control / subscriber / park / reap machinery operates on+`Session.proc`, and only ever calls `.onData()`, `.onExit()`, `.write()`, `.resize()`, `.pause()`,+`.resume()`, `.kill()`/`.destroy()` on it — never `.pid`, never anything ConPTY/Unix-specific.+`SessionHostPty` (`src/core/session-host-pty.ts`) implements exactly that subset, backed by the+session-host connection instead of a real OS pty. Cast at the one construction site in+`spawnSession()` (`as unknown as pty.IPty`), it is otherwise indistinguishable from a real+node-pty `IPty` to every other line in `pty-manager.ts` — every subscriber, every flow-control+ticket, every park/reap decision keeps working unmodified.++## The protocol++Newline-delimited JSON, defined in `src/session-host/protocol.ts` (imported by both sides — it is+the one module the standalone bundle and the Electron-main bundle genuinely share). Every request+carries a monotonic `id`; the host echoes it on the response, so replies self-correlate over one+long-lived connection (no positional-FIFO fragility, unlike this app's tmux control-mode client).++| Verb (`SessionHostRequest.cmd`) | tmux equivalent | Coverage |+|---|---|---|+| `hello` | (no tmux equivalent — auth handshake) | full |+| `attach` | `new-session -A` / `attach-session` | full, plus a screen the tmux path never needed (see below) |+| `hasSession` | `has-session -t <name>` | full (implemented; not on the hot create path — see below) |+| `write` | raw bytes on an attached client's stdin | full |+| `resize` | ConPTY/pty resize + `refresh-client -C` | full; each view claims a size and the effective grid is the componentwise minimum |+| `pause` / `resume` | node-pty `pause()`/`resume()` | full; per-viewer in core and per-connection in the host (first pause / last resume) |+| `sendKeys` | `send-keys -l -- <text>` (+ `Enter`) | full — works with no attached client, exactly like tmux |+| `paneCommand` | `display-message -p '#{pane_current_command}'` | approximated — see `process-tree.ts` |+| `capture` | `capture-pane -p -e [-S -N]` | full, and strictly more (mode restoration — tmux's plain-text capture carries none) |+| `killSession` | `kill-session -t <name>` | full |+| `detach` | a client's own `tmux detach-client` | full |+| `listSessions` | `list-sessions -F '#{session_name}'` | full |+| `ping` | (liveness probe used during the startup race) | full |++**Not implemented — deliberately out of scope for this pass:**++- `paneOwner` / bracketed-paste detection (`bracket_paste_flag`) / `#{cursor_x} #{cursor_y}+#{cursor_flag}` as a _separate_ query. These are real tmux features this app also uses+ (`pty-manager.ts`'s `paneOwner`, `bracketPasteRequested`, `paneCursor`), but none of them are in+ the task's minimum verb list, and cursor position is already carried for free inside `capture`'s+ output (`SerializeAddon` repositions the cursor as part of its own serialization — see below), so+ a separate cursor query would be redundant for this backend specifically. A session-host-backed+ node simply never calls the tmux-only paths that use these (they stay gated on `this.tmuxPath`+ being set, which it never is when session-host is selected).+- The tmux control-mode "shadow client" / shared background-write client+ (`PtyManager.shadowAttach` / `shared`). Session-host does not need an equivalent at all: unlike a+ tmux CLI command (a whole subprocess per invocation), every session-host verb is a stateless+ request over the ONE already-open connection, addressed by session name — the exact problem the+ shadow-client machinery exists to make cheap for tmux is simply not a problem here. See the+ `sendKeys`/`paneCommand`/`capture` rows above: none of them need an attached client.++## The seeding trap (read this before touching `spawnNew`/`join`/`SessionHostPty`)++CLAUDE.md's tmux section states the load-bearing rule for THAT backend: on a warm reattach, the+renderer must **seed nothing**, because tmux's own attaching client repaints the screen by itself+(the redraw arrives as ordinary PTY output, over the same channel as everything else). Writing+into the buffer yourself on top of that is what produced black bands and duplicated screens in an+earlier design.++**The session host is not a painter.** Attaching a new connection to an existing `HostSession`+does not make anything repaint itself — nothing writes fresh bytes into the pty on attach. Get+this backwards in either direction and you ship a visible bug:++- Seed nothing on this backend (copying the tmux rule verbatim) → the reattached terminal is+ **blank** until the next byte of real output arrives.+- Seed unconditionally on every backend → the tmux backend gets a **duplicated screen** on top of+ its own real redraw.++The fix is `Session.proc.ready` + `PtyCreateResult.screen`, used exactly the way the pre-existing+co-attach JOIN path (`PtyManager.join()`) already used `screen` for a same-process second+subscriber — this task did not have to invent a new field, only populate the existing one from a+new source:++- `SessionHostPty.ready` resolves with `{fresh, screen}` from the SAME `attach` round trip the+ constructor kicks off. `fresh: true` (cold start — nothing to paint) or `fresh: false` with a+ `screen` string reconstructed from the host's live headless terminal.+- `spawnNew()` awaits `ready` (after `spawnSession()` returns) and folds `screen` into the+ `PtyCreateResult` it hands back — the exact field `join()` already populates for a same-process+ co-attach.+- A rejected `ready` is a failed create, never a cold-but-working terminal. The provisional local+ `Session` is detached and removed, queued output is cancelled, and the original error reaches the+ renderer. Racing creates wait behind that result instead of joining the provisional index entry;+ a detached relay receives a non-zero sink exit because its legacy API cannot return a promise.+- **The renderer needed zero changes.** `seedPaint()` (`src/renderer/terminal/terminal-config.ts`)+ already treats _any_ non-empty `screen` on a `warm-attach` replay as paintable+ (`create-screen`), regardless of whether it arrived via a co-attach join or a plain reattach —+ that generality already existed, unused by anything but `join()`, before this task. Verified by+ reading `seedPaint`'s body rather than assumed.++Relay/mobile attach does not use that renderer create round trip: it asks+`PtyManager.sessionExists()` and `captureSnapshot()` before `attachDetached()`. Those two public+leaves must route through `sessionHostHasSession` / `sessionHostCapture` when tmux is absent. If+they fall back to the older tmux-only implementation, a live Windows-hosted agent is reported as+fresh and its phone mirror starts blank even though the session host still owns it.++### Private-mode restoration (mouse tracking, bracketed paste, …)++A pane's cursor position and its DEC private modes (has the app running inside it requested mouse+tracking? bracketed paste? is it on the alternate screen?) are not visible in plain captured text.+tmux's own answer to this is `PtyCreateResult.coAttachMouse` / `CO_ATTACH_MOUSE_SEQ` — a hardcoded+mouse-enable sequence the renderer writes because tmux's `capture-pane` carries no mode+information at all, and this app always runs tmux with `mouse on`.++The session host does better, because `@xterm/headless` + `@xterm/addon-serialize` know the real+mode state:++- **Verified, not assumed** (read `SerializeAddon`'s compiled `_serializeModes()` in+ `node_modules/@xterm/addon-serialize/lib/addon-serialize.js` rather than trusted the docs):+ `serialize()`'s output already restores application-cursor-keys, application-keypad,+ bracketed-paste, insert mode, origin mode, reverse-wraparound, send-focus, wraparound, the+ alt-buffer switch, AND the cursor position — all embedded directly in the returned string as+ ANSI escape sequences.+- **The one known gap:** `SerializeAddon` does not emit `CSI ?1006h` (SGR extended mouse+ coordinates) even when mouse tracking is active — there is no separate field on the public+ `IModes` API for it to read (`mouseTrackingMode` only says which tracking _protocol_ is on:+ none/x10/vt200/drag/any, not the coordinate _encoding_). Filled in explicitly by+ `TerminalEmulator.serialize()` in `src/session-host/terminal-emulator.ts`: whenever+ `mouseTrackingMode !== 'none'`, `\x1b[?1006h` is appended by hand.++Because all of this rides inside the `screen` string itself (as real escape sequences the+renderer writes verbatim), **`PtyCreateResult.coAttachMouse` is never set for a session-host+session** — there is nothing left for that separate flag to carry.++### Output ordering, flow ownership, and geometry++`@xterm/headless` applies `Terminal.write()` asynchronously. A PTY data callback therefore does+not mean the emulator is ready to serialize that byte yet. `HostSession.recordOutput()` chains+those promises in arrival order, and every warm attach, capture, resize and final exit crosses the+same tail before it reads or disposes the emulator. Do not replace that with a fire-and-forget+`void term.write(data)`: a relay/phone can then receive a warm snapshot missing output the host has+already observed, and an attach racing a pending write can get the same chunk once live and once in+its seed. The new socket joins the subscriber set only _after_ the barrier and snapshot, which is+the other half of avoiding that duplicate.++That promise tail is also a memory boundary. Bytes accepted but not yet applied to xterm are+counted as UTF-8; at 4 MiB the host takes an emulator-flow ticket and pauses node-pty, then returns+only that ticket after the queue drains to 1 MiB. This ticket is independent from both explicit+renderer flow control and named-pipe backpressure. Likewise, a `socket.write()` returning `false`+takes one transport ticket for every session subscribed on that socket, and only that socket's+`drain` returns it. A drain must never cancel a renderer pause or an emulator backlog.++Ownership is preserved at both aggregation layers. Every in-process `SessionHostPty` is a distinct+pause and geometry owner even though all of them share one `SessionHostClient` socket. The client+sends a pause only on the local 0→1 edge and a resume only on 1→0; the host then combines that one+connection-level ticket with other process sockets. Geometry follows the same shape: the client+reduces its live view claims, the host reduces all socket claims componentwise, and it resizes the+PTY and headless terminal before serializing a warm screen. Detaching a smaller viewer recomputes+the grid so remaining viewers can grow.++The same name is also a generation boundary. Data and exit events contain a session name but no+generation id, so an exiting `HostSession` remains registered until its queued output, final exit+broadcast and disposal complete. A same-name attach waits on that retirement promise before it can+spawn a replacement. The old socket may therefore see its old exit before the new attach response,+but the replacement can never receive an indistinguishable delayed exit from its predecessor. The+whole wait/inspect/create decision is serialized per session name; otherwise two concurrent attach+requests can both wake from the same retirement promise, both observe the empty slot, and spawn two+PTYs before either continuation publishes its choice. Grace-exit cancellation is part of that+atomic claim and runs after the wait, so it also cancels any new empty-host timer retirement just+scheduled before the replacement was created.++### Reconnect (a dropped client connection is not a dead session)++Sessions live in the host process, not in the client. If the Electron-main-side connection drops+(a transient IPC hiccup — not the host dying), `SessionHostClient` begins bounded automatic+reconnect attempts while any desired subscriber remains; an idle viewer does not stay frozen until+some later keypress. Establishing the socket includes an awaited restoration barrier. It replays+every still-live attachment with the local effective geometry and aggregate `paused` flag before+the request that triggered the reconnect is allowed onto the wire. The host applies that pause+before snapshot or live subscriber activation, so output cannot leak through the reattach window.++Any returned `screen` is delivered through the ordinary `onData` path as a full-buffer replacement:+`CSI 3J` clears scrollback, `CSI 2J` clears the viewport, home resets the cursor, and the serialized+screen restores the authoritative cells and DEC modes. Omitting `CSI 3J` merely clears the visible+page and duplicates xterm scrollback after every reconnect. Reusing the ordinary data channel keeps+this recovery local to the session-host client instead of adding a separate renderer resync IPC.++Restoration is never fire-and-forget. A delayed replay attach cannot overtake `hasSession`, `write`,+or a confirmed `killSession` and resurrect the deleted name afterward. If a desired resume, detach,+or replay acknowledgement is transport-ambiguous, the client destroys that socket so the host's+close handler releases all connection-owned tickets, then reconnects and replays only the still-live+desired state. A final unsubscribe racing an in-flight attach schedules a compensating detach after+the attach settles, preventing a ghost subscription.++The `hello` hand-off owns named `connect`/`data`/`error`/`close` listeners. It removes only those+listeners, installs the production frame listener, and then resolves the connection promise. Never+restore broad `removeAllListeners('data')` cleanup here: the original ordering installed the+production listener and immediately deleted it, so all real responses disappeared while the socket+still looked connected.++An initial `attach` registers its local subscriber before sending because startup output may race+the response. If the request rejects, it rolls back only that subscriber and its own remembered+options; a concurrent co-attach remains intact. Empty capture and already-absent kill are confirmed+host responses, while transport rejection remains unknown and propagates. That distinction keeps a+failed snapshot dirty for retry and prevents deletion from claiming an unconfirmed persistent+process is gone.++The same truth boundary reaches the renderer. `pty.destroy` is an acknowledged request on both the+Electron preload bridge and the Server Edition WebSocket bridge. Canvas, sidebar, project, and+agent-control deletion paths remove local nodes and recovery state only after the backing kill is+confirmed; validation, rate-limit, and transport failures keep the node present and retryable.++### A provisional attach is not a session++An `attach` is provisional until the host has authenticated the connection and returned the+correlated successful response. `PtyManager` does not index that shim, report it as persistent, or+expose it to subscribers before `SessionHostPty.ready` resolves.++If the attach is rejected, times out, or the transport fails:++- the provisional shim is destroyed and never enters the persistent-session index;+- queued bytes and a late exit from that rejected shim are ignored;+- every caller coalesced behind the same in-flight create receives the real attach failure;+- failed subscriber registrations are rolled back, so reconnect cannot replay a ghost attach;+- capture or kill transport uncertainty remains an error rather than being read as absence; and+- no plain shell or different profile is spawned as a substitute.++This is deliberately fail-closed. A non-persistent fallback carrying the same node identity would+look healthy while losing the one property this backend promises, and could run a local command in+the wrong shell or directory.++The `hello` hand-off has an equally strict ownership boundary. The handshake installs named+`connect`/`data`/`error`/`close` listeners, accepts only the response carrying its captured hello+request id, removes only those listeners, and then installs the production frame listener before+resolving the connection promise. Never restore broad `removeAllListeners('data')` cleanup here:+the original order installed the production listener and immediately deleted it, so the first+`attach` response and every later frame disappeared while the socket still looked connected.++An initial `attach` registers its local subscriber before sending because startup output may race+the response. If the request rejects, it rolls back only that subscriber and its own remembered+attach options; a concurrent co-attach's state is left intact. Capture and kill preserve the same+failure distinction across reconnects: an empty capture and an idempotently absent kill are both+confirmed `{ok:true}` host responses, while a transport/request rejection remains unknown and is+propagated. That propagation is what lets the periodic snapshot keep its dirty bit for a retry and+what prevents a delete from claiming a persistent process is gone when the host never confirmed it.++The `hello` hand-off has an equally strict ownership boundary. The handshake installs named+`connect`/`data`/`error`/`close` listeners, accepts only the response carrying its captured hello+request id, removes only those listeners, and then installs the production frame listener before+resolving the connection promise. Never restore broad `removeAllListeners('data')` cleanup here:+the original order installed the production listener and immediately deleted it, so the first+`attach` response and every later frame disappeared while the socket still looked connected.++An initial `attach` registers its local subscriber before sending because startup output may race+the response. If the request rejects, it rolls back only that subscriber and its own remembered+attach options; a concurrent co-attach's state is left intact. Capture and kill preserve the same+failure distinction across reconnects: an empty capture and an idempotently absent kill are both+confirmed `{ok:true}` host responses, while a transport/request rejection remains unknown and is+propagated. That propagation is what lets the periodic snapshot keep its dirty bit for a retry and+what prevents a delete from claiming a persistent process is gone when the host never confirmed it.++## Lifetime++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** 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.+ Harmless on a real Node binary too (dev mode): unrecognized, ignored.+- A client disconnecting **detaches only** — the underlying `node-pty` process, and the+ `HostSession` holding it, are completely untouched. This is the entire point.+- The app quitting detaches every client (the OS closes the sockets; the host's own `'close'`+ handler removes that socket from every session's subscriber set **and returns its pause+ ticket**) and leaves the host+ running. `PtyManager.killAll()` was NOT touched — it already never kills tmux sessions, and it+ correctly does nothing to session-host sessions either (no code path in it reaches this backend+ at all).+- The host exits when its **last session is killed** (`killSession`, or a session's own pty+ exiting naturally with nothing else left), plus a **30-second grace window**+ (`GRACE_EXIT_MS` in `host.ts`) so an app restart that briefly closes every node does not tear+ down a host about to be handed a fresh session moments later. A host that never receives a+ single real `attach` also eventually exits via the same grace timer, armed at boot.+- **Startup race** (two app instances launched at once, or two windows racing a lazy first+ connect): both processes may spawn a host. Exactly one may create the state file exclusively+ (`fs.openSync(statePath, 'wx')`); the loser polls that file (bounded, ~1.5s) waiting for the+ winner to finish writing `{pid, endpoint, tokenPath, …}` and answer a real `hello`, then exits+ quietly. A state file that resolves to nothing alive within that window is treated as stale+ (a previous host crashed mid-startup) and reclaimed. The same "connect first, only spawn if that+ fails" shape is what `SessionHostClient.doConnect()` does from the app side, so a host from a+ _previous_ app run is found and reused rather than duplicated.+ The winning state publication uses a PID+counter temp path and a bounded retrying atomic rename+ (`session-host/state-file.ts`, kept local so the standalone bundle does not import `src/core`). A+ fixed `<state>.tmp` lets a stale-lock reclaim collide with another publisher, and a bare rename+ loses startup when a Windows scanner briefly holds the destination open.+ Binding the pipe/socket is not the success boundary: token write and atomic state publication+ must both finish. If either fails, the host closes its listener, destroys any socket from that+ pre-publication window, removes its owned token/state/endpoint, and exits nonzero. This catch is+ explicit because the daemon's `uncaughtException` hook is diagnostic and suppresses Node's+ default fatal exit; letting publication throw into it creates an undiscoverable orphan host.+ Only `ENOENT` means an ownership file is absent. Unreadable, directory, malformed, and empty-token+ observations fail closed without reclaiming or launching a competing host. The client also+ requires the state file's exact protocol version before hello; because the host outlives app+ upgrades, silently connecting a version-2 client to a version-1 host would lose atomic pause and+ geometry restoration.++The spawned program follows the same resolver as a direct local PTY. With no explicit program and+an empty `settings.defaultShell`, Windows selects PowerShell 7, then built-in Windows PowerShell,+then `COMSPEC`/`cmd.exe`; the host must never substitute POSIX-only `bash` there.++## Auth — bearer token, never on argv++`crypto.randomBytes(32)` generated at host start, written to `<userData>/session-host.token` with+mode `0600`, read by every client before its first request and sent in a `hello` frame. Every+other request is refused (`unauthorized`, socket closed) until `hello` succeeds.++**This repository has a measured security incident from putting a bearer token on a command+line** (`docs/node-identity.md` — a hook bearer landed in a long-lived tmux client's+`/proc/<pid>/cmdline` at mode 444, readable by anyone on the box). The session host repeats none+of that shape: the token is never an argv element anywhere (the host is launched with only+`<scriptPath> <userDataDir>` — nothing sensitive), never an environment variable a `ps`/Task+Manager listing could expose, and never logged (`host.ts`'s own diagnostic log never includes it).++**Honest limitation on the transport itself:** the endpoint is a Windows named pipe / POSIX unix+socket. Node's default pipe/socket creation does not carry an explicit, verified per-user ACL in+this implementation — the bearer-token check is the load-bearing access control, not the+transport's own permissions, exactly as the task's instructions require ("Refuse any connection+whose hello token does not match, and close it" is implemented; a separately audited pipe DACL is+not). A local unprivileged process that can guess/observe the token could still connect; guessing+a 256-bit random hex token is not feasible, and observing it requires filesystem access to a+0600-mode file this app's own user account owns — the same trust boundary every other secret this+app already keeps at rest (accounts, hook tokens) relies on.++## Memory bound++Each `HostSession` holds one `@xterm/headless` `Terminal` with `scrollback` capped at+`settings.tmuxScrollback` (default 50,000 lines) — the exact same setting that already bounds real+tmux's `history-limit`, so a machine that already accepted the cost of N tmux panes accepts the+same order of cost for N session-host sessions. The per-session cost is a cell buffer sized+`cols × (rows + scrollback)`, plus `SerializeAddon`'s own transient string-building cost only at+the moment `serialize()` is actually called (attach, join, periodic snapshot, capture request) —+never held continuously. This is a genuinely new per-session cost the tmux backend does not pay+(tmux's server keeps its own C-side pane buffer regardless, but that cost is outside this app's+process); it was a deliberate choice per the task brief ("bound the memory... document the cost+you chose and why") rather than an oversight.++## Honest limitations++- **If the session-host process dies, or the machine reboots, its sessions die with it.** This is+ a strictly weaker guarantee than a real tmux server, which is a mature, independently-shipped C+ daemon this project does not maintain. The existing **cold-restore path** (persisted scrollback+ snapshot + agent `--resume`) already exists for exactly the "machine rebooted" case and applies+ here unchanged: `spawnNew()` correctly reports `fresh: true` when a fresh host has no record of+ a previously-running session, which is what triggers the renderer's cold-start replay+ (`attachReplay` → `'cold-snapshot'`) and the agent CLI's `--resume`. The periodic scrollback+ snapshot (`snapshotScrollback`) runs for session-host-backed sessions on the same 15-second timer+ as the tmux path, using the same on-disk format (`scrollback-store.ts` is entirely+ backend-agnostic — no changes needed there at all).+- **A WSL profile does not turn its distribution's tmux into the Windows backend.** nodeterm+ launches that distribution's default shell through `wsl.exe`, and the Windows session host owns+ the resulting process. A genuinely Windows-reachable tmux found by the existing resolver still+ follows the tmux path; a `tmux` installed only inside WSL is not on the native Windows PATH.+- **`paneCommand`'s answer can be imprecise** when a session has multiple concurrent child+ processes (an agent CLI plus MCP servers) — see `process-tree.ts`'s doc comment. The one caller+ that depends on it (in-place agent restart) only needs "is a shell back in charge of this pane+ yet", which every non-shell answer satisfies equally, so this imprecision is harmless for that+ caller specifically; a future caller with finer-grained needs should not assume more precision+ than this.+- **The node-pty actuator is global, so ownership is ledgered rather than guessed.** Within one app+ process, `pty-manager.ts` keeps a per-viewer/owner `pausedBy` ledger. The standalone host then+ keeps a second set keyed by authenticated socket: the first socket to pause actuates node-pty,+ an unrelated socket's resume is a no-op, and only the last owner leaving/resuming actuates+ resume. `detach` and transport `close` return that socket's ticket. This cannot give two+ connections independent output streams (node-pty has one read side), but it preserves the+ necessary slowest-viewer semantics and, critically, a crashed viewer can no longer freeze the+ live session for every healthy viewer forever.+- **Windows named-pipe/unix-socket ACL is not independently audited** — see "Auth" above; the+ bearer token is the enforced boundary.+- **No equivalent of `paneOwner` / `bracketPasteRequested` / a standalone `paneCursor` query** —+ see the protocol table's "Not implemented" note. Nothing in this app currently calls these for a+ session-host-backed node (they are gated behind `this.tmuxPath` being set), so nothing is+ silently broken; a future feature that wants one of these on Windows needs a new host verb.+- **ConPTY helper teardown can emit `Error: AttachConsole failed`** from+ `node-pty/lib/conpty_console_list_agent.js`. The protocol test determines kill success from the+ host response and follow-up session state rather than stderr text. Whether this cosmetic+ dependency message appears in the packaged app remains part of the pending artifact run.++## Automated verification++The focused suites exercise behaviour rather than scan implementation source:++- the Windows profile resolver covers detection precedence, standard Git Bash locations, custom+ absolute paths containing spaces, `%COMSPEC%`, unavailable executables, malformed ids, WSL+ UTF-16/NUL output, distribution names containing spaces, and cwd-conversion failures;+- resolver/spawn tests assert that `node-pty` and session-host creation receive only the trusted+ launch plan, and that explicit unavailable profiles perform no fallback spawn;+- `pty-session-host.test.ts` exercises successful creation plus provisional/rejected attach+ teardown, coalesced callers, late events, and the persistent result;+- `session-host-client.test.ts` uses real local sockets to exercise the hello transition,+ correlated responses, failed-subscriber rollback, reconnect replay, and transport uncertainty;+ and+- workspace/node-exec tests prove `terminalProfileId` never enters shared/exported/inbound state+ and that the local overlay survives reload.++The guards were mutation-checked by temporarily accepting a hostile profile, allowing a missing+WSL distribution to fall back, and removing machine-local stripping; each corresponding focused+test must turn red. The former source-text shell regression test is intentionally gone.++The original session-host implementation was also verified by hand against a real ConPTY session.+The ordering, connection-owned pause ledger, no-tmux relay probe/capture, platform shell selection,+and atomic state publication are now additionally behaviour-tested with adversarial scheduling and+injected sharing violations. That source/runtime evidence does not replace the packaged check.++## Packaged verification still owed++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, relaunch+around a long-running process, switch a node through the destructive profile warning, and record+the picker, profile terminal, unavailable state, and post-relaunch reattachment. Until that built+artifact evidence exists, this document makes no claim that the full packaged verification has+completed.++`paneOwner`, `bracketPasteRequested`, the standalone `paneCursor` query, and independently audited+Windows named-pipe DACL hardening remain outside this profile pass as described under+"Honest limitations".++## What was deliberately not done++- The original implementation was verified by hand against a real ConPTY session. The ordering,+ connection-owned pause ledger, no-tmux relay probe/capture, platform shell selection and atomic+ state publication are now additionally behavior-tested with adversarial scheduling and injected+ sharing violations. A packaged installer launch on a separate Windows device is still owed (see+ `docs/windows-support.md`); these tests do not pretend to replace that device check.+- `paneOwner`, `bracketPasteRequested`, and a standalone `paneCursor` query were not ported — see+ "Honest limitations".+- Windows named-pipe DACL hardening beyond Node's own defaults was not attempted — the bearer+ token is the enforced boundary, documented as such rather than silently assumed to be perfect.+- The relay host's `createDetached`/`attachDetached` paths were left to fall through to+ `spawnSession()`'s new branch automatically (they call it directly with no prior async+ pre-check), so they work, but were not separately hand-verified end-to-end through the relay+ feature itself in this pass — only the primary create/join/reconnect/capture/kill paths were.diff --git a/package-lock.json b/package-lock.jsonindex dafa98eff..be79adc31 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,17 +1,19 @@{"name": "node-terminal",- "version": "0.3.0",+ "version": "0.3.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "node-terminal",- "version": "0.3.0",+ "version": "0.3.2","hasInstallScript": true,"license": "BUSL-1.1","dependencies": {+ "@xterm/addon-serialize": "^0.14.0","@xterm/addon-unicode11": "^0.9.0","@xterm/addon-web-links": "^0.11.0",+ "@xterm/headless": "^6.0.0","dompurify": "^3.4.13","electron-updater": "^6.8.9","marked": "^12.0.2",@@ -3543,6 +3545,12 @@"dev": true,"license": "MIT"},+ "node_modules/@xterm/addon-serialize": {+ "version": "0.14.0",+ "resolved": "https://registry.npmjs.org/@xterm/addon-serialize/-/addon-serialize-0.14.0.tgz",+ "integrity": "sha512-uteyTU1EkrQa2Ux6P/uFl2fzmXI46jy5uoQMKEOM0fKTyiW7cSn0WrFenHm5vO5uEXX/GpwW/FgILvv3r0WbkA==",+ "license": "MIT"+ },"node_modules/@xterm/addon-unicode11": {"version": "0.9.0","resolved": "https://registry.npmjs.org/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz",@@ -3568,6 +3576,15 @@"@xterm/xterm": "^5.0.0"}},+ "node_modules/@xterm/headless": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/@xterm/headless/-/headless-6.0.0.tgz",+ "integrity": "sha512-5Yj1QINYCyzrZtf8OFIHi47iQtI+0qYFPHmouEfG8dHNxbZ9Tb9YGSuLcsEwj9Z+OL75GJqPyJbyoFer80a2Hw==",+ "license": "MIT",+ "workspaces": [+ "addons/*"+ ]+ },"node_modules/@xterm/xterm": {"version": "5.5.0","resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",diff --git a/package.json b/package.jsonindex 27a5092a5..bcc5ee3dc 100644--- a/package.json+++ b/package.json@@ -19,6 +19,7 @@"test:unit": "vitest run test/remote","rebuild": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper","server:build": "esbuild src/server/main.ts --bundle --platform=node --format=cjs --outfile=out/server/main.cjs --external:node-pty --external:ws --external:smart-whisper --tsconfig=tsconfig.node.json",+ "host:build": "esbuild src/session-host/host.ts --bundle --platform=node --format=cjs --outfile=out/session-host/host.cjs --external:node-pty --tsconfig=tsconfig.node.json","server:start": "node out/server/main.cjs","server:dev": "npm run build && npm run server:build && node out/server/main.cjs","make-icon": "node scripts/make-icon.mjs",@@ -112,8 +113,10 @@}},"dependencies": {+ "@xterm/addon-serialize": "^0.14.0","@xterm/addon-unicode11": "^0.9.0","@xterm/addon-web-links": "^0.11.0",+ "@xterm/headless": "^6.0.0","dompurify": "^3.4.13","electron-updater": "^6.8.9","marked": "^12.0.2",diff --git a/src/core/__fixtures__/no-session-host.ts b/src/core/__fixtures__/no-session-host.tsnew file mode 100644index 000000000..7f8dc8556--- /dev/null+++ b/src/core/__fixtures__/no-session-host.ts@@ -0,0 +1,53 @@+/**+ * A `vi.mock` factory that forces `pty-manager` off the session-host backend.+ *+ * WHY THIS EXISTS. `spawnSession` picks its persistence backend in the order+ * **tmux -> session host -> plain shell**. The session-host branch is taken when tmux is absent+ * (always true on Windows) AND `sessionHostSupported()` is true — and that probe answers nothing+ * more than "is `out/session-host/host.cjs` on disk". So merely having run `npm run build` flips+ * every suite that mocks `node-pty` and expects the plain-shell path: the mocked `spawn` is never+ * called, a real `SessionHostPty` shim is constructed instead, it never connects, and the suite+ * fails with `Cannot read properties of undefined (reading 'killed')` and 5s timeouts. One file+ * went from 78 passing in 2.8s to 73 failing in 355s purely because a build artifact appeared.+ *+ * A suite that cares which backend it exercises must therefore SAY SO rather than inherit whatever+ * the machine happens to have built — the same reasoning that makes `pty-bundled-tmux.test.ts` pin+ * `os.platform()` to darwin instead of trusting the host.+ *+ * This lives in one place on purpose: the mock has to name every export of+ * `./session-host-backend`, and four copies of that list would drift the first time an export is+ * added — the new export would be `undefined` in three suites and fail somewhere unrelated.+ *+ * Usage, at the top of a suite (the path is relative to the TEST file, not to this fixture):+ *+ * vi.mock('./session-host-backend', async () =>+ * (await import('./__fixtures__/no-session-host')).noSessionHost()+ * )+ *+ * Do NOT use this in a suite that is actually testing the session host — that backend has, and+ * needs, its own coverage.+ */+export function noSessionHost(): Record<string, unknown> {+ return {+ // The gate itself: false means `spawnSession` falls through to the plain-shell branch.+ sessionHostSupported: () => false,+ // Never reachable while `sessionHostSupported()` is false. Throwing rather than returning a+ // dummy makes a future regression in the branch condition fail loudly and locally, instead of+ // handing the caller a stub pty that misbehaves somewhere further away.+ createSessionHostPty: () => {+ throw new Error(+ 'session-host backend was selected in a suite that mocked it out — the backend-selection ' ++ 'branch in pty-manager.spawnSession has changed; see src/core/__fixtures__/no-session-host.ts'+ )+ },+ // The remaining exports are only called for a session that was already created on this+ // backend, which cannot happen here. They resolve to benign empties so that an incidental+ // call (e.g. a broad sweep over all sessions) cannot throw and mask the real assertion.+ sessionHostCapture: async () => '',+ sessionHostHasSession: async () => false,+ sessionHostKillSession: async () => {},+ sessionHostListSessions: async () => [],+ sessionHostPaneCommand: async () => null,+ sessionHostSendKeys: async () => false+ }+}diff --git a/src/core/__fixtures__/silent-session-host-child.cjs b/src/core/__fixtures__/silent-session-host-child.cjsnew file mode 100644index 000000000..35de1a483--- /dev/null+++ b/src/core/__fixtures__/silent-session-host-child.cjs@@ -0,0 +1,28 @@+"use strict";++// Real-Windows acceptance fixture. It intentionally emits no stdout/stderr before termination:+// node-pty's Windows kill path historically waited for first output and therefore could strand+// this otherwise valid process forever. Its child makes taskkill's `/T` tree traversal observable:+// killing only the root must leave the child alive and fail the acceptance harness. PID evidence is+// written exclusively to a task-owned file, never through the terminal being tested.+const { spawn } = require("child_process");+const fs = require("fs");++if (process.argv[2] !== "--child") {+ const evidencePath = process.argv[2];+ if (!evidencePath) process.exit(2);+ const child = spawn(process.execPath, [__filename, "--child"], {+ cwd: process.cwd(),+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },+ stdio: "ignore",+ windowsHide: true,+ });+ if (!Number.isSafeInteger(child.pid) || child.pid <= 0) process.exit(3);+ fs.writeFileSync(+ evidencePath,+ JSON.stringify({ parentPid: process.pid, childPid: child.pid }),+ { flag: "wx", mode: 0o600 },+ );+}++setInterval(() => {}, 0x7fffffff);diff --git a/src/core/agent-launch.test.ts b/src/core/agent-launch.test.tsnew file mode 100644index 000000000..6f401aafb--- /dev/null+++ b/src/core/agent-launch.test.ts@@ -0,0 +1,879 @@+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { tmpdir } from "node:os";+import path from "node:path";+import { describe, expect, it, vi } from "vitest";+import type { AgentLaunchIntent } from "../shared/types";+import {+ AgentLaunchPreparationError,+ prepareAgentLaunch,+ type AgentLaunchDialect,+ type AgentLaunchTrustedContext,+ type PreparedAgentLaunch,+ type TrustedCustomAgentLaunchConfig,+} from "./agent-launch";++const WINDOWS = process.platform === "win32";+const WINDOWS_POWERSHELL = WINDOWS+ ? path.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ )+ : null;++function firstWhere(command: string): string | null {+ if (!WINDOWS) return null;+ const result = spawnSync("where.exe", [command], { encoding: "utf8" });+ const first =+ result.status === 0+ ? result.stdout.split(/\r?\n/u).find(Boolean)+ : undefined;+ return first?.trim() || null;+}++const PWSH = firstWhere("pwsh.exe");+const GIT_BASH = WINDOWS+ ? ([+ path.join(+ process.env.ProgramFiles ?? "C:\\Program Files",+ "Git",+ "bin",+ "bash.exe",+ ),+ path.join(+ process.env.LOCALAPPDATA ?? "",+ "Programs",+ "Git",+ "bin",+ "bash.exe",+ ),+ ].find((candidate) => existsSync(candidate)) ?? null)+ : existsSync("/bin/bash")+ ? "/bin/bash"+ : null;++function installedWslDistros(): string[] {+ if (!WINDOWS) return [];+ const result = spawnSync("wsl.exe", ["--list", "--quiet"]);+ if (result.status !== 0 || !Buffer.isBuffer(result.stdout)) return [];+ const stdout = result.stdout.includes(0)+ ? result.stdout.toString("utf16le")+ : result.stdout.toString("utf8");+ return stdout+ .replace(/^\uFEFF/u, "")+ .split(/\r?\n/u)+ .map((line) => line.replace(/\0/g, "").trim())+ .filter(Boolean);+}++const WSL_DISTROS = installedWslDistros();++const start = (+ agentId: string,+ extra: Partial<Extract<AgentLaunchIntent, { action: "start" }>> = {},+): AgentLaunchIntent => ({ kind: "agent", action: "start", agentId, ...extra });++const resume = (+ agentId: string,+ sessionId = "session-1",+ extra: Partial<Extract<AgentLaunchIntent, { action: "resume" }>> = {},+): AgentLaunchIntent => ({+ kind: "agent",+ action: "resume",+ agentId,+ sessionId,+ ...extra,+});++const builtinContext = (+ agentId: string,+ extra: Partial<AgentLaunchTrustedContext> = {},+): AgentLaunchTrustedContext => ({+ expectedAgentId: agentId,+ sharedIdentityAvailable: false,+ ...extra,+});++function customContext(+ customAgent: TrustedCustomAgentLaunchConfig,+ extra: Partial<AgentLaunchTrustedContext> = {},+): AgentLaunchTrustedContext {+ return {+ expectedAgentId: customAgent.id,+ customAgent,+ sharedIdentityAvailable: false,+ ...extra,+ };+}++async function expectFailure(+ intent: AgentLaunchIntent,+ dialect: AgentLaunchDialect,+ context: AgentLaunchTrustedContext,+ code: AgentLaunchPreparationError["code"],+): Promise<AgentLaunchPreparationError> {+ try {+ await prepareAgentLaunch(intent, dialect, context);+ } catch (error) {+ expect(error).toBeInstanceOf(AgentLaunchPreparationError);+ expect((error as AgentLaunchPreparationError).code).toBe(code);+ return error as AgentLaunchPreparationError;+ }+ throw new Error("Expected prepareAgentLaunch to reject");+}++describe("prepareAgentLaunch logical argv", () => {+ it("keeps the historical no-separator order and validates a minted Claude id", async () => {+ await expect(+ prepareAgentLaunch(+ start("claude", {+ prompt: "fix 'this'",+ permissionMode: "plan",+ newSessionId: "550e8400-e29b-41d4-a716-446655440000",+ }),+ "posix",+ builtinContext("claude"),+ ),+ ).resolves.toEqual({+ command:+ "'claude' 'fix '\\''this'\\''' '--permission-mode' 'plan' '--session-id' '550e8400-e29b-41d4-a716-446655440000'",+ });+ });++ it("puts Grok flags before its end-of-options separator", async () => {+ await expect(+ prepareAgentLaunch(+ start("grok", { prompt: "version", permissionMode: "plan" }),+ "posix",+ builtinContext("grok"),+ ),+ ).resolves.toEqual({+ command: "'grok' '--permission-mode' 'plan' '--' 'version'",+ });+ });++ it("uses flag-prompt for OpenCode and preserves a trailing slash", async () => {+ await expect(+ prepareAgentLaunch(+ start("opencode", { prompt: "repo/" }),+ "posix",+ builtinContext("opencode"),+ ),+ ).resolves.toEqual({ command: "'opencode' '--prompt' 'repo/'" });+ });++ it("preserves Gemini's historical positional prompt, including an empty prompt", async () => {+ await expect(+ prepareAgentLaunch(+ start("gemini", { prompt: "", permissionMode: "plan" }),+ "posix",+ builtinContext("gemini"),+ ),+ ).resolves.toEqual({+ command: "'gemini' '' '--approval-mode' 'plan'",+ });+ });++ it("builds every builtin resume grammar and derives shared identity from trusted context", async () => {+ await expect(+ prepareAgentLaunch(+ resume("codex", "thread-1", { permissionMode: "auto" }),+ "posix",+ builtinContext("codex", { sharedIdentityAvailable: true }),+ ),+ ).resolves.toEqual({+ command:+ "'nodeterm-codex' 'resume' 'thread-1' '--ask-for-approval' 'on-request'",+ });+ await expect(+ prepareAgentLaunch(+ resume("opencode", "chat-1"),+ "posix",+ builtinContext("opencode"),+ ),+ ).resolves.toEqual({ command: "'opencode' '--session' 'chat-1'" });+ await expect(+ prepareAgentLaunch(+ resume("claude", "chat-2"),+ "posix",+ builtinContext("claude"),+ ),+ ).resolves.toEqual({ command: "'claude' '--resume' 'chat-2'" });+ });++ it("uses the exact machine-local custom config and honors structural prompt modes", async () => {+ const argv = {+ id: "custom:argv",+ launchCmd: 'npx -y "my agent"',+ promptInjectionMode: "argv",+ } as const;+ await expect(+ prepareAgentLaunch(+ start(argv.id, { prompt: "hello world" }),+ "posix",+ customContext(argv),+ ),+ ).resolves.toEqual({ command: "'npx' '-y' 'my agent' 'hello world'" });++ const flag = {+ id: "custom:flag",+ launchCmd: "agent",+ promptInjectionMode: "flag-prompt",+ } as const;+ await expect(+ prepareAgentLaunch(+ start(flag.id, { prompt: "" }),+ "posix",+ customContext(flag),+ ),+ ).resolves.toEqual({ command: "'agent' '--prompt' ''" });+ });++ it.each(["posix", "pwsh", "windows-powershell", "cmd"] as const)(+ "rejects custom stdin-after-start under %s without a trusted child-readiness handshake",+ async (dialect) => {+ const stdin = {+ id: "custom:stdin",+ launchCmd: "agent --interactive",+ promptInjectionMode: "stdin-after-start",+ } as const;+ await expectFailure(+ start(stdin.id, { prompt: "hello" }),+ dialect,+ customContext(stdin),+ "unsupported-shell",+ );+ },+ );+});++describe("prepareAgentLaunch runtime trust checks", () => {+ it.each([+ [+ "wrong kind",+ { kind: "shell-command", action: "start", agentId: "claude" },+ ],+ ["unknown action", { kind: "agent", action: "branch", agentId: "claude" }],+ [+ "start carrying resume id",+ {+ kind: "agent",+ action: "start",+ agentId: "claude",+ sessionId: "session-1",+ },+ ],+ [+ "resume carrying a prompt",+ {+ kind: "agent",+ action: "resume",+ agentId: "claude",+ sessionId: "session-1",+ prompt: "x",+ },+ ],+ [+ "resume carrying a new id",+ {+ kind: "agent",+ action: "resume",+ agentId: "claude",+ sessionId: "session-1",+ newSessionId: "550e8400-e29b-41d4-a716-446655440000",+ },+ ],+ [+ "forged permission mode",+ {+ kind: "agent",+ action: "start",+ agentId: "claude",+ permissionMode: "plan & calc",+ },+ ],+ [+ "control-bearing prompt",+ { kind: "agent", action: "start", agentId: "claude", prompt: "a\nb" },+ ],+ [+ "Unicode line separator prompt",+ { kind: "agent", action: "start", agentId: "claude", prompt: "a\u2028b" },+ ],+ [+ "Unicode paragraph separator prompt",+ { kind: "agent", action: "start", agentId: "claude", prompt: "a\u2029b" },+ ],+ [+ "unsafe resume id",+ { kind: "agent", action: "resume", agentId: "claude", sessionId: "../x" },+ ],+ [+ "empty resume id",+ { kind: "agent", action: "resume", agentId: "claude", sessionId: "" },+ ],+ [+ "non-v4 minted id",+ {+ kind: "agent",+ action: "start",+ agentId: "claude",+ newSessionId: "550e8400-e29b-11d4-a716-446655440000",+ },+ ],+ ])(+ "rejects %s rather than trusting the TypeScript type",+ async (_name, forged) => {+ await expectFailure(+ forged as unknown as AgentLaunchIntent,+ "posix",+ builtinContext("claude"),+ "invalid-intent",+ );+ },+ );++ it("requires the intent to match the trusted node owner", async () => {+ await expectFailure(+ start("codex"),+ "posix",+ builtinContext("claude"),+ "agent-unavailable",+ );+ });++ it.each(["constructor", "custom:missing", "calc & echo forged"])(+ "does not preserve the renderer unknown-id executable fallback for %s",+ async (agentId) => {+ await expectFailure(+ start(agentId),+ "posix",+ builtinContext(agentId),+ "agent-unavailable",+ );+ },+ );++ it("requires an exact current custom record and rejects custom resume", async () => {+ const custom = {+ id: "custom:one",+ launchCmd: "agent",+ promptInjectionMode: "argv",+ } as const;+ await expectFailure(+ start("custom:one"),+ "posix",+ customContext({ ...custom, id: "custom:other" }),+ "agent-unavailable",+ );+ await expectFailure(+ resume(custom.id),+ "posix",+ customContext(custom),+ "agent-unavailable",+ );+ });++ it.each(["agent && calc", "agent | calc", 'agent "unterminated', "-agent"])(+ "fails closed for an unstructured custom launch command: %s",+ async (launchCmd) => {+ const custom = {+ id: "custom:unsafe",+ launchCmd,+ promptInjectionMode: "argv",+ } as const;+ await expectFailure(+ start(custom.id, { prompt: "safe prompt" }),+ "posix",+ customContext(custom),+ "agent-unavailable",+ );+ },+ );++ it("rejects a minted id for an agent that cannot mint one", async () => {+ await expectFailure(+ start("codex", {+ newSessionId: "550e8400-e29b-41d4-a716-446655440000",+ } as never),+ "posix",+ builtinContext("codex"),+ "invalid-intent",+ );+ });++ it("rejects a permission mode for agents that do not implement one", async () => {+ await expectFailure(+ start("opencode", { permissionMode: "plan" }),+ "posix",+ builtinContext("opencode"),+ "invalid-intent",+ );+ const custom = {+ id: "custom:mode",+ launchCmd: "agent",+ promptInjectionMode: "argv",+ } as const;+ await expectFailure(+ start(custom.id, { permissionMode: "manual" }),+ "posix",+ customContext(custom),+ "invalid-intent",+ );+ });++ it("rejects Unicode command separators in trusted custom config and resolver output", async () => {+ const custom = {+ id: "custom:separator",+ launchCmd: "agent\u2028calc",+ promptInjectionMode: "argv",+ } as const;+ await expectFailure(+ start(custom.id),+ "posix",+ customContext(custom),+ "agent-unavailable",+ );++ await expectFailure(+ start("claude"),+ "pwsh",+ builtinContext("claude", {+ resolveExecutableKind: async () => ({+ kind: "native",+ executable: "C:\\Trusted\\claude\u2029calc.exe",+ }),+ }),+ "agent-unavailable",+ );+ });++ it("never repeats program, argv, prompt, or resolver diagnostics in an error", async () => {+ const secret = "SENSITIVE & PROMPT %PATH% 開発";+ const custom = {+ id: "custom:secret",+ launchCmd: `secret-program && ${secret}`,+ promptInjectionMode: "argv",+ } as const;+ const parseError = await expectFailure(+ start(custom.id, { prompt: secret }),+ "posix",+ customContext(custom),+ "agent-unavailable",+ );+ expect(parseError.message).not.toContain("secret");+ expect(parseError.message).not.toContain(secret);++ const resolverError = await expectFailure(+ start("claude", { prompt: secret }),+ "pwsh",+ builtinContext("claude", {+ resolveExecutableKind: async () => {+ throw new Error(`failed secret-program ${secret}`);+ },+ }),+ "agent-unavailable",+ );+ expect(resolverError.message).not.toContain("secret");+ expect(resolverError.message).not.toContain(secret);+ });++ it("rejects a POSIX argument that exceeds the portable Git Bash/WSL byte boundary", async () => {+ await expectFailure(+ start("claude", { prompt: "開".repeat(11_000) }),+ "posix",+ builtinContext("claude"),+ "invalid-intent",+ );+ });+});++describe("PowerShell executable classification", () => {+ it("uses a trusted resolver for a bare executable and the resolved path", async () => {+ const resolveExecutableKind = vi.fn(async () => ({+ kind: "native" as const,+ executable: "C:\\Trusted Tools\\agent.exe",+ }));+ const plan = await prepareAgentLaunch(+ start("claude", { prompt: "hello" }),+ "pwsh",+ builtinContext("claude", { resolveExecutableKind }),+ );+ expect(resolveExecutableKind).toHaveBeenCalledWith("claude", "pwsh");+ expect(plan.command).toBe(+ "$ntAgent = Start-Process -FilePath 'C:\\Trusted Tools\\agent.exe' -ArgumentList 'hello' -NoNewWindow -Wait -PassThru ; $global:LASTEXITCODE = $ntAgent.ExitCode",+ );+ });++ it.each(["pwsh", "windows-powershell", "cmd"] as const)(+ "refuses a cmd/bat shim under %s instead of applying native quoting",+ async (dialect) => {+ await expectFailure(+ start("claude", { prompt: "%PATH% & calc" }),+ dialect,+ builtinContext("claude", {+ resolveExecutableKind: async () => ({+ kind: "cmd-script",+ executable: "C:\\Tools\\claude.cmd",+ }),+ windowsPowerShellPath: WINDOWS_POWERSHELL ?? undefined,+ }),+ "unsupported-shell",+ );+ },+ );++ it("requires the trusted resolver to verify explicit paths as well as bare commands", async () => {+ const custom = {+ id: "custom:ps1",+ launchCmd: "C:\\Tools\\agent.ps1",+ promptInjectionMode: "argv",+ } as const;+ await expect(+ prepareAgentLaunch(+ start(custom.id, { prompt: "x" }),+ "pwsh",+ customContext(custom, {+ resolveExecutableKind: async () => ({+ kind: "powershell-script",+ executable: "C:\\Tools\\agent.ps1",+ }),+ }),+ ),+ ).resolves.toEqual({ command: "& 'C:\\Tools\\agent.ps1' 'x'" });++ await expectFailure(+ start(custom.id),+ "pwsh",+ customContext(custom),+ "unsupported-shell",+ );+ await expectFailure(+ start("claude"),+ "pwsh",+ builtinContext("claude"),+ "unsupported-shell",+ );+ });++ it.each([+ { kind: "native" as const, executable: "C:\\Tools\\agent.cmd" },+ { kind: "powershell-script" as const, executable: "C:\\Tools\\agent.exe" },+ { kind: "native" as const, executable: "relative\\agent.exe" },+ ])(+ "rejects a mismatched or non-absolute resolver result: $kind/$executable",+ async (resolution) => {+ await expectFailure(+ start("claude"),+ "pwsh",+ builtinContext("claude", {+ resolveExecutableKind: async () => resolution,+ }),+ "agent-unavailable",+ );+ },+ );+});++describe("cmd wrapper", () => {+ it("requires a trusted absolute PowerShell executable and never falls back to cmd interpolation", async () => {+ const resolver = async (): Promise<{+ kind: "native";+ executable: string;+ }> => ({+ kind: "native",+ executable: "C:\\Tools\\agent.exe",+ });+ for (const windowsPowerShellPath of [+ undefined,+ "powershell.exe",+ "C:\\Tools\\power%PATH%shell.exe",+ "C:\\Tools\\power&shell.exe",+ "C:\\Tools\\powershell.cmd",+ ]) {+ await expectFailure(+ start("claude", { prompt: "hello" }),+ "cmd",+ builtinContext("claude", {+ resolveExecutableKind: resolver,+ windowsPowerShellPath,+ }),+ "unsupported-shell",+ );+ }+ });++ it("encodes every logical token as UTF-16LE Base64 and leaves an ASCII-only outer line", async () => {+ if (!WINDOWS_POWERSHELL) return;+ const secret = "space a'b &|<>^%! '$`\" Unicode 開発 /";+ const plan = await prepareAgentLaunch(+ start("claude", { prompt: secret }),+ "cmd",+ builtinContext("claude", {+ resolveExecutableKind: async () => ({+ kind: "native",+ executable: "C:\\Trusted Tools\\claude.exe",+ }),+ windowsPowerShellPath: WINDOWS_POWERSHELL,+ }),+ );+ expect(plan.command).toMatch(+ / -NoLogo -NoProfile -EncodedCommand [A-Za-z0-9+/]+=*$/u,+ );+ expect(plan.command).not.toContain(secret);+ expect([...plan.command].every((ch) => ch.charCodeAt(0) <= 0x7f)).toBe(+ true,+ );++ const payload = plan.command.match(+ /-EncodedCommand ([A-Za-z0-9+/]+=*)$/u,+ )?.[1];+ expect(payload).toBeTruthy();+ const decoded = Buffer.from(payload as string, "base64").toString(+ "utf16le",+ );+ expect(decoded).toContain(+ "$ntAgent = Start-Process -FilePath 'C:\\Trusted Tools\\claude.exe' -ArgumentList",+ );+ expect(decoded).toContain("\"space a''b &|<>^%! ''$`\\\" Unicode 開発 /\"");+ expect(decoded).toContain("$global:LASTEXITCODE = $ntAgent.ExitCode");+ });++ it("rejects data that cannot fit the target Windows command-line boundary", async () => {+ if (!WINDOWS_POWERSHELL) return;+ const resolver = async (): Promise<{+ kind: "native";+ executable: string;+ }> => ({+ kind: "native",+ executable: "C:\\Tools\\agent.exe",+ });+ await expectFailure(+ start("claude", { prompt: "x".repeat(4_000) }),+ "cmd",+ builtinContext("claude", {+ resolveExecutableKind: resolver,+ windowsPowerShellPath: WINDOWS_POWERSHELL,+ }),+ "invalid-intent",+ );+ await expectFailure(+ start("claude", { prompt: "x".repeat(40_000) }),+ "pwsh",+ builtinContext("claude", { resolveExecutableKind: resolver }),+ "invalid-intent",+ );+ });+});++const PROMPTS = [+ "space apostrophe ' &|<>^%!'$` double \" Unicode 開発 🧪",+ "",+ "path/",+ "trailing\\",+ "--version",+ "--",+ "resume",+ "help",+ "--dangerously-skip-permissions",+] as const;++const ARG_PRINTER =+ "process.stdout.write(JSON.stringify(process.argv.slice(1)))";++function neutralQuote(value: string): string {+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;+}++function customNodeConfig(executable: string): TrustedCustomAgentLaunchConfig {+ return {+ id: "custom:argv-printer",+ launchCmd: `${neutralQuote(executable)} -e ${neutralQuote(ARG_PRINTER)} --`,+ promptInjectionMode: "argv",+ };+}++function executeWindowsPlan(+ shell: string,+ dialect: AgentLaunchDialect,+ plan: PreparedAgentLaunch,+): string[] {+ const result =+ dialect === "cmd"+ ? spawnSync(shell, ["/d", "/v:off", "/c", plan.command], {+ encoding: "utf8",+ windowsVerbatimArguments: true,+ })+ : spawnSync(shell, ["-NoLogo", "-NoProfile", "-Command", plan.command], {+ encoding: "utf8",+ });+ expect(result.status, result.stderr || result.stdout).toBe(0);+ return JSON.parse(result.stdout) as string[];+}++describe.runIf(WINDOWS)("real Windows shell argv behavior", () => {+ const windowsCases: Array<[AgentLaunchDialect, string | null]> = [+ ["pwsh", PWSH],+ ["windows-powershell", WINDOWS_POWERSHELL],+ ["cmd", process.env.ComSpec ?? "C:\\Windows\\System32\\cmd.exe"],+ ];++ it.each(windowsCases)(+ "%s delivers the metacharacter and Unicode matrix exactly",+ async (dialect, shell) => {+ if (!shell || !existsSync(shell)) return;+ const custom = customNodeConfig(process.execPath);+ for (const prompt of PROMPTS) {+ const plan = await prepareAgentLaunch(+ start(custom.id, { prompt }),+ dialect,+ customContext(custom, {+ resolveExecutableKind: async () => ({+ kind: "native",+ executable: process.execPath,+ }),+ windowsPowerShellPath: WINDOWS_POWERSHELL ?? undefined,+ }),+ );+ expect(executeWindowsPlan(shell, dialect, plan)).toEqual([prompt]);+ }+ },+ 60_000,+ );++ it.each(windowsCases)(+ "%s delivers exact argv through a verified PowerShell-script entry point",+ async (dialect, shell) => {+ if (!shell || !existsSync(shell)) return;+ const directory = mkdtempSync(+ path.join(tmpdir(), "nodeterm-agent-launch-"),+ );+ const script = path.join(directory, "argv printer.ps1");+ writeFileSync(+ script,+ [+ "param([Parameter(ValueFromRemainingArguments=$true)][string[]] $Rest)",+ "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)",+ "[Console]::Write((ConvertTo-Json -Compress -InputObject @($Rest)))",+ ].join("\r\n"),+ "utf8",+ );+ try {+ const custom = {+ id: "custom:ps1-argv-printer",+ launchCmd: neutralQuote(script),+ promptInjectionMode: "argv",+ } as const;+ const combined = PROMPTS.filter(Boolean).join(" :: ");+ for (const prompt of [combined, ""]) {+ const plan = await prepareAgentLaunch(+ start(custom.id, { prompt }),+ dialect,+ customContext(custom, {+ resolveExecutableKind: async () => ({+ kind: "powershell-script",+ executable: script,+ }),+ windowsPowerShellPath: WINDOWS_POWERSHELL ?? undefined,+ }),+ );+ expect(executeWindowsPlan(shell, dialect, plan)).toEqual([prompt]);+ }+ } finally {+ rmSync(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ }+ },+ 30_000,+ );++ it.runIf(!!GIT_BASH)(+ "Git Bash executes the POSIX encoder with exact argv",+ async () => {+ const bashNode = process.execPath+ .replace(+ /^([A-Za-z]):[\\/]/u,+ (_all, drive: string) => `/${drive.toLowerCase()}/`,+ )+ .replace(/\\/g, "/");+ const custom = customNodeConfig(bashNode);+ for (const prompt of PROMPTS) {+ const plan = await prepareAgentLaunch(+ start(custom.id, { prompt }),+ "posix",+ customContext(custom),+ );+ const result = spawnSync(+ GIT_BASH as string,+ ["--noprofile", "--norc", "-c", plan.command],+ {+ encoding: "utf8",+ },+ );+ expect(result.status, result.stderr || result.stdout).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual([prompt]);+ }+ },+ );+});++describe.runIf(WINDOWS && WSL_DISTROS.length > 0)(+ "real WSL POSIX argv behavior",+ () => {+ it.each(WSL_DISTROS)(+ "%s delivers the metacharacter and Unicode matrix exactly",+ async (distro) => {+ const custom = {+ id: "custom:wsl-argv-printer",+ launchCmd: `/bin/sh -c ${neutralQuote('printf "%s" "$1"')} --`,+ promptInjectionMode: "argv",+ } as const;+ for (const prompt of PROMPTS) {+ const plan = await prepareAgentLaunch(+ start(custom.id, { prompt }),+ "posix",+ customContext(custom),+ );+ const result = spawnSync(+ "wsl.exe",+ ["-d", distro, "--", "/bin/sh"],+ // Feed the rendered line exactly as a terminal does. Passing it as `sh -c` argv through+ // wsl.exe would add Windows command-line parsing before the shell and test that transport+ // instead of the POSIX encoder.+ { encoding: "utf8", input: `${plan.command}\n` },+ );+ expect(result.status, result.stderr || result.stdout).toBe(0);+ expect(result.stdout).toBe(prompt);+ }+ },+ 30_000,+ );+ },+);++describe.runIf(!WINDOWS)("real POSIX shell argv behavior", () => {+ it.runIf(!!GIT_BASH)(+ "delivers the metacharacter and Unicode matrix exactly",+ async () => {+ const custom = customNodeConfig(process.execPath);+ for (const prompt of PROMPTS) {+ const plan = await prepareAgentLaunch(+ start(custom.id, { prompt }),+ "posix",+ customContext(custom),+ );+ const result = spawnSync(+ GIT_BASH as string,+ ["--noprofile", "--norc", "-c", plan.command],+ {+ encoding: "utf8",+ },+ );+ expect(result.status, result.stderr || result.stdout).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual([prompt]);+ }+ },+ );+});diff --git a/src/core/agent-launch.ts b/src/core/agent-launch.tsnew file mode 100644index 000000000..262616cf2--- /dev/null+++ b/src/core/agent-launch.ts@@ -0,0 +1,620 @@+import path from "node:path";+import type { AgentLaunchIntent, CustomAgent } from "../shared/types";+import {+ AGENT_CONFIG,+ agentLaunchProgram,+ canResume,+ hasPermissionMode,+ isPermissionMode,+ mintsSessionId,+ type AgentConfig,+ type AgentId,+ type BuiltinAgentId,+ type PromptInjectionMode,+} from "../shared/agents/config";+import { approvalFlags } from "../shared/agents/approval-mode";++/** The parser that owns a live local Windows-profile terminal. */+export type AgentLaunchDialect =+ "posix" | "pwsh" | "windows-powershell" | "cmd";++/**+ * How PowerShell must invoke the resolved agent entry point. A `.cmd`/`.bat` shim is deliberately+ * distinct: forwarding arbitrary Unicode/metacharacter-bearing argv through another cmd parser is+ * not lossless, so the planner refuses it instead of pretending native quoting applies.+ */+export type AgentLaunchExecutableKind =+ "native" | "powershell-script" | "cmd-script";++export interface AgentLaunchExecutableResolution {+ kind: AgentLaunchExecutableKind;+ /** Trusted currently-existing absolute path returned by the core resolver. */+ executable: string;+}++export type AgentLaunchExecutableKindResolver = (+ executable: string,+ dialect: Exclude<AgentLaunchDialect, "posix">,+) => Promise<AgentLaunchExecutableResolution | null>;++/** The one current custom-agent record selected from machine-local settings. */+export type TrustedCustomAgentLaunchConfig = Pick<+ CustomAgent,+ "id" | "launchCmd" | "promptInjectionMode"+>;++/**+ * Host-authoritative facts. None may be populated from a project file, canvas mutation, or relay+ * peer. In particular, the intent carries no executable and cannot select a different node owner.+ */+export interface AgentLaunchTrustedContext {+ expectedAgentId: AgentId;+ customAgent?: TrustedCustomAgentLaunchConfig;+ sharedIdentityAvailable: boolean;+ resolveExecutableKind?: AgentLaunchExecutableKindResolver;+ /** Trusted absolute Windows PowerShell executable used only as cmd's ASCII-safe wrapper. */+ windowsPowerShellPath?: string;+}++/** Core-private launch material. It must never cross the renderer/preload/relay boundary. */+export interface PreparedAgentLaunch {+ command: string;+ /** Literal follow-up data for an agent whose configured prompt mode is stdin-after-start. */+ stdinAfterStart?: string;+}++export type AgentLaunchPreparationErrorCode =+ "invalid-intent" | "agent-unavailable" | "unsupported-shell";++const SAFE_ERROR_MESSAGES: Record<AgentLaunchPreparationErrorCode, string> = {+ "invalid-intent": "The agent launch request is invalid.",+ "agent-unavailable": "The configured agent is unavailable on this machine.",+ "unsupported-shell":+ "This terminal shell cannot safely launch the configured agent.",+};++/** An error whose code and copy are safe to surface; it never embeds launch material. */+export class AgentLaunchPreparationError extends Error {+ readonly code: AgentLaunchPreparationErrorCode;++ constructor(code: AgentLaunchPreparationErrorCode) {+ super(SAFE_ERROR_MESSAGES[code]);+ this.name = "AgentLaunchPreparationError";+ this.code = code;+ }+}++interface LogicalAgentLaunch {+ executable: string;+ args: string[];+ stdinAfterStart?: string;+}++interface ResolvedAgentConfig {+ id: AgentId;+ launchCmd: string;+ promptInjectionMode: PromptInjectionMode;+ argvPromptSeparator?: string;+ builtin: boolean;+}++const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/;+const SAFE_NEW_SESSION_UUID_V4 =+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;+// PowerShell and POSIX parsers also treat Unicode line/paragraph separators as command boundaries+// in contexts where JavaScript's Cc category does not catch them.+const FORBIDDEN_INLINE_CHARACTER = /[\p{Cc}\u2028\u2029]/u;+const MAX_PROMPT_LENGTH = 128 * 1024;+const MAX_LAUNCH_COMMAND_LENGTH = 32 * 1024;+// `posix` is shared by WSL and Git Bash. The latter ultimately launches a Windows process, so use+// the smaller portable byte budget instead of Linux's larger MAX_ARG_STRLEN and fail closed when+// the environment-specific transport cannot be distinguished here.+const MAX_PORTABLE_POSIX_ARGUMENT_BYTES = 30_000;+const MAX_PORTABLE_POSIX_COMMAND_BYTES = 32_000;+// CreateProcessW caps one native command line at 32,767 UTF-16 code units; cmd.exe caps one+// interactive line at 8,191. Leave a small fixed margin for implementation-added framing/NUL.+const MAX_WINDOWS_COMMAND_LINE = 32_700;+const MAX_CMD_INTERACTIVE_LINE = 8_100;+const START_FIELDS = new Set([+ "kind",+ "action",+ "agentId",+ "prompt",+ "permissionMode",+ "newSessionId",+]);+const RESUME_FIELDS = new Set([+ "kind",+ "action",+ "agentId",+ "sessionId",+ "permissionMode",+]);++function fail(code: AgentLaunchPreparationErrorCode): never {+ throw new AgentLaunchPreparationError(code);+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function hasOnlyOwnFields(+ value: Record<string, unknown>,+ allowed: ReadonlySet<string>,+): boolean {+ return Object.keys(value).every((key) => allowed.has(key));+}++function safeText(value: unknown, maxLength: number): value is string {+ return (+ typeof value === "string" &&+ value.length <= maxLength &&+ !FORBIDDEN_INLINE_CHARACTER.test(value)+ );+}++function validateIntentRuntime(+ intent: AgentLaunchIntent,+ expectedAgentId: AgentId,+): void {+ if (!isRecord(intent)) fail("invalid-intent");+ if (intent.kind !== "agent") fail("invalid-intent");+ if (+ typeof intent.agentId !== "string" ||+ !intent.agentId ||+ intent.agentId !== expectedAgentId+ )+ fail("agent-unavailable");+ if (FORBIDDEN_INLINE_CHARACTER.test(intent.agentId))+ fail("agent-unavailable");+ if (+ intent.permissionMode !== undefined &&+ !isPermissionMode(intent.permissionMode)+ )+ fail("invalid-intent");++ if (intent.action === "start") {+ if (!hasOnlyOwnFields(intent, START_FIELDS)) fail("invalid-intent");+ if (+ intent.prompt !== undefined &&+ !safeText(intent.prompt, MAX_PROMPT_LENGTH)+ )+ fail("invalid-intent");+ if (+ intent.newSessionId !== undefined &&+ (typeof intent.newSessionId !== "string" ||+ !SAFE_NEW_SESSION_UUID_V4.test(intent.newSessionId))+ )+ fail("invalid-intent");+ return;+ }++ if (intent.action === "resume") {+ if (!hasOnlyOwnFields(intent, RESUME_FIELDS)) fail("invalid-intent");+ if (+ typeof intent.sessionId !== "string" ||+ !SAFE_SESSION_ID.test(intent.sessionId)+ )+ fail("invalid-intent");+ return;+ }++ fail("invalid-intent");+}++function isBuiltinAgentId(id: AgentId): id is BuiltinAgentId {+ return Object.hasOwn(AGENT_CONFIG, id);+}++function validPromptMode(value: unknown): value is PromptInjectionMode {+ return (+ value === "argv" || value === "flag-prompt" || value === "stdin-after-start"+ );+}++function resolveTrustedAgentConfig(+ intent: AgentLaunchIntent,+ context: AgentLaunchTrustedContext,+): ResolvedAgentConfig {+ if (isBuiltinAgentId(intent.agentId)) {+ const config: AgentConfig = AGENT_CONFIG[intent.agentId];+ return {+ id: intent.agentId,+ launchCmd: config.launchCmd,+ promptInjectionMode: config.promptInjectionMode,+ argvPromptSeparator: config.argvPromptSeparator,+ builtin: true,+ };+ }++ const custom = context.customAgent;+ if (+ !custom ||+ typeof custom.id !== "string" ||+ custom.id !== intent.agentId ||+ custom.id !== context.expectedAgentId ||+ !safeText(custom.launchCmd, MAX_LAUNCH_COMMAND_LENGTH) ||+ !custom.launchCmd.trim() ||+ !validPromptMode(custom.promptInjectionMode)+ )+ fail("agent-unavailable");++ return {+ id: intent.agentId,+ launchCmd: custom.launchCmd,+ promptInjectionMode: custom.promptInjectionMode,+ builtin: false,+ };+}++/**+ * A deliberately small shell-neutral argv grammar for the machine-local custom launch field.+ * Quotes group literal text; backslash escapes whitespace/quotes/backslash. Unquoted shell+ * operators are refused because silently turning a shell fragment into argv changes its meaning.+ */+function parseTrustedLaunchCommand(source: string): string[] {+ const tokens: string[] = [];+ let token = "";+ let tokenStarted = false;+ let quote: "'" | '"' | null = null;++ const push = (): void => {+ if (!tokenStarted) return;+ tokens.push(token);+ token = "";+ tokenStarted = false;+ };++ for (let i = 0; i < source.length; i++) {+ const ch = source[i];+ if (quote) {+ if (ch === quote) {+ quote = null;+ tokenStarted = true;+ continue;+ }+ if (ch === "\\") {+ const next = source[i + 1];+ if (next === quote || next === "\\") {+ token += next;+ tokenStarted = true;+ i++;+ continue;+ }+ }+ token += ch;+ tokenStarted = true;+ continue;+ }++ if (/\s/u.test(ch)) {+ push();+ continue;+ }+ if (ch === "'" || ch === '"') {+ quote = ch;+ tokenStarted = true;+ continue;+ }+ if (ch === "\\") {+ const next = source[i + 1];+ if (+ next &&+ (/\s/u.test(next) || next === "'" || next === '"' || next === "\\")+ ) {+ token += next;+ tokenStarted = true;+ i++;+ continue;+ }+ token += ch;+ tokenStarted = true;+ continue;+ }+ if (";&|<>()$`\r\n".includes(ch)) fail("agent-unavailable");+ token += ch;+ tokenStarted = true;+ }++ if (quote) fail("agent-unavailable");+ push();+ if (!tokens.length || !tokens[0] || tokens[0].startsWith("-"))+ fail("agent-unavailable");+ return tokens;+}++function logicalLaunch(+ intent: AgentLaunchIntent,+ config: ResolvedAgentConfig,+ context: AgentLaunchTrustedContext,+): LogicalAgentLaunch {+ const parsed = parseTrustedLaunchCommand(config.launchCmd);+ let executable = parsed[0];+ const baseArgs = parsed.slice(1);+ if (config.builtin)+ executable = agentLaunchProgram(+ config.id,+ executable,+ context.sharedIdentityAvailable,+ );++ if (intent.permissionMode !== undefined && !hasPermissionMode(config.id))+ fail("invalid-intent");+ const modeFlags = intent.permissionMode+ ? approvalFlags(config.id, intent.permissionMode)+ : [];++ if (intent.action === "resume") {+ if (!config.builtin || !canResume(config.id)) fail("agent-unavailable");+ const resumeArgs =+ config.id === "codex"+ ? ["resume", intent.sessionId]+ : config.id === "opencode"+ ? ["--session", intent.sessionId]+ : ["--resume", intent.sessionId];+ return { executable, args: [...baseArgs, ...resumeArgs, ...modeFlags] };+ }++ const sessionArgs: string[] = [];+ if (intent.newSessionId !== undefined) {+ if (!mintsSessionId(config.id)) fail("invalid-intent");+ sessionArgs.push("--session-id", intent.newSessionId);+ }++ const hasPrompt = Object.hasOwn(intent, "prompt");+ const prompt = hasPrompt ? (intent.prompt ?? "") : undefined;+ // Gemini's existing creation contract is a positional prompt even though its capability+ // metadata describes a possible stdin transport. Changing that would require a measured child+ // readiness handshake; the generic terminal prompt is not evidence that Gemini is ready.+ const promptInjectionMode =+ config.builtin && config.id === "gemini"+ ? "argv"+ : config.promptInjectionMode;+ if (promptInjectionMode === "stdin-after-start") {+ return {+ executable,+ args: [...baseArgs, ...modeFlags, ...sessionArgs],+ ...(hasPrompt ? { stdinAfterStart: prompt } : {}),+ };+ }++ if (promptInjectionMode === "flag-prompt") {+ return {+ executable,+ args: [+ ...baseArgs,+ ...(hasPrompt ? ["--prompt", prompt as string] : []),+ ...modeFlags,+ ...sessionArgs,+ ],+ };+ }++ if (hasPrompt && config.argvPromptSeparator) {+ return {+ executable,+ args: [+ ...baseArgs,+ ...modeFlags,+ ...sessionArgs,+ config.argvPromptSeparator,+ prompt as string,+ ],+ };+ }++ return {+ executable,+ args: [+ ...baseArgs,+ ...(hasPrompt ? [prompt as string] : []),+ ...modeFlags,+ ...sessionArgs,+ ],+ };+}++function posixQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`;+}++function powershellQuote(value: string): string {+ return `'${value.replace(/'/g, "''")}'`;+}++function explicitExecutableKind(+ executable: string,+): AgentLaunchExecutableKind | null {+ const lower = executable.toLowerCase();+ if (lower.endsWith(".exe") || lower.endsWith(".com")) return "native";+ if (lower.endsWith(".ps1")) return "powershell-script";+ if (lower.endsWith(".cmd") || lower.endsWith(".bat")) return "cmd-script";+ return null;+}++function validateResolvedExecutable(value: unknown): value is string {+ return (+ typeof value === "string" &&+ !!value &&+ !FORBIDDEN_INLINE_CHARACTER.test(value)+ );+}++async function resolveWindowsExecutable(+ executable: string,+ dialect: Exclude<AgentLaunchDialect, "posix">,+ resolver: AgentLaunchExecutableKindResolver | undefined,+): Promise<{ executable: string; kind: AgentLaunchExecutableKind }> {+ if (!resolver) fail("unsupported-shell");++ let resolution: AgentLaunchExecutableResolution | null;+ try {+ resolution = await resolver(executable, dialect);+ } catch {+ fail("agent-unavailable");+ }+ if (!resolution) fail("agent-unavailable");+ if (+ resolution.kind !== "native" &&+ resolution.kind !== "powershell-script" &&+ resolution.kind !== "cmd-script"+ )+ fail("agent-unavailable");+ const resolved = resolution.executable;+ if (+ !validateResolvedExecutable(resolved) ||+ !path.win32.isAbsolute(resolved) ||+ !/^[A-Za-z]:[\\/]/.test(resolved)+ )+ fail("agent-unavailable");+ // The resolver also proves current existence. Its kind must agree with the actual resolved+ // suffix so a forged/stale "native" answer cannot route a .cmd shim through native quoting.+ if (explicitExecutableKind(resolved) !== resolution.kind)+ fail("agent-unavailable");+ return { executable: resolved, kind: resolution.kind };+}++/** Microsoft CRT/CommandLineToArgvW quoting for one native-process argument. */+function windowsNativeArg(value: string): string {+ if (value && !/[\s"]/u.test(value)) return value;+ let quoted = '"';+ let backslashes = 0;+ for (const ch of value) {+ if (ch === "\\") {+ backslashes++;+ continue;+ }+ if (ch === '"') {+ quoted += "\\".repeat(backslashes * 2 + 1) + '"';+ backslashes = 0;+ continue;+ }+ quoted += "\\".repeat(backslashes) + ch;+ backslashes = 0;+ }+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;+}++function powershellInvocation(+ executable: string,+ kind: AgentLaunchExecutableKind,+ args: string[],+): string {+ // A batch shim introduces a second cmd parse. `%`, `!`, quotes and Unicode cannot all be carried+ // losslessly through it as arbitrary argv, so require the trusted resolver to choose a native or+ // PowerShell-script entry point (npm installations normally provide the sibling `.ps1` shim).+ if (kind === "cmd-script") fail("unsupported-shell");+ if (kind === "powershell-script")+ return [+ "&",+ powershellQuote(executable),+ ...args.map(powershellQuote),+ ].join(" ");++ // Windows PowerShell 5.1's native-command marshaller loses embedded quotes before a program's+ // CRT parser sees them. Give Start-Process one already-quoted command-line string instead; it+ // inherits the ConPTY handles with -NoNewWindow and waits so the interactive shell remains the+ // agent's parent for the whole TUI lifetime.+ const argumentLine = args.map(windowsNativeArg).join(" ");+ if (executable.length + argumentLine.length + 2 > MAX_WINDOWS_COMMAND_LINE)+ fail("invalid-intent");+ return [+ `$ntAgent = Start-Process -FilePath ${powershellQuote(executable)}`,+ ...(args.length ? [`-ArgumentList ${powershellQuote(argumentLine)}`] : []),+ "-NoNewWindow -Wait -PassThru",+ "; $global:LASTEXITCODE = $ntAgent.ExitCode",+ ].join(" ");+}++function trustedWindowsPowerShellPath(value: string | undefined): string {+ if (+ !value ||+ !path.win32.isAbsolute(value) ||+ !/^[A-Za-z]:[\\/]/.test(value) ||+ FORBIDDEN_INLINE_CHARACTER.test(value) ||+ /["&|<>^%!]/.test(value) ||+ !value.toLowerCase().endsWith(".exe")+ )+ fail("unsupported-shell");+ return value;+}++function encodedPowerShellCommand(script: string): string {+ return Buffer.from(script, "utf16le").toString("base64");+}++/**+ * Validate a semantic request, resolve only trusted host configuration, and encode it for the+ * concrete live profile dialect. The returned command is core-private launch material.+ */+export async function prepareAgentLaunch(+ intent: AgentLaunchIntent,+ dialect: AgentLaunchDialect,+ context: AgentLaunchTrustedContext,+): Promise<PreparedAgentLaunch> {+ validateIntentRuntime(intent, context.expectedAgentId);+ const config = resolveTrustedAgentConfig(intent, context);+ // A custom process has no trusted readiness signal. Writing its prompt after a timer or generic+ // shell-output probe can race the child, leak text into the parent shell, or lose it on exit.+ if (!config.builtin && config.promptInjectionMode === "stdin-after-start")+ fail("unsupported-shell");+ const logical = logicalLaunch(intent, config, context);++ if (dialect === "posix") {+ const tokens = [logical.executable, ...logical.args];+ if (+ tokens.some(+ (token) =>+ Buffer.byteLength(token, "utf8") > MAX_PORTABLE_POSIX_ARGUMENT_BYTES,+ )+ )+ fail("invalid-intent");+ const command = tokens.map(posixQuote).join(" ");+ if (Buffer.byteLength(command, "utf8") > MAX_PORTABLE_POSIX_COMMAND_BYTES)+ fail("invalid-intent");+ return {+ command,+ ...(logical.stdinAfterStart !== undefined+ ? { stdinAfterStart: logical.stdinAfterStart }+ : {}),+ };+ }++ if (+ dialect !== "pwsh" &&+ dialect !== "windows-powershell" &&+ dialect !== "cmd"+ )+ fail("unsupported-shell");+ const resolved = await resolveWindowsExecutable(+ logical.executable,+ dialect,+ context.resolveExecutableKind,+ );+ const script = powershellInvocation(+ resolved.executable,+ resolved.kind,+ logical.args,+ );+ if (script.length > MAX_WINDOWS_COMMAND_LINE) fail("invalid-intent");++ if (dialect === "cmd") {+ const wrapper = trustedWindowsPowerShellPath(context.windowsPowerShellPath);+ const command = `"${wrapper}" -NoLogo -NoProfile -EncodedCommand ${encodedPowerShellCommand(script)}`;+ if (command.length > MAX_CMD_INTERACTIVE_LINE) fail("invalid-intent");+ return {+ command,+ ...(logical.stdinAfterStart !== undefined+ ? { stdinAfterStart: logical.stdinAfterStart }+ : {}),+ };+ }++ return {+ command: script,+ ...(logical.stdinAfterStart !== undefined+ ? { stdinAfterStart: logical.stdinAfterStart }+ : {}),+ };+}diff --git a/src/core/fs-atomic.guard.test.ts b/src/core/fs-atomic.guard.test.tsindex dbf77d6d0..ae678ee28 100644--- a/src/core/fs-atomic.guard.test.ts+++ b/src/core/fs-atomic.guard.test.ts@@ -20,7 +20,7 @@ import { describe, expect, it } from 'vitest'import { readFileSync, readdirSync, statSync } from 'fs'import { join, relative } from 'path'-const ROOTS = ['core', 'main', 'server'].map((d) => join(__dirname, '..', d))+const ROOTS = ['core', 'main', 'server', 'session-host'].map((d) => join(__dirname, '..', d))const SOURCE_ROOT = join(__dirname, '..')/** Guard comparisons use one separator regardless of the host running Vitest. */@@ -51,7 +51,11 @@ function sources(dir: string, out: string[] = []): string[] {* did not get round to — an exemption that means "later" belongs in an issue, not here.*/const RENAME_ALLOWED = new Map<string, string>([- ['core/fs-atomic.ts', 'the async/core helper; this is its one real rename']+ ['core/fs-atomic.ts', 'the async/core helper; this is its one real rename'],+ [+ 'session-host/state-file.ts',+ 'the standalone host cannot import core; this helper owns its bounded synchronous rename retry'+ ]])function isRenameAllowed(relativeFile: string): boolean {@@ -203,8 +207,12 @@ describe('every store publishes through renameAtomic', () => {expect(normalizedSourcePath(String.raw`core\fs-atomic.ts`)).toBe('core/fs-atomic.ts')expect(isRenameAllowed('core/fs-atomic.ts')).toBe(true)expect(isRenameAllowed(String.raw`core\fs-atomic.ts`)).toBe(true)+ expect(isRenameAllowed('session-host/state-file.ts')).toBe(true)+ expect(isRenameAllowed(String.raw`session-host\state-file.ts`)).toBe(true)expect(isRenameAllowed('nested/core/fs-atomic.ts')).toBe(false)+ expect(isRenameAllowed('nested/session-host/state-file.ts')).toBe(false)expect(isRenameAllowed('core/fs-atomic.ts.bak')).toBe(false)+ expect(isRenameAllowed('session-host/state-file.ts.bak')).toBe(false)const scanned = new Set(files.map(sourceRelativePath))for (const allowed of RENAME_ALLOWED.keys()) expect(scanned.has(allowed)).toBe(true)})@@ -471,7 +479,8 @@ function cryptoRandomUuidBindings(source: string): CryptoRandomUuidBindings {* containers can both be PID 1 with a fresh module counter, worker isolates share a PID with* separate counters, and an OS can reuse a PID while crash litter remains. */function isUniqueTempName(name: string, relativeFile: string, source: string): boolean {- const helperWithBehavioralUuidChut = relativeFile === 'core/fs-atomic.ts'+ const helperWithBehavioralUuidChut =+ relativeFile === 'core/fs-atomic.ts' || relativeFile === 'session-host/state-file.ts'const bindings = cryptoRandomUuidBindings(source)const interpolationBodies = [...name.matchAll(/\$\{([^}]*)\}/g)].map((match) =>match[1]diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 63b18150f..8ccab3295 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -17,6 +17,14 @@ const spawned: FakePty[] = []/** When set, the NEXT pty.spawn throws (simulates posix_spawn failing). */let failNextSpawn = false+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: (_file: string, _args: string[], _opts: unknown) => {if (failNextSpawn) {diff --git a/src/core/pty-idle-reap.test.ts b/src/core/pty-idle-reap.test.tsindex 8d6505775..002520b4b 100644--- a/src/core/pty-idle-reap.test.ts+++ b/src/core/pty-idle-reap.test.ts@@ -28,6 +28,14 @@ interface FakePty {const spawned: FakePty[] = []const spawnArgs: Array<{ file: string; args: string[] }> = []+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: (file: string, args: string[]) => {const p: FakePty = { killed: false, paused: false }diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 2890a6aff..e3074043a 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -13,6 +13,7 @@ import {type PaneCursor,type PtyCreateOptions,type PtyCreateResult,+ type PtyRecycleTarget,type Settings,type TmuxStatus} from '../shared/types'@@ -65,6 +66,7 @@ import {} from './tmux-naming'import { encodeSendKeysHex } from './tmux-control'import { releasePty, type ReleasablePty } from './pty-release'+import { terminateWindowsProcessTree } from '../session-host/windows-process-tree'import { effectiveSize, type PtySize } from './pty-size'import { machOArch, archMismatch } from './macho-arch'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'@@ -96,6 +98,23 @@ import {} from './remote-ssh/session-env'import { foregroundProcessGroup, parsePaneProcess } from './pane-process'import { isShellCommand } from '../shared/agents/pane'+// Third persistence backend, selected when no local tmux was found (primarily Windows, where+// tmux does not exist at all) — see docs/windows-session-host.md. Deliberately a thin, separate+// module rather than inline here: this is the one narrow seam this file needed to grow for a+// whole standalone process + protocol living under src/session-host/.+import {+ attachExistingSessionHostPty,+ createSessionHostPty,+ sessionHostCapture,+ sessionHostHasSession,+ sessionHostKillSession,+ sessionHostListSessions,+ sessionHostPaneCommand,+ sessionHostSendKeys,+ sessionHostSupported,+ SessionHostProtocolCompatibilityError+} from './session-host-backend'+import type { SessionHostPty } from './session-host-pty'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which// kills the tmux server) can still replay recent output on cold restart. A final snapshot also@@ -147,6 +166,15 @@ const runAsync = ((file: string, args: readonly string[], opts?: object) =>...(opts ?? {})} as never)) as unknown as typeof execFileAsync+/** Narrow child-process seam for strict tmux probes/confirmed teardown. Production delegates to+ * the same bounded runner above; focused tests inject a stateful fake so hidden dual-backend+ * generations can be proven ended without source-scanning or platform-specific helper scripts. */+type ConfirmedProcessRun = (+ file: string,+ args: readonly string[],+ opts?: object+) => Promise<unknown>+/*** `runAsync`, with a payload written to the child's STDIN.*@@ -259,6 +287,16 @@ bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X* through the now-resolved tmux.*/function findTmux(resourcesPath?: string): string | null {+ // Windows has none of `tmuxCandidatePaths`' targets (Homebrew, MacPorts, Nix, the distro+ // `/usr/bin` family — all POSIX filesystem layouts) and no bundled tmux (macOS-only, see+ // `bundledTmuxPath`'s doc comment; `scripts/build-tmux.mjs` never runs for a Windows package).+ // Walking either list would just be `existsSync` calls against paths that can never resolve on+ // this platform — skip straight to the PATH probe, the one route that can find a real tmux a+ // Windows user installed themselves (WSL's own tmux is a different filesystem entirely and is+ // never on the Windows PATH; MSYS2/Cygwin tmux, if the user put it there, is).+ if (os.platform() === 'win32') {+ return findInPathString('tmux', shellPathNow() ?? process.env.PATH)+ }// BOTH lookups inside the guard: `os.homedir()` throws the same SystemError as `userInfo()` when// there is no passwd entry and no $HOME (some containers), and a thrown probe here would take// out tmux discovery entirely — degrading a machine that HAS tmux to the plain-shell fallback,@@ -335,6 +373,60 @@ function findSsh(): string | null {// every module that used to spawn its own sync login shell. Prewarmed from init(); create()// awaits it, so terminals still always get the real PATH.+/** Windows PowerShell always ships at this exact path (part of the OS since Vista) — the one+ * fallback that is always available, even when the PATH probe misses it. */+const WIN_POWERSHELL_FALLBACK = (): string =>+ `${process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`++/** PowerShell 7+'s default per-machine install location — a fallback for the case where the+ * installer's PATH update hasn't reached this (GUI-launched) process's inherited environment. */+const WIN_PWSH_FALLBACK = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe'++/**+ * The Windows session program when nothing else picked one (no explicit program, no+ * `settings.defaultShell`): prefer PowerShell 7+ (`pwsh.exe` — the shell most developers actually+ * want once they've installed it), then the Windows PowerShell every machine ships+ * (`powershell.exe`), then whatever the environment itself calls its command processor+ * (`COMSPEC` — normally `cmd.exe`, but respecting it rather than hardcoding keeps this correct on+ * an environment that deliberately points it elsewhere), and only then a bare `cmd.exe` — the one+ * binary guaranteed to exist on every Windows install, so this function can never return nothing.+ */+function resolveWindowsShell(): string {+ const pathStr = shellPathNow() ?? process.env.PATH+ const pwsh = findInPathString('pwsh', pathStr) ?? (fs.existsSync(WIN_PWSH_FALLBACK) ? WIN_PWSH_FALLBACK : null)+ if (pwsh) return pwsh+ const winPsFallback = WIN_POWERSHELL_FALLBACK()+ const powershell = findInPathString('powershell', pathStr) ?? (fs.existsSync(winPsFallback) ? winPsFallback : null)+ if (powershell) return powershell+ return process.env.COMSPEC || 'cmd.exe'+}++/**+ * One legacy local-shell resolver for BOTH direct node-pty and the persistent session-host+ * backend. Windows desktop profile launches bypass this helper with a trusted resolved plan, but+ * Server Edition and older callers without the optional profile service keep the same fallback.+ * Keeping the fallback here prevents the two paths from drifting: the session host previously+ * hardcoded `bash` even on Windows, while the direct path already knew how to find PowerShell or+ * COMSPEC. Injectable platform leaves make that compatibility behavior testable on every CI host.+ */+export function resolveLocalSessionShell(+ program: string | undefined,+ defaultShell: string | undefined,+ deps: {+ platform?: NodeJS.Platform+ windowsShell?: () => string+ posixShell?: string+ } = {}+): string {+ if (program) return program+ if (defaultShell) return defaultShell+ if ((deps.platform ?? os.platform()) === 'win32') {+ return (deps.windowsShell ?? resolveWindowsShell)()+ }+ const posixShell = deps.posixShell !== undefined ? deps.posixShell : process.env.SHELL+ return posixShell || 'bash'+}+/*** A UTF-8 locale for spawned terminals, or null to leave the inherited locale untouched.*@@ -518,6 +610,16 @@ interface Session {/** True when this node had an `accountId` but its config dir was gone at spawn, so we fell back* to the system account. `create()` surfaces it to the renderer (warning chip). */accountFallback?: boolean+ /**+ * This session is backed by the session-host process (docs/windows-session-host.md), not a+ * local tmux — selected only when no local tmux was found (primarily Windows). `session.proc`+ * is then a `SessionHostPty`, not a real node-pty `IPty` (see `createSessionHostPty`). Every+ * call site that reaches past `session.proc` to run a tmux CLI command directly (`sendText`,+ * `paneCommand`, `captureSession`, `captureSnapshot`, `snapshotScrollback`,+ * `captureForResync`, the final kill in `destroySession`) branches on this the same way it+ * already branches on `sshRemote`.+ */+ sessionHost?: boolean}/** Sinks for a detached session whose output is served somewhere other than the renderer@@ -556,6 +658,13 @@ const MAX_BUF_BYTES = 256 * 1024*/const RECYCLE_NOTIFY_TIMEOUT_MS = 10_000+/** A non-Windows plain PTY has no taskkill-style process-absence proof, so confirmed recycle waits+ * for this exact generation's exit event. Bound that wait: a broken native binding must reject the+ * restart rather than leave its awaited IPC (and the renderer's destructive-action UI) hanging+ * forever. Windows uses `terminateWindowsProcessTree` as the stronger absence proof when a valid+ * PID is available. */+export const CONFIRMED_PLAIN_EXIT_TIMEOUT_MS = 5_000+/** Why a session is being ended — the ONE thing `destroySession` could not tell apart. Both kill* the tmux session; they differ entirely in what the OTHER viewers are told.* - `delete`: the × / node deletion. The node leaves the canvas: co-viewers get `pty:closed`@@ -638,13 +747,60 @@ export class PtyManager {* ACROSS the awaits inside a spawn (see create()), not just after them. Entries are removed* as soon as the spawn settles, success or failure. */private inflight = new Map<string, Promise<PtyCreateResult>>()+ /** sessionId → exact generation whose persistent backend is being ended by the awaited profile+ * switch path. A backend can emit exit before its kill response arrives; callbacks for this+ * generation are deferred so no local state changes before acknowledgement. */+ private confirmedBackendEnds = new Map<+ string,+ { session: Session; exitCode?: number; resolveExit?: () => void }+ >()+ /** One awaited profile-switch teardown per node. Without this guard two invocations can both+ * install an exit barrier for the same generation and the second can report success after the+ * first already removed the backend. */+ private confirmedRecycles = new Map<string, Promise<void>>()+ /** One in-flight end per node. Creates wait behind this barrier so a session-host exit that+ * arrives before its kill response cannot be mistaken for permission to respawn the node. */+ private ending = new Map<+ string,+ {+ intent: EndIntent+ everySocket: boolean+ backendAlreadyEnded: boolean+ replacementTarget: PtyRecycleTarget | undefined+ promise: Promise<void>+ }+ >()+ /** A session-host kill request failed after dispatch, so absence is not proven. Keep creates+ * fenced until an idempotent retry acknowledges the end; an exit event alone is not that proof. */+ private unknownEnds = new Set<string>()+ /** Shell-owned cleanup runs after end processing and, for session host, its kill acknowledgement. */+ private sessionEndedListeners = new Set<(persistKey: string) => void>()/** persistKey (node id) → the co-viewers of a session that was RECYCLED (moved into a worktree),* waiting to be told to restart onto the replacement session. Held — not sent — until that* session is registered (`spawnSession`), so a co-viewer's restart can never win the race and* spawn the node in its own stale cwd. See `recycleSession`. */private pendingRecycle = new Map<string,- { sessionId: string; clients: Set<ClientId>; timer: ReturnType<typeof setTimeout> }+ {+ sessionId: string+ clients: Set<ClientId>+ /** The exact view allowed to cold-create the replacement. A Kanban modal shares its+ * renderer's ClientId, but it is still a co-viewer: letting it win would return `fresh:true`+ * to a surface that deliberately performs no cold agent relaunch, while the primary canvas+ * view subsequently joins `fresh:false`. */+ owner: SubKey | null+ /** Trusted target preflighted by confirmed recycle. The primary view is still parked if it+ * races back with stale React props; only a create carrying this exact profile/cwd may spend+ * the replacement reservation and establish the new generation. */+ target?: PtyRecycleTarget+ waiters: Array<{+ clientId: ClientId+ options: PtyCreateOptions+ resolve: (result: PtyCreateResult) => void+ reject: (error: unknown) => void+ }>+ timer: ReturnType<typeof setTimeout>+ }>()/*** persistKey (node id) → the client that DELETED it. The respawn guard for clients the@@ -744,9 +900,20 @@ export class PtyManager {/** The child-process seam for shadow clients. Undefined in production, where `ControlModeClient`* uses `child_process` (see tmux-control-client.ts); tests inject a fake spawner. */private readonly controlSpawn: ControlSpawn | undefined+ private readonly confirmedProcessRun: ConfirmedProcessRun+ /** Injectable only so Windows-only routing stays behavior-testable on every CI host. */+ private readonly runtimePlatform: NodeJS.Platform- constructor(deps: { controlSpawn?: ControlSpawn } = {}) {+ constructor(+ deps: {+ controlSpawn?: ControlSpawn+ confirmedProcessRun?: ConfirmedProcessRun+ runtimePlatform?: NodeJS.Platform+ } = {}+ ) {this.controlSpawn = deps.controlSpawn+ this.confirmedProcessRun = deps.confirmedProcessRun ?? runAsync+ this.runtimePlatform = deps.runtimePlatform ?? os.platform()}private ensureSnapshotTimer(): void {@@ -761,7 +928,7 @@ export class PtyManager {anyPersisted = trueif (!session.outputSinceSnapshot) continue // idle since the last capture — skip the spawnsession.outputSinceSnapshot = false- void this.snapshotScrollback(session.persistKey, session.sshRemote).then((ok) => {+ void this.snapshotScrollback(session.persistKey, session.sshRemote, !!session.sessionHost).then((ok) => {// Transient capture failure (ssh blip, tmux busy): put the dirty bit back so the next// tick retries — otherwise a quiet session would never be snapshotted again.if (!ok) session.outputSinceSnapshot = true@@ -828,7 +995,7 @@ export class PtyManager {// a reboot. The tmux session itself keeps running, so this only races a same-instant capture.// Skipped when nothing arrived since the last periodic capture (pane content is unchanged).if (session.persistKey && session.outputSinceSnapshot)- void this.snapshotScrollback(session.persistKey, session.sshRemote)+ void this.snapshotScrollback(session.persistKey, session.sshRemote, !!session.sessionHost)// Remember what a later shadow would have no other way to learn — the grid the painter last// enforced (so the pane is not left to reflow), and whether this node's tmux was REMOTE (so it// is never shadowed against our local socket). The `Session` holding both goes with `forget`@@ -1398,16 +1565,47 @@ export class PtyManager {// Optional TRAILING `everySocket`: only the session-memory panel's SPECULATIVE kill sets it,// and only for a row it holds no session for (see `localKillSockets`). `=== true` because the// value arrives verbatim off the wire; absent ⇒ the narrow, historical single-socket kill.- platform().onWithSender(+ platform().handleWithSender(IPC.ptyDestroy,(senderId: number, persistKey: string, everySocket?: unknown) =>this.endFromClient(senderId, IPC.ptyDestroy, persistKey, 'delete', everySocket === true))+ // Version skew: older desktop/mobile/relay clients still cast this channel. Keep that path+ // functional, but contain its Promise — a failed host kill must neither tear down local state+ // nor become an unhandled rejection in the shell that cannot receive an acknowledgement.+ platform().onWithSender(+ IPC.ptyDestroy,+ (senderId: number, persistKey: string, everySocket?: unknown) => {+ void this.endFromClient(+ senderId,+ IPC.ptyDestroy,+ persistKey,+ 'delete',+ everySocket === true,+ false+ ).catch((error) =>+ console.warn(+ `[pty] legacy destroy for ${persistKey} was not confirmed`,+ error instanceof Error ? error.message : String(error)+ )+ )+ }+ )// Sender-aware for the opposite reason: the client that RECYCLED the node drives its own// respawn, so it is the one client that must NOT be sent the restart notice.- platform().onWithSender(IPC.ptyRecycle, (senderId: number, persistKey: string) =>+ platform().handleWithSender(IPC.ptyRecycle, (senderId: number, persistKey: string) =>this.endFromClient(senderId, IPC.ptyRecycle, persistKey, 'recycle'))+ // Same compatibility bridge as destroy above. New clients await the handler; old casts keep+ // working, with rejection contained because their protocol has nowhere to return it.+ platform().onWithSender(IPC.ptyRecycle, (senderId: number, persistKey: string) => {+ void this.endFromClient(senderId, IPC.ptyRecycle, persistKey, 'recycle', false, false).catch((error) =>+ console.warn(+ `[pty] legacy recycle for ${persistKey} was not confirmed`,+ error instanceof Error ? error.message : String(error)+ )+ )+ })platform().handle(IPC.ptyReadScrollback, (persistKey: string) =>readScrollback(persistKey))@@ -1495,16 +1693,26 @@ export class PtyManager {channel: string,persistKey: string,intent: EndIntent,- everySocket = false+ everySocket = false,+ acknowledged = true): Promise<void> {if (typeof persistKey !== 'string' || !persistKey || persistKey.length > REF_MAX_LEN)- return Promise.resolve()- if (!this.allowEnd(clientId, channel)) return Promise.resolve()+ return this.refuseClientEnd(channel, acknowledged, 'invalid node id')+ if (!this.allowEnd(clientId, channel))+ return this.refuseClientEnd(channel, acknowledged, 'rate limit exceeded; retry later')return this.endSession(clientId, persistKey, intent, everySocket)}+ /** New end requests must reject on refusal or their renderer will treat a no-op as success.+ * Legacy casts have no response carrier, so they keep their historical silent drop. */+ private refuseClientEnd(channel: string, acknowledged: boolean, reason: string): Promise<void> {+ if (!acknowledged) return Promise.resolve()+ const operation = channel === IPC.ptyRecycle ? 'recycle' : 'destroy'+ return Promise.reject(new Error(`pty ${operation} refused: ${reason}`))+ }+/** Take one token from this client's bucket for a session-ending channel (see PTY_END_BUDGET).- * Excess casts are dropped silently — never an error, never a disconnect. */+ * A request rejects on exhaustion; a legacy cast is dropped silently. */private allowEnd(clientId: ClientId, channel: string): boolean {const key = `${clientId}:${channel}`const now = Date.now()@@ -1570,11 +1778,44 @@ export class PtyManager {`dot, dash, underscore; max ${NODE_ID_MAX}). A project file with an id like this cannot be ` +`trusted — it is how a shared or cloned repo would smuggle a command onto a remote host.`)- // Co-attach: a live session for this node id already exists in THIS process (another client,- // or this client's own second view). Subscribe to it instead of spawning a second tmux client- // — `-D` would otherwise kick the first viewer off.- const joined = this.join(clientId, options, key)- if (joined) return joined+ // A generic end and an awaited profile recycle are separate transactions, but both reserve this+ // node name while their backend outcome is pending. Wait before consulting either the live index+ // or a replacement reservation so an early host exit cannot authorize a competing generation.+ const ending = this.ending.get(key)+ if (ending) {+ await ending.promise.catch(() => undefined)+ return this.create(clientId, options)+ }+ const confirmedRecycle = this.confirmedRecycles.get(key)+ if (confirmedRecycle) {+ await confirmedRecycle.catch(() => undefined)+ return this.create(clientId, options)+ }+ if (this.unknownEnds.has(key))+ throw new Error('session end outcome unknown; retry the close before reopening this node')++ // A recycle reserves the replacement generation for the client that chose its new profile/cwd.+ // A co-viewer's create still carries stale machine-local options; let it wait for the owner's+ // exact replacement and then join, never race to become the new backend creator itself.+ const pendingRecycle = this.pendingRecycle.get(key)+ const requestingView = subKey(clientId, options.viewerId ?? PRIMARY_VIEWER)+ // Profile-switch targets arrive with the windows-terminal-profiles phase; until then no+ // pendingRecycle entry carries one, so an absent target always matches.+ const matchesRecycleTarget = !pendingRecycle?.target+ if (+ pendingRecycle &&+ (pendingRecycle.owner !== requestingView || !matchesRecycleTarget)+ ) {+ return new Promise<PtyCreateResult>((resolve, reject) => {+ // Recheck after allocating the promise: `fireRecycled` is synchronous, but keeping the+ // exact entry check makes a future awaited boundary here unable to strand this waiter.+ if (this.pendingRecycle.get(key) !== pendingRecycle) {+ void this.create(clientId, options).then(resolve, reject)+ return+ }+ pendingRecycle.waiters.push({ clientId, options, resolve, reject })+ })+ }// Same-tick race: spawnNew() awaits a `tmux has-session` SUBPROCESS (tens of ms, not a// microtask) before spawnSession registers the session in `byPersistKey`, so two clients// opening the same node in that window would BOTH miss the index and both spawn — and the@@ -1582,6 +1823,9 @@ export class PtyManager {// is published as an in-flight promise from the TOP of create(): a racing create awaits it// and then takes the subscribe branch. (No locking primitive: the promise IS the barrier —// the single-user path never sees an in-flight entry and behaves exactly as before.)+ // Check the barrier BEFORE the live-session index. A session-host shim is registered while+ // its asynchronous attach is still pending; treating that provisional entry as joinable lets+ // a racing client receive a live-looking id even if `ready` rejects a moment later.const inflight = this.inflight.get(key)if (inflight) {await inflight.catch(() => undefined) // the other spawn failed → fall through and try ourselves@@ -1594,6 +1838,12 @@ export class PtyManager {// on a *new* in-flight entry is exactly the same wait as the one we just did.if (this.inflight.get(key)) return this.create(clientId, options)}+ // Co-attach: a live session for this node id already exists in THIS process (another client,+ // or this client's own second view). Subscribe to it instead of spawning a second tmux client+ // — `-D` would otherwise kick the first viewer off. This runs after the in-flight barrier, so+ // every session visible here has completed its asynchronous session-host attach.+ const joined = this.join(clientId, options, key)+ if (joined) return joined// Another client DELETED this node (and there is no live session for it — `join` above already// covers a resurrection by its owner). Refuse rather than spawn: see `tombstones`. Checked// AFTER the in-flight barrier so a create racing the owner's own respawn joins it instead.@@ -1606,7 +1856,14 @@ export class PtyManager {const clear = (): void => {if (this.inflight.get(key) === spawn) this.inflight.delete(key)}- spawn.then(clear, clear)+ spawn.then(clear, (error) => {+ clear()+ // The reserved owner failed to establish the replacement (resolver failure, spawn throw,+ // rejected attach, or exit-before-ready). Release co-viewers immediately with ready:false;+ // the timeout exists only for an owner that never attempts the create at all.+ if (this.pendingRecycle.get(key)?.owner === requestingView) this.fireRecycled(key, false)+ return error+ })return spawn}@@ -1717,19 +1974,30 @@ export class PtyManager {// — i.e. first open, or after a machine reboot killed the tmux server. Plain (non-tmux)// sessions are always fresh: they have no cross-restart continuity. The renderer uses this// to decide whether to replay the persisted scrollback and re-launch a resumable agent.- const tmuxBacked =- !!this.tmuxPath && this.getSettings().tmuxEnabled && !!options.persistKey+ // The Windows-profile warm-backend probe (attach-only reattach of a proven session-host or+ // tmux generation, decided ahead of trusted profile resolution) lands with the+ // windows-terminal-profiles phase; until then nothing assigns this and every create takes the+ // ordinary attach-or-create path below.+ let warmWindowsBackend: 'session-host' | 'tmux' | undefined+ const tmuxBacked = !!this.tmuxPath && this.getSettings().tmuxEnabled && !!options.persistKey// For an SSH-project node, "fresh" is decided by the REMOTE tmux server (over the project's// ControlMaster), not the local one. The remote `has-session` is a full network round-trip,// so it MUST be async (`runAsync`) — a synchronous probe here would freeze every window/IPC// for its duration. Falls through to the local tmux/plain logic otherwise (also async: a// bulk project load fires one create() per node, and even cheap probes add up serialized).- const fresh = options.sshRemote+ //+ // `true` here for a node that ends up SESSION-HOST-backed is only a PLACEHOLDER: unlike tmux+ // (a cheap name-only `has-session` probe, decided before spawning anything) the session-host+ // backend's attach-or-create IS the probe — see the `spawned?.sessionHost` branch below, which+ // overwrites both `fresh` and `screen` from that same round trip once `spawnSession` returns.+ let fresh = options.sshRemote? !(await this.remoteSessionExists(options.sshRemote,sessionName(options.persistKey as string)))- : tmuxBacked+ : warmWindowsBackend+ ? false+ : tmuxBacked? !(await this.tmuxSessionExists(options.persistKey as string)): true// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)@@ -1741,7 +2009,7 @@ export class PtyManager {if (hasSharedIdentity((options.agentId ?? 'claude') as AgentId) && !options.sshRemote) {installCodexLauncher()}- const sessionId = this.spawnSession(options, clientId, undefined)+ const sessionId = this.spawnSession(options, clientId, undefined, warmWindowsBackend)const spawned = this.sessions.get(sessionId)// PANE OWNERSHIP (agent messaging, PR #237 fix round 2): record the OWNING project of a pane// this process just GENUINELY spawned. Gated on `fresh` — an attach/co-attach to a session@@ -1750,6 +2018,53 @@ export class PtyManager {// machine-local project id, never the git-shared file id. See `agents/pane-ownership.ts`.if (shouldRecordOwnership(fresh, options.persistKey, options.ownerProjectId))recordFreshSpawnOwner(options.persistKey as string, options.ownerProjectId)+ if (warmWindowsBackend === 'tmux') {+ // The first strict probe deliberately preceded profile resolution. Recheck after launching+ // attach-only: if the named session disappeared in that window, never return the transient+ // tmux client as a usable generation. `attach-session` itself cannot cold-create.+ const stillExists = await this.confirmedTmuxSessionExists(options.persistKey as string)+ await new Promise<void>((resolve) => setImmediate(resolve))+ if (!stillExists || !spawned || this.sessions.get(sessionId) !== spawned) {+ if (spawned && this.sessions.get(sessionId) === spawned)+ this.discardFailedSpawn(sessionId, spawned)+ throw new Error('The existing terminal session disappeared before it could be reattached.')+ }+ }+ // The session-host backend is NOT a painter (see docs/windows-session-host.md, "The seeding+ // trap"): a warm attach there gets no free redraw the way a real tmux client provides, so+ // this create must carry the screen to seed itself — exactly the same field a same-process+ // co-attach JOIN already populates via `join()` below. `SessionHostPty.ready` is the SAME+ // attach-or-create round trip `spawnSession` just kicked off; awaiting it here costs nothing+ // extra (the socket write already happened) and is the only way to learn its real `fresh`.+ let screen: string | undefined+ if (spawned?.sessionHost) {+ try {+ const info = await (spawned.proc as unknown as SessionHostPty).ready+ // `ready` and the pty's natural exit are independent host messages. If exit won the race,+ // its handler already retired this exact generation; returning the captured Session object+ // here would hand the renderer a plausible persistent id that no longer accepts writes.+ if (this.sessions.get(sessionId) !== spawned) {+ throw new Error('The terminal session exited before it became ready.')+ }+ fresh = info.fresh+ screen = info.screen+ // Session-host registration is provisional until the exact ready barrier above succeeds.+ // Only now is an owner's resurrection real enough to remove a prior deletion tombstone.+ if (spawned.indexKey) this.tombstones.delete(spawned.indexKey)+ // A recycle notice must describe a usable replacement, not merely a provisional local+ // Session record. Session-host registration precedes this async barrier, so publish now.+ if (spawned.indexKey && this.pendingRecycle.has(spawned.indexKey))+ this.fireRecycled(spawned.indexKey, true)+ } catch (error) {+ // The shim is registered synchronously so output callbacks have somewhere to land, but a+ // rejected attach means no usable pty ever existed. Retire every local claim and detach+ // the shim before propagating the real failure; returning its id creates a terminal that+ // looks alive while every write disappears.+ if (this.sessions.get(sessionId) === spawned) this.discardFailedSpawn(sessionId, spawned)+ if (error instanceof SessionHostProtocolCompatibilityError) throw error+ throw error+ }+ }// Surface a missing-account-dir fallback so the renderer can flag the node's account chip.const accountFallback = spawned?.accountFallback// The session's `persistKey` is set iff the spawn actually landed on a tmux, local or remote@@ -1757,8 +2072,14 @@ export class PtyManager {// which is what the renderer's cache-dispose levers must not assume. See PtyCreateResult.const persistent = !!spawned?.persistKeyreturn accountFallback- ? { sessionId, fresh, accountFallback, persistent }- : { sessionId, fresh, persistent }+ ? {+ sessionId,+ fresh,+ accountFallback,+ persistent,+ ...(screen ? { screen } : {})+ }+ : { sessionId, fresh, persistent, ...(screen ? { screen } : {}) }}/** Does the node's remote tmux session exist (over the project's ControlMaster)? Async so the@@ -1789,6 +2110,12 @@ export class PtyManager {return undefined}+ /** The exact live generation for a node id, including a non-persistent indexed plain shell. */+ private liveSessionForPersistKey(persistKey: string): Session | undefined {+ const indexedId = this.byPersistKey.get(persistKey)+ return (indexedId ? this.sessions.get(indexedId) : undefined) ?? this.sessionByPersistKey(persistKey)+ }+/*** The live SSH-remote handle for a node id, if its session is running on a remote host.* Used by the remote context/subagent tails to read the node's transcript over the same@@ -1814,7 +2141,16 @@ export class PtyManager {* the caller treats it as a warm join and types nothing into it.*/async sessionExists(persistKey: string): Promise<boolean> {- return this.tmuxSessionExists(persistKey)+ if (this.liveSessionForPersistKey(persistKey)) return true+ const probes: Promise<boolean>[] = []+ if (this.tmuxPath) probes.push(this.tmuxSessionExists(persistKey))+ if (this.getSettings().tmuxEnabled && sessionHostSupported()) {+ // A failed host read is not evidence of absence. This mirrors tmuxSessionExists' fail-safe+ // direction and prevents a reconnect blip from being mistaken for a cold generation.+ probes.push(sessionHostHasSession(sessionName(persistKey)).catch(() => true))+ }+ if (probes.length === 0) return false+ return (await Promise.all(probes)).some(Boolean)}/** Whether a tmux session for this node id currently exists (server alive + session present).@@ -1835,6 +2171,29 @@ export class PtyManager {}}+ /** Destructive-confirmation variant of the warm-attach probe. Warm attach treats an unavailable+ * probe as "possibly exists" to avoid typing into a live session; an awaited restart must not+ * report success on uncertainty, because its caller mutates profile state only after this says+ * the old generation ended. */+ private async confirmedTmuxSessionExists(persistKey: string): Promise<boolean> {+ if (!this.tmuxPath) return false+ try {+ await this.confirmedProcessRun(+ this.tmuxPath,+ ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)],+ { timeout: PROBE_TIMEOUT_MS }+ )+ return true+ } catch (error) {+ if (probeSaysAbsent(error)) return false+ throw new Error(+ `Could not confirm the terminal session before restarting it: ${+ error instanceof Error ? error.message : String(error)+ }`+ )+ }+ }+/*** Spawn a PTY whose output/exit are delivered to `sinks` instead of the renderer. Used by* the relay host (Task 6) to serve PTYs over the E2EE transport: the host pipes `onData`@@ -1869,7 +2228,22 @@ export class PtyManager {* live output. Empty string if tmux is unavailable or the session doesn't exist yet.*/async captureSnapshot(persistKey: string): Promise<string> {- if (!this.tmuxPath) return ''+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.sessionHost) {+ try {+ return await sessionHostCapture(sessionName(persistKey), false)+ } catch {+ return ''+ }+ }+ if (!this.tmuxPath) {+ if (!this.getSettings().tmuxEnabled || !sessionHostSupported()) return ''+ try {+ return await sessionHostCapture(sessionName(persistKey), false)+ } catch {+ return ''+ }+ }try {const { stdout } = await runAsync(this.tmuxPath,@@ -1925,7 +2299,9 @@ export class PtyManager {options: PtyCreateOptions,/** The client this session is spawned for, or null for a relay-served (detached) pty. */clientId: ClientId | null,- sinks: DetachedSinks | undefined+ sinks: DetachedSinks | undefined,+ /** A persistent generation proven before profile/cwd resolution; attach-only, never create. */+ warmWindowsBackend?: 'session-host' | 'tmux'): string {// PRE-FLIGHT — refuse before node-pty is touched, not after it fails.//@@ -2027,6 +2403,10 @@ export class PtyManager {// advertise it — without this, zsh themes and TUIs quietly clamp to the 256 palette and// the canvas terminals never match the user's real terminal colors (issue #78).const env = { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor' } as Record<string, string>+ // The Server Edition may receive a first-boot password through its own environment. That+ // bootstrap credential belongs to the server process, never to the interactive shells and+ // agent CLIs it launches; inheriting it here would expose it to every terminal node.+ delete env.NODETERM_SERVER_PASSWORDdelete env.TMUXdelete env.TMUX_PANE@@ -2083,12 +2463,12 @@ export class PtyManager {// ANTHROPIC_API_KEY wins over CLAUDE_CONFIG_DIR credentials). System-default nodes// (no accountId) are untouched. Remote (ssh) sessions get their account env via the// remote tmux `-e` list instead (the local ssh client process doesn't need it).+ let accountFallback = falselet accountDir =options.accountId && !options.sshRemote ? claudeConfigDirFor(options.accountId) : null// Missing/deleted account dir (spec: error handling) → fall back to system default// instead of pointing claude at a dead dir; the node then behaves like an unbound one.// `accountFallback` is surfaced to the renderer (warning chip) via the create() result.- let accountFallback = falseif (accountDir && !fs.existsSync(accountDir)) {console.warn(`[accounts] config dir missing for ${options.accountId}, using system default`)accountDir = null@@ -2137,6 +2517,14 @@ export class PtyManager {const settings = this.getSettings()let file: stringlet args: string[]+ // Set true only by the session-host branch below. Decides which of the two `proc =` paths+ // runs further down — see there for why this can't just be "no local tmux was found" (a+ // remote/ssh node must never fall into it, and neither may a node with no persistKey at all).+ let useSessionHost = false+ let attachExistingHost = false+ // Unlike the installed-binary probe, this records the backend selected for THIS generation.+ // A Windows profile may coexist with an MSYS/Cygwin tmux on PATH and must not inherit it.+ let useLocalTmux = false// Resolve the session program. A bare 'ssh' is resolved to an absolute path because GUI// apps don't inherit the shell PATH; its args come from options.shellArgs.@@ -2151,6 +2539,10 @@ export class PtyManager {const reqShell = safeSessionProgram(options.shell)const program = reqShell === 'ssh' ? findSsh() ?? 'ssh' : reqShellconst programArgs = options.shellArgs ?? []+ // One resolver for BOTH direct node-pty and the persistent session-host backend, so the two+ // paths cannot drift on "which shell" (see resolveLocalSessionShell).+ const localSessionShell = resolveLocalSessionShell(program, settings.defaultShell)+ const localSessionArgs = program ? programArgs : []// SSH project node: run `ssh -t '<remote tmux attach-or-create>'` as the PTY program. The// REMOTE tmux provides persistence (over the project's ControlMaster); the local PTY just@@ -2275,6 +2667,11 @@ export class PtyManager {options.sshRemote.tmuxConfPath,remoteSessionEnv)+ } else if (warmWindowsBackend === 'session-host') {+ useSessionHost = true+ attachExistingHost = true+ file = ''+ args = []} else if (this.tmuxPath && settings.tmuxEnabled && options.persistKey) {// attach-or-create the persistent session for this node.// `-A` = attach-or-create. `-D` = detach OTHER clients on attach. We use `-D` ONLY for the@@ -2286,6 +2683,22 @@ export class PtyManager {// `-e` sets the session environment explicitly (the tmux server is shared, so relying// on the client's inherited env would leak the first session's values into later ones).file = this.tmuxPath+ useLocalTmux = true+ if (warmWindowsBackend === 'tmux') {+ // Attach-only is the critical distinction from `new-session -A`: if the proven warm+ // generation disappears in this window, tmux rejects instead of cold-spawning a shell+ // from options that deliberately skipped trusted profile resolution.+ args = [+ '-L',+ TMUX_SOCKET,+ '-f',+ this.confPath,+ 'attach-session',+ ...(sinks ? [] : ['-d']),+ '-t',+ sessionName(options.persistKey)+ ]+ } else {// The hook-server env (port/token/node id/agent id) is passed explicitly via `-e`// (one `-e KEY=VALUE` per key) since the shared tmux server can't rely on inherited env.const hookEnvArgs = Object.entries(hookEnv).flatMap(([k, v]) => ['-e', `${k}=${v}`])@@ -2335,35 +2748,80 @@ export class PtyManager {args.push(shell)args.push(...programArgs)}+ }+ } else if (+ !options.sshRemote &&+ options.persistKey &&+ settings.tmuxEnabled &&+ sessionHostSupported()+ ) {+ // `file`/`args` are left unused: the real spawn happens INSIDE the session-host process, driven by+ // the `SessionHostPty` constructed below, not by a `pty.spawn()` in this one.+ useSessionHost = true+ file = ''+ args = []} else {- file =- program ||- settings.defaultShell ||- process.env.SHELL ||- (os.platform() === 'win32' ? 'powershell.exe' : 'bash')- args = program ? programArgs : []+ // `process.env.SHELL` is a POSIX-only convention (unset on Windows outside a POSIX+ // subsystem), so it never wins the win32 branch anyway — the ordering below just says so+ // explicitly instead of relying on it being empty there.+ file = localSessionShell+ args = localSessionArgs}let proc: pty.IPty- try {- proc = pty.spawn(file, args, {- name: 'xterm-256color',- cols: options.cols,- rows: options.rows,- cwd,- env- })- } catch (err) {- // node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno.- // Two different field causes wear that same message, so BOTH are measured before anything is- // said: a cross-arch `electron-builder --x64` run clobbering node-pty's spawn-helper (arm64- // app can't exec an x86_64 helper), and the machine being out of pty DEVICES- // (`kern.tty.ptmx_max`, 2026-08-11 — 515 `/dev/ttys*` against a ceiling of 511).- const reason = err instanceof Error ? err.message : String(err)- // Re-read the devices rather than reusing the pre-flight's reading: this spawn just consumed- // (and, per the leak above, kept) devices of its own, so the number the user is shown should- // be the one that was true when the failure happened.- throw this.spawnFailureError(reason, file, cwd, spawnHelperArchMismatch(), readPtyDevices())+ if (useSessionHost) {+ // Cast to the small `IPty` subset this file actually touches — see `SessionHostPty`'s own+ // doc comment for exactly what it implements and why that is enough. Its constructor kicks+ // off the attach-or-create round trip asynchronously and never throws synchronously (a+ // rejection surfaces on `.ready`, awaited by `spawnNew` — see there for how a failure+ // degrades rather than blocking the create).+ // `resolveLocalSessionShell`, NOT a bare `|| 'bash'`.+ //+ // This branch exists BECAUSE the platform has no tmux — which in practice means Windows —+ // and it was defaulting to a POSIX shell that does not exist there. The host dutifully tried+ // to spawn `bash`, node-pty answered `File not found:`, and the attach rejected. Everything+ // downstream then hid it: the rejection was swallowed by a bare catch, `persistent` was+ // derived from the path chosen rather than the outcome, and the renderer fell back to a+ // plain shell. So every terminal on Windows looked fine and silently did not survive a+ // restart — the one thing this whole backend is for.+ //+ // The non-session-host branch above already resolves this correctly. Sharing that logic is+ // the fix; two places deciding "which shell" is what let them disagree.+ proc = (attachExistingHost+ ? attachExistingSessionHostPty(sessionName(options.persistKey as string))+ : createSessionHostPty(+ sessionName(options.persistKey as string),+ {+ cwd,+ shell: localSessionShell,+ args: localSessionArgs,+ env,+ cols: options.cols,+ rows: options.rows+ },+ settings.tmuxScrollback+ )) as unknown as pty.IPty+ } else {+ try {+ proc = pty.spawn(file, args, {+ name: 'xterm-256color',+ cols: options.cols,+ rows: options.rows,+ cwd,+ env+ })+ } catch (err) {+ // node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno.+ // Two different field causes wear that same message, so BOTH are measured before anything is+ // said: a cross-arch `electron-builder --x64` run clobbering node-pty's spawn-helper (arm64+ // app can't exec an x86_64 helper), and the machine being out of pty DEVICES+ // (`kern.tty.ptmx_max`, 2026-08-11 — 515 `/dev/ttys*` against a ceiling of 511).+ const reason = err instanceof Error ? err.message : String(err)+ // Re-read the devices rather than reusing the pre-flight's reading: this spawn just consumed+ // (and, per the leak above, kept) devices of its own, so the number the user is shown should+ // be the one that was true when the failure happened.+ throw this.spawnFailureError(reason, file, cwd, spawnHelperArchMismatch(), readPtyDevices())+ }}// tmux-backed sessions snapshot their scrollback to disk periodically so a machine reboot@@ -2374,8 +2832,12 @@ export class PtyManager {// marked remote — otherwise destroy/capture would target a remote tmux that was never spawned// and silently leak the local session.const remote = options.sshRemote && options.persistKey && remoteSsh ? options.sshRemote : undefined- const tmuxBacked = !!(this.tmuxPath && settings.tmuxEnabled && options.persistKey)- const persisted = !!options.persistKey && (remote ? true : tmuxBacked)+ const tmuxBacked = useLocalTmux+ // `useSessionHost` is exactly "did the branch selection above pick the session-host backend",+ // so it needs no re-derivation here — session-host-backed sessions survive losing their+ // client exactly like tmux-backed ones do, for the same reason: the underlying pty lives in a+ // separate process (the session host), not in this one.+ const persisted = !!options.persistKey && (remote ? true : tmuxBacked || useSessionHost)const spawnSize = normalizeSize(options.cols, options.rows)// The spawning view's composite key. Usually the canvas node (PRIMARY), but a modal that opens// a node whose canvas terminal is closed spawns it too — under its own viewerId, correctly.@@ -2413,7 +2875,8 @@ export class PtyManager {tmuxBacked: persisted,unwatchedSince: null,pausedBy: new Set<string>(),- accountFallback+ accountFallback,+ sessionHost: useSessionHost}// Both shared timers are armed by the first session that needs them: the scrollback snapshots// and the idle reap are both about tmux-backed sessions and nothing else.@@ -2431,31 +2894,90 @@ export class PtyManager {// destroyer can even reach a spawn for a tombstoned node (create() refuses everyone else), so// this is exactly "the owner brought the node back" (⌘Z) — and its co-viewers must be able to// join the new session rather than stay refused.- if (session.indexKey) this.tombstones.delete(session.indexKey)+ // A session-host record is provisional until its async attach succeeds. spawnNew() clears the+ // tombstone after ready so a failed resurrection cannot silently remove deletion protection.+ if (session.indexKey && !session.sessionHost) this.tombstones.delete(session.indexKey)// The replacement session for a RECYCLED node (worktree move) is now live and indexed, so its// co-viewers can safely be told to restart: their create() will `join` THIS session instead of// spawning `nt-<nodeId>` from their own (stale) cwd. This is the whole reason the notice waits.- if (session.indexKey && this.pendingRecycle.has(session.indexKey))+ // A session-host shim is only provisional until its asynchronous `ready` settles. spawnNew()+ // fires this notice after that barrier; publishing here would wake co-viewers onto a dead id.+ if (session.indexKey && !session.sessionHost && this.pendingRecycle.has(session.indexKey))this.fireRecycled(session.indexKey, true)- proc.onData((data) => this.queueData(sessionId, session, data))+ proc.onData((data) => {+ // A session-host attach can fail after the shim has already delivered startup bytes. Once+ // rollback removes this exact generation, late callbacks must not recreate its flush timer+ // or leak bytes into a replacement that happens to reuse the same node id.+ if (this.sessions.get(sessionId) !== session) return+ this.queueData(sessionId, session, data)+ })proc.onExit(({ exitCode }) => {- this.flush(sessionId, session) // deliver any buffered output before the exit signal- session.onExit?.(exitCode) // relay host sink (unchanged)- for (const client of this.clientsOf(session))- this.send(client, IPC.ptyExit(sessionId), exitCode)- this.forget(sessionId, session)+ // The persistent host broadcasts exit before it answers killSession. The confirmed profile+ // switch must await that acknowledgement before mutating the local index/subscribers, so the+ // exact in-flight generation's early exit is consumed by the transaction instead of racing+ // cleanup ahead of the response. Success cleans it below; rejection leaves it untouched.+ const confirmedEnd = this.confirmedBackendEnds.get(sessionId)+ if (confirmedEnd?.session === session) {+ confirmedEnd.exitCode = exitCode+ confirmedEnd.resolveExit?.()+ return+ }+ this.handleSessionExit(sessionId, session, exitCode)})+ if (useSessionHost) {+ ;(proc as unknown as SessionHostPty).onAttachError((error) => {+ // Reconnect replay can be rejected after this generation was already returned to the+ // renderer. Retire only the exact remembered generation; a late callback from an older+ // shim must never take down its replacement.+ if (this.sessions.get(sessionId) !== session) return+ const safeReason = /^(?:no existing session|session '[A-Za-z0-9._-]+' is ending|unauthorized|no such session)/i.test(+ error.message+ )+ ? error.message+ : 'the persistent session host rejected the reattach'+ this.queueData(+ sessionId,+ session,+ `\r\n[nodeterm] Persistent terminal reattach failed: ${safeReason}\r\n`+ )+ this.handleSessionExit(sessionId, session, 1)+ })+ }++ // Detached relay callers cannot await SessionHostPty.ready because their long-standing API+ // returns a session id synchronously. They still must not retain a zombie Session: retire it+ // and surface an ordinary non-zero exit to the sink if the asynchronous attach fails.+ if (useSessionHost && sinks) {+ void (proc as unknown as SessionHostPty).ready.catch(() => {+ if (this.sessions.get(sessionId) !== session) return+ this.discardFailedSpawn(sessionId, session)+ try {+ sinks.onExit(1)+ } catch {+ // A consumer callback cannot resurrect the already-retired provisional Session, and a+ // throw here must not become an unhandled rejection from this deliberately detached task.+ }+ })+ }+return sessionId}/** Park a recycled session's co-viewers until the replacement session shows up (or the timeout* fires). One entry per node: a second recycle before the first resolved supersedes it — the* earlier waiters are folded in, since their session is just as dead. */- private armRecycle(persistKey: string, sessionId: string, clients: ClientId[]): void {+ private armRecycle(+ persistKey: string,+ sessionId: string,+ clients: ClientId[],+ owner: ClientId | null,+ target?: PtyRecycleTarget+ ): void {const prev = this.pendingRecycle.get(persistKey)+ const waiters = prev?.waiters ?? []if (prev) {clearTimeout(prev.timer)for (const c of prev.clients) clients.push(c)@@ -2463,6 +2985,9 @@ export class PtyManager {this.pendingRecycle.set(persistKey, {sessionId,clients: new Set(clients),+ owner: owner === null ? null : subKey(owner, PRIMARY_VIEWER),+ ...(target ? { target } : {}),+ waiters,timer: setTimeout(() => this.fireRecycled(persistKey, false), RECYCLE_NOTIFY_TIMEOUT_MS)})}@@ -2491,6 +3016,15 @@ export class PtyManager {clearTimeout(entry.timer)const channel = IPC.ptyRecycled(entry.sessionId)for (const client of entry.clients) this.send(client, channel, { ready })+ if (ready) {+ // The exact replacement is registered and ready; replay each parked create through the+ // ordinary path so it co-attaches and gets the same screen/size semantics as any joiner.+ for (const waiter of entry.waiters)+ void this.create(waiter.clientId, waiter.options).then(waiter.resolve, waiter.reject)+ } else {+ const error = new Error('The replacement terminal did not become ready. Reopen it to try again.')+ for (const waiter of entry.waiters) waiter.reject(error)+ }}/** Drop a dead/released session from both indexes. Keyed off `indexKey` (not `persistKey`,@@ -2501,6 +3035,48 @@ export class PtyManager {this.byPersistKey.delete(session.indexKey)}+ /** Apply an ordinary process exit for one exact session generation. Kept separate so a+ * confirmed backend kill whose response is lost can replay the exit it deferred: in that case+ * the process really ended, but the profile switch still rejects and never respawns/applies. */+ private handleSessionExit(sessionId: string, session: Session, exitCode: number): void {+ if (this.sessions.get(sessionId) !== session) return+ this.flush(sessionId, session) // deliver any buffered output before the exit signal+ session.onExit?.(exitCode) // relay host sink (unchanged)+ for (const client of this.clientsOf(session))+ this.send(client, IPC.ptyExit(sessionId), exitCode)+ this.forget(sessionId, session)+ }++ /** Roll back the provisional Session installed before a session-host attach settles. Unlike a+ * normal release, this records no shadow/released-session metadata and takes no snapshot: there+ * was never a confirmed live session to preserve. */+ private discardFailedSpawn(sessionId: string, session: Session): void {+ if (session.flushTimer) {+ clearTimeout(session.flushTimer)+ session.flushTimer = null+ }+ session.buf = []+ session.bufBytes = 0+ session.subscribers.clear()+ session.sizes.clear()+ session.shown.clear()+ session.pausedBy.clear()+ // Do not use releasePty here: its defensive resume would issue a fresh host request from a+ // shim whose attach just failed. SessionHostPty.destroy() is the exact detach/unsubscribe.+ const hostPty = session.proc as unknown as SessionHostPty+ hostPty.destroy()+ this.forget(sessionId, session)+ const remaining = [...this.sessions.values()]+ if (!remaining.some((candidate) => candidate.persistKey) && this.snapshotTimer) {+ clearInterval(this.snapshotTimer)+ this.snapshotTimer = null+ }+ if (!remaining.some((candidate) => candidate.tmuxBacked) && this.reapTimer) {+ clearInterval(this.reapTimer)+ this.reapTimer = null+ }+ }+/*** Push the effective (smallest-subscriber) size into the pty, then tell every subscriber whose* xterm is NOT already rendering that grid what it actually is, so each one renders exactly the@@ -2881,9 +3457,10 @@ export class PtyManager {* markdown view); otherwise the recent ~200 lines (AI naming, palette search).*/async captureSession(persistKey: string, full = false): Promise<string> {+ const live = this.liveSessionForPersistKey(persistKey)// Remote (ssh-project) node: there is no local tmux session — capture from the REMOTE tmux// over the project's ControlMaster (mirrors snapshotScrollback / destroySession).- const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote+ const sshRemote = live?.sshRemoteif (sshRemote) {const ssh = findSsh()if (!ssh) return ''@@ -2898,7 +3475,13 @@ export class PtyManager {return ''}}- if (!this.tmuxPath) return ''+ // Backend choice belongs to the live generation, not to whichever binaries happen to be on+ // PATH. A native Windows profile remains session-host-backed beside an MSYS/Cygwin tmux.+ if (live?.sessionHost || !this.tmuxPath) {+ return this.getSettings().tmuxEnabled && sessionHostSupported()+ ? sessionHostCapture(sessionName(persistKey), full)+ : ''+ }try {const { stdout } = await runAsync(this.tmuxPath,@@ -2924,6 +3507,11 @@ export class PtyManager {if (!session) return ''const key = session.persistKey ?? session.indexKeyif (!key) return ''+ // `true` (full scrollback, same cap the emulator was built with): unlike tmux's plain-pane+ // capture, this backend has no separate mechanism for the user to scroll a live session's+ // history (there is no tmux underneath to own the wheel — see docs/windows-session-host.md),+ // so a joiner is seeded generously rather than with just the visible rows.+ if (session.sessionHost) return sessionHostCapture(sessionName(key), true)if (session.sshRemote) return this.captureSession(key)return this.captureSnapshot(key)}@@ -2955,6 +3543,7 @@ export class PtyManager {)return parsePaneCursor(stdout)}+ if (session.sessionHost) return undefinedif (!this.tmuxPath) return undefinedconst { stdout } = await runAsync(this.tmuxPath, ['-L',@@ -2979,7 +3568,8 @@ export class PtyManager {*/private async snapshotScrollback(persistKey: string,- sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>+ sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>,+ sessionHost = false): Promise<boolean> {if (sshRemote) {// Remote (ssh-project) node: capture from the REMOTE tmux over the project's ControlMaster.@@ -2998,7 +3588,21 @@ export class PtyManager {return false}}- if (!this.tmuxPath) return false+ // No local tmux: this is a session-host-backed session (only that backend reaches this+ // periodic snapshot loop at all — see `snapshotTick`'s `session.persistKey` gate). Same+ // "cold-restore across a machine reboot" purpose as the tmux capture below; see+ // docs/windows-session-host.md §7 for the honest limitation this snapshot exists to soften+ // (the session-host process itself does NOT survive a reboot, unlike a real tmux server).+ if (sessionHost || !this.tmuxPath) {+ if (!this.getSettings().tmuxEnabled || !sessionHostSupported()) return false+ try {+ const text = await sessionHostCapture(sessionName(persistKey), true)+ if (text) await writeScrollback(persistKey, text)+ return true+ } catch {+ return false+ }+ }try {const { stdout } = await runAsync(this.tmuxPath,@@ -3055,7 +3659,8 @@ export class PtyManager {async sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<boolean> {const enter = opts?.enter ?? trueconst target = sessionName(persistKey)- const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote+ const live = this.liveSessionForPersistKey(persistKey)+ const sshRemote = live?.sshRemotetry {if (sshRemote) {const ssh = findSsh()@@ -3064,7 +3669,14 @@ export class PtyManager {if (!plan) return truereturn await runPasteDelivery(plan, (args, input) => runWithStdin(ssh, args, input))}- if (!this.tmuxPath) return false+ // No local tmux: this machine persists sessions via the session-host backend instead (see+ // docs/windows-session-host.md). Its `sendKeys` needs no attached client, exactly like+ // tmux's own `send-keys -t <name>` — the host looks the session up by NAME.+ if (live?.sessionHost || !this.tmuxPath) {+ return this.getSettings().tmuxEnabled && sessionHostSupported()+ ? sessionHostSendKeys(target, text, enter)+ : false+ }const tmuxPath = this.tmuxPathconst plan = localPasteDelivery(TMUX_SOCKET, target, text, enter)if (!plan) return true@@ -3089,7 +3701,8 @@ export class PtyManager {*/async paneCommand(persistKey: string): Promise<string | null> {const target = sessionName(persistKey)- const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote+ const live = this.liveSessionForPersistKey(persistKey)+ const sshRemote = live?.sshRemoteif (sshRemote) {const ssh = findSsh()if (!ssh) return null@@ -3103,7 +3716,13 @@ export class PtyManager {return null}}- if (!this.tmuxPath) return null+ // No local tmux: ask the session-host backend's own `#{pane_current_command}` equivalent (a+ // descendant-process walk — see process-tree.ts for the imprecision that carries).+ if (live?.sessionHost || !this.tmuxPath) {+ return this.getSettings().tmuxEnabled && sessionHostSupported()+ ? sessionHostPaneCommand(target)+ : null+ }try {const { stdout } = await runAsync(this.tmuxPath, ['-L',@@ -3224,7 +3843,8 @@ export class PtyManager {*/async paneOwner(persistKey: string): Promise<PaneOwner | null> {const target = sessionName(persistKey)- const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote+ const live = this.liveSessionForPersistKey(persistKey)+ const sshRemote = live?.sshRemotetry {if (sshRemote) {const ssh = findSsh()@@ -3240,7 +3860,9 @@ export class PtyManager {const second = await runAsync(ssh, psArgs)return paneOwnerFrom(identity, second.stdout)}- if (!this.tmuxPath) return null+ // The session host has no tty/tmux identity surface. Do not query an unrelated POSIX tmux+ // merely because one is installed beside this native Windows generation.+ if (live?.sessionHost || !this.tmuxPath) return nullconst first = await runAsync(this.tmuxPath, ['-L',TMUX_SOCKET,@@ -3325,22 +3947,31 @@ export class PtyManager {* never throws.*/async listNodetermSessions(): Promise<string[]> {- if (!this.tmuxPath) return []- try {- const { stdout } = await runAsync(this.tmuxPath, [- '-L',- TMUX_SOCKET,- 'list-sessions',- '-F',- '#{session_name}'- ])- return stdout- .split('\n')- .map((line) => line.trim())- .filter((line) => line.length > 0)- } catch {- return []- }+ // The two persistence backends can legitimately coexist on Windows (native profiles in the+ // session host, legacy/MSYS terminals in tmux). Query each independently so one unavailable+ // backend cannot hide the other's sessions, then de-duplicate a migrated name.+ const tmuxSessions = this.tmuxPath+ ? runAsync(this.tmuxPath, [+ '-L',+ TMUX_SOCKET,+ 'list-sessions',+ '-F',+ '#{session_name}'+ ])+ .then(({ stdout }) =>+ stdout+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ )+ .catch(() => [] as string[])+ : Promise.resolve([] as string[])+ const hostSessions =+ this.getSettings().tmuxEnabled && sessionHostSupported()+ ? sessionHostListSessions().catch(() => [] as string[])+ : Promise.resolve([] as string[])+ const [tmux, host] = await Promise.all([tmuxSessions, hostSessions])+ return [...new Set([...tmux, ...host])]}/**@@ -3370,6 +4001,14 @@ export class PtyManager {return this.endSession(clientId, persistKey, 'delete', opts?.everySocket === true)}+ /** Register shell cleanup after end processing (and the session-host acknowledgement). Failures are+ * isolated from the acknowledgement: a dead transcript tail must not turn a successful kill+ * into an outcome the renderer is told is unknown. */+ onSessionEnded(listener: (persistKey: string) => void): () => void {+ this.sessionEndedListeners.add(listener)+ return () => this.sessionEndedListeners.delete(listener)+ }+/*** End a node's persistent session so the SAME node id can immediately respawn in a NEW cwd —* "move into worktree". The tmux kill is identical to `destroySession` (without it, the respawn's@@ -3395,24 +4034,378 @@ export class PtyManager {return this.endSession(clientId, persistKey, 'recycle')}+ /** Awaited desktop profile-switch variant of recycle. Main registers the invoke handler itself+ * so it can release agent-tail ownership after this teardown succeeds. Keep the client-facing+ * validation and rate budget identical to the existing fire-and-forget recycle channel. */+ recycleSessionFromClient(+ clientId: ClientId,+ persistKey: string,+ target?: PtyRecycleTarget+ ): Promise<void> {+ if (typeof persistKey !== 'string' || !persistKey || persistKey.length > REF_MAX_LEN) {+ return Promise.reject(new Error('Refusing to restart terminal: invalid node id.'))+ }+ if (this.confirmedRecycles.has(persistKey)) {+ return Promise.reject(+ new Error('This terminal is already restarting. Wait for that restart to finish.')+ )+ }+ if (!this.allowEnd(clientId, IPC.ptyRecycleConfirmed)) {+ return Promise.reject(+ new Error('Too many terminal restart requests. Wait a moment and try again.')+ )+ }+ const operation = this.confirmAndRecycleSession(clientId, persistKey, target)+ this.confirmedRecycles.set(persistKey, operation)+ return operation.finally(() => {+ if (this.confirmedRecycles.get(persistKey) === operation)+ this.confirmedRecycles.delete(persistKey)+ })+ }++ /** Confirm the target profile is spawnable before ending the old generation, then tear down the+ * backend transactionally. Actual spawn resolves the stable id again at point of use: preflight+ * prevents a knowingly destructive switch, but never turns executable/argv into persisted state. */+ private async confirmAndRecycleSession(+ clientId: ClientId,+ persistKey: string,+ target?: PtyRecycleTarget+ ): Promise<void> {+ let trustedTarget: PtyRecycleTarget | undefined+ if (target) {+ // Profile-switch replacement targets land with the windows-terminal-profiles phase; until+ // then a target can only be refused (the same copy the fork uses without a resolver).+ throw new Error('Windows terminal profiles are unavailable on this host.')+ }+ const liveId = this.byPersistKey.get(persistKey)+ const live = this.liveSessionForPersistKey(persistKey)+ if (live?.sshRemote) {+ throw new Error('Remote terminals cannot be restarted with a local Windows profile.')+ }+ const liveSessionId = live+ ? liveId ?? [...this.sessions.entries()].find(([, session]) => session === live)?.[0]+ : undefined+ let resolveExit: (() => void) | undefined+ const exited = new Promise<void>((resolve) => {+ resolveExit = resolve+ })+ const deferred:+ | { session: Session; exitCode?: number; resolveExit?: () => void }+ | undefined = liveSessionId && live ? { session: live, resolveExit } : undefined+ // Install the exact-generation barrier before any awaited backend probe. A silent plain+ // process can exit while has-session is in flight; if that natural exit were published first,+ // the rest of this transaction would retain a stale pid and could reject after trying to kill+ // a generation that is already gone. The barrier records that exit as proof without allowing a+ // replacement generation to be confused with this one.+ if (liveSessionId && deferred) this.confirmedBackendEnds.set(liveSessionId, deferred)+ const clearExactBarrier = (): void => {+ if (liveSessionId && this.confirmedBackendEnds.get(liveSessionId) === deferred)+ this.confirmedBackendEnds.delete(liveSessionId)+ }+ const abandonConfirmedRecycle = (error: unknown): never => {+ clearExactBarrier()+ // A failed transaction may still have observed the exact local painter exit. Retire that+ // dead generation honestly, but do not apply/spawn the selected profile without every+ // persistent-backend proof (and, for a hosted replacement, its host-granted lease).+ if (liveSessionId && deferred?.exitCode !== undefined)+ this.handleSessionExit(liveSessionId, deferred.session, deferred.exitCode)+ throw error+ }+ let confirmedSessionHost = false+ let confirmedTmux = false+ const settings = this.getSettings()+ const hostAvailable = sessionHostSupported()+ // A local index identifies one painter, not every persistent backend that may still own this+ // node name. Migration and setting changes can leave a same-name host + tmux generation, so+ // probe both independently even while one local generation is indexed. Failed reads remain+ // uncertainty and reject before any destructive action. Old tmux discovery intentionally does+ // not respect today's tmuxEnabled value: disabling persistence cannot make yesterday's live+ // process disappear.+ try {+ if (hostAvailable) {+ confirmedSessionHost = await sessionHostHasSession(sessionName(persistKey))+ }+ if (this.tmuxPath) confirmedTmux = await this.confirmedTmuxSessionExists(persistKey)+ } catch (error) {+ abandonConfirmedRecycle(+ error instanceof SessionHostProtocolCompatibilityError+ ? error+ : new Error(+ `Could not confirm the terminal session before restarting it: ${+ error instanceof Error ? error.message : String(error)+ }`+ )+ )+ }++ // The confirmed path is transactional at the app boundary: acknowledge the persistent+ // backend kill before dropping the local index/subscribers or publishing recycle state. If the+ // kill rejects, every local mapping remains untouched and main cannot release agent tails or+ // let the renderer apply the new profile. Legacy fire-and-forget recycle keeps its historical+ // cleanup-first behavior through endSession's default parameter.+ const sourceSessionHost = !!live?.sessionHost || confirmedSessionHost+ const sourceTmux =+ confirmedTmux || (!!live?.tmuxBacked && !live.sessionHost && !live.sshRemote)+ // These flags describe independent old backends, not one preferred winner. In particular, a+ // discovered hidden host/tmux generation must not make an indexed direct PTY stop being plain:+ // dropping that local mapping without taskkill/onExit proof leaks the silent process.+ const sourcePlain = !!live && !live.sessionHost && !live.tmuxBacked && !live.sshRemote+ // This is a TARGET lease, not an old-backend property. Acquire it before touching tmux/plain+ // so another app cannot create the name in the gap, and take it exactly when the REPLACEMENT+ // generation will be host-backed — the same predicate spawnSession's backend selection uses:+ // on Windows whenever persistence is on and the host bundle exists, elsewhere only when no+ // local tmux is installed (with a tmux present, the replacement lands on tmux and holds no+ // host lease). A direct replacement deliberately holds no host lease, while old host/tmux+ // duplicates are still ended below.+ const reserveHostReplacement =+ (this.runtimePlatform === 'win32' || !this.tmuxPath) &&+ settings.tmuxEnabled &&+ hostAvailable+ const hostName = sessionName(persistKey)+ const expectHostAbsent =+ reserveHostReplacement && !live?.sessionHost && !confirmedSessionHost+ const confirmedHostKillOptions = {+ reserveReplacement: reserveHostReplacement,+ requireV2: true,+ ...(expectHostAbsent ? { expectedAbsent: true } : {})+ }++ // Host FIRST. The target lease protects the name across app processes before any old+ // tmux/plain teardown begins. Every confirmed profile recycle requires protocol-v2 exact+ // generation semantics, even when the selected replacement is deliberately direct and needs+ // no lease. Generic delete remains the separate, legacy-compatible path in endSession().+ if (reserveHostReplacement || sourceSessionHost) {+ try {+ await sessionHostKillSession(hostName, confirmedHostKillOptions)+ } catch (error) {+ if (error instanceof SessionHostProtocolCompatibilityError)+ abandonConfirmedRecycle(error)++ const exactHostExit = !!live?.sessionHost && deferred?.exitCode !== undefined+ if (reserveHostReplacement) {+ // An exact v2 exit proves teardown, not lease ownership. Retry the SAME retained client+ // operation and require a host-returned token. For an unindexed host whose response was+ // lost, a strict absence probe permits the same retry; a competing client still cannot+ // synthesize ownership because its operation id is different and the host rejects it.+ let mayRetryRetainedOperation = exactHostExit+ if (!mayRetryRetainedOperation) {+ try {+ mayRetryRetainedOperation = !(await sessionHostHasSession(hostName))+ } catch (probeError) {+ abandonConfirmedRecycle(probeError)+ }+ }+ if (mayRetryRetainedOperation) {+ try {+ await sessionHostKillSession(hostName, {+ reserveReplacement: true,+ requireV2: true,+ ...(expectHostAbsent ? { expectedAbsent: true } : {})+ })+ } catch (leaseError) {+ abandonConfirmedRecycle(leaseError)+ }+ } else {+ abandonConfirmedRecycle(error)+ }+ } else {+ // Direct targets hold no replacement lease, but they still require the correlated v2+ // operation result so the client can retire its reconnect/kill barrier. Exact local exit+ // proves backend death; for an unindexed host, first require strict named absence. Then+ // retry the SAME retained non-reserve operation and wait for its idempotent result.+ if (!exactHostExit) {+ let hostStillExists = true+ try {+ hostStillExists = await sessionHostHasSession(hostName)+ } catch (probeError) {+ abandonConfirmedRecycle(probeError)+ }+ if (hostStillExists) abandonConfirmedRecycle(error)+ }+ try {+ await sessionHostKillSession(hostName, confirmedHostKillOptions)+ } catch (retryError) {+ abandonConfirmedRecycle(retryError)+ }+ }+ }+ }++ // Tmux SECOND and independently. A tmux client exit is not pane/session death proof; only the+ // named-session kill acknowledgement or a strict absent re-probe lets this stage commit.+ if (sourceTmux && this.tmuxPath) {+ try {+ await this.confirmedProcessRun(+ this.tmuxPath,+ localTmuxKillArgs(TMUX_SOCKET, hostName)+ )+ } catch (error) {+ let tmuxStillExists = true+ try {+ tmuxStillExists = await this.confirmedTmuxSessionExists(persistKey)+ } catch (probeError) {+ abandonConfirmedRecycle(probeError)+ }+ if (tmuxStillExists) abandonConfirmedRecycle(error)+ }+ }++ // Plain LAST and independently from hidden persistent backends. A natural exact exit recorded+ // during the earlier probes is already proof, so never taskkill its stale pid. On Windows a+ // successful process-tree termination is stronger than node-pty's sometimes-missed callback;+ // elsewhere/no pid, bound the wait for this exact generation's exit.+ if (sourcePlain && live && deferred?.exitCode === undefined) {+ try {+ releasePty(live.proc as ReleasablePty)+ const pid = (live.proc as pty.IPty & { pid?: number }).pid+ if (this.runtimePlatform === 'win32' && Number.isSafeInteger(pid) && (pid as number) > 0) {+ await terminateWindowsProcessTree(pid as number)+ } else if (deferred?.exitCode === undefined) {+ let timeout: ReturnType<typeof setTimeout> | undefined+ try {+ await Promise.race([+ exited,+ new Promise<never>((_, reject) => {+ timeout = setTimeout(+ () =>+ reject(+ new Error(+ 'The terminal process did not confirm that it exited. Try the restart again.'+ )+ ),+ CONFIRMED_PLAIN_EXIT_TIMEOUT_MS+ )+ })+ ])+ } finally {+ if (timeout) clearTimeout(timeout)+ }+ }+ } catch (error) {+ // For a plain generation, this exact callback is destructive commit proof even when the+ // release/taskkill acknowledgement failed. Suppress ordinary ptyExit only if all hidden+ // host/tmux stages above also committed; otherwise abandonConfirmedRecycle handled it.+ if (deferred?.exitCode === undefined) abandonConfirmedRecycle(error)+ }+ }++ clearExactBarrier()+ // Every applicable backend was either ended above or strictly probed absent. Do not fall back+ // to endSession's legacy best-effort kill (which swallows ambiguity and carries no lease).+ await this.endSession(clientId, persistKey, 'recycle', false, true, trustedTarget)+ }+/*** The shared teardown behind `destroySession` / `recycleSession`: drop the session (and its* co-attach index entry, in-flight create, buffered output, flow-control ledger), drop the* cold-restore snapshot, and `tmux kill-session`. Everything the two intents disagree about is* the ONE branch below — what the other subscribers are told (see `EndIntent`).*/- private async endSession(+ private endSession(clientId: ClientId | null,persistKey: string,intent: EndIntent,- everySocket = false+ everySocket = false,+ /** The awaited confirmed-recycle path already received every backend acknowledgement. */+ backendAlreadyEnded = false,+ /** Trusted replacement identity; present only after confirmed profile preflight. */+ replacementTarget?: PtyRecycleTarget+ ): Promise<void> {+ const current = this.ending.get(persistKey)+ if (current) {+ // Identical repeats share one acknowledgement only when the in-flight target scope covers+ // this caller. An every-socket request, a pre-confirmed backend outcome, and an exact profile+ // reservation are each stronger than their generic counterpart, so a stronger request waits+ // for the narrow pass and then performs its own cleanup/reservation before it may resolve.+ const targetCovered =+ !replacementTarget ||+ (current.replacementTarget?.profileId === replacementTarget.profileId &&+ current.replacementTarget.cwd === replacementTarget.cwd)+ const covered =+ current.intent === intent &&+ (!everySocket || current.everySocket) &&+ (!backendAlreadyEnded || current.backendAlreadyEnded) &&+ targetCovered+ return covered+ ? current.promise+ : current.promise.then(() =>+ this.endSession(+ clientId,+ persistKey,+ intent,+ everySocket,+ backendAlreadyEnded,+ replacementTarget+ )+ )+ }+ const promise = this.runEndSession(+ clientId,+ persistKey,+ intent,+ everySocket,+ backendAlreadyEnded,+ replacementTarget+ )+ const entry = { intent, everySocket, backendAlreadyEnded, replacementTarget, promise }+ this.ending.set(persistKey, entry)+ const clear = (): void => {+ if (this.ending.get(persistKey) === entry) this.ending.delete(persistKey)+ }+ promise.then(clear, clear)+ return promise+ }++ private async runEndSession(+ clientId: ClientId | null,+ persistKey: string,+ intent: EndIntent,+ everySocket = false,+ /** The awaited confirmed-recycle path already received a backend kill acknowledgement. */+ backendAlreadyEnded = false,+ /** Trusted replacement identity; present only after confirmed profile preflight. */+ replacementTarget?: PtyRecycleTarget): Promise<void> {// Both callers run while the session is still live, so its sshRemote is known. Capture it// synchronously before any await. The index is the co-attach one (UI sessions); the scan is// the fallback for a session that is live but not indexed.- const dyingId = this.byPersistKey.get(persistKey)- const dying = dyingId ? this.sessions.get(dyingId) : undefined- const sshRemote = dying?.sshRemote ?? this.sessionByPersistKey(persistKey)?.sshRemote+ const indexedId = this.byPersistKey.get(persistKey)+ const indexed = indexedId ? this.sessions.get(indexedId) : undefined+ const fallback = indexed ?? this.sessionByPersistKey(persistKey)+ const dyingId =+ indexedId ??+ (fallback+ ? [...this.sessions.entries()].find(([, candidate]) => candidate === fallback)?.[0]+ : undefined)+ const dying = fallback+ const sshRemote = dying?.sshRemote+ // SessionHostClient has a real request/response acknowledgement. Await it BEFORE any local+ // deletion claim: on transport failure the node, tombstone, subscribers and transcript tails+ // remain available, because the host outcome is unknown and the user must be able to retry.+ // A live session records its backend directly; the second branch preserves the old unheld-row+ // behavior, where the enabled host may own a session this manager is not attached to.+ if (backendAlreadyEnded) {+ // The confirmed profile-switch transaction proved every applicable backend ended (or was+ // strictly absent), so it also resolves any older generic request whose response was lost.+ this.unknownEnds.delete(persistKey)+ } else {+ const sessionHostKill =+ dying?.sessionHost === true ||+ this.unknownEnds.has(persistKey) ||+ (!dying &&+ !this.tmuxPath &&+ this.getSettings().tmuxEnabled &&+ sessionHostSupported())+ if (sessionHostKill) {+ try {+ await sessionHostKillSession(sessionName(persistKey))+ this.unknownEnds.delete(persistKey)+ } catch (error) {+ this.unknownEnds.add(persistKey)+ throw error+ }+ }+ }// Un-index NOW (synchronously): this session is finished either way, so a create() that races// the kill-session below — the worktree-move respawn does exactly that — must spawn a fresh// session instead of co-attaching to the one we are about to end.@@ -3448,8 +4441,8 @@ export class PtyManager {if (intent === 'delete') {const channel = IPC.ptyClosed(dyingId)for (const client of others) this.send(client, channel, { by: clientId })- } else if (others.length > 0) {- this.armRecycle(persistKey, dyingId, others)+ } else {+ this.armRecycle(persistKey, dyingId, others, clientId, replacementTarget)}// Tear the session down HERE rather than leaving it to the client's own `kill` / the pty's// onExit: with N subscribers there is no single kill to wait for, and every one of them may@@ -3469,6 +4462,11 @@ export class PtyManager {releasePty(dying.proc as ReleasablePty)this.forget(dyingId, dying)}+ // Confirmed absence and a solo live session still need an owner reservation: an inactive+ // co-viewer can issue create during kill → settings-apply even when there were no subscribers+ // to notify. It waits on this entry and can never establish a stale replacement generation.+ if (intent === 'recycle' && (!dyingId || !dying))+ this.armRecycle(persistKey, '', [], clientId, replacementTarget)// This session is gone for good — drop its cold-restore snapshot too. A recycle drops it as// well (and always did, when the worktree move went through `destroy`): the snapshot is of the// OLD cwd's session, and the respawn is a cold start (`fresh`), so replaying it would paint the@@ -3509,39 +4507,52 @@ export class PtyManager {// shells' own listeners are the wrong seam twice over: they are registered for `pty:recycle`// too, and there are two of them to keep in step.if (intent === 'delete') clearNodeAgentStatus(persistKey)- if (sshRemote) {- // Remote (ssh-project) node: end the REMOTE session.- const ssh = findSsh()- if (ssh) {- try {- await runAsync(ssh, remoteTmuxKillArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey)))- } catch {- // remote session may not exist / master down; ignore+ if (!backendAlreadyEnded) {+ if (sshRemote) {+ // Remote (ssh-project) node: end the REMOTE session.+ const ssh = findSsh()+ if (ssh) {+ try {+ await runAsync(ssh, remoteTmuxKillArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey)))+ } catch {+ // remote session may not exist / master down; ignore+ }+ }+ // ...and then fall through to the LOCAL kill below rather than returning. A remote node+ // normally has no local session — but it may have one from before `requireRemote`, when a+ // create issued with the master down spawned a local shell under this exact name. That+ // orphan outlived everything (this branch used to return here, so the delete never reached+ // it) with whatever the node had launched still running in it. The node is being deleted:+ // anything wearing its name goes with it. Costs one `kill-session` that usually says "no+ // such session", which is already the ignored case below.+ }+ if (this.tmuxPath) {+ // Which socket(s) to aim at. Holding the session ourselves means we KNOW: it is the local one,+ // one kill, unchanged. Holding nothing means the name is all we have — and then the fan-out+ // is the CALLER's to ask for, because on this machine a `nt-<id>` we hold nothing for can+ // also be living on the `nodeterm-rmt` socket, where ANOTHER machine's nodeterm puts the+ // sessions it SSHes in to spawn. Only the session-memory panel's speculative kill sets+ // `everySocket`: it sweeps both sockets and offers to end what it found, so a kill that only+ // tried `node-terminal` showed a confirm saying "this stops its tmux session" and did+ // nothing. An ordinary node-× on a node never mounted in this process takes the same unheld+ // branch and must NOT inherit that blast radius.+ for (const socket of localKillSockets(dying ? TMUX_SOCKET : null, everySocket)) {+ try {+ await runAsync(this.tmuxPath, localTmuxKillArgs(socket, sessionName(persistKey)))+ } catch {+ // session may not exist on this socket; ignore+ }}}- // ...and then fall through to the LOCAL kill below rather than returning. A remote node- // normally has no local session — but it may have one from before `requireRemote`, when a- // create issued with the master down spawned a local shell under this exact name. That- // orphan outlived everything (this branch used to return here, so the delete never reached- // it) with whatever the node had launched still running in it. The node is being deleted:- // anything wearing its name goes with it. Costs one `kill-session` that usually says "no- // such session", which is already the ignored case below.}- if (!this.tmuxPath) return- // Which socket(s) to aim at. Holding the session ourselves means we KNOW: it is the local one,- // one kill, unchanged. Holding nothing means the name is all we have — and then the fan-out is- // the CALLER's to ask for, because on this machine a `nt-<id>` we hold nothing for can also be- // living on the `nodeterm-rmt` socket, where ANOTHER machine's nodeterm puts the sessions it- // SSHes in to spawn. Only the session-memory panel's speculative kill sets `everySocket`: it- // sweeps both sockets and offers to end what it found, so a kill that only tried- // `node-terminal` showed a confirm saying "this stops its tmux session" and did nothing. An- // ordinary node-× on a node never mounted in this process takes the same unheld branch and- // must NOT inherit that blast radius.- for (const socket of localKillSockets(dying ? TMUX_SOCKET : null, everySocket)) {+ for (const listener of this.sessionEndedListeners) {try {- await runAsync(this.tmuxPath, localTmuxKillArgs(socket, sessionName(persistKey)))- } catch {- // session may not exist on this socket; ignore+ listener(persistKey)+ } catch (error) {+ console.warn(+ `[pty] confirmed ${intent} cleanup for ${persistKey} failed`,+ error instanceof Error ? error.message : String(error)+ )}}}@@ -3568,7 +4579,9 @@ export class PtyManager {// Final scrollback snapshot on quit so a reboot can replay it. Skipped for sessions with// no output since the last periodic capture (unchanged pane content).if (session.persistKey && session.outputSinceSnapshot)- finals.push(this.snapshotScrollback(session.persistKey, session.sshRemote))+ finals.push(+ this.snapshotScrollback(session.persistKey, session.sshRemote, !!session.sessionHost)+ )releasePty(session.proc as ReleasablePty)}// Shadows are child processes of OURS, so quitting takes them with us — the tmux sessions they@@ -3581,12 +4594,20 @@ export class PtyManager {this.byPersistKey.clear()// Pending recycle notices die with the sessions they were waiting on (their timers would// otherwise fire into a manager that has released everything).- for (const entry of this.pendingRecycle.values()) clearTimeout(entry.timer)+ for (const entry of this.pendingRecycle.values()) {+ clearTimeout(entry.timer)+ const error = new Error('Terminal manager shut down before the replacement became ready.')+ for (const waiter of entry.waiters) waiter.reject(error)+ }this.pendingRecycle.clear()// Clear the in-flight index with the other two, or a create still spawning at quit would leave// a promise (and the session it resolves to) reachable from a manager that has released// everything else — a later create would then co-attach to a session we already let go.this.inflight.clear()+ this.confirmedBackendEnds.clear()+ this.confirmedRecycles.clear()+ this.ending.clear()+ this.unknownEnds.clear()return Promise.all(finals).then(() => undefined)}diff --git a/src/core/pty-persist-key-guard.test.ts b/src/core/pty-persist-key-guard.test.tsindex 681043d7f..c4e14c0f8 100644--- a/src/core/pty-persist-key-guard.test.ts+++ b/src/core/pty-persist-key-guard.test.ts@@ -18,6 +18,14 @@ import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'*/const spawned: Array<{ file: string; args: string[] }> = []+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: (file: string, args: string[]) => {spawned.push({ file, args })diff --git a/src/core/pty-require-remote.test.ts b/src/core/pty-require-remote.test.tsindex fadd033c9..934c9d93b 100644--- a/src/core/pty-require-remote.test.ts+++ b/src/core/pty-require-remote.test.ts@@ -15,6 +15,14 @@ import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'*/const spawned: Array<{ file: string; args: string[] }> = []+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: (file: string, args: string[]) => {spawned.push({ file, args })diff --git a/src/core/pty-session-host.test.ts b/src/core/pty-session-host.test.tsnew file mode 100644index 000000000..b3835bd20--- /dev/null+++ b/src/core/pty-session-host.test.ts@@ -0,0 +1,934 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { IPC } from '../shared/ipc'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'++const backend = vi.hoisted(() => ({+ supported: vi.fn(() => true),+ create: vi.fn(),+ attachExisting: vi.fn(),+ capture: vi.fn(async () => ''),+ hasSession: vi.fn(async () => false),+ // Mirrors `sessionHostKillSession(name, options)`. The parameters are load-bearing even though+ // this default body ignores them: several tests assert on the options the caller passed, and a+ // zero-arg mock infers `() => Promise<void>`, which makes every one of those+ // `mockImplementationOnce((name, options) => …)` a type error.+ kill: vi.fn(+ async (+ _name: string,+ _options: {+ reserveReplacement?: boolean+ requireV2?: boolean+ expectedAbsent?: boolean+ } = {}+ ): Promise<void> => {}+ ),+ list: vi.fn(async () => []),+ paneCommand: vi.fn(async () => null),+ sendKeys: vi.fn(async () => false)+}))++vi.mock('./session-host-backend', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./session-host-backend')>()),+ sessionHostSupported: backend.supported,+ createSessionHostPty: backend.create,+ attachExistingSessionHostPty: backend.attachExisting,+ sessionHostCapture: backend.capture,+ sessionHostHasSession: backend.hasSession,+ sessionHostKillSession: backend.kill,+ sessionHostListSessions: backend.list,+ sessionHostPaneCommand: backend.paneCommand,+ sessionHostSendKeys: backend.sendKeys+}))++vi.mock('node-pty', () => ({+ spawn: vi.fn(() => {+ throw new Error('direct node-pty spawn must not run in the session-host suite')+ })+}))++vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++function fakeSessionHostPty(ready = Promise.resolve({ fresh: true })) {+ let dataCb: ((data: string) => void) | undefined+ let exitCb: ((e: { exitCode: number }) => void) | undefined+ let attachErrorCb: ((error: Error) => void) | undefined+ return {+ ready,+ onData: vi.fn((cb: (data: string) => void) => {+ dataCb = cb+ }),+ onExit: vi.fn((cb: (e: { exitCode: number }) => void) => {+ exitCb = cb+ }),+ onAttachError: vi.fn((cb: (error: Error) => void) => {+ attachErrorCb = cb+ }),+ emitData: (data: string) => dataCb?.(data),+ emitExit: (exitCode: number) => exitCb?.({ exitCode }),+ emitAttachError: (error: Error) => attachErrorCb?.(error),+ write: vi.fn(),+ resize: vi.fn(),+ pause: vi.fn(),+ resume: vi.fn(),+ kill: vi.fn(),+ destroy: vi.fn()+ }+}++describe('PtyManager session-host contracts', () => {+ let manager: import('./pty-manager').PtyManager | undefined+ let host: FakePlatform++ beforeEach(() => {+ host = fakePlatform()+ initPlatform(host)+ backend.supported.mockReturnValue(true)+ backend.create.mockReset().mockImplementation(() => fakeSessionHostPty())+ backend.attachExisting+ .mockReset()+ .mockImplementation(() => fakeSessionHostPty(Promise.resolve({ fresh: false })))+ backend.capture.mockReset().mockResolvedValue('')+ backend.hasSession.mockReset().mockResolvedValue(false)+ backend.kill.mockReset().mockResolvedValue(undefined)+ })++ afterEach(async () => {+ await manager?.killAll()+ manager = undefined+ resetPlatformForTests()+ vi.restoreAllMocks()+ })++ async function makeManager() {+ const { PtyManager } = await import('./pty-manager')+ manager = new PtyManager()+ return manager+ }++ it('asks the session host whether a no-tmux persisted session exists', async () => {+ const m = await makeManager()+ backend.hasSession.mockResolvedValue(true)++ await expect(m.sessionExists('node-a')).resolves.toBe(true)+ expect(backend.hasSession).toHaveBeenCalledWith('nt-node-a')+ })++ it('treats an unprobeable session host as possibly warm instead of cold-restoring on a guess', async () => {+ const m = await makeManager()+ backend.hasSession.mockRejectedValue(new Error('host connection unavailable'))++ await expect(m.sessionExists('node-a')).resolves.toBe(true)+ })++ it('captures a relay snapshot from the session host when tmux is absent', async () => {+ const m = await makeManager()+ backend.capture.mockResolvedValue('painted screen')++ await expect(m.captureSnapshot('node-a')).resolves.toBe('painted screen')+ expect(backend.capture).toHaveBeenCalledWith('nt-node-a', false)+ })++ it('passes the platform-resolved local shell into a session-host spawn', async () => {+ const m = await makeManager()+ m.createDetached({ cols: 80, rows: 24, persistKey: 'node-shell' }, { onData: () => {}, onExit: () => {} })++ expect(backend.create).toHaveBeenCalledTimes(1)+ const spawn = backend.create.mock.calls[0][1] as {+ shell: string+ args: string[]+ }+ if (process.platform === 'win32') {+ expect(spawn.shell).not.toBe('bash')+ expect(spawn.shell.toLowerCase()).toMatch(/(?:pwsh|powershell|cmd)(?:\.exe)?$/)+ } else {+ expect(spawn.shell).toBe(process.env.SHELL || 'bash')+ }+ expect(spawn.args).toEqual([])+ })++ it('fails a create closed, parks racing followers, and publishes only the recovered generation', async () => {+ let rejectReady!: (error: Error) => void+ const pendingReady = new Promise<{ fresh: boolean }>((_, reject) => {+ rejectReady = reject+ })+ const failed = fakeSessionHostPty(pendingReady)+ const recovered = fakeSessionHostPty()+ backend.create.mockImplementationOnce(() => failed).mockImplementationOnce(() => recovered)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-retry' }++ const first = create(7, options) as Promise<unknown>+ const firstFailure = expect(first).rejects.toThrow('attach refused after connect')+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(1))+ // Both followers arrive while the failed shim is indexed. They must wait for `ready`, not join+ // the provisional generation and receive a plausible session id whose writes disappear.+ const followerA = create(8, options) as Promise<unknown>+ const followerB = create(9, options) as Promise<unknown>+ failed.emitData('queued before the attach failure')+ rejectReady(new Error('attach refused after connect'))++ await firstFailure+ expect(failed.resume).not.toHaveBeenCalled()+ expect(failed.destroy).toHaveBeenCalledTimes(1)++ const [a, b] = (await Promise.all([followerA, followerB])) as Array<{+ sessionId: string+ fresh: boolean+ persistent: boolean+ }>+ expect(a.sessionId).toBe('pty-2')+ expect(b.sessionId).toBe('pty-2')+ expect([a.fresh, b.fresh].sort()).toEqual([false, true])+ expect(a.persistent).toBe(true)+ expect(b.persistent).toBe(true)+ expect(backend.create).toHaveBeenCalledTimes(2)++ // Rollback cancels queued bytes, and late callbacks from the discarded generation are inert.+ failed.emitData('late bytes')+ failed.emitExit(1)+ await new Promise((resolve) => setTimeout(resolve, 20))+ expect(host.sent.some((m) => m.channel === IPC.ptyData('pty-1'))).toBe(false)+ expect(host.sent.some((m) => m.channel === IPC.ptyExit('pty-1'))).toBe(false)+ })++ it('does not resolve the create as persistent until the provisional attach succeeds', async () => {+ let resolveReady!: (info: { fresh: boolean; screen?: string }) => void+ const pendingReady = new Promise<{ fresh: boolean; screen?: string }>((resolve) => {+ resolveReady = resolve+ })+ backend.create.mockReturnValue(fakeSessionHostPty(pendingReady))+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ let settled = false++ const resultPromise = (create(7, {+ cols: 80,+ rows: 24,+ persistKey: 'node-pending'+ }) as Promise<unknown>).then((result) => {+ settled = true+ return result+ })+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(1))+ await Promise.resolve()+ expect(settled).toBe(false)++ resolveReady({ fresh: false, screen: 'still alive' })+ await expect(resultPromise).resolves.toMatchObject({+ sessionId: 'pty-1',+ fresh: false,+ persistent: true,+ screen: 'still alive'+ })+ })++ it('keeps a deletion tombstone when its owner recovery attach fails', async () => {+ let rejectReady!: (error: Error) => void+ const pendingReady = new Promise<{ fresh: boolean }>((_, reject) => {+ rejectReady = reject+ })+ const failed = fakeSessionHostPty(pendingReady)+ backend.create.mockReturnValue(failed)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-protected' }++ // A confirmed delete leaves the owner able to recover, while other clients remain refused.+ await m.destroySession(7, 'node-protected')+ const ownerRecovery = create(7, options) as Promise<unknown>+ const recoveryFailure = expect(ownerRecovery).rejects.toThrow('recovery attach refused')+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(1))+ rejectReady(new Error('recovery attach refused'))+ await recoveryFailure++ await expect(create(8, options)).resolves.toEqual({+ sessionId: '',+ fresh: false,+ closed: { by: 7 }+ })+ expect(backend.create).toHaveBeenCalledTimes(1)+ })++ it('fences an exit-before-rejection generation until a retry confirms the destroy', async () => {+ const proc = fakeSessionHostPty()+ backend.create.mockReturnValue(proc)+ let rejectKill!: (error: Error) => void+ backend.kill.mockImplementationOnce(+ () =>+ new Promise<void>((_resolve, reject) => {+ rejectKill = reject+ })+ )+ const m = await makeManager()+ m.registerIpc()+ const ended = vi.fn()+ m.onSessionEnded(ended)+ const create = host.handlers[IPC.ptyCreate]+ const destroy = host.handlers[IPC.ptyDestroy]+ const options = { cols: 80, rows: 24, persistKey: 'node-kill-ack' }++ const first = (await create(7, options)) as { sessionId: string; fresh: boolean }+ const second = (await create(8, options)) as { sessionId: string; fresh: boolean }+ expect(second).toMatchObject({ sessionId: first.sessionId, fresh: false })++ const pendingDestroy = destroy(7, 'node-kill-ack') as Promise<void>+ const rejectedDestroy = expect(pendingDestroy).rejects.toThrow('kill acknowledgement lost')+ await vi.waitFor(() => expect(backend.kill).toHaveBeenCalledTimes(1))++ // A create arriving while the host result is unknown waits behind the end barrier. It must+ // neither join a session that may be dying nor spawn a replacement before the outcome lands.+ let followerSettled = false+ const follower = (create(9, options) as Promise<unknown>).finally(() => {+ followerSettled = true+ })+ const followerFailure = expect(follower).rejects.toThrow(+ 'session end outcome unknown; retry the close before reopening this node'+ )+ await Promise.resolve()+ expect(followerSettled).toBe(false)+ expect(backend.create).toHaveBeenCalledTimes(1)++ // The host may have acted and emitted exit before its correlated reply is lost. Exit is not a+ // kill acknowledgement: allowing the waiting create to spawn here resurrects an unknown delete.+ proc.emitExit(0)+ rejectKill(new Error('kill acknowledgement lost'))+ await rejectedDestroy+ await followerFailure++ // Nothing local claimed a confirmed close, and no replacement generation was spawned. The+ // exact same idempotent destroy remains available to establish absence.+ expect(backend.create).toHaveBeenCalledTimes(1)+ expect(proc.destroy).not.toHaveBeenCalled()+ expect(host.sent.some((message) => message.channel === IPC.ptyClosed(first.sessionId))).toBe(false)+ expect(ended).not.toHaveBeenCalled()++ backend.kill.mockResolvedValueOnce(undefined)+ await expect(destroy(7, 'node-kill-ack')).resolves.toBeUndefined()+ expect(backend.kill).toHaveBeenCalledTimes(2)+ expect(ended).toHaveBeenCalledWith('node-kill-ack')+ await expect(create(9, options)).resolves.toEqual({+ sessionId: '',+ fresh: false,+ closed: { by: 7 }+ })+ })++ it('contains a failed legacy destroy cast without local teardown or an unhandled rejection', async () => {+ const proc = fakeSessionHostPty()+ backend.create.mockReturnValue(proc)+ backend.kill.mockRejectedValueOnce(new Error('legacy reply path unavailable'))+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const m = await makeManager()+ m.registerIpc()+ const ended = vi.fn()+ m.onSessionEnded(ended)+ const created = (await host.handlers[IPC.ptyCreate](7, {+ cols: 80,+ rows: 24,+ persistKey: 'legacy-node'+ })) as { sessionId: string }++ host.senderListeners[IPC.ptyDestroy](7, 'legacy-node')+ await vi.waitFor(() => expect(backend.kill).toHaveBeenCalledTimes(1))+ await vi.waitFor(() => expect(warn).toHaveBeenCalled())++ expect(proc.destroy).not.toHaveBeenCalled()+ expect(ended).not.toHaveBeenCalled()+ expect(host.sent.some((message) => message.channel === IPC.ptyClosed(created.sessionId))).toBe(false)+ })++ it('rejects recycle before changing local generation state when the host kill fails', async () => {+ const proc = fakeSessionHostPty()+ backend.create.mockReturnValue(proc)+ backend.kill.mockRejectedValueOnce(new Error('recycle outcome unknown'))+ const m = await makeManager()+ m.registerIpc()+ const ended = vi.fn()+ m.onSessionEnded(ended)+ const created = (await host.handlers[IPC.ptyCreate](7, {+ cols: 80,+ rows: 24,+ persistKey: 'recycle-node'+ })) as { sessionId: string }++ await expect(host.handlers[IPC.ptyRecycle](7, 'recycle-node')).rejects.toThrow(+ 'recycle outcome unknown'+ )+ expect(proc.destroy).not.toHaveBeenCalled()+ expect(ended).not.toHaveBeenCalled()+ expect(host.sent.some((message) => message.channel === IPC.ptyRecycled(created.sessionId))).toBe(false)+ })++ it('kills a live host-owned session even if tmux becomes available later', async () => {+ const proc = fakeSessionHostPty()+ backend.create.mockReturnValue(proc)+ const m = await makeManager()+ m.registerIpc()+ await host.handlers[IPC.ptyCreate](7, {+ cols: 80,+ rows: 24,+ persistKey: 'host-before-tmux'+ })+ ;(m as unknown as { tmuxPath: string }).tmuxPath = 'missing-test-tmux'++ await expect(host.handlers[IPC.ptyDestroy](7, 'host-before-tmux')).resolves.toBeUndefined()+ expect(backend.kill).toHaveBeenCalledWith('nt-host-before-tmux')+ expect(proc.destroy).toHaveBeenCalledTimes(1)+ })++ it('does not route an unheld tmux-session delete through the session host', async () => {+ const m = await makeManager()+ ;(m as unknown as { tmuxPath: string }).tmuxPath = 'missing-test-tmux'++ await expect(m.destroySession(7, 'tmux-orphan')).resolves.toBeUndefined()+ expect(backend.kill).not.toHaveBeenCalled()+ })++ it('does not publish a session that exits in the same turn its ready resolves', async () => {+ let resolveReady!: (info: { fresh: boolean }) => void+ const pendingReady = new Promise<{ fresh: boolean }>((resolve) => {+ resolveReady = resolve+ })+ const exited = fakeSessionHostPty(pendingReady)+ backend.create.mockReturnValue(exited)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]++ const result = create(7, {+ cols: 80,+ rows: 24,+ persistKey: 'node-exited-during-attach'+ }) as Promise<unknown>+ // This suite mocks './session-host-backend', so the create path exercised here is+ // pty-manager.ts's own ready-vs-exit race (the message below is its literal text, line+ // ~1998) — not session-host-client.ts's SessionHostPty class, which is a different,+ // unmocked implementation this harness never reaches. Matches the sibling test "rejects a+ // create whose provisional generation exits before ready resolves" below.+ const failure = expect(result).rejects.toThrow('exited before it became ready')+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(1))+ resolveReady({ fresh: true })+ exited.emitExit(0)++ await failure+ })++ it('retires a detached session-host shim and signals its sink when ready rejects', async () => {+ let rejectReady!: (error: Error) => void+ const pendingReady = new Promise<{ fresh: boolean }>((_, reject) => {+ rejectReady = reject+ })+ const failed = fakeSessionHostPty(pendingReady)+ backend.create.mockReturnValue(failed)+ const m = await makeManager()+ const onData = vi.fn()+ const onExit = vi.fn()++ expect(+ m.createDetached(+ { cols: 80, rows: 24, persistKey: 'relay-node' },+ { onData, onExit }+ )+ ).toBe('pty-1')+ rejectReady(new Error('relay attach failed'))+ await vi.waitFor(() => expect(failed.destroy).toHaveBeenCalledTimes(1))++ expect(onExit).toHaveBeenCalledWith(1)+ failed.emitData('late relay bytes')+ failed.emitExit(9)+ expect(onData).not.toHaveBeenCalled()+ expect(onExit).toHaveBeenCalledTimes(1)+ })++ it('treats confirmed absence as recovered while invalid, uncertain, and rate-limited requests reject', async () => {+ const m = await makeManager()+ backend.supported.mockReturnValue(true)++ await expect(m.recycleSessionFromClient(7, '')).rejects.toThrow('invalid node id')+ expect(backend.kill).not.toHaveBeenCalled()++ backend.hasSession.mockResolvedValue(false)+ await expect(m.recycleSessionFromClient(7, 'node-missing')).resolves.toBeUndefined()+ expect(backend.kill).toHaveBeenCalledWith('nt-node-missing', {+ reserveReplacement: true,+ requireV2: true,+ expectedAbsent: true+ })+ backend.kill.mockClear()++ backend.hasSession.mockRejectedValueOnce(new Error('host probe unavailable'))+ await expect(m.recycleSessionFromClient(7, 'node-uncertain')).rejects.toThrow(+ 'Could not confirm the terminal session'+ )+ expect(backend.kill).not.toHaveBeenCalled()++ const { PTY_END_BUDGET } = await import('./pty-manager')+ backend.hasSession.mockResolvedValue(true)+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-08-16T00:00:00Z'))+ try {+ for (let i = 0; i < PTY_END_BUDGET.burst; i += 1)+ await m.recycleSessionFromClient(8, 'node-budget')+ await expect(m.recycleSessionFromClient(8, 'node-budget')).rejects.toThrow(+ 'Too many terminal restart requests'+ )+ expect(backend.kill).toHaveBeenCalledTimes(PTY_END_BUDGET.burst)+ } finally {+ vi.useRealTimers()+ }+ })++ it('binds an honestly absent host reservation to expected absence', async () => {+ const m = await makeManager()+ backend.hasSession.mockResolvedValueOnce(false).mockResolvedValue(true)+ backend.kill.mockImplementationOnce(async (_name, options) => {+ expect(options).toEqual({+ reserveReplacement: true,+ requireV2: true,+ expectedAbsent: true+ })+ throw new Error('another client created the name before reservation')+ })++ await expect(m.recycleSessionFromClient(7, 'node-absence-race')).rejects.toThrow(+ 'another client created the name before reservation'+ )+ expect(backend.kill).toHaveBeenCalledTimes(1)+ })++ it('requires protocol v2 for a confirmed host teardown even when the replacement is direct', async () => {+ const active = fakeSessionHostPty()+ backend.create.mockReturnValue(active)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-v1-direct-target' }+ await create(7, options)+ m.init(() => ({+ tmuxEnabled: false+ }) as never)+ backend.hasSession.mockResolvedValue(true)+ const { SessionHostProtocolCompatibilityError } = await import('./session-host-backend')+ backend.kill.mockImplementationOnce(async (_name, killOptions) => {+ if (killOptions?.requireV2)+ throw new SessionHostProtocolCompatibilityError('restart this terminal')+ active.emitExit(0)+ })++ await expect(m.recycleSessionFromClient(7, options.persistKey)).rejects.toBeInstanceOf(+ SessionHostProtocolCompatibilityError+ )+ expect(backend.kill).toHaveBeenCalledWith('nt-node-v1-direct-target', {+ reserveReplacement: false,+ requireV2: true+ })+ await expect(create(8, options)).resolves.toMatchObject({ sessionId: 'pty-1', fresh: false })+ expect(backend.create).toHaveBeenCalledTimes(1)+ })++ it('leaves the live generation joinable when the confirmed backend kill rejects', async () => {+ const active = fakeSessionHostPty()+ backend.create.mockReturnValue(active)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-kill-reject' }++ await expect(create(7, options)).resolves.toMatchObject({+ sessionId: 'pty-1',+ persistent: true+ })+ backend.kill.mockImplementationOnce(async () => {+ throw new Error('kill acknowledgement lost')+ })+ backend.hasSession.mockResolvedValue(true)++ await expect(m.recycleSessionFromClient(7, options.persistKey)).rejects.toThrow(+ 'kill acknowledgement lost'+ )+ expect(active.resume).not.toHaveBeenCalled()+ expect(active.kill).not.toHaveBeenCalled()+ expect(active.destroy).not.toHaveBeenCalled()++ // The original index and subscriber ledger remain intact: another client joins the same+ // generation, and no replacement host attach is attempted.+ await expect(create(8, options)).resolves.toMatchObject({+ sessionId: 'pty-1',+ fresh: false,+ persistent: true+ })+ expect(backend.create).toHaveBeenCalledTimes(1)+ })++ it('commits an exact early exit when the host response is lost and preserves the replacement lease', async () => {+ const active = fakeSessionHostPty()+ const replacement = fakeSessionHostPty()+ backend.create.mockImplementationOnce(() => active).mockImplementationOnce(() => replacement)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-exit-then-reject' }++ await create(7, options)+ backend.kill.mockImplementationOnce(async () => {+ // This is the real host order: exit broadcast first, then a response that may be lost.+ active.emitExit(23)+ throw new Error('kill response lost after exit')+ })++ await expect(m.recycleSessionFromClient(7, options.persistKey)).resolves.toBeUndefined()+ expect(backend.kill).toHaveBeenNthCalledWith(2, 'nt-node-exit-then-reject', {+ reserveReplacement: true,+ requireV2: true+ })+ expect(+ host.sent.some(+ (message) =>+ message.channel === IPC.ptyExit('pty-1') && message.args[0] === 23+ )+ ).toBe(false)+ expect(host.sent.some((message) => message.channel === IPC.ptyRecycled('pty-1'))).toBe(false)++ // The committed transaction reserved replacement creation for its primary owner. Its create+ // establishes the fresh generation; no ordinary exit/rejected-switch path intervenes.+ await expect(create(7, options)).resolves.toMatchObject({ sessionId: 'pty-2', fresh: true })+ expect(backend.create).toHaveBeenCalledTimes(2)+ })++ it('does not retain a replacement lease for generic node deletion', async () => {+ const active = fakeSessionHostPty()+ backend.create.mockReturnValue(active)+ const m = await makeManager()+ m.registerIpc()+ const options = { cols: 80, rows: 24, persistKey: 'node-generic-delete' }+ await host.handlers[IPC.ptyCreate](7, options)+ backend.kill.mockClear()++ await m.destroySession(7, options.persistKey)++ expect(backend.kill).toHaveBeenCalledTimes(1)+ expect(backend.kill.mock.calls[0]).toEqual(['nt-node-generic-delete'])+ })++ it('waits for backend kill acknowledgement before cleaning the confirmed generation', async () => {+ const order: string[] = []+ const active = fakeSessionHostPty()+ const replacement = fakeSessionHostPty()+ active.resume.mockImplementation(() => order.push('cleanup-resume'))+ active.destroy.mockImplementation(() => order.push('cleanup-destroy'))+ backend.create.mockImplementationOnce(() => active).mockImplementationOnce(() => replacement)+ backend.kill.mockImplementationOnce(async () => {+ order.push('host-exit')+ active.emitExit(0)+ order.push('kill-ack')+ })+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-kill-order' }++ await create(7, options)+ await create(8, options)+ await m.recycleSessionFromClient(7, options.persistKey)++ expect(order).toEqual(['host-exit', 'kill-ack', 'cleanup-resume', 'cleanup-destroy'])+ expect(host.sent.some((message) => message.channel === IPC.ptyExit('pty-1'))).toBe(false)++ // The co-viewer's subscriber ledger survived until the acknowledged cleanup, so registering+ // the replacement releases it through the recycle event rather than losing it to early exit.+ await create(7, options)+ expect(+ host.sent.some((message) => message.channel === IPC.ptyRecycled('pty-1'))+ ).toBe(true)+ })++ it('rejects a create whose provisional generation exits before ready resolves', async () => {+ let resolveReady!: (info: { fresh: boolean }) => void+ const pendingReady = new Promise<{ fresh: boolean }>((resolve) => {+ resolveReady = resolve+ })+ const exited = fakeSessionHostPty(pendingReady)+ const replacement = fakeSessionHostPty()+ backend.create.mockImplementationOnce(() => exited).mockImplementationOnce(() => replacement)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-exit-before-ready' }++ const first = create(7, options) as Promise<unknown>+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(1))+ exited.emitExit(17)+ resolveReady({ fresh: true })++ await expect(first).rejects.toThrow('exited before it became ready')+ expect(+ host.sent.some(+ (message) => message.channel === IPC.ptyExit('pty-1') && message.args[0] === 17+ )+ ).toBe(true)+ await expect(create(8, options)).resolves.toMatchObject({ sessionId: 'pty-2', fresh: true })+ })++ it('retains a deletion tombstone when the owner recovery attach rejects', async () => {+ const original = fakeSessionHostPty()+ let rejectRecovery!: (error: Error) => void+ const recoveryReady = new Promise<{ fresh: boolean }>((_, reject) => {+ rejectRecovery = reject+ })+ const failedRecovery = fakeSessionHostPty(recoveryReady)+ const forbiddenFollower = fakeSessionHostPty()+ backend.create+ .mockImplementationOnce(() => original)+ .mockImplementationOnce(() => failedRecovery)+ .mockImplementationOnce(() => forbiddenFollower)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-deleted-recovery' }++ await create(7, options)+ await m.destroySession(7, options.persistKey)+ const ownerRecovery = create(7, options) as Promise<unknown>+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(2))+ const follower = create(8, options) as Promise<unknown>+ rejectRecovery(new Error('recovery attach refused'))++ await expect(ownerRecovery).rejects.toThrow('recovery attach refused')+ await expect(follower).resolves.toMatchObject({+ sessionId: '',+ fresh: false,+ closed: { by: 7 }+ })+ expect(backend.create).toHaveBeenCalledTimes(2)+ })++ it('retires only the exact generation when reconnect replay is rejected', async () => {+ const original = fakeSessionHostPty()+ const replacement = fakeSessionHostPty()+ backend.create.mockImplementationOnce(() => original).mockImplementationOnce(() => replacement)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-replay-reject' }++ await create(7, options)+ original.emitAttachError(new Error("no existing session 'nt-node-replay-reject'"))+ expect(+ host.sent.some(+ (message) => message.channel === IPC.ptyExit('pty-1') && message.args[0] === 1+ )+ ).toBe(true)+ await expect(create(7, options)).resolves.toMatchObject({ sessionId: 'pty-2', fresh: true })++ // A delayed duplicate callback from the retired shim cannot forget the replacement.+ original.emitAttachError(new Error('late replay failure'))+ await expect(create(8, options)).resolves.toMatchObject({ sessionId: 'pty-2', fresh: false })+ expect(backend.create).toHaveBeenCalledTimes(2)+ })++ it('reserves a recycled replacement for its owner and releases parked co-viewers on failure', async () => {+ const original = fakeSessionHostPty()+ let rejectReplacement!: (error: Error) => void+ const replacementReady = new Promise<{ fresh: boolean }>((_, reject) => {+ rejectReplacement = reject+ })+ const failedReplacement = fakeSessionHostPty(replacementReady)+ backend.create+ .mockImplementationOnce(() => original)+ .mockImplementationOnce(() => failedReplacement)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-owner-reservation' }++ await create(7, options)+ await create(8, options)+ await m.recycleSessionFromClient(7, options.persistKey)+ const parkedFollower = create(8, options) as Promise<unknown>+ const ownerReplacement = create(7, options) as Promise<unknown>+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(2))+ rejectReplacement(new Error('selected replacement failed'))++ await expect(ownerReplacement).rejects.toThrow('selected replacement failed')+ await expect(parkedFollower).rejects.toThrow('replacement terminal did not become ready')+ expect(backend.create).toHaveBeenCalledTimes(2)+ expect(+ host.sent.some(+ (message) =>+ message.to === 8 &&+ message.channel === IPC.ptyRecycled('pty-1') &&+ (message.args[0] as { ready: boolean }).ready === false+ )+ ).toBe(true)+ })++ it('reserves a solo session replacement from an inactive co-viewer', async () => {+ const original = fakeSessionHostPty()+ let rejectReplacement!: (error: Error) => void+ const replacementReady = new Promise<{ fresh: boolean }>((_, reject) => {+ rejectReplacement = reject+ })+ backend.create+ .mockImplementationOnce(() => original)+ .mockImplementationOnce(() => fakeSessionHostPty(replacementReady))+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-solo-reservation' }+ await create(7, options)+ await m.recycleSessionFromClient(7, options.persistKey)++ const inactiveViewer = create(9, options) as Promise<unknown>+ const owner = create(7, options) as Promise<unknown>+ await vi.waitFor(() => expect(backend.create).toHaveBeenCalledTimes(2))+ rejectReplacement(new Error('owner replacement rejected'))++ await expect(owner).rejects.toThrow('owner replacement rejected')+ await expect(inactiveViewer).rejects.toThrow('replacement terminal did not become ready')+ expect(backend.create).toHaveBeenCalledTimes(2)+ })++ it('parks a same-client modal behind the primary replacement owner', async () => {+ const original = fakeSessionHostPty()+ const replacement = fakeSessionHostPty()+ backend.create.mockImplementationOnce(() => original).mockImplementationOnce(() => replacement)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-primary-view-owner' }++ await create(7, options)+ await m.recycleSessionFromClient(7, options.persistKey)++ let modalSettled = false+ const modal = (create(7, { ...options, viewerId: 'kanban-modal' }) as Promise<unknown>).then(+ (result) => {+ modalSettled = true+ return result+ }+ )+ await Promise.resolve()+ expect(modalSettled).toBe(false)+ expect(backend.create).toHaveBeenCalledTimes(1)++ await expect(create(7, options)).resolves.toMatchObject({ sessionId: 'pty-2', fresh: true })+ await expect(modal).resolves.toMatchObject({ sessionId: 'pty-2', fresh: false })+ expect(backend.create).toHaveBeenCalledTimes(2)+ })++ it('reserves an honestly absent session until the owner establishes its replacement', async () => {+ backend.hasSession.mockResolvedValue(false)+ backend.create.mockReturnValue(fakeSessionHostPty())+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-absent-reservation' }++ await expect(m.recycleSessionFromClient(7, options.persistKey)).resolves.toBeUndefined()+ const inactiveViewer = create(9, options) as Promise<unknown>+ const owner = create(7, options) as Promise<unknown>++ await expect(owner).resolves.toMatchObject({ sessionId: 'pty-1', fresh: true })+ await expect(inactiveViewer).resolves.toMatchObject({ sessionId: 'pty-1', fresh: false })+ expect(backend.create).toHaveBeenCalledTimes(1)+ })++ it('rejects a duplicate confirmed recycle while the first kill is in flight', async () => {+ let acknowledgeKill!: () => void+ const killPending = new Promise<void>((resolve) => {+ acknowledgeKill = resolve+ })+ backend.kill.mockReturnValue(killPending)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-double-recycle' }+ await create(7, options)++ const first = m.recycleSessionFromClient(7, options.persistKey)+ await vi.waitFor(() => expect(backend.kill).toHaveBeenCalledTimes(1))+ await expect(m.recycleSessionFromClient(7, options.persistKey)).rejects.toThrow(+ 'already restarting'+ )+ acknowledgeKill()+ await expect(first).resolves.toBeUndefined()+ expect(backend.kill).toHaveBeenCalledTimes(1)+ })++ it('rejects parked create waiters when the manager shuts down', async () => {+ const original = fakeSessionHostPty()+ backend.create.mockReturnValue(original)+ const m = await makeManager()+ m.registerIpc()+ const create = host.handlers[IPC.ptyCreate]+ const options = { cols: 80, rows: 24, persistKey: 'node-shutdown-waiter' }+ await create(7, options)+ await create(8, options)+ await m.recycleSessionFromClient(7, options.persistKey)+ const parked = create(8, options) as Promise<unknown>++ await m.killAll()+ await expect(parked).rejects.toThrow('shut down before the replacement became ready')+ })+})++describe('resolveLocalSessionShell', () => {+ it('uses the Windows resolver when both explicit and configured shells are empty', async () => {+ const { resolveLocalSessionShell } = await import('./pty-manager')+ const windowsShell = vi.fn(() => String.raw`C:\Windows\System32\cmd.exe`)++ expect(+ resolveLocalSessionShell(undefined, '', {+ platform: 'win32',+ windowsShell,+ posixShell: '/bin/should-not-win'+ })+ ).toBe(String.raw`C:\Windows\System32\cmd.exe`)+ expect(windowsShell).toHaveBeenCalledTimes(1)+ })++ it('keeps an explicit program above a configured shell and every platform fallback', async () => {+ const { resolveLocalSessionShell } = await import('./pty-manager')+ const windowsShell = vi.fn(() => 'cmd.exe')++ expect(+ resolveLocalSessionShell('/opt/custom-shell', '/bin/configured', {+ platform: 'win32',+ windowsShell+ })+ ).toBe('/opt/custom-shell')+ expect(windowsShell).not.toHaveBeenCalled()+ })++ it('keeps a configured compatibility shell above platform fallback', async () => {+ const { resolveLocalSessionShell } = await import('./pty-manager')+ const windowsShell = vi.fn(() => 'cmd.exe')++ expect(+ resolveLocalSessionShell(undefined, String.raw`C:\Tools\My Shell\shell.exe`, {+ platform: 'win32',+ windowsShell+ })+ ).toBe(String.raw`C:\Tools\My Shell\shell.exe`)+ expect(windowsShell).not.toHaveBeenCalled()+ })++ it('uses the POSIX shell, then bash, outside Windows', async () => {+ const { resolveLocalSessionShell } = await import('./pty-manager')++ expect(+ resolveLocalSessionShell(undefined, '', { platform: 'linux', posixShell: '/bin/zsh' })+ ).toBe('/bin/zsh')+ expect(resolveLocalSessionShell(undefined, '', { platform: 'linux', posixShell: '' })).toBe(+ 'bash'+ )+ })+})diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.tsindex f1fa4a31e..c519cc411 100644--- a/src/core/pty-shadow.test.ts+++ b/src/core/pty-shadow.test.ts@@ -36,6 +36,14 @@ const spawned: FakePty[] = []/** Spawn/dispose events across BOTH child kinds, so a test can assert their relative ORDER. */const log: string[] = []+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: () => {const p: FakePty = { killed: false }diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.tsindex cca1c3ccd..2ea5a4523 100644--- a/src/core/pty-single-user.test.ts+++ b/src/core/pty-single-user.test.ts@@ -40,6 +40,14 @@ const spawnArgs: Array<{env: Record<string, string>}> = []+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: (file: string,@@ -600,7 +608,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =// must reach `endSession`, which is the half a `destroySession`-only test cannot see.it('honours everySocket off the wire, and only for a literal true', async () => {await tmuxManager()- await (fake.senderListeners[IPC.ptyDestroy](+ await (fake.handlers[IPC.ptyDestroy](SOLO,'never-opened-here',true@@ -610,7 +618,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () ='nodeterm-rmt'])execCalls.length = 0- await (fake.senderListeners[IPC.ptyDestroy](+ await (fake.handlers[IPC.ptyDestroy](SOLO,'never-opened-2','yes' as unknown as boolean@@ -628,7 +636,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =await tmuxManager()const { sessionId } = await create(80, 24)fake.sent.length = 0- await (fake.senderListeners[IPC.ptyRecycle](SOLO, 'solo-1') as unknown as Promise<void>)+ await (fake.handlers[IPC.ptyRecycle](SOLO, 'solo-1') as unknown as Promise<void>)const kills = tmuxCalls('kill-session')expect(kills).toHaveLength(1) // we hold the session; one socket, one killdiff --git a/src/core/pty-spawn-diagnosis.test.ts b/src/core/pty-spawn-diagnosis.test.tsindex 892016146..3b2b464b5 100644--- a/src/core/pty-spawn-diagnosis.test.ts+++ b/src/core/pty-spawn-diagnosis.test.ts@@ -27,6 +27,14 @@ import type { PtyDevices } from './pty-devices'* still produce a passing, and identical, message.*/const attempts = vi.hoisted(() => ({ n: 0 }))+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: () => {attempts.n++diff --git a/src/core/pty-spawn-preflight.test.ts b/src/core/pty-spawn-preflight.test.tsindex 7fc6f8dc3..e8f374fe8 100644--- a/src/core/pty-spawn-preflight.test.ts+++ b/src/core/pty-spawn-preflight.test.ts@@ -30,6 +30,14 @@ import type { PtyCreateResult } from '../shared/types'*/const spawned: Array<{ file: string }> = []const nodePty = vi.hoisted(() => ({ throws: false }))+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: (file: string) => {spawned.push({ file })diff --git a/src/core/pty-typing.test.ts b/src/core/pty-typing.test.tsindex f6b8852e2..d84c782e8 100644--- a/src/core/pty-typing.test.ts+++ b/src/core/pty-typing.test.ts@@ -13,6 +13,14 @@ import { fakePlatform, type FakePlatform } from './platform-fake'import { presenceHub } from './presence/hub'import { IPC } from '../shared/ipc'+// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({spawn: () => ({onData: () => {},diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.tsnew file mode 100644index 000000000..7837ca413--- /dev/null+++ b/src/core/session-host-backend.ts@@ -0,0 +1,123 @@+// The thin facade `pty-manager.ts` talks to — owns the ONE process-wide `SessionHostClient` (one+// long-lived connection per app process, matching how `PtyManager` itself keeps one `tmuxPath`+// for the whole process) and exposes exactly the operations pty-manager's existing tmux/ssh call+// 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 { platform } from './platform'+import {+ SessionHostClient,+ SessionHostProtocolCompatibilityError+} from './session-host-client'+import { SessionHostPty } from './session-host-pty'+import type { ExecuteLaunchResult, SessionHostSpawnOptions } from '../session-host/protocol'+import type { PreparedAgentLaunch } from './agent-launch'++let client: SessionHostClient | null = null++function getClient(): SessionHostClient {+ if (!client) {+ client = new SessionHostClient({+ userDataDir: platform().userDataDir,+ resourcesPath: platform().resourcesPath,+ // 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()+ })+ }+ return client+}++/**+ * Is the session-host bundle actually present on this machine? False only in a dev checkout that+ * never ran `npm run host:build` (or `npm run build`, which now runs it too) — unlike tmux, this+ * backend has no external binary to be "missing"; the only way it can be unavailable is an+ * incomplete build. `pty-manager.ts` combines this with "no local tmux was found" and the+ * `tmuxEnabled` setting to decide whether to actually select this backend for a given session.+ */+export function sessionHostSupported(): boolean {+ try {+ return getClient().bundleAvailable()+ } catch {+ // platform() throws before initPlatform() runs at boot — no real caller reaches this before+ // then, but fail closed (never select an unusable backend) rather than throw from a probe.+ return false+ }+}++/** Construct a (lazily-attaching) session-host-backed pty for `name`. Cast at the call site to+ * `pty.IPty` — see `SessionHostPty`'s own doc comment for exactly what subset it implements. */+export function createSessionHostPty(+ name: string,+ spawn: SessionHostSpawnOptions,+ scrollback: number+): SessionHostPty {+ return new SessionHostPty(getClient(), name, spawn, scrollback)+}++/** Atomically attach to an already-running host session without resolving or transmitting any+ * spawn profile. If the session exits before this reaches the host, `ready` rejects and no shell+ * is created. This is the warm cross-process path used before profile/cwd resolution. */+export function attachExistingSessionHostPty(name: string): SessionHostPty {+ return new SessionHostPty(getClient(), name, null, 0)+}++/** Background write — works whether or not this process currently has a live client for `name`,+ * exactly like `sendText`'s tmux `send-keys -t <name>` needs no attached client. */+export async function sessionHostSendKeys(name: string, text: string, enter: boolean): Promise<boolean> {+ return getClient().sendKeys(name, text, enter)+}++/** `#{pane_current_command}`'s equivalent — see `process-tree.ts`'s doc comment for the+ * imprecision this carries versus tmux's real foreground-process-group tracking. */+export async function sessionHostPaneCommand(name: string): Promise<string | null> {+ return getClient().paneCommand(name)+}++/** `capture-pane` equivalent. `full` mirrors `captureSession`'s own `full` parameter: false asks+ * for the recent ~200 lines only (AI naming / palette search), true asks for everything the+ * emulator is holding (bounded by `settings.tmuxScrollback`, exactly like tmux's own+ * `history-limit`). Includes full SGR/mode restoration — see `TerminalEmulator.serialize`. */+export async function sessionHostCapture(name: string, full: boolean): Promise<string> {+ return getClient().capture(name, full)+}++/** Execute already-rendered trusted input through the persistent generation's exactly-once+ * launch ledger. The plan never crosses preload/renderer/relay boundaries. */+export async function sessionHostExecuteLaunch(+ name: string,+ launchId: string,+ plan: PreparedAgentLaunch+): Promise<ExecuteLaunchResult> {+ return getClient().executeLaunch(name, launchId, plan)+}++/** The one call that actually ENDS a session (as opposed to `SessionHostPty.kill()`, which only+ * detaches). Mirrors `tmux kill-session -t <name>` exactly, and is called from the same place+ * (`destroySession`'s final kill block). */+export async function sessionHostKillSession(+ name: string,+ options: {+ reserveReplacement?: boolean+ requireV2?: boolean+ expectedAbsent?: boolean+ } = {}+): Promise<void> {+ return getClient().killSession(name, options)+}++export { SessionHostProtocolCompatibilityError }++/** `tmux has-session`'s equivalent — currently unused by the create path (which gets `fresh`+ * straight from the real attach-or-create round trip instead, via `SessionHostPty.ready`) but+ * kept for parity/diagnostics and any future caller that wants a cheap existence check without+ * actually attaching. */+export async function sessionHostHasSession(name: string): Promise<boolean> {+ return getClient().hasSession(name)+}++/** `tmux -L <socket> list-sessions`'s equivalent, for the same class of caller+ * (`listNodetermSessions` — the relay host's session browser). */+export async function sessionHostListSessions(): Promise<string[]> {+ return getClient().listSessions()+}diff --git a/src/core/session-host-client-flow.test.ts b/src/core/session-host-client-flow.test.tsnew file mode 100644index 000000000..6db6099a2--- /dev/null+++ b/src/core/session-host-client-flow.test.ts@@ -0,0 +1,1133 @@+import fs from 'fs'+import net from 'net'+import os from 'os'+import path from 'path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { sessionHostPaths } from '../session-host/paths'+import {+ SESSION_HOST_PROTOCOL_VERSION,+ LineFramer,+ encodeFrame,+ type SessionHostRequest,+ type SessionHostSpawnOptions+} from '../session-host/protocol'+import { SessionHostClient } from './session-host-client'+import { SessionHostPty } from './session-host-pty'++const openServers = new Set<net.Server>()+const openSockets = new Set<net.Socket>()+const tempDirs = new Set<string>()+const livePtys = new Set<SessionHostPty>()++interface Deferred<T> {+ promise: Promise<T>+ resolve(value: T): void+ reject(error: unknown): void+}++function deferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void+ let reject!: (error: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}++function within<T>(promise: Promise<T>, label: string, ms = 2_500): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`${label} did not finish within ${ms}ms`)), ms)+ promise.then(+ (value) => {+ clearTimeout(timer)+ resolve(value)+ },+ (error) => {+ clearTimeout(timer)+ reject(error)+ }+ )+ })+}++function eventLoopTurn(): Promise<void> {+ return new Promise((resolve) => setImmediate(resolve))+}++function fixture(prefix: string): { userDataDir: string; endpoint: string } {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ fs.writeFileSync(paths.tokenPath, 'a'.repeat(64))+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: process.pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: Date.now(),+ // These fixtures must model a CURRENT host: the flows here create terminals, and creation is+ // a v2-only operation the client rightly refuses against a legacy host. So the published+ // version, the advertised hello version and the per-attach `generation` all have to agree —+ // a fake host that publishes 2 while answering like a v1 host is inconsistent, not legacy.+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ )+ return { userDataDir, endpoint: paths.endpoint }+}++function spawnOptions(+ userDataDir: string,+ cols: number,+ rows: number,+ args: string[] = []+): SessionHostSpawnOptions {+ return {+ cwd: userDataDir,+ shell: process.execPath,+ args,+ env: {},+ cols,+ rows+ }+}++function trackSocket(socket: net.Socket): void {+ openSockets.add(socket)+ socket.once('close', () => openSockets.delete(socket))+}++function sessionPty(+ client: SessionHostClient,+ name: string,+ spawn: SessionHostSpawnOptions,+ scrollback: number+): SessionHostPty {+ const pty = new SessionHostPty(client, name, spawn, scrollback)+ livePtys.add(pty)+ return pty+}++async function listen(server: net.Server, endpoint: string): Promise<void> {+ openServers.add(server)+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+}++afterEach(async () => {+ for (const pty of livePtys) pty.destroy()+ livePtys.clear()+ // Let synchronous unsubscribe bookkeeping cancel every idle reconnect timer before its socket+ // is torn down by the harness. A failed assertion must not leak a client into the next Chut.+ await eventLoopTurn()+ for (const socket of openSockets) socket.destroy()+ openSockets.clear()+ await Promise.all(+ [...openServers].map(+ (server) =>+ new Promise<void>((resolve) => {+ if (!server.listening) {+ resolve()+ return+ }+ server.close(() => resolve())+ })+ )+ )+ openServers.clear()+ for (const dir of tempDirs) {+ const endpoint = sessionHostPaths(dir).endpoint+ if (process.platform !== 'win32') fs.rmSync(endpoint, { force: true })+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+ }+ tempDirs.clear()+})++describe('SessionHostClient subscriber flow and reconnect barriers', () => {+ it('holds one host pause ticket until the last exact local owner resumes or unsubscribes', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-owner-')+ const flowCommands: Array<'pause' | 'resume' | 'detach'> = []+ const firstPause = deferred<void>()+ const firstResume = deferred<void>()+ const secondPause = deferred<void>()+ const secondResume = deferred<void>()+ const detached = deferred<void>()+ const ownerBoundaryResize = deferred<void>()+ const unsubscribeBoundaryResize = deferred<void>()+ let pauseCount = 0+ let resumeCount = 0++ const server = net.createServer((socket) => {+ trackSocket(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else if (request.cmd === 'attachExisting') {+ // The second local subscriber co-attaches to the same already-live generation, so the+ // client sends `attachExisting` (warm, no spawn plan) rather than a second `attach`.+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false, generation: 'flow-generation' } }))+ } else if (request.cmd === 'pause') {+ flowCommands.push('pause')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ pauseCount+++ if (pauseCount === 1) firstPause.resolve()+ if (pauseCount === 2) secondPause.resolve()+ } else if (request.cmd === 'resume') {+ flowCommands.push('resume')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ resumeCount+++ if (resumeCount === 1) firstResume.resolve()+ if (resumeCount === 2) secondResume.resolve()+ } else if (request.cmd === 'detach') {+ flowCommands.push('detach')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ detached.resolve()+ } else if (request.cmd === 'resize') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ if (request.cols === 79 && request.rows === 23) ownerBoundaryResize.resolve()+ if (request.cols === 78 && request.rows === 22) unsubscribeBoundaryResize.resolve()+ } else if (request.cmd === 'write') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const first = sessionPty(client, 'nt-flow-owner', spawnOptions(userDataDir, 120, 40), 500)+ const second = sessionPty(client, 'nt-flow-owner', spawnOptions(userDataDir, 80, 24), 500)+ await expect(within(Promise.all([first.ready, second.ready]), 'both local attaches')).resolves.toHaveLength(2)++ first.pause()+ await within(firstPause.promise, 'first aggregate pause')+ second.pause()+ first.resume()+ first.resize(79, 23)+ await within(ownerBoundaryResize.promise, 'co-owner flow boundary')+ expect(flowCommands).toEqual(['pause'])+ second.resume()+ await within(firstResume.promise, 'last-owner resume')++ first.pause()+ await within(secondPause.promise, 'second aggregate pause')+ second.destroy()+ first.resize(78, 22)+ await within(unsubscribeBoundaryResize.promise, 'surviving-owner flow boundary')+ expect(flowCommands).toEqual(['pause', 'resume', 'pause'])+ first.destroy()+ await within(secondResume.promise, 'unsubscribe-owned resume')+ await within(detached.promise, 'last-subscriber detach')+ await eventLoopTurn()++ expect(flowCommands).toEqual(['pause', 'resume', 'pause', 'resume', 'detach'])+ })++ it('returns a pause acknowledged during last-subscriber teardown before detaching', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-retiring-pause-')+ const pauseReachedHost = deferred<void>()+ const resumed = deferred<void>()+ const detached = deferred<void>()+ const flowCommands: Array<'pause' | 'resume' | 'detach'> = []++ const server = net.createServer((socket) => {+ trackSocket(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else if (request.cmd === 'attachExisting') {+ // The second local subscriber co-attaches to the same already-live generation, so the+ // client sends `attachExisting` (warm, no spawn plan) rather than a second `attach`.+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false, generation: 'flow-generation' } }))+ } else if (request.cmd === 'pause') {+ flowCommands.push('pause')+ // Resolve in this same server callback after writing the acknowledgement. The test's+ // continuation removes the owners before the client socket can consume that frame.+ socket.write(encodeFrame({ id: request.id, ok: true }))+ pauseReachedHost.resolve()+ } else if (request.cmd === 'resume') {+ flowCommands.push('resume')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ resumed.resolve()+ } else if (request.cmd === 'detach') {+ flowCommands.push('detach')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ detached.resolve()+ } else if (request.cmd === 'resize' || request.cmd === 'write') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const first = sessionPty(+ client,+ 'nt-retiring-pause',+ spawnOptions(userDataDir, 100, 32),+ 500+ )+ const second = sessionPty(+ client,+ 'nt-retiring-pause',+ spawnOptions(userDataDir, 80, 24),+ 500+ )+ await within(Promise.all([first.ready, second.ready]), 'retiring-pause co-attach')++ first.pause()+ await within(pauseReachedHost.promise, 'in-flight pause acknowledgement')+ first.destroy()+ second.destroy()+ await within(resumed.promise, 'retiring pause resume')+ await within(detached.promise, 'retiring pause detach')+ await eventLoopTurn()+ expect(flowCommands).toEqual(['pause', 'resume', 'detach'])+ })++ it('returns the surviving pause ticket and detaches when a delayed co-attach rejects after its neighbor leaves', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-rejected-neighbor-')+ const pauseReachedHost = deferred<void>()+ const rejectedAttach = deferred<{ socket: net.Socket; id: number }>()+ const resumed = deferred<void>()+ const detached = deferred<void>()+ const commands: string[] = []++ const server = net.createServer((socket) => {+ trackSocket(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ // The owner is the only fresh create for this name; the neighbor co-attaches to the+ // already-live generation and therefore sends `attachExisting` instead (below).+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else if (request.cmd === 'attachExisting') {+ commands.push('attach:rejected-neighbor')+ rejectedAttach.resolve({ socket, id: request.id })+ } else if (request.cmd === 'pause') {+ commands.push('pause')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ pauseReachedHost.resolve()+ } else if (request.cmd === 'resume') {+ commands.push('resume')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ resumed.resolve()+ } else if (request.cmd === 'detach') {+ commands.push('detach')+ socket.write(encodeFrame({ id: request.id, ok: true }))+ detached.resolve()+ } else if (request.cmd === 'resize' || request.cmd === 'write') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const owner = sessionPty(+ client,+ 'nt-rejected-neighbor',+ spawnOptions(userDataDir, 100, 30, ['surviving-owner']),+ 500+ )+ await within(owner.ready, 'surviving owner attach')+ owner.pause()+ await within(pauseReachedHost.promise, 'surviving owner pause')++ const neighbor = sessionPty(+ client,+ 'nt-rejected-neighbor',+ spawnOptions(userDataDir, 80, 24, ['rejected-neighbor']),+ 500+ )+ const heldAttach = await within(rejectedAttach.promise, 'delayed neighbor attach')+ owner.destroy()+ await eventLoopTurn()+ expect(commands).toEqual(['pause', 'attach:rejected-neighbor'])++ heldAttach.socket.write(+ encodeFrame({ id: heldAttach.id, ok: false, error: 'neighbor attach rejected' })+ )+ await expect(within(neighbor.ready, 'rejected neighbor settlement')).rejects.toThrow(+ 'neighbor attach rejected'+ )+ await within(resumed.promise, 'rejected-neighbor resume')+ await within(detached.promise, 'rejected-neighbor detach')+ expect(commands).toEqual(['pause', 'attach:rejected-neighbor', 'resume', 'detach'])+ })++ it('buffers a cold session data frame received before attach acknowledgement and delivers it exactly once', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-cold-data-')+ const attachHeld = deferred<{ socket: net.Socket; id: number }>()+ const preAckFrameWritten = deferred<void>()+ const delivered: string[] = []+ const order: string[] = []++ const server = net.createServer((socket) => {+ trackSocket(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ attachHeld.resolve({ socket, id: request.id })+ // A v2 event frame is dropped by the client unless it carries a valid `generation`+ // (session-host-client.ts's `handleFrame`); a pre-ack frame with no expected generation+ // yet is what the client adopts as this session's generation, so it must match the+ // generation the held attach acknowledgement below eventually confirms.+ socket.write(+ encodeFrame({+ type: 'data',+ name: request.name,+ data: 'COLD-PRE-ACK',+ generation: 'flow-generation'+ }),+ () => preAckFrameWritten.resolve()+ )+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ type: 'data',+ name: request.name,+ data: 'POST-ACK',+ generation: 'flow-generation'+ }) + encodeFrame({ id: request.id, ok: true, result: { exists: true, generation: 'flow-generation' } })+ )+ } else if (request.cmd === 'detach' || request.cmd === 'resize') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const pty = sessionPty(+ client,+ 'nt-cold-pre-ack',+ spawnOptions(userDataDir, 80, 24),+ 500+ )+ pty.onData((data) => {+ delivered.push(data)+ order.push(`data:${data}`)+ })+ const ready = pty.ready.then((result) => {+ order.push('ready')+ return result+ })++ const heldAttach = await within(attachHeld.promise, 'cold attach request')+ await within(preAckFrameWritten.promise, 'pre-ack data write')+ await eventLoopTurn()+ expect(delivered).toEqual([])+ heldAttach.socket.write(+ encodeFrame({ id: heldAttach.id, ok: true, result: { fresh: true, generation: 'flow-generation' } })+ )+ await expect(within(ready, 'cold attach acknowledgement')).resolves.toEqual({ fresh: true, generation: 'flow-generation' })+ expect(order).toEqual(['data:COLD-PRE-ACK', 'ready'])++ await expect(within(client.hasSession('nt-cold-pre-ack'), 'post-ack data barrier')).resolves.toBe(+ true+ )+ expect(delivered).toEqual(['COLD-PRE-ACK', 'POST-ACK'])+ })++ it('uses componentwise local geometry, normalizes invalid axes, and grows when the limiting view leaves', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-geometry-')+ // `narrow`'s attach co-attaches to the already-live generation `wide` created, so it reaches+ // the host as `attachExisting` rather than a second `attach` — and `attachExisting` deliberately+ // carries no spawn plan (session-host-client.ts's `SubscriberEntry.spawn` doc comment), so only+ // cols/rows are checkable for it, not `args`.+ const attachClaims: Array<{ cmd: 'attach' | 'attachExisting'; cols: number; rows: number }> = []+ const resizeRequests: Array<{ cols: number; rows: number }> = []+ const normalizedFirst = deferred<void>()+ const normalizedSecond = deferred<void>()+ const grownAfterDetach = deferred<void>()++ const server = net.createServer((socket) => {+ trackSocket(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ attachClaims.push({+ cmd: 'attach',+ cols: request.spawn.cols,+ rows: request.spawn.rows+ })+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else if (request.cmd === 'attachExisting') {+ attachClaims.push({+ cmd: 'attachExisting',+ cols: request.cols ?? -1,+ rows: request.rows ?? -1+ })+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false, generation: 'flow-generation' } }))+ } else if (request.cmd === 'resize') {+ resizeRequests.push({ cols: request.cols, rows: request.rows })+ socket.write(encodeFrame({ id: request.id, ok: true }))+ if (request.cols === 80 && request.rows === 1) normalizedFirst.resolve()+ if (request.cols === 90 && request.rows === 1) normalizedSecond.resolve()+ if (request.cols === 90 && request.rows === 40) grownAfterDetach.resolve()+ } else if (request.cmd === 'detach' || request.cmd === 'write') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const wide = sessionPty(+ client,+ 'nt-local-geometry',+ spawnOptions(userDataDir, 120, 30, ['wide-short']),+ 500+ )+ await within(wide.ready, 'wide geometry attach')+ const narrow = sessionPty(+ client,+ 'nt-local-geometry',+ spawnOptions(userDataDir, 80, 40, ['narrow-tall']),+ 500+ )+ await within(narrow.ready, 'narrow geometry attach')+ expect(attachClaims).toEqual([+ { cmd: 'attach', cols: 120, rows: 30 },+ { cmd: 'attachExisting', cols: 80, rows: 30 }+ ])++ wide.resize(Number.NaN, -5)+ await within(normalizedFirst.promise, 'NaN and negative geometry normalization')+ narrow.resize(90.9, Number.POSITIVE_INFINITY)+ await within(normalizedSecond.promise, 'fractional and infinite geometry normalization')+ wide.destroy()+ await within(grownAfterDetach.promise, 'geometry growth after limiting view detach')++ expect(resizeRequests).toEqual([+ { cols: 80, rows: 1 },+ { cols: 90, rows: 1 },+ { cols: 90, rows: 40 }+ ])+ })++ it('finishes paused geometry replay before normal requests and releases buffered repaint data only after resume', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-replay-')+ const firstClosed = deferred<void>()+ const initialPause = deferred<void>()+ // v2 reconnect restoration warm-replays via `attachExisting`, not a second `attach` — see+ // `restoreSocket` in session-host-client.ts, which never sends a spawn plan on reattach.+ const replayAttach = deferred<Extract<SessionHostRequest, { cmd: 'attachExisting' }>>()+ const bothNormalRequests = deferred<void>()+ const replayResume = deferred<{ socket: net.Socket; id: number }>()+ const replayBufferFlushed = deferred<void>()+ const sequence: string[] = []+ const secondNormalCommands: string[] = []+ let connection = 0+ let firstSocket: net.Socket | undefined+ let replaySocket: net.Socket | undefined+ let replayRequestId: number | undefined+ let normalCount = 0++ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ if (ownConnection === 1) firstSocket = socket+ trackSocket(socket)+ socket.once('close', () => {+ if (ownConnection === 1) firstClosed.resolve()+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ if (ownConnection === 2) sequence.push('request:hello')+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ // Only the initial cold create (`larger`) arrives here — `smaller` co-attaches below,+ // and the reconnect below that, both via `attachExisting`.+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else if (request.cmd === 'attachExisting') {+ if (ownConnection === 1) {+ // `smaller` co-attaches to the already-live generation `larger` just created.+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false, generation: 'flow-generation' } }))+ } else {+ // The label stays `request:attach` — it names the attach-family step in the test's+ // own sequence, not the literal wire command.+ sequence.push('request:attach')+ replaySocket = socket+ replayRequestId = request.id+ replayAttach.resolve(request)+ }+ } else if (request.cmd === 'pause') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ if (ownConnection === 1) initialPause.resolve()+ } else if (request.cmd === 'resume') {+ sequence.push('request:resume')+ replayResume.resolve({ socket, id: request.id })+ } else if (request.cmd === 'hasSession') {+ sequence.push('request:hasSession')+ secondNormalCommands.push(request.cmd)+ socket.write(+ encodeFrame({ id: request.id, ok: true, result: { exists: true, generation: 'flow-generation' } })+ )+ if (++normalCount === 2) bothNormalRequests.resolve()+ } else if (request.cmd === 'write') {+ sequence.push('request:write')+ secondNormalCommands.push(request.cmd)+ socket.write(encodeFrame({ id: request.id, ok: true }))+ if (++normalCount === 2) bothNormalRequests.resolve()+ } else if (request.cmd === 'resize' || request.cmd === 'detach') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const largerDelivered: string[] = []+ const smallerDelivered: string[] = []+ const maybeFinishReplayDelivery = (): void => {+ if (+ largerDelivered.join('').includes('REPLAY-SCREEN') &&+ largerDelivered.join('').includes('LIVE-WHILE-PAUSED') &&+ smallerDelivered.join('').includes('REPLAY-SCREEN') &&+ smallerDelivered.join('').includes('LIVE-WHILE-PAUSED')+ ) {+ replayBufferFlushed.resolve()+ }+ }+ const client = new SessionHostClient({ userDataDir })+ const larger = sessionPty(+ client,+ 'nt-replay-barrier',+ spawnOptions(userDataDir, 120, 40, ['larger']),+ 500+ )+ const smaller = sessionPty(+ client,+ 'nt-replay-barrier',+ spawnOptions(userDataDir, 80, 24, ['smaller']),+ 500+ )+ larger.onData((data) => {+ sequence.push('data:larger')+ largerDelivered.push(data)+ maybeFinishReplayDelivery()+ })+ smaller.onData((data) => {+ sequence.push('data:smaller')+ smallerDelivered.push(data)+ maybeFinishReplayDelivery()+ })+ await within(Promise.all([larger.ready, smaller.ready]), 'initial co-attach')+ larger.pause()+ await within(initialPause.promise, 'initial pause acknowledgement')++ firstSocket?.destroy()+ await within(firstClosed.promise, 'first socket close')+ const replay = await within(replayAttach.promise, 'automatic reconnect attach')+ const hasSession = client.hasSession('nt-replay-barrier')+ smaller.write('normal-write-after-replay')++ await eventLoopTurn()+ expect(sequence.slice(0, 2)).toEqual(['request:hello', 'request:attach'])+ expect(secondNormalCommands).toEqual([])+ expect(largerDelivered).toEqual([])+ expect(smallerDelivered).toEqual([])+ expect(replay.paused).toBe(true)+ expect(replay.cols).toBe(80)+ expect(replay.rows).toBe(24)++ // Written as two SEPARATE socket writes, the second only once the first's bytes have flushed:+ // the repaint screen the response carries is delivered through `restoreSocket`'s own awaited+ // continuation (a microtask, scheduled once the response frame is parsed), while a raw `data`+ // event frame is delivered synchronously the instant it is parsed. Concatenating both frames+ // into one write lets the client parse them in the same synchronous pass, which would hand the+ // live marker to `deliverData` before the repaint's continuation has even run — reversing the+ // very ordering this test exists to prove. A real flush boundary between the two writes is what+ // gives the response's continuation a chance to run first.+ replaySocket!.write(+ encodeFrame({+ id: replayRequestId!,+ ok: true,+ result: { fresh: false, screen: 'REPLAY-SCREEN', generation: 'flow-generation' }+ }),+ () => {+ replaySocket!.write(+ encodeFrame({+ type: 'data',+ name: 'nt-replay-barrier',+ data: 'LIVE-WHILE-PAUSED',+ generation: 'flow-generation'+ })+ )+ }+ )+ await expect(within(hasSession, 'post-replay hasSession')).resolves.toBe(true)+ await within(bothNormalRequests.promise, 'both requests held behind replay')+ expect(largerDelivered).toEqual([])+ expect(smallerDelivered).toEqual([])++ larger.resume()+ const heldResume = await within(replayResume.promise, 'reconnect resume request')+ await eventLoopTurn()+ expect(largerDelivered).toEqual([])+ expect(smallerDelivered).toEqual([])+ heldResume.socket.write(encodeFrame({ id: heldResume.id, ok: true }))+ await within(replayBufferFlushed.promise, 'buffered reconnect data release')+ for (const delivered of [largerDelivered, smallerDelivered]) {+ const repaintIndex = delivered.findIndex((data) => data.includes('REPLAY-SCREEN'))+ const liveIndex = delivered.findIndex((data) => data.includes('LIVE-WHILE-PAUSED'))+ expect(repaintIndex).toBeGreaterThanOrEqual(0)+ expect(repaintIndex).toBeLessThan(liveIndex)+ }+ expect(sequence.indexOf('request:attach')).toBeLessThan(sequence.indexOf('request:hasSession'))+ expect(sequence.indexOf('request:attach')).toBeLessThan(sequence.indexOf('request:write'))+ expect(sequence.indexOf('request:resume')).toBeLessThan(sequence.indexOf('data:larger'))+ })++ it('reconnects and reattaches an idle live subscriber without another client API call', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-idle-')+ const firstClosed = deferred<void>()+ const idleReplay = deferred<void>()+ const markerDelivered = deferred<string>()+ let connection = 0+ let firstSocket: net.Socket | undefined++ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ if (ownConnection === 1) firstSocket = socket+ trackSocket(socket)+ socket.once('close', () => {+ if (ownConnection === 1) firstClosed.resolve()+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ // Only the initial cold create arrives here; v2 reconnect replay warm-reattaches via+ // `attachExisting` (below), never a second `attach`.+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else if (request.cmd === 'attachExisting') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false, generation: 'flow-generation' } }))+ idleReplay.resolve()+ socket.write(+ encodeFrame({+ type: 'data',+ name: request.name,+ data: 'IDLE-RECONNECT-MARKER',+ generation: 'flow-generation'+ })+ )+ } else if (request.cmd === 'detach' || request.cmd === 'resize') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const pty = sessionPty(+ client,+ 'nt-idle-reconnect',+ spawnOptions(userDataDir, 90, 30),+ 500+ )+ pty.onData((data) => {+ if (data.includes('IDLE-RECONNECT-MARKER')) markerDelivered.resolve(data)+ })+ await within(pty.ready, 'initial idle attach')++ firstSocket?.destroy()+ await within(firstClosed.promise, 'idle socket close')+ await within(idleReplay.promise, 'automatic idle replay', 4_000)+ await expect(within(markerDelivered.promise, 'idle replay data', 4_000)).resolves.toContain(+ 'IDLE-RECONNECT-MARKER'+ )+ expect(connection).toBeGreaterThanOrEqual(2)+ })++ it('compensates a canceled delayed attach with detach and never replays the retired subscriber', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-cancel-')+ const attachSeen = deferred<void>()+ const detachSeen = deferred<void>()+ const firstClosed = deferred<void>()+ let connection = 0+ let firstSocket: net.Socket | undefined+ let delayedAttachId: number | undefined+ const reconnectCommands: string[] = []+ const firstDetachNames: string[] = []++ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ if (ownConnection === 1) firstSocket = socket+ trackSocket(socket)+ socket.once('close', () => {+ if (ownConnection === 1) firstClosed.resolve()+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ if (ownConnection === 1) {+ delayedAttachId = request.id+ attachSeen.resolve()+ } else {+ reconnectCommands.push(request.cmd)+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false } }))+ }+ } else if (request.cmd === 'detach') {+ if (ownConnection === 1) {+ firstDetachNames.push(request.name)+ detachSeen.resolve()+ }+ socket.write(encodeFrame({ id: request.id, ok: true }))+ } else if (request.cmd === 'hasSession') {+ if (ownConnection === 1) {+ // Give the test a client-observed disconnect: awaiting this request's rejection is+ // stronger than observing the peer socket's local close event.+ socket.destroy()+ } else {+ reconnectCommands.push(request.cmd)+ socket.write(+ encodeFrame({ id: request.id, ok: true, result: { exists: true, generation: 'flow-generation' } })+ )+ }+ } else if (request.cmd === 'listSessions') {+ reconnectCommands.push(request.cmd)+ socket.write(encodeFrame({ id: request.id, ok: true, result: { names: [] } }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const pty = sessionPty(+ client,+ 'nt-canceled-attach',+ spawnOptions(userDataDir, 80, 24),+ 500+ )+ const readySettled = pty.ready.then(+ () => 'resolved' as const,+ () => 'rejected' as const+ )+ await within(attachSeen.promise, 'delayed attach request')+ pty.destroy()+ firstSocket!.write(+ encodeFrame({ id: delayedAttachId!, ok: true, result: { fresh: true, generation: 'flow-generation' } })+ )+ await within(detachSeen.promise, 'compensating detach')+ await expect(within(readySettled, 'canceled ready settlement')).resolves.toBe('rejected')++ await expect(+ within(client.hasSession('nt-canceled-attach'), 'disconnect observation probe')+ ).rejects.toThrow(/connection lost/i)+ await within(firstClosed.promise, 'canceled attach socket close')+ await expect(within(client.hasSession('nt-canceled-attach'), 'forced reconnect')).resolves.toBe(+ true+ )+ await expect(within(client.listSessions(), 'post-reconnect request barrier')).resolves.toEqual([])+ expect(reconnectCommands).toEqual(['hasSession', 'listSessions'])+ expect(firstDetachNames).toEqual(['nt-canceled-attach'])+ })++ it('keeps kill ordered ahead of a replacement attach after the old local state retires', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-kill-lane-')+ const oldWriteReachedHost = deferred<void>()+ const releaseOldWrite = deferred<void>()+ const killReachedHost = deferred<void>()+ const replacementAttachReachedHost = deferred<void>()+ const afterInitial: string[] = []+ let killCount = 0++ const server = net.createServer((socket) => {+ trackSocket(socket)+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ if (request.spawn.args[0] === 'old-generation') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'flow-generation' } }))+ } else {+ afterInitial.push('attach:replacement')+ replacementAttachReachedHost.resolve()+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'replacement-generation-id' }+ })+ )+ }+ } else if (request.cmd === 'write') {+ afterInitial.push('write:old')+ oldWriteReachedHost.resolve()+ void releaseOldWrite.promise.then(() => {+ if (!socket.destroyed) socket.write(encodeFrame({ id: request.id, ok: true }))+ })+ } else if (request.cmd === 'killSession') {+ afterInitial.push('kill')+ killCount+++ socket.write(encodeFrame({ id: request.id, ok: true, result: {} }))+ killReachedHost.resolve()+ } else if (request.cmd === 'detach' || request.cmd === 'resize') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const old = sessionPty(+ client,+ 'nt-kill-name-lane',+ spawnOptions(userDataDir, 100, 32, ['old-generation']),+ 500+ )+ await within(old.ready, 'old generation attach')+ old.write('hold-old-name-lane')+ await within(oldWriteReachedHost.promise, 'old queued write')++ const killedOld = client.killSession('nt-kill-name-lane')+ old.destroy()+ await eventLoopTurn()+ expect(afterInitial).toEqual(['write:old'])++ releaseOldWrite.resolve()+ await within(killReachedHost.promise, 'old generation kill')+ // The kill barrier (`killReplayBarriers` in session-host-client.ts) refuses ANY attach for+ // this name — cold create included, not just reconnect replay — until the kill is confirmed;+ // see session-host-client.test.ts's "rejects a concurrent attach while kill confirmation is+ // in progress" for the same contract asserted directly. The replacement therefore only+ // attaches once the kill has actually settled, which is what keeps its wire request ordered+ // strictly behind the kill's rather than racing it.+ await expect(within(killedOld, 'old generation kill acknowledgement')).resolves.toBeUndefined()++ const replacement = sessionPty(+ client,+ 'nt-kill-name-lane',+ spawnOptions(userDataDir, 80, 24, ['replacement-generation']),+ 500+ )+ await within(replacementAttachReachedHost.promise, 'post-kill replacement attach')+ await expect(within(replacement.ready, 'replacement generation attach')).resolves.toEqual({+ fresh: true,+ generation: 'replacement-generation-id'+ })+ expect(afterInitial).toEqual(['write:old', 'kill', 'attach:replacement'])+ expect(killCount).toBe(1)+ })++ it('retires an exiting generation before a synchronous replacement attach and replays only the replacement', async () => {+ const { userDataDir, endpoint } = fixture('nodeterm-session-flow-generation-')+ const oldExit = vi.fn()+ const replacementExit = vi.fn()+ const replacementCreated = deferred<SessionHostPty>()+ const replacementData = deferred<string>()+ const firstClosed = deferred<void>()+ // v2 reconnect restoration warm-replays via `attachExisting`, not a second `attach` — see+ // `restoreSocket` in session-host-client.ts, which never sends a spawn plan on reattach.+ const replayAttach = deferred<Extract<SessionHostRequest, { cmd: 'attachExisting' }>>()+ let connection = 0+ let firstSocket: net.Socket | undefined+ const firstConnectionAttachArgs: string[][] = []+ // `attachExisting` deliberately carries no spawn plan, so the reconnect is identified by the+ // exact generation it expects rather than by `spawn.args`.+ const reconnectExpectedGenerations: Array<string | undefined> = []++ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ if (ownConnection === 1) firstSocket = socket+ trackSocket(socket)+ socket.once('close', () => {+ if (ownConnection === 1) firstClosed.resolve()+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ // Both `old` and its replacement are cold creates (the replacement attaches only after+ // `old`'s state has fully retired, so there is nothing local to co-attach onto) — both+ // therefore arrive here as plain `attach`, distinguished by generation below.+ if (request.spawn.args[0] === 'old-generation') {+ firstConnectionAttachArgs.push(request.spawn.args)+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: true, generation: 'old-generation-id' } }))+ } else {+ firstConnectionAttachArgs.push(request.spawn.args)+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'replacement-generation-id' }+ })+ )+ }+ } else if (request.cmd === 'attachExisting') {+ // The automatic reconnect warm-replays whichever generation is still locally attached —+ // proven below to be the replacement's, never the retired old one.+ reconnectExpectedGenerations.push(request.expectedGeneration)+ replayAttach.resolve(request)+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation: 'replacement-generation-id' }+ }) ++ encodeFrame({+ type: 'data',+ name: request.name,+ data: 'REPLACEMENT-REPLAY-MARKER',+ generation: 'replacement-generation-id'+ })+ )+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({ id: request.id, ok: true, result: { exists: true, generation: 'flow-generation' } })+ )+ } else if (request.cmd === 'detach' || request.cmd === 'resize') {+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ }+ })+ })+ await listen(server, endpoint)++ const client = new SessionHostClient({ userDataDir })+ const old = sessionPty(+ client,+ 'nt-generation-replace',+ spawnOptions(userDataDir, 100, 32, ['old-generation']),+ 500+ )+ old.onExit((event) => {+ oldExit(event)+ const replacement = sessionPty(+ client,+ 'nt-generation-replace',+ spawnOptions(userDataDir, 70, 20, ['replacement-generation']),+ 500+ )+ replacement.onExit(replacementExit)+ replacement.onData((data) => {+ if (data.includes('REPLACEMENT-REPLAY-MARKER')) replacementData.resolve(data)+ })+ replacementCreated.resolve(replacement)+ })+ await within(old.ready, 'old generation attach')++ firstSocket!.write(+ encodeFrame({ type: 'exit', name: 'nt-generation-replace', exitCode: 17, generation: 'old-generation-id' })+ )+ const replacement = await within(replacementCreated.promise, 'synchronous replacement creation')+ await within(replacement.ready, 'replacement attach')+ expect(oldExit).toHaveBeenCalledTimes(1)+ expect(oldExit).toHaveBeenCalledWith({ exitCode: 17 })+ expect(replacementExit).not.toHaveBeenCalled()+ expect(firstConnectionAttachArgs).toEqual([['old-generation'], ['replacement-generation']])++ firstSocket?.destroy()+ await within(firstClosed.promise, 'replacement socket close')+ const replay = await within(replayAttach.promise, 'replacement automatic replay', 4_000)+ expect(replay.expectedGeneration).toBe('replacement-generation-id')+ await expect(+ within(replacementData.promise, 'replacement replay data', 4_000)+ ).resolves.toContain('REPLACEMENT-REPLAY-MARKER')+ await expect(+ within(client.hasSession('nt-generation-replace'), 'replacement replay request barrier')+ ).resolves.toBe(true)+ expect(reconnectExpectedGenerations).toEqual(['replacement-generation-id'])+ expect(replacementExit).not.toHaveBeenCalled()+ })+})diff --git a/src/core/session-host-client-repaint.test.ts b/src/core/session-host-client-repaint.test.tsnew file mode 100644index 000000000..c3a73bd56--- /dev/null+++ b/src/core/session-host-client-repaint.test.ts@@ -0,0 +1,244 @@+import fs from 'fs'+import net from 'net'+import os from 'os'+import path from 'path'+import { Terminal } from '@xterm/headless'+import { afterEach, describe, expect, it } from 'vitest'+import { sessionHostPaths } from '../session-host/paths'+import {+ LineFramer,+ SESSION_HOST_PROTOCOL_VERSION,+ encodeFrame,+ type SessionHostRequest+} from '../session-host/protocol'+import { TerminalEmulator } from '../session-host/terminal-emulator'+import { SessionHostClient } from './session-host-client'++const openServers = new Set<net.Server>()+const openSockets = new Set<net.Socket>()+const tempDirs = new Set<string>()+const terminals = new Set<Terminal>()+const emulators = new Set<TerminalEmulator>()++function within<T>(promise: Promise<T>, ms = 1_000): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error(`session-host reconnect repaint did not finish within ${ms}ms`)),+ ms+ )+ promise.then(+ (value) => {+ clearTimeout(timer)+ resolve(value)+ },+ (error) => {+ clearTimeout(timer)+ reject(error)+ }+ )+ })+}++function writeTerminal(term: Terminal, data: string): Promise<void> {+ return new Promise<void>((resolve) => term.write(data, resolve))+}++function activeLines(term: Terminal): string[] {+ const buffer = term.buffer.active+ return Array.from({ length: buffer.length }, (_, index) =>+ buffer.getLine(index)?.translateToString(true) ?? ''+ )+}++function markerCount(lines: string[], marker: string): number {+ return lines.reduce((count, line) => count + line.split(marker).length - 1, 0)+}++async function listen(server: net.Server, endpoint: string): Promise<void> {+ openServers.add(server)+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+}++afterEach(async () => {+ for (const terminal of terminals) terminal.dispose()+ terminals.clear()+ for (const emulator of emulators) emulator.dispose()+ emulators.clear()+ for (const socket of openSockets) socket.destroy()+ openSockets.clear()+ await Promise.all(+ [...openServers].map(+ (server) =>+ new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ )+ )+ openServers.clear()+ for (const dir of tempDirs) {+ const endpoint = sessionHostPaths(dir).endpoint+ if (process.platform !== 'win32') fs.rmSync(endpoint, { force: true })+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+ }+ tempDirs.clear()+})++describe('SessionHostClient reconnect repaint', () => {+ it('replaces the whole xterm buffer instead of appending a second serialized screen', async () => {+ const cols = 22+ const rows = 4+ const marker = 'RECONNECT-MARKER'+ const hostScreen = new TerminalEmulator({ cols, rows, scrollback: 100 })+ emulators.add(hostScreen)+ await hostScreen.write(+ '\x1b[?2004h\x1b[?1002h\x1b[?1006h' ++ [+ 'history-01',+ 'history-02',+ 'history-03',+ marker,+ 'history-05',+ 'visible-01',+ 'visible-02',+ 'cursor-here'+ ].join('\r\n')+ )+ const screen = hostScreen.serialize(100)++ const expected = new Terminal({ cols, rows, scrollback: 100, allowProposedApi: true })+ terminals.add(expected)+ await writeTerminal(expected, screen)+ const expectedLines = activeLines(expected)+ expect(markerCount(expectedLines, marker)).toBe(1)+ expect(expected.buffer.active.length).toBeGreaterThan(rows)+ expect(expected.modes.bracketedPasteMode).toBe(true)+ expect(expected.modes.mouseTrackingMode).toBe('drag')++ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-session-repaint-'))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ fs.writeFileSync(paths.tokenPath, 'b'.repeat(64))+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: process.pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: Date.now(),+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ )++ // Protocol v2 requires attach/attachExisting/hasSession(exists:true) results to all carry a+ // matching generation (session-host-client.ts requireAttachResult / hasSession) — the exact+ // identity the reconnect path (restoreSocket -> 'attachExisting') cross-checks against what+ // the original 'attach' reported, refusing the warm replay otherwise.+ const generation = 'fixturegen01'+ let connection = 0+ let firstSocket: net.Socket | undefined+ let firstClosed!: () => void+ const firstSocketClosed = new Promise<void>((resolve) => {+ firstClosed = resolve+ })+ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ if (ownConnection === 1) firstSocket = socket+ openSockets.add(socket)+ socket.once('close', () => {+ openSockets.delete(socket)+ if (ownConnection === 1) firstClosed()+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (request.cmd === 'hello') {+ // A real host (src/session-host/host.ts) always advertises its protocol version in+ // the hello result; the client negotiates against that, then cross-checks it against+ // the version this same fixture published in state.json. Omitting it here negotiates+ // the legacy (pre-v2) protocol while the state file claims v2, which the client+ // correctly refuses as an inconsistent host.+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (request.cmd === 'attach') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation, screen }+ })+ )+ } else if (request.cmd === 'attachExisting') {+ // The reconnect path (restoreSocket) sends this on the second connection instead of+ // 'attach'. It must report the SAME generation the first 'attach' did, and the+ // serialized screen the client repaints the local xterm buffer with.+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation, screen }+ })+ )+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({ id: request.id, ok: true, result: { exists: true, generation } })+ )+ }+ }+ })+ })+ await listen(server, paths.endpoint)++ const actual = new Terminal({ cols, rows, scrollback: 100, allowProposedApi: true })+ terminals.add(actual)+ let repaintApplied!: () => void+ const repaintDone = new Promise<void>((resolve) => {+ repaintApplied = resolve+ })+ const client = new SessionHostClient({ userDataDir })+ const subscriber = {+ onData: (data: string) => {+ actual.write(data, repaintApplied)+ },+ onExit: () => {}+ }+ const attached = await within(+ client.attach(+ 'nt-repaint',+ {+ cwd: userDataDir,+ shell: process.execPath,+ args: [],+ env: {},+ cols,+ rows+ },+ 100,+ subscriber+ )+ )+ expect(attached.screen).toBe(screen)+ await writeTerminal(actual, attached.screen!)+ expect(activeLines(actual)).toEqual(expectedLines)++ firstSocket?.destroy()+ await within(firstSocketClosed)+ await expect(within(client.hasSession('nt-repaint'))).resolves.toBe(true)+ await within(repaintDone)++ const actualLines = activeLines(actual)+ expect(actual.buffer.active.length).toBe(expected.buffer.active.length)+ expect(actualLines).toEqual(expectedLines)+ expect(markerCount(actualLines, marker)).toBe(1)+ expect(actual.modes.bracketedPasteMode).toBe(true)+ expect(actual.modes.mouseTrackingMode).toBe('drag')+ client.unsubscribe('nt-repaint', subscriber)+ })+})diff --git a/src/core/session-host-client-transport.test.ts b/src/core/session-host-client-transport.test.tsnew file mode 100644index 000000000..b22b41586--- /dev/null+++ b/src/core/session-host-client-transport.test.ts@@ -0,0 +1,544 @@+import { EventEmitter } from "events";+import fs from "fs";+import net from "net";+import os from "os";+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { sessionHostPaths } from "../session-host/paths";+import {+ SESSION_HOST_PROTOCOL_VERSION,+ LineFramer,+ encodeFrame,+ type SessionHostRequest,+} from "../session-host/protocol";++const launcherMocks = vi.hoisted(() => ({+ resolveSessionHostScript: vi.fn(),+ spawnSessionHost: vi.fn(),+}));++const identityMocks = vi.hoisted(() => ({+ readExistingSessionHostIdentity: vi.fn(),+}));++vi.mock("./session-host-launcher", () => launcherMocks);+vi.mock("../session-host/existing-host-state", () => identityMocks);++import { SessionHostClient } from "./session-host-client";++const openServers = new Set<net.Server>();+const openSockets = new Set<net.Socket>();+const tempDirs = new Set<string>();++type WriteCallback = (error?: Error | null) => void;+type FakeWriteHandler = (+ request: SessionHostRequest,+ callback?: WriteCallback,+) => void;++class FakeSocket extends EventEmitter {+ destroyed = false;++ constructor(private readonly onWrite: FakeWriteHandler) {+ super();+ }++ begin(): void {+ queueMicrotask(() => {+ if (!this.destroyed) this.emit("connect");+ });+ }++ unref(): this {+ return this;+ }++ write(chunk: string | Uint8Array, ...args: unknown[]): boolean {+ const callback = args.find(+ (arg): arg is WriteCallback => typeof arg === "function",+ );+ for (const line of Buffer.from(chunk).toString("utf8").split("\n")) {+ if (line.trim())+ this.onWrite(JSON.parse(line) as SessionHostRequest, callback);+ }+ return true;+ }++ respond(frame: Parameters<typeof encodeFrame>[0]): void {+ queueMicrotask(() => {+ if (!this.destroyed) this.emit("data", Buffer.from(encodeFrame(frame)));+ });+ }++ destroy(): this {+ if (this.destroyed) return this;+ this.destroyed = true;+ queueMicrotask(() => this.emit("close"));+ return this;+ }+}++function useFakeConnections(+ ...sockets: FakeSocket[]+): ReturnType<typeof vi.spyOn> {+ let index = 0;+ const spy = vi.spyOn(net, "connect").mockImplementation(((+ ..._args: unknown[]+ ) => {+ const socket = sockets[index++];+ if (!socket) throw new Error("unexpected extra session-host connection");+ socket.begin();+ return socket as unknown as net.Socket;+ }) as typeof net.connect);+ return spy;+}++function within<T>(promise: Promise<T>, ms = 750): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(+ () =>+ reject(+ new Error(`session-host transport did not answer within ${ms}ms`),+ ),+ ms,+ );+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ });+}++function makeTempDir(): string {+ const dir = fs.mkdtempSync(+ path.join(os.tmpdir(), "nodeterm-session-transport-"),+ );+ tempDirs.add(dir);+ return dir;+}++function readyIdentity(userDataDir: string, token = "a".repeat(64)) {+ const paths = sessionHostPaths(userDataDir);+ return {+ kind: "ready" as const,+ state: {+ pid: 42,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: 1,+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION,+ },+ token,+ };+}++function spawnOptions(userDataDir: string) {+ return {+ cwd: userDataDir,+ shell: process.execPath,+ args: [],+ env: {},+ cols: 80,+ rows: 24,+ };+}++async function listen(server: net.Server, endpoint: string): Promise<void> {+ openServers.add(server);+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(endpoint, resolve);+ });+}++function successSocket(+ onRequest: (+ request: SessionHostRequest,+ socket: FakeSocket,+ callback?: WriteCallback,+ ) => void,+): FakeSocket {+ let socket!: FakeSocket;+ socket = new FakeSocket((request, callback) => {+ if (request.cmd === "hello") {+ callback?.();+ // `readyIdentity()` (the identity every caller of this helper publishes) defaults to+ // SESSION_HOST_PROTOCOL_VERSION, and the client refuses a state file that disagrees with+ // what hello actually negotiates ("session-host protocol publication disagrees with+ // hello"). Advertising it here — not omitting it, which negotiates legacy v1 — is what+ // keeps this fake host internally consistent with the identity these tests publish.+ socket.respond({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION },+ });+ return;+ }+ onRequest(request, socket, callback);+ });+ return socket;+}++beforeEach(() => {+ launcherMocks.resolveSessionHostScript.mockReset();+ launcherMocks.resolveSessionHostScript.mockReturnValue(null);+ launcherMocks.spawnSessionHost.mockReset();+ identityMocks.readExistingSessionHostIdentity.mockReset();+});++afterEach(async () => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ for (const socket of openSockets) socket.destroy();+ openSockets.clear();+ await Promise.all(+ [...openServers].map(+ (server) =>+ new Promise<void>((resolve) => {+ server.close(() => resolve());+ }),+ ),+ );+ openServers.clear();+ for (const dir of tempDirs) {+ const endpoint = sessionHostPaths(dir).endpoint;+ if (process.platform !== "win32") fs.rmSync(endpoint, { force: true });+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ }+ tempDirs.clear();+});++describe("SessionHostClient transport boundaries", () => {+ it("accepts only the response correlated to its hello request", async () => {+ const userDataDir = makeTempDir();+ const paths = sessionHostPaths(userDataDir);+ identityMocks.readExistingSessionHostIdentity.mockReturnValue(+ readyIdentity(userDataDir),+ );+ let attachRequests = 0;++ const server = net.createServer((socket) => {+ openSockets.add(socket);+ socket.once("close", () => openSockets.delete(socket));+ const framer = new LineFramer();+ socket.on("data", (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(+ chunk.toString("utf8"),+ )) {+ if (request.cmd === "hello") {+ socket.write(+ encodeFrame({ id: request.id + 10_000, ok: true }) ++ encodeFrame({+ id: request.id,+ ok: false,+ error: "token refused",+ }),+ );+ } else if (request.cmd === "attach") {+ attachRequests++;+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true },+ }),+ );+ }+ }+ });+ });+ await listen(server, paths.endpoint);++ const client = new SessionHostClient({ userDataDir });+ const subscriber = { onData: vi.fn(), onExit: vi.fn() };+ await expect(+ within(+ client.attach(+ "nt-wrong-hello",+ spawnOptions(userDataDir),+ 1_000,+ subscriber,+ ),+ ),+ ).rejects.toThrow();+ expect(attachRequests).toBe(0);+ expect(subscriber.onData).not.toHaveBeenCalled();+ });++ it("treats only a missing token as permission to launch and retry", async () => {+ const userDataDir = makeTempDir();+ const paths = sessionHostPaths(userDataDir);+ identityMocks.readExistingSessionHostIdentity+ .mockReturnValueOnce({ kind: "absent", missing: "state" })+ .mockReturnValue(readyIdentity(userDataDir, "b".repeat(64)));+ launcherMocks.resolveSessionHostScript.mockReturnValue(+ "fake-session-host.cjs",+ );++ const server = net.createServer((socket) => {+ openSockets.add(socket);+ socket.once("close", () => openSockets.delete(socket));+ const framer = new LineFramer();+ socket.on("data", (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(+ chunk.toString("utf8"),+ )) {+ if (request.cmd === "hello") {+ expect(request.token).toBe("b".repeat(64));+ // `readyIdentity()` publishes SESSION_HOST_PROTOCOL_VERSION; the hello answer must+ // advertise the same version or the client refuses it as an inconsistent host.+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION },+ }),+ );+ } else if (request.cmd === "listSessions") {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { names: ["nt-launched"] },+ }),+ );+ }+ }+ });+ });+ await listen(server, paths.endpoint);++ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions(), 1_500)).resolves.toEqual([+ "nt-launched",+ ]);+ expect(launcherMocks.spawnSessionHost).toHaveBeenCalledTimes(1);+ });++ it.each(["EISDIR", "EACCES", "EIO"])(+ "propagates a %s token read failure without invoking the launcher",+ async (code) => {+ const userDataDir = makeTempDir();+ launcherMocks.resolveSessionHostScript.mockReturnValue(+ "fake-session-host.cjs",+ );+ launcherMocks.spawnSessionHost.mockImplementation(() => {+ throw new Error("launcher must not run after a token read failure");+ });+ const error = Object.assign(+ new Error(`synthetic ${code} token failure`),+ { code },+ );+ identityMocks.readExistingSessionHostIdentity.mockImplementation(() => {+ throw error;+ });++ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions())).rejects.toMatchObject({+ code,+ });+ expect(launcherMocks.spawnSessionHost).not.toHaveBeenCalled();+ },+ );++ it("rejects an empty token without invoking the launcher", async () => {+ const userDataDir = makeTempDir();+ launcherMocks.resolveSessionHostScript.mockReturnValue(+ "fake-session-host.cjs",+ );+ launcherMocks.spawnSessionHost.mockImplementation(() => {+ throw new Error("launcher must not run for an empty token");+ });+ identityMocks.readExistingSessionHostIdentity.mockImplementation(() => {+ throw new Error("invalid session-host token: file is empty");+ });++ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions())).rejects.toThrow(+ /token: file is empty/i,+ );+ expect(launcherMocks.spawnSessionHost).not.toHaveBeenCalled();+ });++ // `1` is NOT the incompatible case: session-host-client.ts keeps protocol-v1 hosts connectable+ // on purpose, for warm terminal continuity across an app upgrade — only a specific v2-only+ // OPERATION (one that needs atomic generation semantics) refuses a v1 host, with+ // SessionHostProtocolCompatibilityError, and that refusal happens after a successful connect+ // (see session-host-client.test.ts, which documents and exercises exactly that split). The+ // pre-connect guard this test is actually about fires only for a state.protocolVersion that is+ // neither 1 nor SESSION_HOST_PROTOCOL_VERSION — a host from neither a supported legacy nor the+ // current release.+ it("rejects a host publishing an unsupported protocol version without connecting or launching", async () => {+ const userDataDir = makeTempDir();+ const identity = readyIdentity(userDataDir);+ const unsupportedVersion = 3;+ identityMocks.readExistingSessionHostIdentity.mockReturnValue({+ ...identity,+ state: { ...identity.state, protocolVersion: unsupportedVersion },+ });+ launcherMocks.resolveSessionHostScript.mockReturnValue(+ "fake-session-host.cjs",+ );+ const connectSpy = vi.spyOn(net, "connect").mockImplementation(() => {+ throw new Error("an incompatible host must not be contacted");+ });++ expect(SESSION_HOST_PROTOCOL_VERSION).toBe(2);+ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions())).rejects.toThrow(+ `incompatible session-host protocol: host=${unsupportedVersion}, client=2`,+ );+ expect(connectSpy).not.toHaveBeenCalled();+ expect(launcherMocks.spawnSessionHost).not.toHaveBeenCalled();+ });++ it("rejects a 64-character non-hex token without connecting or launching", async () => {+ const userDataDir = makeTempDir();+ identityMocks.readExistingSessionHostIdentity.mockReturnValue(+ readyIdentity(userDataDir, "g".repeat(64)),+ );+ launcherMocks.resolveSessionHostScript.mockReturnValue(+ "fake-session-host.cjs",+ );+ const connectSpy = vi.spyOn(net, "connect").mockImplementation(() => {+ throw new Error("a malformed token must not reach the socket");+ });++ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions())).rejects.toThrow(+ "invalid session-host token: expected 64 hexadecimal characters",+ );+ expect(connectSpy).not.toHaveBeenCalled();+ expect(launcherMocks.spawnSessionHost).not.toHaveBeenCalled();+ });++ it("rejects an async write failure promptly and reconnects the next request", async () => {+ const userDataDir = makeTempDir();+ identityMocks.readExistingSessionHostIdentity.mockReturnValue(+ readyIdentity(userDataDir, "c".repeat(64)),+ );+ const writeError = new Error("asynchronous socket write exploded");+ const first = successSocket((request, _socket, callback) => {+ expect(request.cmd).toBe("listSessions");+ queueMicrotask(() => callback?.(writeError));+ });+ const second = successSocket((request, socket, callback) => {+ expect(request.cmd).toBe("listSessions");+ callback?.();+ socket.respond({+ id: request.id,+ ok: true,+ result: { names: ["nt-reconnected"] },+ });+ });+ const connectSpy = useFakeConnections(first, second);++ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions())).rejects.toThrow(+ writeError.message,+ );+ await expect(within(client.listSessions())).resolves.toEqual([+ "nt-reconnected",+ ]);+ expect(connectSpy).toHaveBeenCalledTimes(2);+ });++ it("ignores a late write callback error after that exact request already resolved", async () => {+ const userDataDir = makeTempDir();+ identityMocks.readExistingSessionHostIdentity.mockReturnValue(+ readyIdentity(userDataDir, "d".repeat(64)),+ );+ let listRequest = 0;+ let lateFirstCallback: WriteCallback | undefined;+ let secondRequest: SessionHostRequest | undefined;+ const socket = successSocket((request, ownSocket, callback) => {+ expect(request.cmd).toBe("listSessions");+ listRequest++;+ if (listRequest === 1) {+ lateFirstCallback = callback;+ ownSocket.respond({+ id: request.id,+ ok: true,+ result: { names: ["first"] },+ });+ } else {+ secondRequest = request;+ }+ });+ const connectSpy = useFakeConnections(socket);+ const client = new SessionHostClient({ userDataDir });++ await expect(within(client.listSessions())).resolves.toEqual(["first"]);+ const second = client.listSessions();+ await expect.poll(() => secondRequest).toBeDefined();+ lateFirstCallback?.(new Error("late error for the completed write"));+ await Promise.resolve();+ socket.respond({+ id: secondRequest!.id,+ ok: true,+ result: { names: ["second"] },+ });++ await expect(within(second)).resolves.toEqual(["second"]);+ expect(connectSpy).toHaveBeenCalledTimes(1);+ expect(socket.destroyed).toBe(false);+ });++ it("closes the uncertain socket and rejects a request whose deadline expires", async () => {+ const userDataDir = makeTempDir();+ identityMocks.readExistingSessionHostIdentity.mockReturnValue(+ readyIdentity(userDataDir, "e".repeat(64)),+ );+ const socket = successSocket((request, ownSocket, callback) => {+ if (request.cmd === "hasSession") {+ callback?.();+ ownSocket.respond({+ id: request.id,+ ok: true,+ // A v2 host names the generation of a live session; the client records it so the+ // following attachExisting can assert it (ABA protection on the warm-reattach path).+ result: { exists: true, generation: 'prewarm-generation' },+ });+ }+ // listSessions deliberately receives neither a write error nor a response.+ });+ useFakeConnections(socket);+ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.hasSession("nt-prewarm"))).resolves.toBe(true);++ vi.useFakeTimers();+ const ignored = client.listSessions();+ const rejection = expect(ignored).rejects.toThrow(/timed out|deadline/i);+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ await rejection;+ expect(socket.destroyed).toBe(true);+ });++ it("propagates listSessions protocol failures as unavailable instead of an empty list", async () => {+ const userDataDir = makeTempDir();+ identityMocks.readExistingSessionHostIdentity.mockReturnValue(+ readyIdentity(userDataDir, "f".repeat(64)),+ );+ const socket = successSocket((request, ownSocket, callback) => {+ expect(request.cmd).toBe("listSessions");+ callback?.();+ ownSocket.respond({+ id: request.id,+ ok: false,+ error: "session inventory unavailable",+ });+ });+ useFakeConnections(socket);++ const client = new SessionHostClient({ userDataDir });+ await expect(within(client.listSessions())).rejects.toThrow(+ "session inventory unavailable",+ );+ });+});diff --git a/src/core/session-host-client.test.ts b/src/core/session-host-client.test.tsnew file mode 100644index 000000000..a0da43bad--- /dev/null+++ b/src/core/session-host-client.test.ts@@ -0,0 +1,1970 @@+import { createHash } from 'crypto'+import fs from 'fs'+import net from 'net'+import os from 'os'+import path from 'path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { sessionHostPaths } from '../session-host/paths'+import {+ LineFramer,+ SESSION_HOST_PROTOCOL_VERSION,+ encodeFrame,+ type SessionHostRequest,+ type SessionHostSpawnOptions+} from '../session-host/protocol'+import {+ SessionHostClient,+ SessionHostProtocolCompatibilityError,+ type SessionSubscriber+} from './session-host-client'++const openServers = new Set<net.Server>()+const openSockets = new Set<net.Socket>()+const tempDirs = new Set<string>()++function within<T>(promise: Promise<T>, ms = 1_000): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error(`session-host client did not answer within ${ms}ms`)),+ ms+ )+ promise.then(+ (value) => {+ clearTimeout(timer)+ resolve(value)+ },+ (error) => {+ clearTimeout(timer)+ reject(error)+ }+ )+ })+}++/**+ * The hardened reader requires exactly 64 lowercase hex characters, so a readable placeholder like+ * `'test-token'` is now rejected as corruption before any connection is even attempted.+ *+ * Callers still pass a readable LABEL (`'test-token-kept-off-argv'`) because that is what makes a+ * failure legible; this turns the label into a valid token deterministically, and `createUserData`+ * returns the real one. Tests assert against that returned value, so distinctness per label is+ * preserved and nothing has to know the encoding.+ */+function tokenFor(label: string): string {+ // An empty or whitespace label is passed through UNCHANGED and deliberately: those tests assert+ // the reader's own corruption refusals ("token is empty or whitespace"), so hashing them into a+ // valid token would quietly delete the case being tested.+ if (label.trim().length === 0) return label+ return createHash('sha256').update(label).digest('hex')+}++/**+ * `protocolVersion` must match what the served fake host answers in its hello:+ * `acceptedHello` -> 2 (advertises a version, so the handshake negotiates 2)+ * `acceptedLegacyHello` -> 1 (omits it, so the handshake negotiates 1)+ *+ * The client refuses a state file that disagrees with the negotiated version, and it is right to:+ * a host that publishes 2 while speaking 1 is not a legacy host, it is an inconsistent one. Real+ * legacy hosts publish 1, which is what a legacy test must simulate to reach the OPERATION-level+ * `SessionHostProtocolCompatibilityError` those tests actually assert.+ */+function createUserData(+ label = 'default-test-token',+ protocolVersion: 1 | 2 = SESSION_HOST_PROTOCOL_VERSION+): {+ userDataDir: string+ paths: ReturnType<typeof sessionHostPaths>+ token: string+} {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-session-client-'))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ const token = tokenFor(label)+ fs.writeFileSync(paths.tokenPath, token)+ // Publish the ownership state too, not just the token.+ //+ // `12a1f9ac` ("reconcile shared terminal ownership") made discovery fail closed: the client now+ // finds a running host ONLY through a fully valid state file, because a socket that merely+ // answers is not proof of who owns the name lane. These fixtures predate that and wrote a token+ // alone, so every one of them looked like "no host is running" — the client then tried to LAUNCH+ // one and failed on the bundle, reporting `session-host bundle not found` for tests that are not+ // about launching at all. That misleading symptom is why this looked like a protocol defect.+ //+ // `pid` is this process deliberately: the reader treats a live pid as an owner, and the test+ // host really is served from here.+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: process.pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: 1,+ protocolVersion+ })+ )+ return { userDataDir, paths, token }+}++function spawnOptions(cwd: string, args: string[] = []): SessionHostSpawnOptions {+ return {+ cwd,+ shell: process.execPath,+ args,+ env: {},+ cols: 80,+ rows: 24+ }+}++async function serve(+ endpoint: string,+ onRequest: (request: SessionHostRequest, socket: net.Socket, connection: number) => void+): Promise<net.Server> {+ let connection = 0+ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ openSockets.add(socket)+ socket.once('close', () => openSockets.delete(socket))+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ onRequest(request, socket, ownConnection)+ }+ })+ })+ openServers.add(server)+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+ return server+}++function subscriber(onData: (data: string) => void = vi.fn()): SessionSubscriber {+ return { onData, onExit: vi.fn() }+}++function acceptedHello(id: number): string {+ return encodeFrame({+ id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+}++function acceptedLegacyHello(id: number): string {+ return encodeFrame({ id, ok: true })+}++function clientOutcome<T>(source: Promise<T>): {+ promise: Promise<+ { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown }+ >+ settled: () => boolean+} {+ let settled = false+ const promise = source.then(+ (value) => ({ status: 'fulfilled' as const, value }),+ (reason: unknown) => ({ status: 'rejected' as const, reason })+ )+ void promise.then(() => {+ settled = true+ })+ return { promise, settled: () => settled }+}++afterEach(async () => {+ vi.useRealTimers()+ for (const socket of openSockets) socket.destroy()+ openSockets.clear()+ await Promise.all(+ [...openServers].map(+ (server) =>+ new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ )+ )+ openServers.clear()+ for (const dir of tempDirs) {+ const endpoint = sessionHostPaths(dir).endpoint+ if (process.platform !== 'win32') fs.rmSync(endpoint, { force: true })+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+ }+ tempDirs.clear()+ vi.restoreAllMocks()+})++describe('SessionHostClient handshake transition', () => {+ it('hands the socket to the production listener before the first attach response and data', async () => {+ const { userDataDir, paths, token } = createUserData('test-token-kept-off-argv')++ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ expect(request.token).toBe(token)+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ // One write deliberately carries the correlated response and first push frame. Broad+ // handshake cleanup loses both after installing the production listener.+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-transition' }+ }) ++ encodeFrame({+ type: 'data',+ name: request.name,+ data: 'first production frame',+ generation: 'generation-transition'+ })+ )+ }+ })++ let deliver!: (data: string) => void+ const firstData = new Promise<string>((resolve) => {+ deliver = resolve+ })+ const client = new SessionHostClient({ userDataDir })+ const attached = client.attach(+ 'nt-real-transition',+ spawnOptions(userDataDir),+ 1_000,+ subscriber(deliver)+ )++ await expect(within(attached)).resolves.toEqual({+ fresh: true,+ generation: 'generation-transition'+ })+ await expect(within(firstData)).resolves.toBe('first production frame')+ })++ it('accepts only the response correlated to its hello request', async () => {+ const { userDataDir, paths } = createUserData('real-token')+ let sawAttach = false++ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: request.id + 10_000,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ }) ++ encodeFrame({ id: request.id, ok: false, error: 'unauthorized' })+ )+ } else if (request.cmd === 'attach') {+ sawAttach = true+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-refused' }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ const attach = client.attach(+ 'nt-refused',+ spawnOptions(userDataDir),+ 1_000,+ subscriber()+ )++ await expect(within(attach)).rejects.toThrow('unauthorized')+ expect(sawAttach).toBe(false)+ })++ it('does not turn a token read failure into host absence', async () => {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-session-client-'))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ fs.mkdirSync(paths.tokenPath)+ // The reader only reaches the token once the state file it points at is itself valid — see+ // `readExistingSessionHostIdentity`. Without a published state file this fixture never+ // observes a token-read failure at all: it looks like "no host published a state file yet",+ // the client tries to LAUNCH one, and dies on the missing bundle instead.+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: process.pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: 1,+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ )+ let tokenReadCode: string | undefined+ try {+ fs.readFileSync(paths.tokenPath, 'utf8')+ } catch (error) {+ tokenReadCode = (error as NodeJS.ErrnoException).code+ }+ expect(tokenReadCode).toBeTruthy()++ const client = new SessionHostClient({ userDataDir })+ await expect(client.hasSession('nt-never-probed')).rejects.toMatchObject({+ code: tokenReadCode+ })+ })++ it('rejects an empty token as corruption instead of spawning a competing host', async () => {+ const { userDataDir } = createUserData(' \r\n')+ const client = new SessionHostClient({ userDataDir })++ // Message per `readExistingSessionHostIdentity` (src/session-host/existing-host-state.ts),+ // which its own sibling test (existing-host-state.test.ts) pins to this exact wording.+ await expect(within(client.hasSession('nt-empty-token'))).rejects.toThrow(+ 'invalid session-host token: file is empty'+ )+ })++ it('surfaces a connected hello timeout instead of treating the host as absent', async () => {+ const { userDataDir, paths } = createUserData()+ let resolveHelloSeen!: () => void+ const helloSeen = new Promise<void>((resolve) => {+ resolveHelloSeen = resolve+ })+ await serve(paths.endpoint, (request) => {+ if (request.cmd === 'hello') resolveHelloSeen()+ })++ vi.useFakeTimers()+ const result = clientOutcome(new SessionHostClient({ userDataDir }).hasSession('nt-silent-hello'))+ await helloSeen+ await vi.advanceTimersByTimeAsync(1_999)+ expect(result.settled()).toBe(false)+ await vi.advanceTimersByTimeAsync(1)+ // `12a1f9ac` dropped the embedded duration from this message (git log -S"hello timed out" —+ // it read 'session-host hello timed out after 2000ms' as recently as a4e3b13d). The 2000ms+ // deadline itself is still exactly what this test exercises via the fake timers above.+ await expect(result.promise).resolves.toMatchObject({+ status: 'rejected',+ reason: expect.objectContaining({+ message: 'session-host hello timed out'+ })+ })+ })++ it('surfaces a malformed correlated hello response as a protocol failure', async () => {+ const { userDataDir, paths } = createUserData()+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') socket.write(encodeFrame({ id: request.id, status: 'maybe' }))+ })++ const client = new SessionHostClient({ userDataDir })+ // `12a1f9ac`'s rewrite of the handshake no longer distinguishes "malformed" from "rejected+ // with no reason": a frame with no `ok:true` is treated as a hello rejection and reports+ // whatever `frame.error` holds, `undefined` here since this fixture's frame has neither `ok`+ // nor `error`. a4e3b13d's handshake used to detect this shape and say+ // 'session-host returned an invalid correlated hello response' instead — see git log+ // -S"invalid correlated hello response" on src/core/session-host-client.ts.+ await expect(within(client.hasSession('nt-bad-hello'))).rejects.toThrow(+ 'session-host hello rejected: undefined'+ )+ })+})++function publishHostIdentity(userDataDir: string, token = 'a'.repeat(64)): string {+ const paths = sessionHostPaths(userDataDir)+ fs.writeFileSync(paths.tokenPath, token)+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: process.pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: Date.now(),+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ )+ return token+}++async function listen(server: net.Server, endpoint: string): Promise<void> {+ openServers.add(server)+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+}++describe('SessionHostClient legacy host continuity', () => {+ it('warm-attaches, captures, writes, and receives output without sending a selected spawn plan', async () => {+ const { userDataDir, paths } = createUserData('legacy-host', 1)+ const onData = vi.fn()+ let warmRequest: Extract<SessionHostRequest, { cmd: 'attach' }> | undefined+ let hostSocket: net.Socket | undefined+ let resolveWrite!: () => void+ const writeSeen = new Promise<void>((resolve) => {+ resolveWrite = resolve+ })++ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedLegacyHello(request.id))+ } else if (request.cmd === 'hasSession') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { exists: true } }))+ } else if (request.cmd === 'attach') {+ warmRequest = request+ hostSocket = socket+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, screen: 'legacy screen' }+ })+ )+ } else if (request.cmd === 'capture') {+ socket.write(+ encodeFrame({ id: request.id, ok: true, result: { text: 'legacy capture' } })+ )+ } else if (request.cmd === 'write') {+ resolveWrite()+ socket.write(encodeFrame({ id: request.id, ok: true }))+ }+ })++ const client = new SessionHostClient({ userDataDir })+ const warmSub = subscriber(onData)+ await expect(within(client.hasSession('nt-legacy-warm'))).resolves.toBe(true)+ await expect(+ within(client.attachExisting('nt-legacy-warm', warmSub))+ ).resolves.toEqual({ fresh: false, screen: 'legacy screen' })+ await expect(within(client.capture('nt-legacy-warm', true))).resolves.toBe('legacy capture')+ client.write('nt-legacy-warm', warmSub, 'dir\r')+ await within(writeSeen)++ hostSocket?.write(+ encodeFrame({ type: 'data', name: 'nt-legacy-warm', data: 'legacy live output' })+ )+ await vi.waitFor(() => {+ expect(onData).toHaveBeenCalledWith('legacy live output')+ })+ expect(warmRequest).toMatchObject({+ cmd: 'attach',+ name: 'nt-legacy-warm',+ scrollback: 1,+ spawn: {+ cwd: userDataDir,+ shell: process.execPath,+ args: ['-e', 'process.stdout.write("nodeterm legacy warm-only sentinel\\n")'],+ cols: 1,+ rows: 1,+ env: expect.objectContaining({ ELECTRON_RUN_AS_NODE: '1' })+ }+ })+ })++ it('uses only the sentinel and fails closed when a warm v1 session disappears before attach', async () => {+ const { userDataDir, paths } = createUserData('legacy-host', 1)+ const onData = vi.fn()+ let warmRequest: Extract<SessionHostRequest, { cmd: 'attach' }> | undefined++ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedLegacyHello(request.id))+ } else if (request.cmd === 'hasSession') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { exists: true } }))+ } else if (request.cmd === 'attach') {+ warmRequest = request+ socket.write(+ encodeFrame({+ type: 'data',+ name: request.name,+ data: 'sentinel output must stay hidden'+ }) ++ encodeFrame({ id: request.id, ok: true, result: { fresh: true } })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(within(client.hasSession('nt-legacy-race'))).resolves.toBe(true)+ await expect(+ within(client.attachExisting('nt-legacy-race', subscriber(onData)))+ ).rejects.toThrow(+ "legacy session-host lost 'nt-legacy-race' before warm attach; no requested shell was spawned"+ )+ expect(onData).not.toHaveBeenCalled()+ expect(warmRequest?.spawn).toMatchObject({+ cwd: userDataDir,+ shell: process.execPath,+ args: ['-e', 'process.stdout.write("nodeterm legacy warm-only sentinel\\n")'],+ cols: 1,+ rows: 1+ })+ })++ it('never sends a selected cold spawn plan to a live legacy host', async () => {+ const { userDataDir, paths } = createUserData('legacy-host', 1)+ const commands: string[] = []+ await serve(paths.endpoint, (request, socket) => {+ commands.push(request.cmd)+ if (request.cmd === 'hello') socket.write(acceptedLegacyHello(request.id))+ })++ const selected: SessionHostSpawnOptions = {+ cwd: 'C:\\selected-project',+ shell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',+ args: ['-NoLogo'],+ env: {},+ cols: 80,+ rows: 24+ }+ const client = new SessionHostClient({ userDataDir })+ const outcome = within(+ client.attach('nt-legacy-cold', selected, 1_000, subscriber())+ )+ await expect(outcome).rejects.toBeInstanceOf(SessionHostProtocolCompatibilityError)+ expect(commands).toEqual(['hello'])+ })++ it('never sends a replacement-reservation kill to a live legacy host', async () => {+ const { userDataDir, paths } = createUserData('legacy-host', 1)+ let killRequests = 0+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') socket.write(acceptedLegacyHello(request.id))+ else if (request.cmd === 'killSession') killRequests+++ })++ const client = new SessionHostClient({ userDataDir })+ const outcome = within(+ client.killSession('nt-legacy-recycle', { reserveReplacement: true })+ )+ await expect(outcome).rejects.toBeInstanceOf(SessionHostProtocolCompatibilityError)+ expect(killRequests).toBe(0)+ })++ it('never sends a direct-target confirmed recycle kill to a live legacy host', async () => {+ const { userDataDir, paths } = createUserData('legacy-host', 1)+ let killRequests = 0+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') socket.write(acceptedLegacyHello(request.id))+ else if (request.cmd === 'killSession') killRequests+++ })++ const client = new SessionHostClient({ userDataDir })+ const outcome = within(+ client.killSession('nt-legacy-direct-recycle', {+ reserveReplacement: false,+ requireV2: true+ })+ )+ await expect(outcome).rejects.toBeInstanceOf(SessionHostProtocolCompatibilityError)+ expect(killRequests).toBe(0)+ })+})++/**+ * White-box shape of the client's private per-name state, mirrored from `ClientSessionState` /+ * `SubscriberEntry` in session-host-client.ts (neither is exported). `12a1f9ac` replaced the+ * older `subs: Map<string, Set<SessionSubscriber>>` + `attachMemory: Map<string, AttachMemory>`+ * pair with one `sessions: Map<string, ClientSessionState>`, keeping only `sessionGenerations`+ * unchanged (git log -S"nameTails" / -S"subs = new Map" on session-host-client.ts).+ */+type SubscriberEntryLike = {+ sub: SessionSubscriber+ scrollback: number+ phase: 'attaching' | 'attached'+}++type ClientSessionStateLike = {+ name: string+ generation?: string+ protocolVersion?: 1 | 2+ entries: Map<SessionSubscriber, SubscriberEntryLike>+ pauseOwners: Set<SessionSubscriber>+ sizeClaims: Map<SessionSubscriber, { cols: number; rows: number }>+ bufferedData: unknown[]+ preAckEntries: Set<SubscriberEntryLike>+ preAckExit: boolean+ releasePending: boolean+ appliedSocket: net.Socket | null+ appliedAttached: boolean+ appliedPaused: boolean+ appliedSize: { cols: number; rows: number } | null+}++describe('SessionHostClient socket and generation identity', () => {+ it('ignores a retired socket independently from a stale same-name generation', () => {+ const name = 'nt-generation-aba'+ const onData = vi.fn()+ const onExit = vi.fn()+ const sub: SessionSubscriber = { onData, onExit }+ const client = new SessionHostClient({ userDataDir: 'unused-direct-socket-fixture' })+ const internals = client as unknown as {+ attachSocket(socket: net.Socket, protocolVersion: 1 | 2): void+ sessions: Map<string, ClientSessionStateLike>+ sessionGenerations: Map<string, string>+ }+ const entry: SubscriberEntryLike = { sub, scrollback: 0, phase: 'attached' }+ const state: ClientSessionStateLike = {+ name,+ generation: 'generation-new',+ protocolVersion: 2,+ entries: new Map([[sub, entry]]),+ pauseOwners: new Set(),+ sizeClaims: new Map([[sub, { cols: 80, rows: 24 }]]),+ bufferedData: [],+ preAckEntries: new Set(),+ preAckExit: false,+ releasePending: false,+ appliedSocket: null,+ appliedAttached: false,+ appliedPaused: false,+ appliedSize: null+ }+ internals.sessions.set(name, state)+ internals.sessionGenerations.set(name, 'generation-new')++ const retired = new net.Socket()+ const current = new net.Socket()+ internals.attachSocket(retired, 2)+ internals.attachSocket(current, 2)++ retired.emit(+ 'data',+ Buffer.from(+ encodeFrame({+ type: 'data',+ name,+ data: 'retired data',+ generation: 'generation-new'+ }) ++ encodeFrame({+ type: 'exit',+ name,+ exitCode: 9,+ generation: 'generation-new'+ })+ )+ )+ expect(onData).not.toHaveBeenCalled()+ expect(onExit).not.toHaveBeenCalled()+ expect(internals.sessions.has(name)).toBe(true)++ current.emit(+ 'data',+ Buffer.from(+ encodeFrame({+ type: 'data',+ name,+ data: 'old generation data',+ generation: 'generation-old'+ }) ++ encodeFrame({+ type: 'exit',+ name,+ exitCode: 8,+ generation: 'generation-old'+ })+ )+ )+ expect(onData).not.toHaveBeenCalled()+ expect(onExit).not.toHaveBeenCalled()+ expect(internals.sessions.has(name)).toBe(true)++ current.emit(+ 'data',+ Buffer.from(+ encodeFrame({+ type: 'data',+ name,+ data: 'current generation data',+ generation: 'generation-new'+ }) ++ encodeFrame({+ type: 'exit',+ name,+ exitCode: 0,+ generation: 'generation-new'+ })+ )+ )+ expect(onData).toHaveBeenCalledWith('current generation data')+ expect(onExit).toHaveBeenCalledWith(0)+ expect(internals.sessions.has(name)).toBe(false)+ retired.destroy()+ current.destroy()+ })+})++describe('SessionHostClient attach rollback', () => {+ it('removes a rejected initial attach so reconnect does not replay a ghost subscriber', async () => {+ const { userDataDir, paths } = createUserData()+ const commands = new Map<number, string[]>()+ let closeFirst!: () => void+ const firstClosed = new Promise<void>((resolve) => {+ closeFirst = resolve+ })++ await serve(paths.endpoint, (request, socket, connection) => {+ let connectionCommands = commands.get(connection)+ if (!connectionCommands) {+ connectionCommands = []+ commands.set(connection, connectionCommands)+ if (connection === 1) socket.once('close', closeFirst)+ }+ connectionCommands.push(request.cmd)+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach' && connection === 1) {+ socket.write(+ encodeFrame({ id: request.id, ok: false, error: 'initial attach refused' }),+ () => socket.destroy()+ )+ } else if (request.cmd === 'attach') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation: 'generation-no-ghost' }+ })+ )+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-no-ghost' }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(+ within(+ client.attach(+ 'nt-no-ghost',+ spawnOptions(userDataDir),+ 1_000,+ subscriber()+ )+ )+ ).rejects.toThrow('initial attach refused')+ await firstClosed++ await expect(within(client.hasSession('nt-no-ghost'))).resolves.toBe(true)+ await new Promise((resolve) => setTimeout(resolve, 20))+ expect(commands.get(2)).toEqual(['hello', 'hasSession'])+ })++ it('rolls back only the failed concurrent attach and replays the survivor attach-only', async () => {+ const { userDataDir, paths } = createUserData()+ const confirmedCwd = path.join(userDataDir, 'confirmed')+ let firstSocket: net.Socket | undefined+ // `12a1f9ac` introduced `nameTails`, a per-name FIFO that fully serializes every+ // `attachSubscriber` call for the same session name (git log -S"nameTails" —+ // it did not exist before that rewrite). Two `client.attach()` calls for the same already-+ // attached name therefore can no longer race at the transport level the way this test+ // originally modeled it (both requests genuinely in flight, the host answering them+ // together): the second call's request is not even built, let alone sent, until the first+ // one's entire round trip — including its own `reconcileState` follow-ups — has settled.+ // It is also no longer a plain `attach`: co-attaching a SECOND local subscriber to a name+ // that already has an attached entry goes warm-only (`attachExisting`, no spawn plan) via+ // `attachSubscriber`'s `useWarmOnly = requestKind.kind === 'existing' || alreadyAttached`.+ // Distinguish "surviving" from "rejected" by arrival order instead of by `spawn.cwd`.+ let attachExistingCount = 0+ let replayedRequest: SessionHostRequest | undefined+ let resolveReplay!: () => void+ const replayed = new Promise<void>((resolve) => {+ resolveReplay = resolve+ })++ await serve(paths.endpoint, (request, socket, connection) => {+ if (connection === 1) firstSocket = socket+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach' && connection === 1) {+ // Only the very first ('confirmed') attach for this name is a cold-create `attach`.+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-concurrent' }+ })+ )+ } else if (request.cmd === 'attachExisting' && connection === 1) {+ attachExistingCount+++ if (attachExistingCount === 1) {+ // 'surviving': the first co-attach to already-attached 'nt-concurrent'.+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation: 'generation-concurrent' }+ })+ )+ } else {+ // 'rejected': fully serialized behind 'surviving', so this only arrives once+ // 'surviving' has already been answered above.+ socket.write(+ encodeFrame({ id: request.id, ok: false, error: 'concurrent attach refused' })+ )+ }+ } else if (request.cmd === 'attachExisting' && connection === 2) {+ replayedRequest = request+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation: 'generation-concurrent' }+ })+ )+ resolveReplay()+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-concurrent' }+ })+ )+ }+ })++ const initialData = vi.fn()+ const survivingData = vi.fn()+ const rejectedData = vi.fn()+ const client = new SessionHostClient({ userDataDir })+ await expect(+ within(+ client.attach(+ 'nt-concurrent',+ spawnOptions(confirmedCwd),+ 1_000,+ subscriber(initialData)+ )+ )+ ).resolves.toEqual({ fresh: true, generation: 'generation-concurrent' })++ const outcomes = await Promise.allSettled([+ within(+ client.attach('nt-concurrent', spawnOptions(userDataDir), 2_000, subscriber(survivingData))+ ),+ within(+ client.attach('nt-concurrent', spawnOptions(userDataDir), 3_000, subscriber(rejectedData))+ )+ ])+ expect(outcomes[0]).toMatchObject({ status: 'fulfilled', value: { fresh: false } })+ expect(outcomes[1]).toMatchObject({+ status: 'rejected',+ reason: expect.objectContaining({ message: 'concurrent attach refused' })+ })++ firstSocket?.write(+ encodeFrame({+ type: 'data',+ name: 'nt-concurrent',+ data: 'survivors only',+ generation: 'generation-concurrent'+ })+ )+ await vi.waitFor(() => {+ expect(initialData).toHaveBeenCalledWith('survivors only')+ expect(survivingData).toHaveBeenCalledWith('survivors only')+ })+ expect(rejectedData).not.toHaveBeenCalled()++ const closingSocket = firstSocket+ expect(closingSocket).toBeDefined()+ const firstClosed = new Promise<void>((resolve) => closingSocket?.once('close', resolve))+ closingSocket?.destroy()+ await firstClosed+ await expect(within(client.hasSession('nt-concurrent'))).resolves.toBe(true)+ await within(replayed)+ expect(replayedRequest).toEqual({+ id: expect.any(Number),+ cmd: 'attachExisting',+ name: 'nt-concurrent',+ expectedGeneration: 'generation-concurrent',+ cols: 80,+ rows: 24,+ paused: false+ })+ expect(replayedRequest && 'spawn' in replayedRequest).toBe(false)+ })+})++describe('SessionHostClient atomic warm attach and reconnect replay', () => {+ // Regression guard: `hasSession()` must RECORD the generation it observes, so the+ // `attachExisting` that follows a probe carries an `expectedGeneration`. The ownership rewrite+ // (12a1f9ac) dropped that bookkeeping while attachExisting's doc comment still promised it,+ // which silently removed ABA protection from the Windows warm-reattach path. Restored.+ it('fails a probe-to-attach race without sending any spawn plan', async () => {+ const { userDataDir, paths } = createUserData()+ let attachExistingRequest: SessionHostRequest | undefined+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-raced' }+ })+ )+ } else if (request.cmd === 'attachExisting') {+ attachExistingRequest = request+ socket.write(+ encodeFrame({ id: request.id, ok: false, error: "no existing session 'nt-raced'" })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(within(client.hasSession('nt-raced'))).resolves.toBe(true)+ await expect(within(client.attachExisting('nt-raced', subscriber()))).rejects.toThrow(+ "no existing session 'nt-raced'"+ )+ // `attachExisting`'s optional aggregate-reconnect fields (cols/rows/paused) are always sent+ // by this client (`attachSubscriber`'s `{kind:'existing'}` request), defaulted to the size+ // `attachExisting()`'s public signature hardcodes (80x24) since this call attaches no prior+ // local geometry. `expectedGeneration` is the one field production no longer supplies here —+ // see the block comment above.+ expect(attachExistingRequest).toEqual({+ id: expect.any(Number),+ cmd: 'attachExisting',+ name: 'nt-raced',+ expectedGeneration: 'generation-raced',+ cols: 80,+ rows: 24,+ paused: false+ })+ expect(attachExistingRequest && 'spawn' in attachExistingRequest).toBe(false)+ })++ it('returns the existing reconstructed screen without a spawn-capable request', async () => {+ const { userDataDir, paths } = createUserData()+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attachExisting') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: {+ fresh: false,+ screen: '\u001b[32mexisting screen',+ generation: 'generation-warm'+ }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(within(client.attachExisting('nt-warm', subscriber()))).resolves.toEqual({+ fresh: false,+ screen: '\u001b[32mexisting screen',+ generation: 'generation-warm'+ })+ })++ it('retires an exact attachment and surfaces the host reason when reconnect replay rejects', async () => {+ const { userDataDir, paths } = createUserData()+ const commands = new Map<number, string[]>()+ const sockets = new Map<number, net.Socket>()+ let resolveReplayError!: (error: Error) => void+ const replayError = new Promise<Error>((resolve) => {+ resolveReplayError = resolve+ })++ await serve(paths.endpoint, (request, socket, connection) => {+ sockets.set(connection, socket)+ const seen = commands.get(connection) ?? []+ seen.push(request.cmd)+ commands.set(connection, seen)+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach' && connection === 1) {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-replay-rejected' }+ })+ )+ } else if (request.cmd === 'attachExisting') {+ socket.write(+ encodeFrame({ id: request.id, ok: false, error: 'replay rejected by host' })+ )+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-replay-rejected' }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(+ client.attach('nt-replay-rejected', spawnOptions(userDataDir), 1_000, {+ onData: vi.fn(),+ onExit: vi.fn(),+ onAttachError: resolveReplayError+ })+ )+ sockets.get(1)?.destroy()+ await new Promise((resolve) => setTimeout(resolve, 20))+ await expect(within(client.hasSession('nt-replay-rejected'))).resolves.toBe(true)+ await expect(within(replayError)).resolves.toMatchObject({ message: 'replay rejected by host' })++ sockets.get(2)?.destroy()+ await new Promise((resolve) => setTimeout(resolve, 20))+ await expect(within(client.hasSession('nt-replay-rejected'))).resolves.toBe(true)+ await new Promise((resolve) => setTimeout(resolve, 20))+ expect(commands.get(3)).toEqual(['hello', 'hasSession'])+ })++ it('reconstructs the screen when reconnect replay succeeds', async () => {+ const { userDataDir, paths } = createUserData()+ const sockets = new Map<number, net.Socket>()+ const onData = vi.fn()+ const onAttachError = vi.fn()+ await serve(paths.endpoint, (request, socket, connection) => {+ sockets.set(connection, socket)+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach' && connection === 1) {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-replay-screen' }+ })+ )+ } else if (request.cmd === 'attachExisting') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: {+ fresh: false,+ screen: '\u001b[34mrestored screen',+ generation: 'generation-replay-screen'+ }+ })+ )+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-replay-screen' }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(+ client.attach('nt-replay-screen', spawnOptions(userDataDir), 1_000, {+ onData,+ onExit: vi.fn(),+ onAttachError+ })+ )+ sockets.get(1)?.destroy()+ await new Promise((resolve) => setTimeout(resolve, 20))+ await expect(within(client.hasSession('nt-replay-screen'))).resolves.toBe(true)+ // RECONNECT_REPAINT_PREFIX (session-host-client.ts) gained a leading `\x1b[3J` (clear+ // scrollback, not only the visible screen) on top of the a4e3b13d-era `\x1b[2J\x1b[H` this+ // test predates -- git log -S"RECONNECT_REPAINT_PREFIX".+ await vi.waitFor(() => {+ expect(onData).toHaveBeenCalledWith('\u001b[3J\u001b[2J\u001b[H\u001b[34mrestored screen')+ })+ expect(onAttachError).not.toHaveBeenCalled()+ })+})++describe('SessionHostClient persistent launch requests', () => {+ it('retries the same generation and launch id after an executed reply is lost', async () => {+ const { userDataDir, paths } = createUserData()+ const launchRequests: Array<Extract<SessionHostRequest, { cmd: 'executeLaunch' }>> = []+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: {+ fresh: true,+ generation: 'generation-launch-ledger',+ launchDialect: 'pwsh'+ }+ })+ )+ } else if (request.cmd === 'attachExisting') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: {+ fresh: false,+ generation: 'generation-launch-ledger',+ launchDialect: 'pwsh'+ }+ })+ )+ } else if (request.cmd === 'executeLaunch') {+ launchRequests.push(request)+ if (launchRequests.length === 1) socket.destroy()+ else {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { status: 'already-executed' }+ })+ )+ }+ }+ })++ const client = new SessionHostClient({ userDataDir })+ const info = await within(+ client.attach('nt-launch-ledger', spawnOptions(userDataDir), 1_000, subscriber())+ )+ expect(info.launchDialect).toBe('pwsh')+ const launchId = '123e4567-e89b-42d3-a456-426614174000'+ const plan = { command: 'private rendered command', stdinAfterStart: 'private prompt' }+ await expect(within(client.executeLaunch('nt-launch-ledger', launchId, plan))).rejects.toThrow(+ 'session-host connection lost'+ )+ await expect(+ within(client.executeLaunch('nt-launch-ledger', launchId, plan))+ ).resolves.toEqual({ status: 'already-executed' })+ expect(launchRequests).toHaveLength(2)+ expect(launchRequests[1]).toMatchObject({+ name: 'nt-launch-ledger',+ generation: 'generation-launch-ledger',+ launchId,+ command: plan.command,+ stdinAfterStart: plan.stdinAfterStart+ })+ })++ it('fails closed before sending an opaque launch to a legacy host', async () => {+ const { userDataDir, paths } = createUserData('legacy-host', 1)+ let launchRequests = 0+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') socket.write(acceptedLegacyHello(request.id))+ else if (request.cmd === 'hasSession') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { exists: true } }))+ } else if (request.cmd === 'attach') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { fresh: false } }))+ } else if (request.cmd === 'executeLaunch') launchRequests+++ })+ const client = new SessionHostClient({ userDataDir })+ await within(client.hasSession('nt-legacy-launch'))+ await within(client.attachExisting('nt-legacy-launch', subscriber()))+ await expect(+ within(+ client.executeLaunch('nt-legacy-launch', '123e4567-e89b-42d3-a456-426614174000', {+ command: 'must never cross legacy wire'+ })+ )+ ).rejects.toBeInstanceOf(SessionHostProtocolCompatibilityError)+ expect(launchRequests).toBe(0)+ })+})++describe('SessionHostClient confirmed kill barrier', () => {+ it('reuses one reserve operation and consumes its token only on the matching fresh attach', async () => {+ const { userDataDir, paths } = createUserData()+ const kills: Array<Extract<SessionHostRequest, { cmd: 'killSession' }>> = []+ const attaches: Array<Extract<SessionHostRequest, { cmd: 'attach' }>> = []+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ attaches.push(request)+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: {+ fresh: true,+ generation: attaches.length === 1 ? 'generation-reserve-a' : 'generation-reserve-b'+ }+ })+ )+ } else if (request.cmd === 'killSession') {+ kills.push(request)+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { replacementToken: request.operationId }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(client.attach('nt-reserved', spawnOptions(userDataDir), 1_000, subscriber()))+ await within(client.killSession('nt-reserved', { reserveReplacement: true }))+ // Simulate a later source-backend teardown failure: retry must refresh lease A, not invent B.+ await within(client.killSession('nt-reserved', { reserveReplacement: true }))+ await within(+ client.attach(+ 'nt-reserved',+ spawnOptions(path.join(userDataDir, 'replacement')),+ 1_000,+ subscriber()+ )+ )++ expect(kills).toHaveLength(2)+ expect(kills[0]).toMatchObject({+ expectedGeneration: 'generation-reserve-a',+ reserveReplacement: true,+ operationId: expect.any(String)+ })+ expect(kills[1]).toMatchObject({+ name: kills[0].name,+ operationId: kills[0].operationId,+ expectedGeneration: kills[0].expectedGeneration,+ reserveReplacement: kills[0].reserveReplacement+ })+ expect(attaches[0].replacementToken).toBeUndefined()+ expect(attaches[1].replacementToken).toBe(kills[0].operationId)+ const internals = client as unknown as {+ replacementTokens: Map<string, string>+ killOperations: Map<string, unknown>+ }+ expect(internals.replacementTokens.has('nt-reserved')).toBe(false)+ expect(internals.killOperations.has('nt-reserved')).toBe(false)+ })++ it('replays the same token after a replacement spawn succeeds but its attach reply is lost', async () => {+ const { userDataDir, paths } = createUserData()+ let phase: 'old' | 'reserved' | 'replacement-created' = 'old'+ let replacementSpawns = 0+ const replacementTokens: string[] = []+ let operationId = ''+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach' && phase === 'old') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-lost-reply-old' }+ })+ )+ } else if (request.cmd === 'killSession') {+ operationId = request.operationId+ phase = 'reserved'+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { replacementToken: request.operationId }+ })+ )+ } else if (request.cmd === 'attach' && phase === 'reserved') {+ replacementTokens.push(request.replacementToken ?? '')+ replacementSpawns+++ phase = 'replacement-created'+ // The host generation exists and owns this token, but the correlated response is lost.+ socket.destroy()+ } else if (request.cmd === 'attach' && phase === 'replacement-created') {+ replacementTokens.push(request.replacementToken ?? '')+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: {+ fresh: true,+ screen: 'screen from the already-created replacement',+ generation: 'generation-lost-reply-new'+ }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(client.attach('nt-lost-reply', spawnOptions(userDataDir), 1_000, subscriber()))+ await within(client.killSession('nt-lost-reply', { reserveReplacement: true }))+ await expect(+ within(+ client.attach(+ 'nt-lost-reply',+ spawnOptions(path.join(userDataDir, 'replacement')),+ 1_000,+ subscriber()+ ),+ 2_000+ )+ ).resolves.toMatchObject({+ fresh: true,+ screen: 'screen from the already-created replacement',+ generation: 'generation-lost-reply-new'+ })+ expect(replacementSpawns).toBe(1)+ expect(replacementTokens).toEqual([operationId, operationId])+ })++ it('keeps generic deletion token-free and probes the current generation before killing', async () => {+ const { userDataDir, paths } = createUserData()+ let killRequest: Extract<SessionHostRequest, { cmd: 'killSession' }> | undefined+ let coldAttach: Extract<SessionHostRequest, { cmd: 'attach' }> | undefined+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-current-delete' }+ })+ )+ } else if (request.cmd === 'killSession') {+ killRequest = request+ socket.write(encodeFrame({ id: request.id, ok: true, result: {} }))+ } else if (request.cmd === 'attach') {+ coldAttach = request+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-after-delete' }+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(client.killSession('nt-generic-delete'))+ await within(+ client.attach('nt-generic-delete', spawnOptions(userDataDir), 1_000, subscriber())+ )+ expect(killRequest).toMatchObject({+ expectedGeneration: 'generation-current-delete',+ reserveReplacement: false,+ operationId: expect.any(String)+ })+ expect(coldAttach?.replacementToken).toBeUndefined()+ })++ it('keeps an expected-absent lease atomic instead of adopting a later generation', async () => {+ const { userDataDir, paths } = createUserData()+ let hasSessionRequests = 0+ const kills: Array<Extract<SessionHostRequest, { cmd: 'killSession' }>> = []+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'hasSession') {+ hasSessionRequests+++ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-created-by-peer' }+ })+ )+ } else if (request.cmd === 'killSession') {+ kills.push(request)+ socket.write(+ encodeFrame({+ id: request.id,+ ok: false,+ error: 'session became live before its replacement lease was acquired'+ })+ )+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(+ within(+ client.killSession('nt-expected-absent', {+ reserveReplacement: true,+ requireV2: true,+ expectedAbsent: true+ }),+ 2_000+ )+ ).rejects.toThrow('remains unconfirmed')+ expect(hasSessionRequests).toBe(0)+ expect(kills).toHaveLength(2)+ // `expectedGeneration` is `undefined` here by design (an expected-absent lease knows no+ // generation), and `JSON.stringify` (`encodeFrame`) drops an `undefined`-valued key rather+ // than serializing it — so the wire request the fake host actually parses never has this key+ // at all. `toMatchObject({expectedGeneration: undefined, ...})` does not accept an absent+ // key as a match for an expected `undefined` (unlike Jest, vitest's `toMatchObject` requires+ // the key to be present); assert the absence directly instead.+ expect(kills[0]).toMatchObject({+ reserveReplacement: true,+ operationId: expect.any(String)+ })+ expect(kills[0].expectedGeneration).toBeUndefined()+ expect(kills[1]).toMatchObject({+ operationId: kills[0].operationId,+ reserveReplacement: true+ })+ expect(kills[1].expectedGeneration).toBeUndefined()+ })++ it('never replays a killed target after a lost reply and still restores another session', async () => {+ const { userDataDir, paths } = createUserData()+ let targetExists = true+ const targetReplayCommands: string[] = []+ let otherReplayCount = 0+ let killCount = 0+ let resolveOtherReplay!: () => void+ const otherReplayed = new Promise<void>((resolve) => {+ resolveOtherReplay = resolve+ })++ await serve(paths.endpoint, (request, socket, connection) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ if (connection > 1 && request.name === 'nt-kill-target') {+ targetReplayCommands.push(request.cmd)+ targetExists = true+ }+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: connection === 1, generation: `generation-${request.name}` }+ })+ )+ } else if (request.cmd === 'attachExisting') {+ if (request.name === 'nt-kill-target') {+ targetReplayCommands.push(request.cmd)+ targetExists = true+ } else if (request.name === 'nt-kill-other') {+ otherReplayCount+++ resolveOtherReplay()+ }+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: false, generation: `generation-${request.name}` }+ })+ )+ } else if (request.cmd === 'killSession') {+ killCount+++ if (connection === 1) {+ // The destructive operation happened, but its acknowledgement was lost.+ targetExists = false+ socket.destroy()+ } else {+ // Idempotent retry observes absence and confirms it.+ socket.write(encodeFrame({ id: request.id, ok: true, result: {} }))+ }+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(+ client.attach(+ 'nt-kill-target',+ spawnOptions(path.join(userDataDir, 'old-target-profile')),+ 1_000,+ subscriber()+ )+ )+ await within(+ client.attach(+ 'nt-kill-other',+ spawnOptions(path.join(userDataDir, 'other-profile')),+ 1_000,+ subscriber()+ )+ )++ await expect(within(client.killSession('nt-kill-target'))).resolves.toBeUndefined()+ await within(otherReplayed)+ expect(killCount).toBe(2)+ expect(targetReplayCommands).toEqual([])+ expect(targetExists).toBe(false)+ expect(otherReplayCount).toBe(1)+ })++ it('reconnects and confirms the kill when the first write provably was not sent', async () => {+ const { userDataDir, paths } = createUserData()+ const killRequests: Array<{ connection: number; name: string }> = []+ await serve(paths.endpoint, (request, socket, connection) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-unsent-kill' }+ })+ )+ } else if (request.cmd === 'killSession') {+ killRequests.push({ connection, name: request.name })+ socket.write(encodeFrame({ id: request.id, ok: true, result: {} }))+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(+ client.attach('nt-unsent-kill', spawnOptions(userDataDir), 1_000, subscriber())+ )+ const liveSocket = (client as unknown as { socket: net.Socket | null }).socket+ expect(liveSocket).not.toBeNull()+ const writeFailure = new Error('kill write never reached the host')+ vi.spyOn(liveSocket as net.Socket, 'write').mockImplementationOnce(+ ((...args: unknown[]) => {+ const callback = args.find((arg) => typeof arg === 'function') as+ | ((error?: Error | null) => void)+ | undefined+ queueMicrotask(() => {+ callback?.(writeFailure)+ liveSocket?.destroy()+ })+ return false+ }) as net.Socket['write']+ )++ await expect(within(client.killSession('nt-unsent-kill'))).resolves.toBeUndefined()+ expect(killRequests).toEqual([{ connection: 2, name: 'nt-unsent-kill' }])+ })++ it('rejects a concurrent attach while kill confirmation is in progress', async () => {+ const { userDataDir, paths } = createUserData()+ let firstKillSocket: net.Socket | undefined+ let resolveKillSeen!: () => void+ const killSeen = new Promise<void>((resolve) => {+ resolveKillSeen = resolve+ })+ const requestedCwds: string[] = []+ await serve(paths.endpoint, (request, socket, connection) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ requestedCwds.push(request.spawn.cwd)+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-killing' }+ })+ )+ } else if (request.cmd === 'killSession' && connection === 1) {+ firstKillSocket = socket+ resolveKillSeen()+ } else if (request.cmd === 'killSession') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: {} }))+ }+ })++ const client = new SessionHostClient({ userDataDir })+ const oldCwd = path.join(userDataDir, 'old-profile')+ const replacementCwd = path.join(userDataDir, 'replacement-profile')+ await within(client.attach('nt-killing', spawnOptions(oldCwd), 1_000, subscriber()))+ const killing = client.killSession('nt-killing')+ await killSeen++ await expect(+ within(client.attach('nt-killing', spawnOptions(replacementCwd), 1_000, subscriber()))+ ).rejects.toThrow("cannot attach 'nt-killing' while its kill result is unconfirmed")+ expect(requestedCwds).toEqual([oldCwd])+ firstKillSocket?.destroy()+ await expect(within(killing)).resolves.toBeUndefined()+ })++ it('keeps replay barred after bounded uncertainty and allows a later explicit kill retry', async () => {+ const { userDataDir, paths } = createUserData()+ let killRequests = 0+ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'attach') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { fresh: true, generation: 'generation-uncertain-kill' }+ })+ )+ } else if (request.cmd === 'killSession') {+ killRequests+++ if (killRequests <= 2) socket.destroy()+ else socket.write(encodeFrame({ id: request.id, ok: true, result: {} }))+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await within(client.attach('nt-uncertain-kill', spawnOptions(userDataDir), 1_000, subscriber()))+ await expect(within(client.killSession('nt-uncertain-kill'))).rejects.toThrow(+ "kill of 'nt-uncertain-kill' remains unconfirmed after 2 attempts"+ )+ await expect(+ within(+ client.attach(+ 'nt-uncertain-kill',+ spawnOptions(path.join(userDataDir, 'must-not-spawn')),+ 1_000,+ subscriber()+ )+ )+ ).rejects.toThrow("cannot attach 'nt-uncertain-kill' while its kill result is unconfirmed")++ await expect(within(client.killSession('nt-uncertain-kill'))).resolves.toBeUndefined()+ expect(killRequests).toBe(3)+ })+})++describe('SessionHostClient request failures', () => {+ it('propagates uncertain capture and kill failures instead of claiming empty or gone', async () => {+ const { userDataDir, paths } = createUserData()++ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') socket.write(acceptedHello(request.id))+ else if (request.cmd === 'hasSession') {+ socket.write(encodeFrame({ id: request.id, ok: true, result: { exists: false } }))+ }+ else if (request.cmd === 'capture' || request.cmd === 'killSession') socket.destroy()+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(within(client.capture('nt-uncertain', true))).rejects.toThrow(+ 'session-host connection lost'+ )+ await expect(within(client.killSession('nt-uncertain'))).rejects.toThrow(+ 'session-host connection lost'+ )+ })++ it('rejects an asynchronous socket.write failure and clears the pending request', async () => {+ const writeError = new Error('asynchronous write failed')+ const fakeSocket = {+ destroyed: false,+ write: vi.fn((...args: unknown[]) => {+ const callback = args.find((arg) => typeof arg === 'function') as+ | ((error?: Error | null) => void)+ | undefined+ queueMicrotask(() => callback?.(writeError))+ return true+ })+ } as unknown as net.Socket+ const client = new SessionHostClient({ userDataDir: 'unused-for-live-fake-socket' })+ ;(client as unknown as { socket: net.Socket | null }).socket = fakeSocket++ await expect(within(client.capture('nt-write-error', true), 250)).rejects.toBe(writeError)+ expect(fakeSocket.write).toHaveBeenCalledOnce()+ expect((client as unknown as { pending: Map<number, unknown> }).pending.size).toBe(0)+ })++ it('rejects a request that receives no response after the preserved ten-second deadline', async () => {+ const { userDataDir, paths } = createUserData()+ let resolveCaptureSeen!: () => void+ const captureSeen = new Promise<void>((resolve) => {+ resolveCaptureSeen = resolve+ })++ await serve(paths.endpoint, (request, socket) => {+ if (request.cmd === 'hello') {+ socket.write(acceptedHello(request.id))+ } else if (request.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: request.id,+ ok: true,+ result: { exists: true, generation: 'generation-timeout' }+ })+ )+ } else if (request.cmd === 'capture') {+ resolveCaptureSeen()+ // Intentionally stay connected and silent: only the request deadline can settle this.+ }+ })++ const client = new SessionHostClient({ userDataDir })+ await expect(within(client.hasSession('nt-timeout'))).resolves.toBe(true)+ vi.useFakeTimers()+ const capture = client.capture('nt-timeout', true)+ let settled = false+ const outcome = capture.then(+ (value) => ({ status: 'fulfilled' as const, value }),+ (reason: unknown) => ({ status: 'rejected' as const, reason })+ )+ void outcome.then(() => {+ settled = true+ })+ await captureSeen++ await vi.advanceTimersByTimeAsync(9_999)+ expect(settled).toBe(false)+ await vi.advanceTimersByTimeAsync(1)+ const result = await outcome+ expect(result.status).toBe('rejected')+ if (result.status === 'rejected') {+ expect(result.reason).toBeInstanceOf(Error)+ // `12a1f9ac` dropped the embedded "within Xms" wording (git log -S"no reply to" — it read+ // "session-host: no reply to '<cmd>' within <ms>ms" as far back as c488de42). The 10s+ // deadline itself is what this test actually exercises via the fake timers above: advancing+ // 9999ms leaves the request unsettled, advancing the final 1ms (to exactly+ // SESSION_HOST_REQUEST_TIMEOUT_MS) settles it.+ expect((result.reason as Error).message).toContain(+ "session-host request timed out: capture"+ )+ }+ expect(settled).toBe(true)+ })+})++describe('SessionHostClient failure boundaries', () => {+ it('keeps the production frame listener through hello and the first attach frames', async () => {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-session-client-'))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ const token = publishHostIdentity(userDataDir)++ const server = net.createServer((socket) => {+ openSockets.add(socket)+ socket.once('close', () => openSockets.delete(socket))+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const req of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (req.cmd === 'hello') {+ expect(req.token).toBe(token)+ // `publishHostIdentity` publishes protocol v2 state; the hello response must+ // negotiate the SAME version or the handshake refuses it as an inconsistent host+ // (`session-host protocol publication disagrees with hello`) — see `acceptedHello`+ // above, which every `serve()`-based fixture in this file already relies on.+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (req.cmd === 'attach') {+ // v2 requires a valid `generation` on every attach result (`requireAttachResult`).+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { fresh: true, generation: 'generation-real-transition' }+ }) ++ encodeFrame({+ type: 'data',+ name: req.name,+ data: 'first production frame',+ generation: 'generation-real-transition'+ })+ )+ }+ }+ })+ })+ await listen(server, paths.endpoint)++ const client = new SessionHostClient({ userDataDir })+ let deliver!: (data: string) => void+ const firstData = new Promise<string>((resolve) => {+ deliver = resolve+ })+ const subscriber = { onData: deliver, onExit: () => {} }+ const attached = client.attach(+ 'nt-real-transition',+ spawnOptions(userDataDir),+ 1_000,+ subscriber+ )++ await expect(within(attached)).resolves.toEqual({+ fresh: true,+ generation: 'generation-real-transition'+ })+ await expect(within(firstData)).resolves.toBe('first production frame')+ client.unsubscribe('nt-real-transition', subscriber)+ })++ it('rolls back only a rejected co-attach and replays the neighboring attachment', async () => {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-session-client-'))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ publishHostIdentity(userDataDir)+ let connection = 0+ let firstAttach = true+ let firstSocket: net.Socket | undefined+ // `attachExisting` (the reconnect-replay request for an already-attached name, and the+ // warm-only co-attach request for a second local subscriber joining one) carries no `spawn`+ // field at all — see its doc comment ("carries no spawn plan") — so a replay can no longer+ // be distinguished by `req.spawn.args` the way an `attach` request could. Record the whole+ // request instead.+ const replayedRequests: SessionHostRequest[] = []+ let closeFirst!: () => void+ const firstClosed = new Promise<void>((resolve) => {+ closeFirst = resolve+ })++ const server = net.createServer((socket) => {+ const ownConnection = ++connection+ if (ownConnection === 1) firstSocket = socket+ openSockets.add(socket)+ socket.once('close', () => {+ openSockets.delete(socket)+ if (ownConnection === 1) closeFirst()+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const req of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (req.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (req.cmd === 'attach' && ownConnection === 1 && firstAttach) {+ // The very first attach for this name (cold-create, connection 1): refused.+ firstAttach = false+ socket.write(encodeFrame({ id: req.id, ok: false, error: 'one subscriber refused' }))+ } else if (req.cmd === 'attach' && ownConnection === 1) {+ // The surviving subscriber's attach. Per-name attaches are serialized (`nameTails`),+ // so this cannot arrive until the refused one above has already been answered — no+ // session was ever attached yet, so this is still a cold-create `attach`, not a+ // warm-only `attachExisting`. v2 requires a valid `generation` in the result.+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { fresh: false, generation: 'generation-shared' }+ })+ )+ } else if (req.cmd === 'attachExisting' && ownConnection > 1) {+ // Reconnect replay of the surviving (only remaining) subscriber, after connection 1+ // is destroyed below. Warm-only: no `spawn` field exists to inspect.+ replayedRequests.push(req)+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { fresh: false, generation: 'generation-shared' }+ }) ++ encodeFrame({+ type: 'data',+ name: req.name,+ data: 'replayed-live-data',+ generation: 'generation-shared'+ })+ )+ } else if (req.cmd === 'hasSession') {+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { exists: true, generation: 'generation-shared' }+ })+ )+ }+ }+ })+ })+ await listen(server, paths.endpoint)++ const refusedData = vi.fn()+ const keptData = vi.fn()+ const client = new SessionHostClient({ userDataDir })+ const refusedSubscriber = { onData: refusedData, onExit: () => {} }+ const keptSubscriber = { onData: keptData, onExit: () => {} }+ const refused = client.attach(+ 'nt-shared',+ spawnOptions(userDataDir, ['failed-options']),+ 1_000,+ refusedSubscriber+ )+ const kept = client.attach(+ 'nt-shared',+ spawnOptions(userDataDir, ['kept-options']),+ 1_000,+ keptSubscriber+ )++ await expect(within(refused)).rejects.toThrow('one subscriber refused')+ await expect(within(kept)).resolves.toEqual({ fresh: false, generation: 'generation-shared' })+ firstSocket?.destroy()+ await firstClosed+ await expect(within(client.hasSession('nt-shared'))).resolves.toBe(true)+ await expect.poll(() => replayedRequests).toHaveLength(1)+ expect(replayedRequests[0]).toMatchObject({+ cmd: 'attachExisting',+ name: 'nt-shared',+ expectedGeneration: 'generation-shared'+ })+ expect('spawn' in replayedRequests[0]).toBe(false)+ await expect.poll(() => keptData.mock.calls).toEqual([['replayed-live-data']])+ expect(refusedData).not.toHaveBeenCalled()+ client.unsubscribe('nt-shared', keptSubscriber)+ })++ it.each(['capture', 'killSession'] as const)(+ 'propagates an uncertain %s failure instead of claiming success',+ async (command) => {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-session-client-'))+ tempDirs.add(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ publishHostIdentity(userDataDir)++ const server = net.createServer((socket) => {+ openSockets.add(socket)+ socket.once('close', () => openSockets.delete(socket))+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const req of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {+ if (req.cmd === 'hello') {+ socket.write(+ encodeFrame({+ id: req.id,+ ok: true,+ result: { protocolVersion: SESSION_HOST_PROTOCOL_VERSION }+ })+ )+ } else if (req.cmd === 'hasSession') {+ // `killSession` with no known generation probes `hasSession` first+ // (`prepareAndConfirmKillSession`) before ever sending the destructive frame this+ // test destroys the socket on; `capture` never sends this probe, so it is unused+ // there. Answer 'absent' so the kill proceeds straight to the killSession attempt.+ socket.write(encodeFrame({ id: req.id, ok: true, result: { exists: false } }))+ } else if (req.cmd === command) socket.destroy()+ }+ })+ })+ await listen(server, paths.endpoint)++ const client = new SessionHostClient({ userDataDir })+ const request: Promise<unknown> =+ command === 'capture'+ ? client.capture('nt-uncertain', true)+ : client.killSession('nt-uncertain')+ // `killSession` retries its confirmation once through a fresh reconnect before giving up+ // (`KILL_CONFIRMATION_ATTEMPTS`), so its final rejection is the wrapping "remains+ // unconfirmed" error — which still carries this exact message as its trailing+ // "Last error: ..." — while `capture` rejects with it directly. `toThrow` matches either+ // way since it checks message containment, not equality.+ await expect(within(request)).rejects.toThrow('session-host connection lost')+ }+ )+})diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsnew file mode 100644index 000000000..bdc556cd0--- /dev/null+++ b/src/core/session-host-client.ts@@ -0,0 +1,1638 @@+// The Electron-main-side client for the session host: one long-lived connection per app process,+// auto-spawning the host on first use and restoring every live local attachment before allowing+// ordinary traffic through a replacement connection.++import net from 'net'+import { randomUUID } from 'crypto'+// The REAL scheduler, immune to vi.useFakeTimers (which patches the global, not this module's+// exports): requestOnSocket defers each frame's write by one genuine event-loop turn so queued+// socket 'close' events dispatch first, even inside fake-timer tests.+import { setImmediate as realSetImmediate } from 'timers'+import { sessionHostPaths } from '../session-host/paths'+import { readExistingSessionHostIdentity } from '../session-host/existing-host-state'+import {+ SESSION_HOST_PROTOCOL_VERSION,+ LineFramer,+ encodeFrame,+ type SessionHostRequest,+ type SessionHostRequestBody,+ type SessionHostFrame,+ type SessionHostSpawnOptions,+ type AttachResult,+ type HasSessionResult,+ type PaneCommandResult,+ type CaptureResult,+ type KillSessionResult,+ type ExecuteLaunchResult,+ type ListSessionsResult+} from '../session-host/protocol'+import { resolveSessionHostScript, spawnSessionHost } from './session-host-launcher'+import type { PreparedAgentLaunch } from './agent-launch'++export interface SessionSubscriber {+ onData(data: string): void+ onExit(exitCode: number): void+ /** A previously confirmed attachment failed to restore. This is not an exit: the host's+ * rejection is retained so the owning manager can retire only the affected generation. */+ onAttachError?(error: Error): void+}++export const SESSION_HOST_REQUEST_TIMEOUT_MS = 10_000++const RECONNECT_DELAYS_MS = [50, 100, 250, 500, 1_000, 2_000] as const+const RECONNECT_REPAINT_PREFIX = '\x1b[3J\x1b[2J\x1b[H'+const HANDSHAKE_TIMEOUT_MS = 2_000+const KILL_CONFIRMATION_ATTEMPTS = 2++type PendingEntry = {+ socket: net.Socket+ timer: ReturnType<typeof setTimeout> | null+ /** True once the frame has been handed to socket.write. Until then the frame provably never+ * left this process, so a transport drop rejects the entry as resendable (see dropSocket). */+ sent: boolean+ resolve: (result: unknown) => void+ reject: (error: Error) => void+}++type SubscriberEntry = {+ sub: SessionSubscriber+ /** Present only on a cold create request. Warm reconnect and attachExisting deliberately carry+ * no spawn plan, so a stale profile can never recreate an exited generation. */+ spawn?: SessionHostSpawnOptions+ scrollback: number+ phase: 'attaching' | 'attached'+}++type BufferedFrame = {+ data: string+ /** Entry identity, not merely the callback object: an unsubscribe/re-attach using the same+ * object must not inherit bytes that belonged to its retired registration. */+ recipients: Set<SubscriberEntry>+}++type TerminalSize = { cols: number; rows: number }++/** Identity of one in-flight/retried `killSession` operation, keyed by name in `killOperations`.+ * `prepared` marks the point past which a failure must preserve (never roll back) the barrier+ * and identity, because a destructive frame may already be in flight or answered. */+type KillOperationIdentity = {+ operationId: string+ expectedGeneration?: string+ reserveReplacement: boolean+ requireV2: boolean+ expectedAbsent: boolean+ prepared?: boolean+}++type ClientSessionState = {+ name: string+ generation?: string+ protocolVersion?: 1 | 2+ entries: Map<SessionSubscriber, SubscriberEntry>+ pauseOwners: Set<SessionSubscriber>+ sizeClaims: Map<SessionSubscriber, TerminalSize>+ bufferedData: BufferedFrame[]+ /** Attaches that have actually reached their request phase. Only these may own data arriving+ * before the correlated attach response; a merely queued replacement must not absorb bytes+ * from the generation whose detach/kill still precedes it in the name lane. */+ preAckEntries: Set<SubscriberEntry>+ /** An exit can race the correlated attach response in the same socket turn. Remember it so the+ * response cannot promote a process generation the host has already retired. */+ preAckExit: boolean+ /** True after the last local pause owner leaves, until a host acknowledgement makes flowing+ * certain again. Data that raced the acknowledgement is retained behind this gate. */+ releasePending: boolean+ appliedSocket: net.Socket | null+ appliedAttached: boolean+ appliedPaused: boolean+ appliedSize: TerminalSize | null+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}++function asError(error: unknown): Error {+ return error instanceof Error ? error : new Error(String(error))+}++function isTransportUncertainty(value: unknown): boolean {+ const error = asError(value) as NodeJS.ErrnoException+ if (+ error.code === 'ECONNRESET' ||+ error.code === 'EPIPE' ||+ error.code === 'ECONNABORTED' ||+ error.code === 'ERR_STREAM_DESTROYED'+ ) {+ return true+ }+ return (+ error.message.includes('session-host connection lost') ||+ error.message.includes('session-host request timed out') ||+ error.message.includes('socket')+ )+}++/** Protocol-v1 hosts stay alive for warm terminal continuity. Operations that need atomic+ * generation or replacement semantics fail closed without replacing that live host. */+export class SessionHostProtocolCompatibilityError extends Error {+ readonly code = 'SESSION_HOST_PROTOCOL_INCOMPATIBLE'++ constructor(operation: string) {+ super(+ `The persistent terminal host is from an older nodeterm version and cannot ${operation}. ` ++ 'Existing terminals remain attachable; close them and let the legacy host exit before ' ++ 'starting or restarting a Windows terminal.'+ )+ this.name = 'SessionHostProtocolCompatibilityError'+ }+}++/** A request frame that provably never left this process: the tracked socket was already gone+ * when the write was attempted, or the write callback itself reported the failure. Unlike a+ * timeout or a mid-flight connection drop — where the host may have received and acted on the+ * frame — resending this exact request on a fresh connection cannot double-apply anything.+ * `code` carries the underlying errno so `isTransportUncertainty` classification is unchanged+ * for any caller the bounded resend in `request()` re-throws to. */+class SessionHostRequestNotDeliveredError extends Error {+ code?: string+ /** The raw transport failure. `request()` surfaces THIS when a resend cannot happen (reconnect+ * refused, attempts exhausted), so callers keep the exact error object shape they always got. */+ readonly original: Error++ constructor(original: Error) {+ super(original.message)+ this.original = original+ const code = (original as NodeJS.ErrnoException).code+ if (code) this.code = code+ }+}++/** How many times `request()` re-runs connect + send for a frame that provably never left the+ * process. Purely a spin bound: each retry only happens after a successful fresh hello, so a+ * host that dies right after every accept cannot loop this forever. */+const SESSION_HOST_RESEND_ATTEMPTS = 3++function requireAttachResult(+ result: AttachResult | undefined,+ name: string,+ protocolVersion: 1 | 2+): AttachResult {+ if (!result || typeof result.fresh !== 'boolean') {+ throw new Error(`session-host returned an invalid attachment result for '${name}'`)+ }+ if (+ protocolVersion === 2 &&+ (typeof result.generation !== 'string' || !/^[A-Za-z0-9_-]{8,128}$/.test(result.generation))+ ) {+ throw new Error(`session-host returned no generation for attachment '${name}'`)+ }+ return result+}++function legacyWarmOnlySentinel(userDataDir: string): SessionHostSpawnOptions {+ const env: Record<string, string> = {}+ for (const [key, value] of Object.entries(process.env)) {+ if (typeof value === 'string') env[key] = value+ }+ env.ELECTRON_RUN_AS_NODE = '1'+ return {+ cwd: userDataDir,+ shell: process.execPath,+ args: ['-e', 'process.stdout.write("nodeterm legacy warm-only sentinel\\n")'],+ env,+ cols: 1,+ rows: 1+ }+}++function sameSize(left: TerminalSize | null, right: TerminalSize): boolean {+ return left?.cols === right.cols && left.rows === right.rows+}++function normalizeDimension(value: number, fallback: number): number {+ return Number.isFinite(value) ? Math.max(1, Math.floor(value)) : fallback+}++export class SessionHostClient {+ private socket: net.Socket | null = null+ private negotiatedProtocolVersion: 1 | 2 | null = null+ private nextId = 1+ private readonly pending = new Map<number, PendingEntry>()+ private readonly sessions = new Map<string, ClientSessionState>()+ /** Survives state replacement. Cleanup invoked for an old generation always stays ahead of a+ * later same-name attach, even after the old state has left `sessions`. */+ private readonly nameTails = new Map<string, Promise<void>>()+ private readonly sessionGenerations = new Map<string, string>()+ /** Installed before the first destructive write so reconnect restoration cannot resurrect an+ * old generation whose kill reply may have been lost. */+ private readonly killReplayBarriers = new Set<string>()+ private readonly killsInFlight = new Map<string, Promise<void>>()+ private readonly killOperations = new Map<string, KillOperationIdentity>()+ private readonly replacementTokens = new Map<string, string>()+ private connecting: Promise<void> | null = null+ private everConnected = false+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null+ private reconnectAttempt = 0++ constructor(+ private readonly deps: {+ userDataDir: string+ resourcesPath?: string | null+ repoRoot?: string | null+ }+ ) {}++ bundleAvailable(): boolean {+ return (+ resolveSessionHostScript({+ resourcesPath: this.deps.resourcesPath,+ repoRoot: this.deps.repoRoot+ }) !== null+ )+ }++ private newState(name: string): ClientSessionState {+ return {+ name,+ entries: new Map(),+ pauseOwners: new Set(),+ sizeClaims: new Map(),+ bufferedData: [],+ preAckEntries: new Set(),+ preAckExit: false,+ releasePending: false,+ appliedSocket: null,+ appliedAttached: false,+ appliedPaused: false,+ appliedSize: null+ }+ }++ private enqueueState<T>(state: ClientSessionState, task: () => Promise<T>): Promise<T> {+ return this.enqueueName(state.name, task)+ }++ private enqueueName<T>(name: string, task: () => Promise<T>): Promise<T> {+ const previous = this.nameTails.get(name) ?? Promise.resolve()+ const run = previous.then(task, task)+ const settled = run.then(+ () => undefined,+ () => undefined+ )+ this.nameTails.set(name, settled)+ void settled.then(() => {+ if (this.nameTails.get(name) === settled) this.nameTails.delete(name)+ })+ return run+ }++ private hasAttachedEntry(state: ClientSessionState): boolean {+ for (const entry of state.entries.values()) {+ if (entry.phase === 'attached') return true+ }+ return false+ }++ private hasDesiredAttachments(): boolean {+ for (const state of this.sessions.values()) {+ if (this.hasAttachedEntry(state)) return true+ }+ return false+ }++ private effectiveSize(state: ClientSessionState): TerminalSize {+ let cols = Number.POSITIVE_INFINITY+ let rows = Number.POSITIVE_INFINITY+ for (const claim of state.sizeClaims.values()) {+ cols = Math.min(cols, claim.cols)+ rows = Math.min(rows, claim.rows)+ }+ // Every entry receives a claim before it enters the map. This fallback only protects a+ // teardown race from ever putting non-finite geometry on the wire.+ return {+ cols: Number.isFinite(cols) ? cols : 80,+ rows: Number.isFinite(rows) ? rows : 24+ }+ }++ private async ensureConnected(): Promise<void> {+ // A newly authenticated socket is visible while its reconnect restoration is still running.+ // The barrier wins over the raw socket check so no later request can overtake replay.+ if (this.connecting) return this.connecting+ if (this.socket && !this.socket.destroyed) return+ const attempt = this.doConnect()+ this.connecting = attempt+ void attempt.then(+ () => {+ if (this.connecting === attempt) this.connecting = null+ this.reconnectAttempt = 0+ },+ () => {+ if (this.connecting === attempt) this.connecting = null+ this.scheduleAutoReconnect()+ }+ )+ return attempt+ }++ private async doConnect(): Promise<void> {+ const wasConnectedBefore = this.everConnected+ if (await this.tryConnectBeforeLaunch()) {+ const socket = this.socket+ if (wasConnectedBefore && socket) await this.restoreSocket(socket)+ return+ }++ const script = resolveSessionHostScript({+ resourcesPath: this.deps.resourcesPath,+ repoRoot: this.deps.repoRoot+ })+ if (!script) {+ throw new Error(+ 'session-host bundle not found (out/session-host/host.cjs is missing — run `npm run host:build`, ' ++ 'or `npm run build` which now runs it too)'+ )+ }+ spawnSessionHost(script, this.deps.userDataDir)+ let lastPublicationError: Error | null = null+ for (let attempt = 0; attempt < 30; attempt++) {+ await sleep(150)+ try {+ if (await this.tryConnectOnce()) {+ const socket = this.socket+ if (wasConnectedBefore && socket) await this.restoreSocket(socket)+ return+ }+ lastPublicationError = null+ } catch (error) {+ const typed = asError(error)+ if (!this.isTransientPublicationLock(typed)) throw typed+ lastPublicationError = typed+ }+ }+ if (lastPublicationError) throw lastPublicationError+ throw new Error('session-host did not come up in time')+ }++ private isTransientPublicationLock(error: Error): boolean {+ return error.message === 'invalid session-host state: file is empty'+ }++ /** An exclusive-create startup lock is briefly empty before atomic state publication. Retry+ * only that exact state within a small bound; every other unreadable or malformed observation+ * remains an immediate integrity failure and never reaches the launcher. */+ private async tryConnectBeforeLaunch(): Promise<boolean> {+ let lastError: Error | null = null+ for (let attempt = 0; attempt < 5; attempt++) {+ try {+ return await this.tryConnectOnce()+ } catch (error) {+ const typed = asError(error)+ if (!this.isTransientPublicationLock(typed)) throw typed+ lastError = typed+ await sleep(50)+ }+ }+ throw lastError ?? new Error('session-host state publication did not complete')+ }++ private async tryConnectOnce(): Promise<boolean> {+ const paths = sessionHostPaths(this.deps.userDataDir)+ const identity = readExistingSessionHostIdentity(paths.statePath, {+ expectedEndpoint: paths.endpoint,+ expectedTokenPath: paths.tokenPath+ })+ if (identity.kind === 'absent') return false+ if (+ identity.state.protocolVersion !== 1 &&+ identity.state.protocolVersion !== SESSION_HOST_PROTOCOL_VERSION+ ) {+ throw new Error(+ `incompatible session-host protocol: host=${identity.state.protocolVersion}, ` ++ `client=${SESSION_HOST_PROTOCOL_VERSION}`+ )+ }+ const token = identity.token+ if (!/^[a-f0-9]{64}$/.test(token)) {+ throw new Error('invalid session-host token: expected 64 hexadecimal characters')+ }+ const endpoint = identity.state.endpoint+ return new Promise((resolve, reject) => {+ let settled = false+ let connected = false+ const socket = net.connect(endpoint)+ socket.unref?.()+ const framer = new LineFramer()+ const helloId = this.nextId+++ let protocolVersion: 1 | 2 | null = null+ const finish = (ok: boolean, trailing: SessionHostFrame[] = []): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ socket.removeListener('connect', onHandshakeConnect)+ socket.removeListener('data', onHandshakeData)+ socket.removeListener('error', onHandshakeError)+ socket.removeListener('close', onHandshakeClose)+ if (ok) {+ if (!protocolVersion) {+ failHandshake(new Error('session-host hello did not negotiate a protocol version'))+ return+ }+ this.attachSocket(socket, protocolVersion)+ for (const frame of trailing) this.handleFrame(socket, frame)+ } else {+ try {+ socket.destroy()+ } catch {+ /* already gone */+ }+ }+ resolve(ok)+ }+ const failHandshake = (error: Error): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ socket.removeListener('connect', onHandshakeConnect)+ socket.removeListener('data', onHandshakeData)+ socket.removeListener('error', onHandshakeError)+ socket.removeListener('close', onHandshakeClose)+ try {+ socket.destroy()+ } catch {+ /* already gone */+ }+ reject(error)+ }+ const onHandshakeError = (error: Error): void => {+ if (connected) failHandshake(error)+ else finish(false)+ }+ const onHandshakeClose = (): void => {+ if (connected) failHandshake(new Error('session-host closed during hello'))+ else finish(false)+ }+ const onHandshakeConnect = (): void => {+ connected = true+ try {+ socket.write(+ encodeFrame({+ id: helloId,+ cmd: 'hello',+ token,+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ }),+ (error) => {+ if (error) failHandshake(asError(error))+ }+ )+ } catch (error) {+ failHandshake(asError(error))+ }+ }+ const onHandshakeData = (chunk: Buffer): void => {+ const frames = framer.push<SessionHostFrame>(chunk.toString('utf8'))+ for (let index = 0; index < frames.length; index++) {+ const frame = frames[index]+ if ('type' in frame || frame.id !== helloId) continue+ if (frame.ok) {+ const advertised = (frame.result as { protocolVersion?: unknown } | undefined)+ ?.protocolVersion+ const negotiated =+ advertised === undefined+ ? 1+ : advertised === SESSION_HOST_PROTOCOL_VERSION+ ? 2+ : null+ if (!negotiated) {+ failHandshake(+ new Error(+ `session-host protocol is incompatible: expected version ` ++ `${SESSION_HOST_PROTOCOL_VERSION}, received ${String(advertised ?? 'none')}`+ )+ )+ return+ }+ if (identity.state.protocolVersion !== negotiated) {+ failHandshake(+ new Error(+ `session-host protocol publication disagrees with hello: state=` ++ `${identity.state.protocolVersion}, hello=${negotiated}`+ )+ )+ return+ }+ protocolVersion = negotiated+ finish(true, frames.slice(index + 1))+ } else {+ failHandshake(new Error(`session-host hello rejected: ${frame.error}`))+ }+ return+ }+ }+ const timer = setTimeout(() => {+ if (connected) failHandshake(new Error('session-host hello timed out'))+ else finish(false)+ }, HANDSHAKE_TIMEOUT_MS)+ timer.unref?.()+ socket.once('error', onHandshakeError)+ socket.once('close', onHandshakeClose)+ socket.once('connect', onHandshakeConnect)+ socket.on('data', onHandshakeData)+ })+ }++ private attachSocket(socket: net.Socket, protocolVersion: 1 | 2): void {+ this.socket = socket+ this.negotiatedProtocolVersion = protocolVersion+ this.everConnected = true+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {+ this.handleFrame(socket, frame)+ }+ })+ const onError = (error: Error): void => this.dropSocket(socket, error)+ const onClose = (): void => this.dropSocket(socket, new Error('session-host connection lost'))+ socket.on('error', onError)+ socket.once('close', onClose)+ }++ private dropSocket(socket: net.Socket, error: Error, destroy = false): void {+ const wasCurrent = this.socket === socket+ if (wasCurrent) {+ this.socket = null+ this.negotiatedProtocolVersion = null+ for (const state of this.sessions.values()) {+ if (state.appliedSocket !== socket) continue+ state.appliedSocket = null+ state.appliedAttached = false+ state.appliedPaused = false+ state.appliedSize = null+ }+ }+ for (const [id, entry] of this.pending) {+ if (entry.socket !== socket) continue+ this.pending.delete(id)+ if (entry.timer) clearTimeout(entry.timer)+ // A frame never handed to socket.write is CERTAINLY undelivered — reject it as resendable+ // so request() can replay it on a fresh connection. A written frame stays uncertainty.+ entry.reject(entry.sent ? error : new SessionHostRequestNotDeliveredError(error))+ }+ if (destroy && !socket.destroyed) {+ try {+ socket.destroy()+ } catch {+ /* already gone */+ }+ }+ if (wasCurrent) this.scheduleAutoReconnect()+ }++ private scheduleAutoReconnect(): void {+ if (this.socket || this.connecting || this.reconnectTimer || !this.hasDesiredAttachments()) {+ return+ }+ const delay = RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]+ this.reconnectAttempt+++ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null+ if (!this.hasDesiredAttachments()) return+ void this.ensureConnected().catch(() => {+ // ensureConnected's rejection handler schedules the next bounded-backoff attempt.+ })+ }, delay)+ this.reconnectTimer.unref?.()+ }++ private stopReconnectIfIdle(): void {+ if (this.hasDesiredAttachments()) return+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer)+ this.reconnectTimer = null+ this.reconnectAttempt = 0+ }++ private handleFrame(socket: net.Socket, frame: SessionHostFrame): void {+ if (this.socket !== socket) return+ if ('type' in frame) {+ const state = this.sessions.get(frame.name)+ if (!state) return+ const protocolVersion = this.negotiatedProtocolVersion+ if (protocolVersion === 2) {+ if (+ typeof frame.generation !== 'string' ||+ !/^[A-Za-z0-9_-]{8,128}$/.test(frame.generation)+ ) {+ return+ }+ const expected = state.generation ?? this.sessionGenerations.get(frame.name)+ if (expected && expected !== frame.generation) return+ if (!expected && state.preAckEntries.size > 0) {+ state.generation = frame.generation+ this.sessionGenerations.set(frame.name, frame.generation)+ } else if (!expected) {+ return+ }+ } else if (state.protocolVersion === 2) {+ return+ }+ if (frame.type === 'data') {+ this.deliverData(state, frame.data)+ } else {+ this.handleExit(state, frame.exitCode)+ }+ return+ }++ const entry = this.pending.get(frame.id)+ if (!entry || entry.socket !== socket) return+ this.pending.delete(frame.id)+ if (entry.timer) clearTimeout(entry.timer)+ if (frame.ok) entry.resolve(frame.result)+ else entry.reject(new Error(frame.error))+ }++ private deliverData(state: ClientSessionState, data: string): void {+ if (state.preAckExit) return+ const attached = [...state.entries.values()].filter((entry) => entry.phase === 'attached')+ if (attached.length === 0) {+ // A cold process can write between host-side subscriber activation and the attach response.+ // Retain those bytes for the attaching owner; the correlated response promotes it before+ // this queue is flushed. An old-generation exit clears the queue instead.+ if (state.preAckEntries.size > 0) {+ state.bufferedData.push({ data, recipients: new Set(state.preAckEntries) })+ }+ return+ }+ if (state.pauseOwners.size > 0 || state.releasePending) {+ state.bufferedData.push({ data, recipients: new Set(attached) })+ return+ }+ this.deliverToEntries(attached, data)+ }++ private deliverToEntries(entries: Iterable<SubscriberEntry>, data: string): void {+ for (const entry of entries) {+ try {+ entry.sub.onData(data)+ } catch {+ // One renderer subscriber must not starve its co-attached neighbors.+ }+ }+ }++ private flushData(state: ClientSessionState): void {+ if (state.pauseOwners.size > 0 || state.releasePending || state.bufferedData.length === 0) return+ const queued = state.bufferedData+ state.bufferedData = []+ for (const frame of queued) {+ const liveRecipients = [...frame.recipients].filter(+ (entry) =>+ entry.phase === 'attached' && state.entries.get(entry.sub) === entry+ )+ this.deliverToEntries(liveRecipients, frame.data)+ }+ }++ private handleExit(state: ClientSessionState, exitCode: number): void {+ const retired = [...state.entries.values()].filter((entry) => entry.phase === 'attached')+ if (retired.length === 0 && state.preAckEntries.size > 0) state.preAckExit = true+ // Retire the old generation before callbacks. An onExit callback may synchronously attach the+ // same name; post-callback deletion would otherwise erase that replacement generation.+ for (const entry of retired) {+ state.entries.delete(entry.sub)+ state.preAckEntries.delete(entry)+ state.pauseOwners.delete(entry.sub)+ state.sizeClaims.delete(entry.sub)+ }+ state.bufferedData = []+ state.releasePending = false+ state.appliedSocket = null+ state.appliedAttached = false+ state.appliedPaused = false+ state.appliedSize = null+ if (state.entries.size === 0 && this.sessions.get(state.name) === state) {+ this.sessions.delete(state.name)+ }+ if (retired.length > 0) {+ this.sessionGenerations.delete(state.name)+ state.generation = undefined+ }+ this.stopReconnectIfIdle()+ for (const entry of retired) {+ try {+ entry.sub.onExit(exitCode)+ } catch {+ // Exit delivery is isolated for the same reason as data delivery.+ }+ }+ }++ private async request<T>(+ request: SessionHostRequestBody,+ onSuccess?: (result: T, socket: net.Socket) => void+ ): Promise<T> {+ // A peer-initiated close races the client's own 'close' event: a cached socket can look live+ // here while the peer already hung up, and a frame written into that gap fails (EPIPE) for+ // work the host never saw. requestOnSocket defers the actual write by one REAL event-loop+ // turn, so a raced hangup is discovered before any bytes are committed; such a frame is the+ // one provably-undelivered case and the only one resent here on a fresh connection. A failure+ // discovered by the write itself stays a plain rejection: by then the frame's delivery is the+ // transport's business and other requests may already ride on it.+ let undelivered: SessionHostRequestNotDeliveredError | undefined+ for (let attempt = 0; ; attempt++) {+ try {+ await this.ensureConnected()+ } catch (connectError) {+ // A resend that cannot even reconnect reports the transport failure the caller actually+ // hit, not the follow-up connect refusal; a cold first connect keeps its own error.+ throw undelivered?.original ?? connectError+ }+ const socket = this.socket+ if (!socket) throw new Error('session-host: not connected')+ try {+ return await this.requestOnSocket(socket, request, onSuccess)+ } catch (error) {+ if (!(error instanceof SessionHostRequestNotDeliveredError)) throw error+ if (attempt + 1 >= SESSION_HOST_RESEND_ATTEMPTS) throw error.original+ undelivered = error+ }+ }+ }++ /** Request on an already-authenticated socket. Reconnect restoration uses this directly because+ * calling ensureConnected from inside the connection barrier would recursively await itself. */+ private requestOnSocket<T>(+ socket: net.Socket,+ request: SessionHostRequestBody,+ onSuccess?: (result: T, socket: net.Socket) => void+ ): Promise<T> {+ if (this.socket !== socket || socket.destroyed) {+ return Promise.reject(+ new SessionHostRequestNotDeliveredError(new Error('session-host connection lost'))+ )+ }+ const id = this.nextId+++ const full = { id, ...request } as SessionHostRequest+ return new Promise<T>((resolve, reject) => {+ const pending: PendingEntry = {+ socket,+ timer: null,+ sent: false,+ resolve: (result) => {+ try {+ const typed = result as T+ onSuccess?.(typed, socket)+ resolve(typed)+ } catch (error) {+ reject(asError(error))+ }+ },+ reject+ }+ pending.timer = setTimeout(() => {+ if (this.pending.get(id) !== pending) return+ const deadline = new Error(`session-host request timed out: ${request.cmd}`)+ // The deadline is uncertainty even for a frame still queued behind the send turn below:+ // reject THIS entry directly (never as resendable), then retire the socket for the rest.+ this.pending.delete(id)+ pending.reject(deadline)+ this.dropSocket(socket, deadline, true)+ }, SESSION_HOST_REQUEST_TIMEOUT_MS)+ pending.timer.unref?.()+ this.pending.set(id, pending)+ // The send is deferred one REAL event-loop turn (immune to fake timers — the deadline above+ // is already armed). A peer hangup that has reached this process marks the socket destroyed+ // during the poll phase, BEFORE immediates run, so the recheck sees the loss while the frame+ // is still provably unwritten and dropSocket can reject it as resendable; writes stay FIFO+ // because immediates run in scheduling order.+ realSetImmediate(() => {+ if (this.pending.get(id) !== pending) return+ if (this.socket !== socket || socket.destroyed) {+ this.dropSocket(socket, new Error('session-host connection lost'), true)+ return+ }+ pending.sent = true+ try {+ socket.write(encodeFrame(full), (error) => {+ // A response may beat a late write callback. Identity-check this exact pending entry so+ // that callback can neither settle nor delete a newer request that reused surrounding state.+ if (!error || this.pending.get(id) !== pending) return+ this.dropSocket(socket, asError(error), true)+ })+ } catch (error) {+ if (this.pending.get(id) === pending) this.dropSocket(socket, asError(error), true)+ }+ })+ })+ }++ private applyAttachment(+ state: ClientSessionState,+ socket: net.Socket,+ paused: boolean,+ size: TerminalSize+ ): void {+ if (this.sessions.get(state.name) !== state || !this.hasAttachedEntry(state)) return+ state.appliedSocket = socket+ state.appliedAttached = true+ state.appliedPaused = paused+ state.appliedSize = size+ if (!paused && state.pauseOwners.size === 0) {+ state.releasePending = false+ this.flushData(state)+ }+ }++ private async restoreSocket(socket: net.Socket): Promise<void> {+ try {+ for (const state of [...this.sessions.values()]) {+ if (this.sessions.get(state.name) !== state) continue+ if (this.killReplayBarriers.has(state.name)) continue+ const anchor = [...state.entries.values()].find((entry) => entry.phase === 'attached')+ if (!anchor) continue+ const size = this.effectiveSize(state)+ const paused = state.pauseOwners.size > 0+ const protocolVersion = this.negotiatedProtocolVersion+ if (!protocolVersion) throw new Error('session-host: not connected')+ try {+ if (state.protocolVersion && state.protocolVersion !== protocolVersion) {+ throw new Error(+ `session-host protocol changed while '${state.name}' was detached; warm replay is unsafe`+ )+ }+ const expectedGeneration = state.generation ?? this.sessionGenerations.get(state.name)+ // Validation and repaint delivery run SYNCHRONOUSLY inside the response frame's parse+ // pass (requestOnSocket's onSuccess), not in the awaited continuation below. On a unix+ // socket the host's next raw 'data' frame can share one read chunk with this response;+ // deferring the repaint to the microtask behind `await` would let that live frame reach+ // deliverData first and reverse the repaint-then-live order subscribers depend on.+ let staleAttachment = false+ const applyReplay = (response: AttachResult, replaySocket: net.Socket): void => {+ const result = requireAttachResult(response, state.name, protocolVersion)+ if (result.fresh) {+ throw new Error(+ protocolVersion === 1+ ? `legacy session-host lost '${state.name}' before warm replay; no requested shell was spawned`+ : `session-host protocol violation: attachExisting '${state.name}' reported a fresh session`+ )+ }+ if (+ protocolVersion === 2 &&+ expectedGeneration &&+ result.generation !== expectedGeneration+ ) {+ throw new Error(+ `session-host generation changed while '${state.name}' was detached; warm replay is unsafe`+ )+ }+ if (this.sessions.get(state.name) !== state || !this.hasAttachedEntry(state)) {+ staleAttachment = true+ return+ }+ state.protocolVersion = protocolVersion+ state.generation = result.generation ?? expectedGeneration+ if (state.generation) this.sessionGenerations.set(state.name, state.generation)+ this.applyAttachment(state, replaySocket, paused, size)+ if (result.screen && state.appliedSocket === replaySocket) {+ this.deliverData(state, RECONNECT_REPAINT_PREFIX + result.screen)+ }+ }+ if (protocolVersion === 1) {+ await this.requestOnSocket<AttachResult>(+ socket,+ {+ cmd: 'attach',+ name: state.name,+ spawn: legacyWarmOnlySentinel(this.deps.userDataDir),+ scrollback: 1,+ paused+ },+ applyReplay+ )+ } else {+ await this.requestOnSocket<AttachResult>(+ socket,+ {+ cmd: 'attachExisting',+ name: state.name,+ expectedGeneration,+ cols: size.cols,+ rows: size.rows,+ paused+ },+ applyReplay+ )+ }+ if (staleAttachment) {+ await this.requestOnSocket(socket, { cmd: 'detach', name: state.name })+ continue+ }+ await this.reconcileOnSocket(state, socket)+ } catch (error) {+ if (this.socket !== socket || socket.destroyed || isTransportUncertainty(error)) throw error+ // A correlated warm-attach rejection retires exactly this generation. It must not keep+ // retrying forever or be translated into a process exit that the host never reported.+ if (this.sessions.get(state.name) === state) this.sessions.delete(state.name)+ this.sessionGenerations.delete(state.name)+ state.generation = undefined+ state.bufferedData = []+ state.preAckEntries.clear()+ state.appliedSocket = null+ state.appliedAttached = false+ state.appliedPaused = false+ state.appliedSize = null+ const failure = asError(error)+ for (const entry of state.entries.values()) {+ try {+ entry.sub.onAttachError?.(failure)+ } catch {+ /* one owner callback must not hide the same failure from its co-attached neighbors */+ }+ }+ state.entries.clear()+ this.stopReconnectIfIdle()+ }+ }+ } catch (error) {+ this.dropSocket(socket, asError(error), true)+ throw error+ }+ }++ private async reconcileOnSocket(state: ClientSessionState, socket: net.Socket): Promise<void> {+ if (+ this.sessions.get(state.name) !== state ||+ !this.hasAttachedEntry(state) ||+ state.appliedSocket !== socket ||+ !state.appliedAttached+ ) {+ return+ }+ const desiredPaused = state.pauseOwners.size > 0+ if (desiredPaused && !state.appliedPaused) {+ await this.requestOnSocket(socket, { cmd: 'pause', name: state.name })+ if (this.socket !== socket) return+ // Record a confirmed host ticket even if the final local owner retired while the request+ // was in flight. Its teardown lane then knows it owes the matching resume before detach.+ state.appliedPaused = true+ if (this.sessions.get(state.name) !== state) return+ }++ const desiredSize = this.effectiveSize(state)+ if (!sameSize(state.appliedSize, desiredSize)) {+ await this.requestOnSocket(socket, {+ cmd: 'resize',+ name: state.name,+ cols: desiredSize.cols,+ rows: desiredSize.rows+ })+ if (this.socket !== socket) return+ state.appliedSize = desiredSize+ if (this.sessions.get(state.name) !== state) return+ }++ if (!desiredPaused && state.appliedPaused) {+ await this.requestOnSocket(socket, { cmd: 'resume', name: state.name })+ if (this.socket !== socket) return+ state.appliedPaused = false+ if (this.sessions.get(state.name) !== state) return+ }+ if (state.pauseOwners.size === 0 && !state.appliedPaused) {+ state.releasePending = false+ this.flushData(state)+ }+ }++ private async reconcileState(state: ClientSessionState): Promise<void> {+ if (this.sessions.get(state.name) !== state || !this.hasAttachedEntry(state)) return+ await this.ensureConnected()+ const socket = this.socket+ if (!socket) throw new Error('session-host: not connected')+ await this.reconcileOnSocket(state, socket)+ }++ private queueReconcile(state: ClientSessionState): void {+ void this.enqueueState(state, () => this.reconcileState(state)).catch((error) => {+ const socket = this.socket+ if (socket) this.dropSocket(socket, asError(error), true)+ })+ }++ private async teardownRetiredState(state: ClientSessionState): Promise<void> {+ const socket = state.appliedSocket+ if (!socket || this.socket !== socket || socket.destroyed || !state.appliedAttached) return+ try {+ // `releasePending` covers the conservative edge where the last owner retired while its+ // pause acknowledgement was still crossing the wire. Resume is idempotent on the host.+ if (state.appliedPaused || state.releasePending) {+ await this.requestOnSocket(socket, { cmd: 'resume', name: state.name })+ state.appliedPaused = false+ state.releasePending = false+ }+ await this.requestOnSocket(socket, { cmd: 'detach', name: state.name })+ state.appliedAttached = false+ } catch (error) {+ // A failed detach is unknown membership. Closing the socket makes the host release every+ // ticket and subscriber deterministically, with no ghost to replay.+ this.dropSocket(socket, asError(error), true)+ }+ }++ async attach(+ name: string,+ spawn: SessionHostSpawnOptions,+ scrollback: number,+ sub: SessionSubscriber+ ): Promise<AttachResult> {+ const normalizedSpawn = {+ ...spawn,+ cols: normalizeDimension(spawn.cols, 80),+ rows: normalizeDimension(spawn.rows, 24)+ }+ return this.attachSubscriber(+ name,+ sub,+ { kind: 'create', spawn: normalizedSpawn, scrollback },+ { cols: normalizedSpawn.cols, rows: normalizedSpawn.rows }+ )+ }++ /** Warm-only attach. The request carries the generation confirmed by hasSession/attach and no+ * spawn plan, so an exit racing the attach cannot recreate a shell with stale options. */+ async attachExisting(name: string, sub: SessionSubscriber): Promise<AttachResult> {+ return this.attachSubscriber(+ name,+ sub,+ { kind: 'existing', scrollback: 1 },+ { cols: 80, rows: 24 }+ )+ }++ private async attachSubscriber(+ name: string,+ sub: SessionSubscriber,+ requestKind:+ | { kind: 'create'; spawn: SessionHostSpawnOptions; scrollback: number }+ | { kind: 'existing'; scrollback: number },+ initialSize: TerminalSize+ ): Promise<AttachResult> {+ if (this.killReplayBarriers.has(name)) {+ throw new Error(+ `session-host: cannot attach '${name}' while its kill result is unconfirmed; ` ++ 'retry the kill before creating or attaching a replacement'+ )+ }+ let state = this.sessions.get(name)+ if (!state) {+ state = this.newState(name)+ this.sessions.set(name, state)+ }+ const previous = state.entries.get(sub)+ if (previous) throw new Error(`session-host subscriber is already attached: ${name}`)+ const entry: SubscriberEntry = {+ sub,+ ...(requestKind.kind === 'create' ? { spawn: requestKind.spawn } : {}),+ scrollback: requestKind.scrollback,+ phase: 'attaching'+ }+ state.entries.set(sub, entry)+ state.sizeClaims.set(sub, initialSize)++ return this.enqueueState(state, async () => {+ if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) {+ throw new Error(`session-host attachment was canceled: ${name}`)+ }+ const size = this.effectiveSize(state)+ const paused = state.pauseOwners.size > 0+ try {+ await this.ensureConnected()+ const protocolVersion = this.negotiatedProtocolVersion+ if (!protocolVersion) throw new Error('session-host: not connected')+ const alreadyAttached = this.hasAttachedEntry(state)+ const useWarmOnly = requestKind.kind === 'existing' || alreadyAttached+ if (!useWarmOnly && protocolVersion === 1) {+ throw new SessionHostProtocolCompatibilityError(`create terminal '${name}'`)+ }+ if (state.protocolVersion && state.protocolVersion !== protocolVersion) {+ throw new Error(+ `session-host protocol changed while '${name}' was attached; co-attach is unsafe`+ )+ }+ const expectedGeneration = state.generation ?? this.sessionGenerations.get(name)+ const replacementToken = useWarmOnly ? undefined : this.replacementTokens.get(name)+ state.preAckEntries.add(entry)+ let response: AttachResult | undefined+ const attempts = replacementToken ? 2 : 1+ for (let attempt = 0; attempt < attempts; attempt++) {+ try {+ response = useWarmOnly+ ? protocolVersion === 1+ ? await this.request<AttachResult>({+ cmd: 'attach',+ name,+ spawn: legacyWarmOnlySentinel(this.deps.userDataDir),+ scrollback: 1,+ paused+ })+ : await this.request<AttachResult>({+ cmd: 'attachExisting',+ name,+ expectedGeneration,+ cols: size.cols,+ rows: size.rows,+ paused+ })+ : await this.request<AttachResult>({+ cmd: 'attach',+ name,+ spawn: {+ ...(requestKind.kind === 'create'+ ? requestKind.spawn+ : legacyWarmOnlySentinel(this.deps.userDataDir)),+ cols: size.cols,+ rows: size.rows+ },+ scrollback: requestKind.scrollback,+ replacementToken,+ paused+ })+ break+ } catch (error) {+ if (!replacementToken || attempt + 1 >= attempts || !isTransportUncertainty(error)) {+ throw error+ }+ }+ }+ const result = requireAttachResult(response, name, protocolVersion)+ if (state.preAckExit) {+ throw new Error(`session-host session exited before its attach completed: ${name}`)+ }+ if (useWarmOnly && result.fresh) {+ throw new Error(+ protocolVersion === 1+ ? `legacy session-host lost '${name}' before warm attach; no requested shell was spawned`+ : `session-host protocol violation: attachExisting '${name}' reported a fresh session`+ )+ }+ if (+ useWarmOnly &&+ protocolVersion === 2 &&+ expectedGeneration &&+ result.generation !== expectedGeneration+ ) {+ throw new Error(+ `session-host generation changed before warm attach '${name}' completed`+ )+ }+ if (replacementToken && !result.fresh) {+ throw new Error(`session-host protocol violation: reserved replacement '${name}' was not fresh`)+ }+ state.preAckEntries.delete(entry)+ state.protocolVersion = protocolVersion+ state.generation = result.generation ?? expectedGeneration+ if (state.generation) this.sessionGenerations.set(name, state.generation)+ if (replacementToken && result.fresh) {+ if (this.replacementTokens.get(name) === replacementToken) {+ this.replacementTokens.delete(name)+ }+ if (this.killOperations.get(name)?.operationId === replacementToken) {+ this.killOperations.delete(name)+ }+ }+ const socket = this.socket+ if (!socket) throw new Error('session-host: not connected')+ if (this.sessions.get(name) === state && state.entries.get(sub) === entry) {+ entry.phase = 'attached'+ this.applyAttachment(state, socket, paused, size)+ } else {+ // The attach reached the host before its owner retired. Remember the confirmed+ // membership on the retired state so its ordered teardown can return pause + detach.+ state.appliedSocket = socket+ state.appliedAttached = true+ state.appliedPaused = paused+ state.appliedSize = size+ }+ if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) {+ // If another local subscriber remains, this attach also restored its socket membership;+ // detaching here would evict that neighbor. Only compensate when nobody still owns it.+ if (this.sessions.get(name) !== state || !this.hasAttachedEntry(state)) {+ await this.teardownRetiredState(state)+ } else {+ await this.reconcileState(state)+ }+ throw new Error(`session-host attachment was canceled: ${name}`)+ }+ await this.reconcileState(state)+ return result+ } catch (error) {+ state.preAckEntries.delete(entry)+ if (state.entries.get(sub) === entry) {+ state.entries.delete(sub)+ const releasedPause = state.pauseOwners.delete(sub)+ state.sizeClaims.delete(sub)+ if (releasedPause && state.pauseOwners.size === 0) state.releasePending = true+ }+ if (state.entries.size === 0 && this.sessions.get(name) === state) {+ this.sessions.delete(name)+ if (!state.generation || this.sessionGenerations.get(name) === state.generation) {+ this.sessionGenerations.delete(name)+ }+ state.bufferedData = []+ this.stopReconnectIfIdle()+ await this.teardownRetiredState(state)+ } else if (this.sessions.get(name) === state && this.hasAttachedEntry(state)) {+ if (+ state.pauseOwners.size === 0 &&+ state.appliedSocket === this.socket &&+ !state.appliedPaused+ ) {+ state.releasePending = false+ this.flushData(state)+ }+ this.queueReconcile(state)+ }+ throw error+ }+ })+ }++ unsubscribe(name: string, sub: SessionSubscriber): void {+ const state = this.sessions.get(name)+ const entry = state?.entries.get(sub)+ if (!state || !entry) return+ state.entries.delete(sub)+ state.preAckEntries.delete(entry)+ const releasedPause = state.pauseOwners.delete(sub)+ state.sizeClaims.delete(sub)+ if (!this.hasAttachedEntry(state)) state.bufferedData = []+ if (releasedPause && state.pauseOwners.size === 0) state.releasePending = true++ if (state.entries.size > 0) {+ this.queueReconcile(state)+ return+ }+ if (this.sessions.get(name) === state) this.sessions.delete(name)+ state.bufferedData = []+ this.stopReconnectIfIdle()+ void this.enqueueState(state, () => this.teardownRetiredState(state))+ }++ /**+ * Probe for a live session AND remember the generation it reports.+ *+ * The bookkeeping is not incidental. `attachExisting` sends+ * `state.generation ?? this.sessionGenerations.get(name)` as its `expectedGeneration`, and the+ * Windows warm-reattach path in pty-manager reaches it through exactly this sequence: probe with+ * `sessionHostHasSession(name)`, then `attachExisting(name, sub)` with no generation of its own.+ * With nothing recorded here that attach carries no expectation, and the ABA protection the kill+ * machinery treats as load-bearing elsewhere is silently absent — a replacement process created+ * under the same name between the probe and the attach would be adopted as the original.+ *+ * This was dropped in the ownership rewrite (`12a1f9ac`) while `attachExisting`'s own doc comment+ * continued to promise it, and is restored here from `a4e3b13d`. A v2 host must supply a+ * well-formed generation; v1 has none, so the entry is cleared rather than left stale.+ */+ async hasSession(name: string): Promise<boolean> {+ const result = await this.request<HasSessionResult>({ cmd: 'hasSession', name })+ // Read the negotiated version AFTER the request: `request()` is what establishes the+ // connection on a cold client, so reading it first sees `null` on the very first probe — the+ // exact call the warm-reattach path makes — and would silently take the "no generation" branch.+ const protocolVersion = this.negotiatedProtocolVersion+ if (!result || typeof result.exists !== 'boolean') {+ throw new Error(`session-host returned an invalid existence result for '${name}'`)+ }+ if (result.exists && protocolVersion === 2) {+ const generation = result.generation+ if (typeof generation !== 'string' || !/^[A-Za-z0-9_-]{8,128}$/.test(generation)) {+ throw new Error(`session-host returned no generation for existing session '${name}'`)+ }+ this.sessionGenerations.set(name, generation)+ } else {+ // Absent, or a v1 host that cannot name a generation: never leave a stale one behind, or a+ // later attach would assert an expectation about a process this probe did not observe.+ this.sessionGenerations.delete(name)+ }+ return result.exists+ }++ write(name: string, sub: SessionSubscriber, data: string): void {+ const state = this.sessions.get(name)+ const entry = state?.entries.get(sub)+ if (!state || !entry) return+ void this.enqueueState(state, async () => {+ if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) return+ try {+ await this.request({ cmd: 'write', name, data })+ } catch (error) {+ const socket = this.socket+ if (socket) this.dropSocket(socket, asError(error), true)+ }+ })+ }++ resize(name: string, sub: SessionSubscriber, cols: number, rows: number): void {+ const state = this.sessions.get(name)+ if (!state || !state.entries.has(sub)) return+ const previous = state.sizeClaims.get(sub) ?? { cols: 80, rows: 24 }+ state.sizeClaims.set(sub, {+ cols: normalizeDimension(cols, previous.cols),+ rows: normalizeDimension(rows, previous.rows)+ })+ this.queueReconcile(state)+ }++ pause(name: string, sub: SessionSubscriber): void {+ const state = this.sessions.get(name)+ if (!state || !state.entries.has(sub) || state.pauseOwners.has(sub)) return+ const wasFlowing = state.pauseOwners.size === 0+ state.pauseOwners.add(sub)+ if (wasFlowing) this.queueReconcile(state)+ }++ resume(name: string, sub: SessionSubscriber): void {+ const state = this.sessions.get(name)+ if (!state || !state.entries.has(sub) || !state.pauseOwners.delete(sub)) return+ if (state.pauseOwners.size === 0) {+ state.releasePending = true+ this.queueReconcile(state)+ }+ }++ async sendKeys(name: string, text: string, enter: boolean): Promise<boolean> {+ try {+ await this.request({ cmd: 'sendKeys', name, text, enter })+ return true+ } catch {+ return false+ }+ }++ async paneCommand(name: string): Promise<string | null> {+ try {+ const result = await this.request<PaneCommandResult>({ cmd: 'paneCommand', name })+ return result.command+ } catch {+ return null+ }+ }++ async capture(name: string, full: boolean): Promise<string> {+ const result = await this.request<CaptureResult>({ cmd: 'capture', name, full })+ return result.text+ }++ /** Execute already-rendered trusted input through the persistent generation's exactly-once+ * launch ledger. Retrying with the SAME `launchId` after a lost reply is safe: the host answers+ * `already-executed` rather than typing the command a second time. Never retries internally —+ * the caller (session-host-backend.ts's `sessionHostExecuteLaunch`) owns that decision, exactly+ * as it owns the `launchId` that makes a retry idempotent. */+ async executeLaunch(+ name: string,+ launchId: string,+ plan: PreparedAgentLaunch+ ): Promise<ExecuteLaunchResult> {+ await this.ensureConnected()+ const protocolVersion = this.negotiatedProtocolVersion+ if (protocolVersion !== 2) {+ throw new SessionHostProtocolCompatibilityError(`launch an agent in terminal '${name}'`)+ }+ const state = this.sessions.get(name)+ const generation = state?.generation ?? this.sessionGenerations.get(name)+ if (!generation) throw new Error(`session-host has no confirmed generation for '${name}'`)+ const result = await this.request<ExecuteLaunchResult>({+ cmd: 'executeLaunch',+ name,+ generation,+ launchId,+ command: plan.command,+ ...(plan.stdinAfterStart !== undefined ? { stdinAfterStart: plan.stdinAfterStart } : {})+ })+ if (!result || (result.status !== 'executed' && result.status !== 'already-executed')) {+ throw new Error(`session-host returned an invalid launch result for '${name}'`)+ }+ return result+ }++ /** The one call that actually ENDS a session. `reserveReplacement` atomically reserves the+ * now-vacated name for THIS operation (`replacementTokens`) so only the client that confirmed+ * the kill can spawn the replacement — other authenticated app clients cannot steal it.+ * `expectedAbsent` skips the generation probe entirely for a lease acquired before any local+ * attach ever observed a generation (e.g. "restart a session I never attached"), so the lease+ * can never silently adopt a generation created by someone else after this call started.+ * `requireV2` demands the same atomic guarantees on a legacy (v1) host, which cannot provide+ * them — protocol-incompatible rather than silently degraded.+ *+ * Retrying with the SAME options reuses the SAME `operationId` (`killOperations`), so a lost+ * reply can be retried without risking a second, different destructive operation (host-side+ * ABA safety). A confirmed kill installs `killReplayBarriers` for `name` BEFORE the first+ * destructive write and only clears it on confirmation — see `attachSubscriber`'s barrier+ * check and `restoreSocket`'s reconnect-replay skip, both of which already depend on this. */+ async killSession(+ name: string,+ options: {+ reserveReplacement?: boolean+ requireV2?: boolean+ expectedAbsent?: boolean+ } = {}+ ): Promise<void> {+ const reserveReplacement = options.reserveReplacement === true+ const requireV2 = options.requireV2 === true+ const expectedAbsent = options.expectedAbsent === true+ if (expectedAbsent && !reserveReplacement) {+ throw new Error('session-host expected-absent mode requires a replacement reservation')+ }+ const knownIdentity = this.killOperations.get(name)+ if (+ knownIdentity &&+ (knownIdentity.reserveReplacement !== reserveReplacement ||+ knownIdentity.requireV2 !== requireV2 ||+ knownIdentity.expectedAbsent !== expectedAbsent)+ ) {+ throw new Error(+ `session-host: kill retry mode changed for '${name}'; retry with ` ++ `reserveReplacement=${String(knownIdentity.reserveReplacement)} and ` ++ `requireV2=${String(knownIdentity.requireV2)} and ` ++ `expectedAbsent=${String(knownIdentity.expectedAbsent)}`+ )+ }+ const active = this.killsInFlight.get(name)+ if (active) return active++ // Install the barrier before the first write. The host may complete the kill and lose its+ // reply; without this ordering, reconnect's attach-or-create replay resurrects the old shell.+ this.killReplayBarriers.add(name)+ const state = this.sessions.get(name)+ const identity: KillOperationIdentity = knownIdentity ?? {+ operationId: randomUUID(),+ expectedGeneration: state?.generation ?? this.sessionGenerations.get(name),+ reserveReplacement,+ requireV2,+ expectedAbsent+ }+ this.killOperations.set(name, identity)+ let operation!: Promise<void>+ operation = this.prepareAndConfirmKillSession(name, identity)+ .catch((error) => {+ // Compatibility/probe failures happen before a destructive frame exists. Roll the local+ // barrier back so a live attachment is not stranded behind an operation the host never+ // saw. Once confirmKillSession starts, it deliberately retains identity/barrier on doubt.+ if (this.killOperations.get(name) === identity && identity.prepared !== true) {+ this.killOperations.delete(name)+ this.killReplayBarriers.delete(name)+ }+ throw error+ })+ .finally(() => {+ if (this.killsInFlight.get(name) === operation) this.killsInFlight.delete(name)+ })+ this.killsInFlight.set(name, operation)+ return operation+ }++ private async prepareAndConfirmKillSession(+ name: string,+ identity: KillOperationIdentity+ ): Promise<void> {+ await this.ensureConnected()+ const protocolVersion = this.negotiatedProtocolVersion+ if (!protocolVersion) throw new Error('session-host: not connected')+ if (protocolVersion === 1 && (identity.reserveReplacement || identity.requireV2)) {+ throw new SessionHostProtocolCompatibilityError(`restart terminal '${name}'`)+ }++ // With no live authoritative attachment, determine the exact current generation immediately+ // before creating this destructive operation. An uncertain prior operation skips this probe+ // because its original operationId/generation is precisely what makes retry ABA-safe.+ if (protocolVersion === 2 && !identity.expectedGeneration && !identity.expectedAbsent) {+ const result = await this.request<HasSessionResult>({ cmd: 'hasSession', name })+ if (!result || typeof result.exists !== 'boolean') {+ throw new Error(`session-host returned an invalid existence result for '${name}'`)+ }+ if (result.exists) {+ const generation = result.generation+ if (typeof generation !== 'string' || !/^[A-Za-z0-9_-]{8,128}$/.test(generation)) {+ throw new Error(`session-host returned no generation for existing session '${name}'`)+ }+ identity.expectedGeneration = generation+ this.sessionGenerations.set(name, generation)+ }+ }++ identity.prepared = true+ await this.confirmKillSession(+ name,+ identity.operationId,+ identity.expectedGeneration,+ identity.reserveReplacement,+ identity.requireV2+ )+ }++ private async confirmKillSession(+ name: string,+ operationId: string,+ expectedGeneration: string | undefined,+ reserveReplacement: boolean,+ requireV2: boolean+ ): Promise<void> {+ let lastError = new Error('session-host kill did not run')+ for (let attempt = 0; attempt < KILL_CONFIRMATION_ATTEMPTS; attempt++) {+ try {+ await this.ensureConnected()+ const protocolVersion = this.negotiatedProtocolVersion+ if (!protocolVersion) throw new Error('session-host: not connected')+ if (protocolVersion === 1 && (reserveReplacement || requireV2)) {+ throw new SessionHostProtocolCompatibilityError(`restart terminal '${name}'`)+ }+ // The host defines missing as success and coalesces an in-progress kill by name. Resending+ // after reconnect is therefore the confirmation operation for both "reply lost after+ // kill" and "first write never reached the host".+ const result = await this.request<KillSessionResult>({+ cmd: 'killSession',+ name,+ operationId,+ expectedGeneration,+ reserveReplacement+ })+ if (protocolVersion === 2 && (!result || typeof result !== 'object')) {+ throw new Error(`session-host returned an invalid kill result for '${name}'`)+ }+ if (reserveReplacement) {+ if (result?.replacementToken !== operationId) {+ throw new Error(+ `session-host did not confirm the replacement reservation for '${name}'`+ )+ }+ this.replacementTokens.set(name, result.replacementToken)+ } else {+ if (result?.replacementToken) {+ throw new Error(+ `session-host returned an unexpected replacement reservation for '${name}'`+ )+ }+ this.replacementTokens.delete(name)+ }+ this.clearLocalSessionState(name)+ this.sessionGenerations.delete(name)+ this.killReplayBarriers.delete(name)+ if (!reserveReplacement && this.killOperations.get(name)?.operationId === operationId) {+ this.killOperations.delete(name)+ }+ return+ } catch (error) {+ lastError = asError(error)+ if (attempt + 1 < KILL_CONFIRMATION_ATTEMPTS) {+ // A timeout or explicit error can leave an apparently-live socket behind. Force the+ // retry through a fresh authenticated connection; target replay remains barred while+ // unrelated attachments are eligible for ordinary reconnect replay.+ const socket = this.socket+ if (socket) {+ this.dropSocket(+ socket,+ new Error(`session-host connection reset to retry kill '${name}'`),+ true+ )+ }+ }+ }+ }++ // Preserve subscribers/memory as evidence of the uncertain generation, but never replay it.+ // A later explicit killSession(name) starts a fresh bounded confirmation pass and can clear+ // this barrier once the idempotent host operation answers.+ throw new Error(+ `session-host: kill of '${name}' remains unconfirmed after ` ++ `${KILL_CONFIRMATION_ATTEMPTS} attempts; attach replay is suspended to prevent recreating ` ++ `the old process. Retry the kill before starting a replacement. Last error: ${lastError.message}`+ )+ }++ /** Drop every locally attached subscriber for a confirmed-killed `name` without notifying them+ * (the caller of `killSession` already knows the session ended; an explicit kill is not a+ * surprise `onExit`, exactly as the pre-recovery implementation this replaces never fired one+ * either). Mirrors `unsubscribe`'s teardown fields so no stale flow-control/applied-state+ * survives into whatever reuses this name next. */+ private clearLocalSessionState(name: string): void {+ const state = this.sessions.get(name)+ if (!state) return+ if (this.sessions.get(name) === state) this.sessions.delete(name)+ state.entries.clear()+ state.preAckEntries.clear()+ state.pauseOwners.clear()+ state.sizeClaims.clear()+ state.bufferedData = []+ state.releasePending = false+ state.appliedSocket = null+ state.appliedAttached = false+ state.appliedPaused = false+ state.appliedSize = null+ this.stopReconnectIfIdle()+ }++ async listSessions(): Promise<string[]> {+ const result = await this.request<ListSessionsResult>({ cmd: 'listSessions' })+ return result.names+ }+}diff --git a/src/core/session-host-launch-ledger.test.ts b/src/core/session-host-launch-ledger.test.tsnew file mode 100644index 000000000..aaeb66f74--- /dev/null+++ b/src/core/session-host-launch-ledger.test.ts@@ -0,0 +1,184 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { SessionHostSpawnOptions } from '../session-host/protocol'++class FakePty {+ readonly pid = 4242+ readonly cols = 80+ readonly rows = 24+ readonly process = 'fake-shell'+ handleFlowControl = false+ readonly writes: string[] = []+ echoWrites = true+ onWrite: ((data: string) => void) | undefined+ private readonly dataListeners = new Set<(data: string) => void>()+ private readonly exitListeners = new Set<(event: { exitCode: number }) => void>()++ readonly onData = (listener: (data: string) => void): { dispose(): void } => {+ this.dataListeners.add(listener)+ return { dispose: () => this.dataListeners.delete(listener) }+ }++ readonly onExit = (+ listener: (event: { exitCode: number }) => void+ ): { dispose(): void } => {+ this.exitListeners.add(listener)+ return { dispose: () => this.exitListeners.delete(listener) }+ }++ write(data: string): void {+ this.writes.push(data)+ this.onWrite?.(data)+ if (this.echoWrites && data !== '\r' && data !== '\x15') this.emitData(data)+ }++ emitData(data: string): void {+ for (const listener of [...this.dataListeners]) listener(data)+ }++ emitExit(exitCode = 0): void {+ for (const listener of [...this.exitListeners]) listener({ exitCode })+ }++ resize(): void {}+ clear(): void {}+ kill(): void {}+ pause(): void {}+ resume(): void {}+}++const mocks = vi.hoisted(() => ({+ spawn: vi.fn(),+ termWrite: vi.fn(),+ termSerialize: vi.fn(() => ''),+ termDispose: vi.fn()+}))++vi.mock('node-pty', () => ({ spawn: mocks.spawn }))+vi.mock('../session-host/terminal-emulator', () => ({+ TerminalEmulator: class {+ write = mocks.termWrite+ serialize = mocks.termSerialize+ dispose = mocks.termDispose+ resize = vi.fn()+ }+}))++import { HostSession } from '../session-host/session'++const LAUNCH_ID = '123e4567-e89b-42d3-a456-426614174000'+const COMMAND = 'private command --with opaque arguments'++function spawnOptions(over: Partial<SessionHostSpawnOptions> = {}): SessionHostSpawnOptions {+ return {+ cwd: 'C:\\project',+ shell: 'C:\\Windows\\System32\\cmd.exe',+ args: [],+ env: {},+ cols: 80,+ rows: 24,+ launchDialect: 'cmd',+ ...over+ }+}++function session(over: Partial<SessionHostSpawnOptions> = {}): {+ host: HostSession+ proc: FakePty+ spawn: SessionHostSpawnOptions+} {+ const proc = new FakePty()+ mocks.spawn.mockReturnValueOnce(proc)+ const spawn = spawnOptions(over)+ return { host: new HostSession('nt-launch', spawn, 1_000), proc, spawn }+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.clearAllMocks()+})++describe('HostSession generation-scoped launch ledger', () => {+ it('executes one launch id once, caches success, and rejects a changed fingerprint', async () => {+ const { host, proc } = session()+ const privateStates: boolean[] = []+ proc.onWrite = () => privateStates.push(host.suppressingPrivateLaunchOutput)++ const first = host.executeLaunch(LAUNCH_ID, COMMAND)+ await vi.advanceTimersByTimeAsync(1_500)+ await expect(first).resolves.toEqual({ status: 'executed' })+ await expect(host.executeLaunch(LAUNCH_ID, COMMAND)).resolves.toEqual({+ status: 'already-executed'+ })+ await expect(host.executeLaunch(LAUNCH_ID, COMMAND + ' changed')).rejects.toThrow(+ 'launch id was reused with different input'+ )++ expect(proc.writes).toEqual([COMMAND, '\r'])+ expect(privateStates).toEqual([true, true])+ expect(host.suppressingPrivateLaunchOutput).toBe(false)+ })++ it('caches a sanitized failed outcome and never writes the same id again', async () => {+ const { host, proc } = session()+ proc.echoWrites = false+ // Attach the rejection handler BEFORE advancing timers. The launch rejects during the timer+ // advance, so creating the promise and only asserting on it afterwards leaves a window with+ // no handler attached — Vitest reports that as an unhandled rejection and warns it "might+ // cause false positive tests". It was the only thing making an otherwise all-passing suite+ // exit non-zero.+ const first = host.executeLaunch(LAUNCH_ID, COMMAND)+ const firstSettled = expect(first).rejects.toThrow('session-host launch delivery failed')+ await vi.advanceTimersByTimeAsync(8_000)+ await firstSettled+ const writesAfterFailure = [...proc.writes]+ await expect(host.executeLaunch(LAUNCH_ID, COMMAND)).rejects.toThrow(+ 'session-host launch delivery previously failed'+ )+ expect(proc.writes).toEqual(writesAfterFailure)+ expect(proc.writes.filter((value) => value === COMMAND)).toHaveLength(3)+ expect(host.suppressingPrivateLaunchOutput).toBe(false)+ })++ it('uses the same ledger for an atomic initial launch and its lost-reply replay', async () => {+ const { host, proc, spawn } = session({+ initialLaunch: { launchId: LAUNCH_ID, command: COMMAND }+ })+ const first = host.executeInitialLaunch(spawn)+ await vi.advanceTimersByTimeAsync(1_500)+ await expect(first).resolves.toEqual({ status: 'executed' })+ await expect(host.executeInitialLaunch(spawn)).resolves.toEqual({+ status: 'already-executed'+ })+ expect(proc.writes.filter((value) => value === COMMAND)).toHaveLength(1)+ })++ it('never types stdin-after-start when the agent readiness probe stays false', async () => {+ const { host, proc } = session()+ const prompt = 'private Gemini prompt'+ // Attach the rejection handler BEFORE advancing timers. The launch rejects during the timer+ // advance, so creating the promise and only asserting on it afterwards leaves a window with+ // no handler attached — Vitest reports that as an unhandled rejection and warns it "might+ // cause false positive tests". It was the only thing making an otherwise all-passing suite+ // exit non-zero.+ const launched = host.executeLaunch(LAUNCH_ID, COMMAND, prompt, async () => false)+ const settled = expect(launched).rejects.toThrow('session-host launch delivery failed')+ await vi.advanceTimersByTimeAsync(7_000)+ await settled+ expect(proc.writes).not.toContain(prompt)+ expect(proc.writes.filter((value) => value === COMMAND)).toHaveLength(1)+ })++ it('types stdin-after-start exactly once only after readiness is confirmed', async () => {+ const { host, proc } = session()+ const prompt = 'private Gemini prompt'+ let probes = 0+ const launched = host.executeLaunch(LAUNCH_ID, COMMAND, prompt, async () => ++probes >= 2)+ await vi.advanceTimersByTimeAsync(4_000)+ await expect(launched).resolves.toEqual({ status: 'executed' })+ await expect(+ host.executeLaunch(LAUNCH_ID, COMMAND, prompt, async () => true)+ ).resolves.toEqual({ status: 'already-executed' })+ expect(proc.writes.filter((value) => value === prompt)).toHaveLength(1)+ expect(probes).toBeGreaterThanOrEqual(2)+ })+})diff --git a/src/core/session-host-launcher.ts b/src/core/session-host-launcher.tsnew file mode 100644index 000000000..95b49ab5a--- /dev/null+++ b/src/core/session-host-launcher.ts@@ -0,0 +1,65 @@+// Resolves the standalone session-host bundle and spawns it DETACHED so it outlives this app —+// the exact same "system-first, bundled-as-floor" resolution shape `tmux-hint.ts`'s+// `bundledTmuxPath` already uses, one level over: there is no "system session-host" to prefer, so+// this only has the dev/packaged split.++import fs from 'fs'+import path from 'path'+import { spawn } from 'child_process'++/**+ * Where `out/session-host/host.cjs` lives, in dev vs a packaged build.+ *+ * - Packaged: `electron-builder`'s `extraResources` copies `out/session-host` to+ * `<resourcesPath>/session-host` (see package.json's `build.extraResources`), mirroring how the+ * bundled tmux binary lands under `<resourcesPath>/bin`.+ * - Dev (`electron-vite dev`): `process.cwd()` is the repo root, and `npm run build` /+ * `npm run host:build` write straight to `<repoRoot>/out/session-host/host.cjs`.+ */+export function resolveSessionHostScript(opts: {+ resourcesPath?: string | null+ repoRoot?: string | null+ exists?: (p: string) => boolean+}): string | null {+ const exists = opts.exists ?? fs.existsSync+ const candidates: string[] = []+ if (opts.resourcesPath) candidates.push(path.join(opts.resourcesPath, 'session-host', 'host.cjs'))+ if (opts.repoRoot) candidates.push(path.join(opts.repoRoot, 'out', 'session-host', 'host.cjs'))+ for (const c of candidates) {+ try {+ if (exists(c)) return c+ } catch {+ /* unreadable — keep looking */+ }+ }+ return null+}++/**+ * Spawn the session host, detached, unref'd, with no attached stdio — so it survives this+ * process exiting (`app.quit()` never touches it; `PtyManager.killAll()` explicitly does not+ * either, matching how it never kills tmux sessions).+ *+ * `ELECTRON_RUN_AS_NODE=1` is what makes this work when `process.execPath` is the Electron+ * binary itself (a packaged app has no separate `node` executable to shell out to) — Electron+ * treats that env var as "run this as a plain Node process, skip the Chromium/BrowserWindow+ * machinery entirely". It is harmless to set when `process.execPath` already IS a real Node+ * binary (dev, or a CI box running the bundle directly): unrecognized by real Node, ignored.+ *+ * Never throws — a spawn failure here is reported by the CALLER failing to connect afterward,+ * exactly like `pty.spawn` failures elsewhere in this codebase degrade to an error the renderer+ * can show rather than crashing the main process.+ */+export function spawnSessionHost(scriptPath: string, userDataDir: string): void {+ try {+ const child = spawn(process.execPath, [scriptPath, userDataDir], {+ detached: true,+ stdio: 'ignore',+ windowsHide: true,+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }+ })+ child.unref()+ } catch {+ /* the caller's subsequent connect attempt will fail and surface the real error */+ }+}diff --git a/src/core/session-host-pty.ts b/src/core/session-host-pty.tsnew file mode 100644index 000000000..5a5bf3910--- /dev/null+++ b/src/core/session-host-pty.ts@@ -0,0 +1,112 @@+// The IPty-shim: makes a session-host-backed session look, to `pty-manager.ts`, exactly like the+// small subset of node-pty's `IPty` it actually touches (`onData`/`onExit`/`write`/`resize`/+// `pause`/`resume`/`kill`/`destroy` — see `Session.proc` and `ReleasablePty` in pty-manager.ts /+// pty-release.ts). This is what lets the session-host backend slot into the EXISTING+// subscriber/flow-control/co-attach machinery in `PtyManager` with no changes to any of that: as+// far as that code is concerned, `session.proc` is just a pty, however it is actually implemented.++import type { SessionHostClient, SessionSubscriber } from './session-host-client'+import type { SessionHostSpawnOptions, AttachResult } from '../session-host/protocol'++export class SessionHostPty {+ readonly name: string+ private readonly client: SessionHostClient+ private readonly sub: SessionSubscriber+ private readonly dataCbs: Array<(data: string) => void> = []+ private readonly exitCbs: Array<(e: { exitCode: number }) => void> = []+ private readonly attachErrorCbs: Array<(error: Error) => void> = []+ private attachError: Error | null = null+ private detached = false++ /**+ * Resolves once the initial attach-or-create round trip completes, carrying exactly what the+ * tmux backend gets for free from a warm reattach's own redraw: whether this was a cold start,+ * and — when it wasn't — the screen to seed. `spawnNew()` awaits this to build the outer+ * `PtyCreateResult` (`fresh`, `screen`) the same way `join()` already does for a same-process+ * co-attach. See docs/windows-session-host.md, "The seeding trap".+ */+ readonly ready: Promise<AttachResult>++ constructor(+ client: SessionHostClient,+ name: string,+ spawn: SessionHostSpawnOptions | null,+ scrollback: number+ ) {+ this.client = client+ this.name = name+ this.sub = {+ onData: (data) => {+ for (const cb of this.dataCbs) cb(data)+ },+ onExit: (exitCode) => {+ for (const cb of this.exitCbs) cb({ exitCode })+ },+ onAttachError: (error) => {+ this.attachError = error+ for (const cb of this.attachErrorCbs) cb(error)+ }+ }+ this.ready = spawn+ ? client.attach(name, spawn, scrollback, this.sub)+ : client.attachExisting(name, this.sub)+ // node-pty's real spawn never rejects asynchronously (a spawn failure throws synchronously,+ // before a Session is even constructed) — an attach failure here is the closest analogue, and+ // it must not become an unhandled rejection just because some callers (write/resize/pause/+ // resume) never look at `ready` at all. `spawnNew()` DOES await it and will see the failure.+ this.ready.catch(() => {})+ }++ onData(cb: (data: string) => void): void {+ this.dataCbs.push(cb)+ }++ onExit(cb: (e: { exitCode: number }) => void): void {+ this.exitCbs.push(cb)+ }++ /** Reconnect replay failed for a previously-confirmed generation. Late registration receives+ * the stored error immediately so manager wiring cannot miss a fast rejection. */+ onAttachError(cb: (error: Error) => void): void {+ this.attachErrorCbs.push(cb)+ if (this.attachError) cb(this.attachError)+ }++ write(data: string): void {+ this.client.write(this.name, this.sub, data)+ }++ resize(cols: number, rows: number): void {+ this.client.resize(this.name, this.sub, cols, rows)+ }++ pause(): void {+ this.client.pause(this.name, this.sub)+ }++ resume(): void {+ this.client.resume(this.name, this.sub)+ }++ /**+ * DETACH only — never ends the remote session. Mirrors the tmux backend exactly: there,+ * `proc.kill()` kills the LOCAL tmux CLIENT process, not the tmux session it was attached to.+ * The real "end this session for good" lives in `pty-manager.ts`'s `destroySession`, via+ * `sessionHostBackend.killSession(name)` — the one path that maps to a real `tmux kill-session`.+ */+ kill(): void {+ this.detach()+ }++ /** `releasePty` prefers `destroy()` over `kill()` when both exist (deterministic fd close for a+ * real pty) — here they are the same detach, so either is safe to call, including both. */+ destroy(): void {+ this.detach()+ }++ private detach(): void {+ if (this.detached) return+ this.detached = true+ this.client.unsubscribe(this.name, this.sub)+ }+}diff --git a/src/session-host/existing-host-state.test.ts b/src/session-host/existing-host-state.test.tsnew file mode 100644index 000000000..c5aaee012--- /dev/null+++ b/src/session-host/existing-host-state.test.ts@@ -0,0 +1,158 @@+import { describe, expect, it } from 'vitest'+import { readExistingSessionHostIdentity } from './existing-host-state'++const statePath = 'session-host.json'+const tokenPath = 'session-host.token'+const endpoint = 'session-host-endpoint'+const bearerToken = 'a'.repeat(64)+const validState = JSON.stringify({+ pid: 42,+ endpoint,+ tokenPath,+ startedAt: 1234,+ protocolVersion: 2+})++function codedError(code: string): NodeJS.ErrnoException {+ const error: NodeJS.ErrnoException = new Error(`${code}: injected read failure`)+ error.code = code+ return error+}++function reader(entries: Record<string, string | Error>): (filePath: string) => string {+ return (filePath) => {+ const value = entries[filePath]+ if (value instanceof Error) throw value+ if (value === undefined) throw new Error(`unexpected read: ${filePath}`)+ return value+ }+}++function options(readText: (filePath: string) => string) {+ return { expectedEndpoint: endpoint, expectedTokenPath: tokenPath, readText }+}++describe('existing session-host ownership reads', () => {+ it('returns a complete identity only after both valid files are read', () => {+ const result = readExistingSessionHostIdentity(statePath, {+ ...options(reader({ [statePath]: validState, [tokenPath]: bearerToken }))+ })++ expect(result).toEqual({+ kind: 'ready',+ state: {+ pid: 42,+ endpoint,+ tokenPath,+ startedAt: 1234,+ protocolVersion: 2+ },+ token: bearerToken+ })+ })++ it.each(['state', 'token'] as const)('treats only an ENOENT %s file as absent', (missing) => {+ const entries: Record<string, string | Error> = {+ [statePath]: missing === 'state' ? codedError('ENOENT') : validState,+ [tokenPath]: codedError('ENOENT')+ }++ expect(+ readExistingSessionHostIdentity(statePath, options(reader(entries)))+ ).toEqual({ kind: 'absent', missing })+ })++ it.each(['EISDIR', 'EACCES', 'EIO'])('propagates a %s state read instead of claiming absence', (code) => {+ const failure = codedError(code)++ expect(() =>+ readExistingSessionHostIdentity(statePath, {+ ...options(reader({ [statePath]: failure }))+ })+ ).toThrow(failure)+ })++ it.each(['EISDIR', 'EACCES', 'EIO'])('propagates a %s token read instead of claiming absence', (code) => {+ const failure = codedError(code)++ expect(() =>+ readExistingSessionHostIdentity(statePath, {+ ...options(reader({ [statePath]: validState, [tokenPath]: failure }))+ })+ ).toThrow(failure)+ })++ it.each([+ ['', 'file is empty'],+ [' \n', 'file is empty'],+ ['{broken', 'file is not valid JSON'],+ ['null', 'root must be an object'],+ ['[]', 'root must be an object'],+ ['{}', 'pid must be a positive integer'],+ [JSON.stringify({ ...JSON.parse(validState), endpoint: '' }), 'endpoint must be a non-empty string'],+ [JSON.stringify({ ...JSON.parse(validState), tokenPath: null }), 'tokenPath must be a non-empty string'],+ [JSON.stringify({ ...JSON.parse(validState), protocolVersion: 0 }), 'protocolVersion must be a positive integer']+ ])('rejects corrupt state %j without reading a token', (raw, reason) => {+ let tokenReads = 0+ expect(() =>+ readExistingSessionHostIdentity(statePath, {+ ...options((filePath) => {+ if (filePath === statePath) return raw+ tokenReads+++ return bearerToken+ })+ })+ ).toThrow(reason)+ expect(tokenReads).toBe(0)+ })++ it.each(['', ' \r\n'])('rejects an empty token instead of claiming absence', (token) => {+ expect(() =>+ readExistingSessionHostIdentity(statePath, {+ ...options(reader({ [statePath]: validState, [tokenPath]: token }))+ })+ ).toThrow('invalid session-host token: file is empty')+ })++ it.each([+ ['not-hex', 'non-hex text'],+ ['A'.repeat(64), 'uppercase hex'],+ ['a'.repeat(63), '63 hex characters'],+ ['a'.repeat(65), '65 hex characters'],+ [`${'a'.repeat(64)}\n`, 'newline-padded hex'],+ [` ${'a'.repeat(64)}`, 'space-padded hex']+ ])('rejects %s token bytes before they can become hello credentials (%s)', (token) => {+ let helloCredential: string | undefined+ expect(() => {+ const result = readExistingSessionHostIdentity(+ statePath,+ options(reader({ [statePath]: validState, [tokenPath]: token }))+ )+ if (result.kind === 'ready') helloCredential = result.token+ }).toThrow('expected 64 lowercase hexadecimal characters')+ expect(helloCredential).toBeUndefined()+ })++ it.each([+ ['endpoint', { endpoint: 'attacker-endpoint' }],+ ['tokenPath', { tokenPath: 'attacker.token' }]+ ] as const)('rejects a state-file %s redirect before any redirected read or hello', (field, change) => {+ const reads: string[] = []+ let helloTarget: string | undefined+ const tampered = JSON.stringify({ ...JSON.parse(validState), ...change })++ expect(() => {+ const result = readExistingSessionHostIdentity(+ statePath,+ options((filePath) => {+ reads.push(filePath)+ if (filePath === statePath) return tampered+ return bearerToken+ })+ )+ if (result.kind === 'ready') helloTarget = result.state.endpoint+ }).toThrow(field === 'endpoint' ? 'derived endpoint' : 'derived token path')+ expect(reads).toEqual([statePath])+ expect(helloTarget).toBeUndefined()+ })+})diff --git a/src/session-host/existing-host-state.ts b/src/session-host/existing-host-state.tsnew file mode 100644index 000000000..7b8e41275--- /dev/null+++ b/src/session-host/existing-host-state.ts@@ -0,0 +1,126 @@+// Fail-closed ownership-state reads for the standalone session-host startup race. A startup+// lock can be absent, but a lock that exists and cannot be understood is still evidence that+// another process may own it. Treating those two facts alike lets a second host reclaim or+// overwrite ownership that it never proved stale.++import fs from 'fs'+import type { SessionHostState } from './paths'++export interface ExistingSessionHostIdentity {+ kind: 'ready'+ state: SessionHostState+ token: string+}++export interface MissingSessionHostIdentity {+ kind: 'absent'+ missing: 'state' | 'token'+}++export type ExistingSessionHostRead =+ | ExistingSessionHostIdentity+ | MissingSessionHostIdentity++export interface ExistingSessionHostReadOptions {+ /** Paths derived independently from the caller's userDataDir. Never trust redirects in state. */+ expectedEndpoint: string+ expectedTokenPath: string+ /** Deterministic filesystem seam for the failure-mode Chuts. */+ readText?: (filePath: string) => string+}++function isEnoent(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ 'code' in error &&+ (error as NodeJS.ErrnoException).code === 'ENOENT'+ )+}++function invalidState(detail: string): Error {+ return new Error(`invalid session-host state: ${detail}`)+}++function parseState(raw: string): SessionHostState {+ if (raw.trim().length === 0) throw invalidState('file is empty')++ let value: unknown+ try {+ value = JSON.parse(raw)+ } catch {+ throw invalidState('file is not valid JSON')+ }++ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ throw invalidState('root must be an object')+ }+ const state = value as Partial<SessionHostState>+ if (!Number.isInteger(state.pid) || (state.pid ?? 0) <= 0) {+ throw invalidState('pid must be a positive integer')+ }+ if (typeof state.endpoint !== 'string' || state.endpoint.trim().length === 0) {+ throw invalidState('endpoint must be a non-empty string')+ }+ if (typeof state.tokenPath !== 'string' || state.tokenPath.trim().length === 0) {+ throw invalidState('tokenPath must be a non-empty string')+ }+ if (+ typeof state.startedAt !== 'number' ||+ !Number.isFinite(state.startedAt) ||+ state.startedAt < 0+ ) {+ throw invalidState('startedAt must be a finite non-negative number')+ }+ if (+ !Number.isInteger(state.protocolVersion) ||+ (state.protocolVersion ?? 0) <= 0+ ) {+ throw invalidState('protocolVersion must be a positive integer')+ }++ return state as SessionHostState+}++/**+ * Read the ownership state and its referenced bearer token as one fail-closed observation.+ *+ * Only `ENOENT` is absence. Permission errors, directories in place of files, I/O errors,+ * malformed state, and empty state/token files all throw, so a caller cannot accidentally use+ * them as permission to reclaim the startup lock or launch a competing host.+ */+export function readExistingSessionHostIdentity(+ statePath: string,+ options: ExistingSessionHostReadOptions+): ExistingSessionHostRead {+ const readText = options.readText ?? ((filePath) => fs.readFileSync(filePath, 'utf8'))++ let rawState: string+ try {+ rawState = readText(statePath)+ } catch (error) {+ if (isEnoent(error)) return { kind: 'absent', missing: 'state' }+ throw error+ }++ const state = parseState(rawState)+ if (state.endpoint !== options.expectedEndpoint) {+ throw invalidState('endpoint does not match the derived endpoint')+ }+ if (state.tokenPath !== options.expectedTokenPath) {+ throw invalidState('tokenPath does not match the derived token path')+ }+ let token: string+ try {+ token = readText(state.tokenPath)+ } catch (error) {+ if (isEnoent(error)) return { kind: 'absent', missing: 'token' }+ throw error+ }+ if (token.trim().length === 0) throw new Error('invalid session-host token: file is empty')+ if (!/^[0-9a-f]{64}$/.test(token)) {+ throw new Error('invalid session-host token: expected 64 lowercase hexadecimal characters')+ }++ return { kind: 'ready', state, token }+}diff --git a/src/session-host/generation-barrier.test.ts b/src/session-host/generation-barrier.test.tsnew file mode 100644index 000000000..0439cfed1--- /dev/null+++ b/src/session-host/generation-barrier.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from 'vitest'+import {+ currentSessionAfterRetirement,+ RETRY_SESSION_GENERATION,+ retireSessionGeneration,+ SessionGenerationCoordinator,+ type RetiringSessionGeneration+} from './generation-barrier'++interface Generation extends RetiringSessionGeneration {+ subscribers: Array<(frame: string) => void>+}++describe('same-name session generation barrier', () => {+ it('publishes the old data and exit before a replacement can attach to that wire name', async () => {+ let releaseOutput!: () => void+ const outputBarrier = new Promise<void>((resolve) => {+ releaseOutput = resolve+ })+ let replacementAttached = false+ const oldFrames: string[] = []+ const replacementFrames: string[] = []+ // The same transport socket can issue the replacement attach. Because frames carry only the+ // session name, anything arriving after that attach would be interpreted as replacement data.+ const sharedSocket = (frame: string): void => {+ if (replacementAttached) replacementFrames.push(frame)+ else oldFrames.push(frame)+ }+ const old: Generation = { exited: true, ending: null, subscribers: [sharedSocket] }+ const sessions = new Map<string, Generation>([['same-name', old]])++ old.ending = retireSessionGeneration(sessions, 'same-name', old, async () => {+ await outputBarrier+ for (const subscriber of old.subscribers) subscriber('old-data')+ for (const subscriber of old.subscribers) subscriber('old-exit')+ }).then(() => {})++ const attachReplacement = (async () => {+ const active = await currentSessionAfterRetirement(sessions, 'same-name')+ expect(active).toBeUndefined()+ const replacement: Generation = {+ exited: false,+ ending: null,+ subscribers: [sharedSocket]+ }+ sessions.set('same-name', replacement)+ replacementAttached = true+ return replacement+ })()++ await Promise.resolve()+ const attachedBeforeOutputRelease = replacementAttached+ const generationBeforeOutputRelease = sessions.get('same-name')++ releaseOutput()+ const replacement = await attachReplacement++ expect(replacementFrames).toEqual([])+ expect(oldFrames).toEqual(['old-data', 'old-exit'])+ expect(attachedBeforeOutputRelease).toBe(false)+ expect(generationBeforeOutputRelease).toBe(old)+ expect(sessions.get('same-name')).toBe(replacement)+ })++ it('atomically gives two retirement waiters one cold replacement and one warm generation', async () => {+ let releaseRetirement!: () => void+ const retirementBarrier = new Promise<void>((resolve) => {+ releaseRetirement = resolve+ })+ const old: Generation = { exited: true, ending: null, subscribers: [] }+ const sessions = new Map<string, Generation>([['same-name', old]])+ old.ending = retireSessionGeneration(sessions, 'same-name', old, async () => {+ await retirementBarrier+ }).then(() => {})+ const coordinator = new SessionGenerationCoordinator(sessions, () => {})+ let creates = 0++ const attach = () =>+ coordinator.run('same-name', async (current) => {+ if (current) return { fresh: false, session: current }+ creates+++ const replacement: Generation = { exited: false, ending: null, subscribers: [] }+ sessions.set('same-name', replacement)+ return { fresh: true, session: replacement }+ })++ const first = attach()+ const second = attach()+ await Promise.resolve()+ releaseRetirement()+ const results = await Promise.all([first, second])++ expect(creates).toBe(1)+ expect(results.map((result) => result.fresh).sort()).toEqual([false, true])+ expect(results[0].session).toBe(results[1].session)+ expect(sessions.get('same-name')).toBe(results[0].session)+ })++ it('cancels a grace timer scheduled by retirement before publishing the replacement', async () => {+ let releaseRetirement!: () => void+ const retirementBarrier = new Promise<void>((resolve) => {+ releaseRetirement = resolve+ })+ const old: Generation = { exited: true, ending: null, subscribers: [] }+ const sessions = new Map<string, Generation>([['same-name', old]])+ let graceTimerArmed = false+ old.ending = retireSessionGeneration(sessions, 'same-name', old, async () => {+ await retirementBarrier+ }).then((released) => {+ if (released) graceTimerArmed = true+ })+ const coordinator = new SessionGenerationCoordinator(sessions, () => {+ graceTimerArmed = false+ })++ const attach = coordinator.run('same-name', async (current) => {+ expect(current).toBeUndefined()+ const replacement: Generation = { exited: false, ending: null, subscribers: [] }+ sessions.set('same-name', replacement)+ return replacement+ })++ await Promise.resolve()+ releaseRetirement()+ const replacement = await attach++ expect(sessions.get('same-name')).toBe(replacement)+ expect(graceTimerArmed).toBe(false)+ })++ it('retries within the same atomic claim when an inspected generation retires', async () => {+ const active: Generation = { exited: false, ending: null, subscribers: [] }+ const sessions = new Map<string, Generation>([['same-name', active]])+ const coordinator = new SessionGenerationCoordinator(sessions, () => {})+ let operations = 0++ const result = await coordinator.run('same-name', async (current) => {+ operations+++ if (current === active) {+ active.exited = true+ active.ending = retireSessionGeneration(sessions, 'same-name', active, async () => {}).then(+ () => {}+ )+ return RETRY_SESSION_GENERATION+ }+ return 'replacement-slot'+ })++ expect(result).toBe('replacement-slot')+ expect(operations).toBe(2)+ })+})diff --git a/src/session-host/generation-barrier.ts b/src/session-host/generation-barrier.tsnew file mode 100644index 000000000..a952ee027--- /dev/null+++ b/src/session-host/generation-barrier.ts@@ -0,0 +1,92 @@+/** A same-name PTY can have only one protocol generation at a time. The wire format identifies+ * data/exit frames by session name alone, so reusing that name while the prior generation still+ * has final frames to publish makes those frames indistinguishable from the replacement's. */+export interface RetiringSessionGeneration {+ exited: boolean+ /** Explicit kill has successfully dispatched but process exit is not observed yet. */+ retiring?: boolean+ ending: Promise<void> | null+}++/** Keep an exiting generation visible until its final output, exit frame and teardown have all+ * completed. The identity check is defensive: the attach gate below should prevent replacement,+ * but an unrelated future writer must never let an old cleanup delete a newer generation. */+export async function retireSessionGeneration<T>(+ sessions: Map<string, T>,+ name: string,+ generation: T,+ publishAndDispose: () => Promise<void>+): Promise<boolean> {+ await publishAndDispose()+ if (sessions.get(name) !== generation) return false+ sessions.delete(name)+ return true+}++/** Return the active generation, or an empty slot only after an exiting generation has finished+ * publishing. Waiting rather than deleting is the protocol-compatible generation boundary: a+ * socket may receive the old exit before its attach response, but never after it has attached to+ * a new same-name PTY. */+export async function currentSessionAfterRetirement<T extends RetiringSessionGeneration>(+ sessions: Map<string, T>,+ name: string+): Promise<T | undefined> {+ for (;;) {+ const current = sessions.get(name)+ if (!current || (!current.exited && !current.retiring)) return current+ if (!current.ending) {+ throw new Error(`exited session ${name} has no retirement barrier`)+ }+ await current.ending+ }+}++/** Returned by a coordinated operation when the generation it inspected changed during an async+ * step (for example, while a warm snapshot drained). The coordinator retains the same-name claim+ * and re-enters through the retirement barrier instead of recursively racing a second claim. */+export const RETRY_SESSION_GENERATION = Symbol('retry-session-generation')++/** Serializes the entire "retire old / cancel grace / inspect or create replacement" decision for+ * one session name. Merely awaiting `ending` is not enough: two awaiters resume from the same+ * promise before either outer continuation can publish its replacement, so both can observe an+ * empty map and spawn duplicate PTYs. Different names remain fully concurrent. */+export class SessionGenerationCoordinator<T extends RetiringSessionGeneration> {+ private readonly turns = new Map<string, Promise<void>>()++ constructor(+ private readonly sessions: Map<string, T>,+ private readonly onNameClaimed: () => void+ ) {}++ async run<R>(+ name: string,+ operation: (+ current: T | undefined+ ) => Promise<R | typeof RETRY_SESSION_GENERATION>+ ): Promise<R> {+ const previous = this.turns.get(name) ?? Promise.resolve()+ let release!: () => void+ const turn = new Promise<void>((resolve) => {+ release = resolve+ })+ const tail = previous.then(() => turn)+ this.turns.set(name, tail)++ await previous+ try {+ for (;;) {+ const current = await currentSessionAfterRetirement(this.sessions, name)+ // Retirement may have just scheduled the empty-host grace timer after deleting the old+ // map entry. Cancel HERE, under the atomic name claim, immediately before inspect/create.+ this.onNameClaimed()+ const result = await operation(current)+ if (result !== RETRY_SESSION_GENERATION) return result+ }+ } finally {+ release()+ // A queued successor replaces `tail` in the map before reaching this point; never delete+ // that successor's claim while releasing ours.+ if (this.turns.get(name) === tail) this.turns.delete(name)+ }+ }+}diff --git a/src/session-host/hello-probe.test.ts b/src/session-host/hello-probe.test.tsnew file mode 100644index 000000000..095f1a46e--- /dev/null+++ b/src/session-host/hello-probe.test.ts@@ -0,0 +1,78 @@+import { afterEach, describe, expect, it } from 'vitest'+import net from 'net'+import os from 'os'+import path from 'path'+import { randomUUID } from 'crypto'+import { rmSync } from 'fs'+import { encodeFrame } from './protocol'+import { trySessionHostHello } from './hello-probe'++const cleanupPaths: string[] = []+afterEach(() => {+ for (const target of cleanupPaths.splice(0)) rmSync(target, { force: true })+})++function testEndpoint(): string {+ const id = randomUUID()+ if (process.platform === 'win32') return `\\\\.\\pipe\\nodeterm-hello-probe-${id}`+ const endpoint = path.join(os.tmpdir(), `nodeterm-hello-probe-${id}.sock`)+ cleanupPaths.push(endpoint)+ return endpoint+}++describe('session-host hello liveness probe', () => {+ it('ignores an unrelated ok frame and waits for the exact hello response ID', async () => {+ const endpoint = testEndpoint()+ const server = net.createServer((socket) => {+ socket.once('data', () => {+ socket.write(+ encodeFrame({ id: 999, ok: true }) + encodeFrame({ id: 0, ok: false, error: 'wrong token' })+ )+ })+ })+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+ try {+ await expect(trySessionHostHello(endpoint, 'not-the-token', 1_000)).resolves.toBe(false)+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ })++ it('keeps waiting after an unrelated ok until the delayed exact ID succeeds', async () => {+ const endpoint = testEndpoint()+ const server = net.createServer((socket) => {+ socket.once('data', () => {+ socket.write(encodeFrame({ id: 999, ok: true }))+ setTimeout(() => socket.write(encodeFrame({ id: 0, ok: true })), 20)+ })+ })+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+ try {+ await expect(trySessionHostHello(endpoint, 'token', 1_000)).resolves.toBe(true)+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ })++ it('accepts the exact correlated ok response', async () => {+ const endpoint = testEndpoint()+ const server = net.createServer((socket) => {+ socket.once('data', () => socket.write(encodeFrame({ id: 0, ok: true })))+ })+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject)+ server.listen(endpoint, resolve)+ })+ try {+ await expect(trySessionHostHello(endpoint, 'token', 1_000)).resolves.toBe(true)+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ })+})diff --git a/src/session-host/hello-probe.ts b/src/session-host/hello-probe.tsnew file mode 100644index 000000000..3f8c4baf6--- /dev/null+++ b/src/session-host/hello-probe.ts@@ -0,0 +1,41 @@+import net from 'net'+import { LineFramer, encodeFrame } from './protocol'++const HELLO_PROBE_ID = 0++/** One bounded liveness check for an ownership-state endpoint. Only the response correlated to the+ * exact hello request can decide the result; an unrelated queued `{ok:true}` frame is not proof+ * that this host accepted our token. */+export function trySessionHostHello(+ endpoint: string,+ token: string,+ timeoutMs: number+): Promise<boolean> {+ return new Promise((resolve) => {+ let settled = false+ const socket = net.connect(endpoint)+ const finish = (ok: boolean): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ try {+ socket.destroy()+ } catch {+ /* already gone */+ }+ resolve(ok)+ }+ const timer = setTimeout(() => finish(false), timeoutMs)+ socket.once('error', () => finish(false))+ socket.once('connect', () => {+ socket.write(encodeFrame({ id: HELLO_PROBE_ID, cmd: 'hello', token }))+ })+ const framer = new LineFramer()+ socket.on('data', (chunk: Buffer) => {+ for (const frame of framer.push<{ id: number; ok?: boolean }>(chunk.toString('utf8'))) {+ if (frame.id !== HELLO_PROBE_ID) continue+ finish(frame.ok === true)+ }+ })+ })+}diff --git a/src/session-host/host-routing.test.ts b/src/session-host/host-routing.test.tsnew file mode 100644index 000000000..df6f1dcd7--- /dev/null+++ b/src/session-host/host-routing.test.ts@@ -0,0 +1,337 @@+import { afterEach, describe, expect, it } from 'vitest'+import { spawn, type ChildProcess } from 'child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'fs'+import net, { type Socket } from 'net'+import os from 'os'+import path from 'path'+import { build, type Plugin } from 'esbuild'+import {+ LineFramer,+ encodeFrame,+ type SessionHostFrame,+ type SessionHostResponse,+ type SessionHostSpawnOptions+} from './protocol'+import { sessionHostPaths, type SessionHostState } from './paths'++function fakePtyPlugin(killMode: 'throw' | 'deferred-exit'): Plugin {+ const killBody =+ killMode === 'throw'+ ? `throw new Error('synthetic kill refusal')`+ : `setTimeout(() => onExit?.({ exitCode: 0 }), 150)`+ return {+ name: 'session-host-routing-fake-pty',+ setup(bundle) {+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({+ path: 'node-pty',+ namespace: 'host-routing'+ }))+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'host-routing' }, () => ({+ loader: 'js',+ contents: `+ export function spawn() {+ let onExit+ return {+ pid: 4242,+ onData() {},+ onExit(callback) { onExit = callback },+ write() {},+ resize() {},+ pause() {},+ resume() {},+ kill() { ${killBody} }+ }+ }+ `+ }))+ }+ }+}++async function waitForIdentity(dataDir: string): Promise<{ state: SessionHostState; token: string }> {+ const paths = sessionHostPaths(dataDir)+ for (let attempt = 0; attempt < 100; attempt++) {+ try {+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8')) as SessionHostState+ const token = readFileSync(paths.tokenPath, 'utf8').trim()+ if (state.endpoint && token) return { state, token }+ } catch {+ /* publication is intentionally asynchronous; keep polling within the test bound */+ }+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+ throw new Error('session host did not publish its identity')+}++function connectFrames(endpoint: string): Promise<{+ socket: Socket+ response(id: number): Promise<SessionHostResponse>+}> {+ return new Promise((resolve, reject) => {+ const socket = net.connect(endpoint)+ const framer = new LineFramer()+ const received = new Map<number, SessionHostResponse>()+ const waiters = new Map<number, (frame: SessionHostResponse) => void>()+ socket.on('data', (chunk: Buffer) => {+ for (const frame of framer.push<SessionHostFrame>(chunk.toString('utf8'))) {+ if (!('id' in frame)) continue+ const waiter = waiters.get(frame.id)+ if (waiter) {+ waiters.delete(frame.id)+ waiter(frame)+ } else {+ received.set(frame.id, frame)+ }+ }+ })+ socket.once('error', reject)+ socket.once('connect', () =>+ resolve({+ socket,+ response: (id) => {+ const frame = received.get(id)+ if (frame) {+ received.delete(id)+ return Promise.resolve(frame)+ }+ return new Promise<SessionHostResponse>((resolveResponse, rejectResponse) => {+ const timer = setTimeout(+ () => rejectResponse(new Error(`timed out waiting for response ${id}`)),+ 2_000+ )+ waiters.set(id, (next) => {+ clearTimeout(timer)+ resolveResponse(next)+ })+ })+ }+ })+ )+ })+}++function waitForExit(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()+ return new Promise((resolve) => child.once('exit', () => resolve()))+}++const cleanupPaths: string[] = []+afterEach(() => {+ for (const target of cleanupPaths.splice(0)) rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+})++describe('bundled session-host request boundaries', () => {+ it('keeps same-name wire order, enforces membership, and retains a generation on kill failure', async () => {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-routing-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ const bundlePath = path.join(fixtureDir, 'host.cjs')+ await build({+ absWorkingDir: process.cwd(),+ entryPoints: ['src/session-host/host.ts'],+ outfile: bundlePath,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ plugins: [fakePtyPlugin('throw')],+ logLevel: 'silent'+ })+ const child = spawn(process.execPath, [bundlePath, dataDir], {+ cwd: process.cwd(),+ stdio: 'ignore',+ windowsHide: true+ })+ let socket: Socket | null = null+ try {+ const { state, token } = await waitForIdentity(dataDir)+ const connected = await connectFrames(state.endpoint)+ socket = connected.socket+ socket.write(encodeFrame({ id: 0, cmd: 'hello', token }))+ await expect(connected.response(0)).resolves.toMatchObject({ id: 0, ok: true })++ const spawnOptions: SessionHostSpawnOptions = {+ cwd: '.',+ shell: 'fake-shell',+ args: [],+ env: {},+ cols: 80,+ rows: 24+ }+ // One transport chunk is the old inversion: dispatching each parsed frame independently let+ // detach observe no session while attach was waiting on its first generation microtask.+ socket.write(+ encodeFrame({+ id: 1,+ cmd: 'attach',+ name: 'ordered',+ spawn: spawnOptions,+ scrollback: 100+ }) + encodeFrame({ id: 2, cmd: 'detach', name: 'ordered' })+ )+ await expect(connected.response(1)).resolves.toMatchObject({ id: 1, ok: true })+ await expect(connected.response(2)).resolves.toMatchObject({ id: 2, ok: true })++ socket.write(+ encodeFrame({ id: 3, cmd: 'write', name: 'ordered', data: 'must-not-land' }) ++ encodeFrame({ id: 4, cmd: 'resize', name: 'ordered', cols: 120, rows: 40 }) ++ encodeFrame({ id: 5, cmd: 'pause', name: 'ordered' })+ )+ for (const id of [3, 4, 5]) {+ await expect(connected.response(id)).resolves.toMatchObject({+ id,+ ok: false,+ error: 'not attached to session'+ })+ }++ socket.write(encodeFrame({ id: 6, cmd: 'killSession', name: 'ordered' }))+ if (process.platform === 'win32') {+ // On win32, host.ts's killSession handler never calls the (fake) node-pty proc.kill() at+ // all: it goes through terminateWindowsProcessTree instead, because node-pty defers+ // WindowsTerminal.kill() until first output (see windows-process-tree.ts). That real+ // taskkill call fails for the fixture's hardcoded, never-actually-spawned pid 4242, and+ // host.ts intentionally reports that failure with its own fixed, non-leaking message+ // rather than the underlying taskkill diagnostic — so the fake plugin's 'synthetic kill+ // refusal' text (which only ever reaches session.proc.kill() on non-Windows) is never+ // seen here. The invariant this assertion exists to prove — a failed kill still reports+ // ok:false and leaves the session's generation intact (checked below via hasSession) —+ // holds identically on both platforms; only the wire-visible error text differs.+ await expect(connected.response(6)).resolves.toMatchObject({+ id: 6,+ ok: false,+ error: 'session-host could not confirm terminal process termination'+ })+ } else {+ await expect(connected.response(6)).resolves.toMatchObject({+ id: 6,+ ok: false,+ error: expect.stringContaining('synthetic kill refusal')+ })+ }+ socket.write(encodeFrame({ id: 7, cmd: 'hasSession', name: 'ordered' }))+ await expect(connected.response(7)).resolves.toMatchObject({+ id: 7,+ ok: true,+ result: { exists: true }+ })+ expect(existsSync(paths.statePath)).toBe(true)+ } finally {+ socket?.destroy()+ child.kill()+ await waitForExit(child)+ }+ }, 15_000)++ // On win32, host.ts's killSession handler for a 'ordered'/'exit-barrier'-style session never+ // calls the fake node-pty proc.kill()/onExit() this test controls: it dispatches+ // terminateWindowsProcessTree instead (see the same win32 branch documented in the previous+ // test), because node-pty defers WindowsTerminal.kill() until first output. That real taskkill+ // call targets the fixture's hardcoded, never-actually-spawned pid 4242, fails fast (there is no+ // such process to terminate), and resolves the kill near-instantly — the fake plugin's+ // 'deferred-exit' onExit timer is simply never reached, so the "acknowledgment held back until+ // real exit" scenario this test exists to prove cannot be exercised at all through this fake+ // pty on Windows. Proving the Windows-equivalent invariant (acknowledgment held back until+ // taskkill's PID-absence poll actually confirms termination) needs a fake/mock of+ // terminateWindowsProcessTree itself, not of node-pty — a different fixture design, out of+ // scope here. Precedent: 99dfb2db (src/core/codex-session-name.test.ts) skips suites on win32+ // whose fixture cannot reach the code path under test in this environment.+ it.skipIf(process.platform === 'win32')(+ 'holds kill acknowledgement and cross-socket replacement behind actual onExit',+ async () => {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-kill-exit-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ const bundlePath = path.join(fixtureDir, 'host.cjs')+ await build({+ absWorkingDir: process.cwd(),+ entryPoints: ['src/session-host/host.ts'],+ outfile: bundlePath,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ plugins: [fakePtyPlugin('deferred-exit')],+ logLevel: 'silent'+ })+ const child = spawn(process.execPath, [bundlePath, dataDir], {+ cwd: process.cwd(),+ stdio: 'ignore',+ windowsHide: true+ })+ let firstSocket: Socket | null = null+ let secondSocket: Socket | null = null+ try {+ const { state, token } = await waitForIdentity(dataDir)+ const first = await connectFrames(state.endpoint)+ const second = await connectFrames(state.endpoint)+ firstSocket = first.socket+ secondSocket = second.socket+ firstSocket.write(encodeFrame({ id: 0, cmd: 'hello', token }))+ secondSocket.write(encodeFrame({ id: 0, cmd: 'hello', token }))+ await Promise.all([first.response(0), second.response(0)])++ const spawnOptions: SessionHostSpawnOptions = {+ cwd: '.',+ shell: 'fake-shell',+ args: [],+ env: {},+ cols: 80,+ rows: 24+ }+ firstSocket.write(+ encodeFrame({+ id: 1,+ cmd: 'attach',+ name: 'exit-barrier',+ spawn: spawnOptions,+ scrollback: 100+ })+ )+ await expect(first.response(1)).resolves.toMatchObject({ id: 1, ok: true })++ firstSocket.write(encodeFrame({ id: 2, cmd: 'killSession', name: 'exit-barrier' }))+ // Let the host synchronously dispatch proc.kill() and publish its `retiring` name claim.+ await new Promise((resolve) => setTimeout(resolve, 20))+ secondSocket.write(+ encodeFrame({+ id: 2,+ cmd: 'attach',+ name: 'exit-barrier',+ spawn: spawnOptions,+ scrollback: 100+ })+ )++ let killSettled = false+ let attachSettled = false+ const killed = first.response(2).then((response) => {+ killSettled = true+ return response+ })+ const replacement = second.response(2).then((response) => {+ attachSettled = true+ return response+ })+ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(killSettled).toBe(false)+ expect(attachSettled).toBe(false)++ await expect(killed).resolves.toMatchObject({ id: 2, ok: true })+ await expect(replacement).resolves.toMatchObject({+ id: 2,+ ok: true,+ result: { fresh: true }+ })+ } finally {+ firstSocket?.destroy()+ secondSocket?.destroy()+ child.kill()+ await waitForExit(child)+ }+ }, 15_000)+})diff --git a/src/session-host/host.ts b/src/session-host/host.tsnew file mode 100644index 000000000..10d57a5f3--- /dev/null+++ b/src/session-host/host.ts@@ -0,0 +1,1057 @@+// The standalone session-host process: a plain Node entry point (NOT Electron-dependent — it is+// launched with ELECTRON_RUN_AS_NODE=1 when process.execPath is the Electron binary, see+// src/core/session-host-launcher.ts) that owns PTYs and outlives the app that spawned it. This is+// the Windows-and-anywhere-tmux-is-missing analogue of a tmux server.+//+// Bundled by esbuild (`npm run host:build`) to out/session-host/host.cjs, mirroring the existing+// `server:build` script's shape — node-pty stays external (native module). See+// docs/windows-session-host.md for the full architecture, lifetime rules, protocol and the+// warm-attach seeding trap this file's `handleAttach` exists to avoid.+//+// Invocation: `node host.cjs <userDataDir>`. Everything the host needs — where to bind, where to+// write its token/state — is DERIVED from userDataDir alone (see paths.ts); nothing else is ever+// passed on argv, so nothing sensitive ever appears in this process's command line.++import fs from 'fs'+import net from 'net'+import path from 'path'+import crypto from 'crypto'+import { sessionHostPaths, currentProtocolVersion, type SessionHostState } from './paths'+import {+ LineFramer,+ encodeFrame,+ type SessionHostRequest,+ type SessionHostFrame,+ type AttachResult,+ type HasSessionResult,+ type PaneCommandResult,+ type CaptureResult,+ type KillSessionResult,+ type ListSessionsResult+} from './protocol'+import { HostSession } from './session'+import { paneCommand as readPaneCommand } from './process-tree'+import { terminateWindowsProcessTree } from './windows-process-tree'+import { publishSessionHostState } from './state-file'+import { readExistingSessionHostIdentity } from './existing-host-state'+import {+ RETRY_SESSION_GENERATION,+ SessionGenerationCoordinator,+ retireSessionGeneration+} from './generation-barrier'+import { drainSessionHostTransport, writeSessionHostFrame } from './socket-flow'+import { SessionHostSocketRequestQueue } from './socket-request-queue'+import { trySessionHostHello } from './hello-probe'+import { killHostSession } from './kill-session'++/** How long a session-less host lingers before exiting — mirrors tmux's own server lifetime rule+ * ("the server exits when its last session dies"), plus a grace window so an app restart that+ * briefly drops to zero sessions (closing every node, or a launcher racing a real create) does+ * not tear down a host that is about to be handed a fresh session moments later. */+const GRACE_EXIT_MS = 30_000+const COMPLETED_KILL_TTL_MS = 10 * 60_000+const MAX_COMPLETED_KILLS = 1_024+const REPLACEMENT_RESERVATION_TTL_MS = 30_000++/** Bounded log file — this is a headless daemon with `stdio: 'ignore'`, so this is the only way+ * to see what it did after the fact. Best-effort: a failure to write here must never affect a+ * session. Capped by truncating rather than rotating — simplicity over completeness for a file+ * nobody reads except when diagnosing a report. */+let logPath = ''+const LOG_CAP_BYTES = 512 * 1024+function log(line: string): void {+ if (!logPath) return+ try {+ const stat = fs.existsSync(logPath) ? fs.statSync(logPath) : null+ if (stat && stat.size > LOG_CAP_BYTES) fs.writeFileSync(logPath, '')+ fs.appendFileSync(logPath, `${new Date().toISOString()} ${line}\n`)+ } catch {+ /* diagnostics only */+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}++/** Poll for a WINNER of the startup race to finish writing its state file and come up — the state+ * file can legitimately exist-but-be-incomplete for a brief window between this process losing+ * the exclusive-create race and the winner actually binding + writing token + state. */+async function probeExisting(+ statePath: string,+ expectedEndpoint: string,+ expectedTokenPath: string+): Promise<boolean> {+ let lastFailure: unknown = null+ for (let attempt = 0; attempt < 10; attempt++) {+ try {+ const identity = readExistingSessionHostIdentity(statePath, {+ expectedEndpoint,+ expectedTokenPath+ })+ // ENOENT is the only observation that can prove absence. It also supersedes an earlier+ // partial-publication read failure: the final bounded observation is what owns reclaim.+ lastFailure = null+ if (+ identity.kind === 'ready' &&+ (await trySessionHostHello(identity.state.endpoint, identity.token, 1000))+ ) {+ return true+ }+ } catch (error) {+ // A winner can be between exclusive-create and atomic publication, so retry within the+ // existing bound. If the final observation is still unreadable/invalid, propagate it: that+ // is evidence of possible ownership, never permission to unlink and steal the state path.+ lastFailure = error+ }+ await sleep(150)+ }+ if (lastFailure) throw lastFailure+ return false+}++async function main(): Promise<void> {+ const userDataDir = process.argv[2]+ if (!userDataDir) {+ process.stderr.write('session-host: missing userDataDir argument\n')+ process.exit(1)+ }+ const paths = sessionHostPaths(userDataDir)+ logPath = path.join(userDataDir, 'session-host.log')+ log(`starting pid=${process.pid} endpoint=${paths.endpoint}`)++ // 1) Exclusive-create race gate. Two app instances launched at once will both spawn a host;+ // exactly one of them may proceed past this point on the first try.+ let haveLock = false+ try {+ fs.closeSync(fs.openSync(paths.statePath, 'wx'))+ haveLock = true+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') {+ log(`fatal: could not create state file: ${String(e)}`)+ process.exit(1)+ }+ }+ if (!haveLock) {+ let alive: boolean+ try {+ alive = await probeExisting(paths.statePath, paths.endpoint, paths.tokenPath)+ } catch (error) {+ log(`fatal: existing host ownership state is unreadable: ${String(error)}`)+ process.exit(1)+ return+ }+ if (alive) {+ log('another host is already running and answered hello — exiting quietly')+ process.exit(0)+ }+ // Stale lock: a previous host crashed before cleaning up, or lost the race and left a+ // half-written file. Steal it — we already waited out the whole probe window above.+ log('stale state file with no live host behind it — reclaiming')+ try {+ fs.unlinkSync(paths.statePath)+ } catch {+ /* already gone */+ }+ try {+ fs.closeSync(fs.openSync(paths.statePath, 'wx'))+ } catch (e) {+ log(`fatal: could not reclaim state file: ${String(e)}`)+ process.exit(1)+ }+ }++ // POSIX: a stale socket FILE left by an unclean shutdown makes bind() fail EADDRINUSE even+ // though nothing is listening. Safe to clear now — we hold the state-file lock, so nothing+ // legitimate can be bound here without having just re-won that same lock.+ if (process.platform !== 'win32') {+ try {+ fs.unlinkSync(paths.endpoint)+ } catch {+ /* nothing to remove */+ }+ }++ const sessions = new Map<string, HostSession>()+ type EndingOperation = {+ session: HostSession+ promise: Promise<KillSessionResult>+ resolve: (result: KillSessionResult) => void+ reject: (error: Error) => void+ operationIds: Set<string>+ reserveReplacement: boolean+ expectedGeneration?: string+ }+ const ending = new Map<string, EndingOperation>()+ const inProgressKillIds = new Map<string, { name: string; operation: EndingOperation }>()+ const completedKillIds = new Map<+ string,+ {+ name: string+ completedAt: number+ reserveReplacement: boolean+ expectedGeneration?: string+ }+ >()+ const replacementReservations = new Map<+ string,+ { token: string; expiresAt: number }+ >()+ let graceTimer: ReturnType<typeof setTimeout> | null = null++ function pruneCompletedKills(now = Date.now()): void {+ for (const [operationId, entry] of completedKillIds) {+ if (now - entry.completedAt <= COMPLETED_KILL_TTL_MS) continue+ completedKillIds.delete(operationId)+ }+ while (completedKillIds.size > MAX_COMPLETED_KILLS) {+ const oldest = completedKillIds.keys().next().value as string | undefined+ if (!oldest) break+ completedKillIds.delete(oldest)+ }+ }++ function rememberCompletedKill(+ operationId: string,+ name: string,+ reserveReplacement: boolean,+ expectedGeneration?: string+ ): void {+ completedKillIds.delete(operationId)+ completedKillIds.set(operationId, {+ name,+ completedAt: Date.now(),+ reserveReplacement,+ expectedGeneration+ })+ pruneCompletedKills()+ }++ function validateKillOperationId(operationId: string): void {+ if (!/^[A-Za-z0-9_-]{8,128}$/.test(operationId)) {+ throw new Error('invalid kill operation id')+ }+ }++ function activeReplacementReservation(+ name: string+ ): { token: string; expiresAt: number } | undefined {+ const reservation = replacementReservations.get(name)+ if (reservation && reservation.expiresAt <= Date.now()) {+ replacementReservations.delete(name)+ return undefined+ }+ return reservation+ }++ function setReplacementReservation(name: string, token: string): void {+ replacementReservations.set(name, {+ token,+ expiresAt: Date.now() + REPLACEMENT_RESERVATION_TTL_MS+ })+ // A zero-session host is now carrying a live cross-client replacement lease. Restart its+ // grace window so it cannot exit underneath the owner before the equally-bounded lease does.+ cancelGraceExit()+ scheduleGraceExitIfEmpty()+ }++ function cancelGraceExit(): void {+ if (graceTimer) {+ clearTimeout(graceTimer)+ graceTimer = null+ }+ }+ function scheduleGraceExitIfEmpty(): void {+ if (sessions.size > 0) return+ cancelGraceExit()+ graceTimer = setTimeout(() => {+ if (sessions.size > 0) return+ log('no sessions left — exiting')+ cleanupFiles()+ process.exit(0)+ }, GRACE_EXIT_MS)+ graceTimer.unref?.()+ }+ function cleanupFiles(): void {+ for (const p of [paths.statePath, paths.tokenPath]) {+ try {+ fs.unlinkSync(p)+ } catch {+ /* best-effort */+ }+ }+ if (process.platform !== 'win32') {+ try {+ fs.unlinkSync(paths.endpoint)+ } catch {+ /* best-effort */+ }+ }+ }+ const generationCoordinator = new SessionGenerationCoordinator(sessions, cancelGraceExit)++ function broadcast(session: HostSession, frame: SessionHostFrame): void {+ const line = encodeFrame(frame)+ for (const sub of session.subscribers) {+ writeSessionHostFrame(sub, line, sessions.values())+ }+ }++ /** Publish and remove a generation only after node-pty has authoritatively observed process+ * exit. A successful `proc.kill()` call merely dispatched a signal and cannot enter here. */+ async function publishSessionEnd(session: HostSession, exitCode: number): Promise<void> {+ const kill = ending.get(session.name)+ const ownedKill = kill?.session === session ? kill : undefined+ const ownerToken = ownedKill?.operationIds.values().next().value as string | undefined+ const killResult: KillSessionResult | undefined = ownedKill+ ? { replacementToken: ownedKill.reserveReplacement ? ownerToken : undefined }+ : undefined+ const released = await retireSessionGeneration(+ sessions,+ session.name,+ session,+ async () => {+ await session.settleOutput()+ if (ownerToken && ownedKill?.reserveReplacement) {+ // The reservation is the confirmed-replacement commit. Publish the generation exit only+ // after it exists so a lost correlated reply can reclaim the same operation id safely.+ // Start its bounded TTL after the output drain, not while teardown is still pending.+ setReplacementReservation(session.name, ownerToken)+ }+ broadcast(session, {+ type: 'exit',+ name: session.name,+ exitCode,+ generation: session.generation+ })+ session.dispose()+ }+ )+ if (released) scheduleGraceExitIfEmpty()+ log(`session ended name=${session.name} exitCode=${exitCode}`)+ if (ownedKill && killResult) {+ if (ending.get(session.name) === ownedKill) ending.delete(session.name)+ for (const operationId of ownedKill.operationIds) {+ rememberCompletedKill(+ operationId,+ session.name,+ ownedKill.reserveReplacement,+ ownedKill.expectedGeneration+ )+ inProgressKillIds.delete(operationId)+ }+ ownedKill.resolve(killResult)+ }+ }++ function endSession(session: HostSession, exitCode: number): Promise<void> {+ if (session.ending) return session.ending+ session.retiring = true+ session.ending = publishSessionEnd(session, exitCode)+ return session.ending+ }++ /** Claim the name immediately after a kill signal succeeds, then wait for onExit. The generation+ * coordinator sees `retiring` and blocks same-name attach until the real exit frame, output drain+ * and disposal have all completed. */+ function beginKillRetirement(session: HostSession): Promise<void> {+ if (session.ending) return session.ending+ session.retiring = true+ session.ending = (async () => {+ const exitCode = await session.waitForProcessExit()+ await publishSessionEnd(session, exitCode)+ })()+ return session.ending+ }++ function wireSession(session: HostSession): void {+ session.proc.onData((data) => {+ // node-pty may flush a queued data callback after its exit callback. Once endSession has+ // disposed the emulator and broadcast exit, no data may touch or appear after that boundary.+ if (session.exited) return+ // Trusted launch input is typed through the same ConPTY and therefore echoed by the shell.+ // While HostSession verifies that echo, keep the entire chunk out of both renderer push+ // frames and the reconstructable screen so executable/argv/prompt material stays core-only.+ if (session.suppressingPrivateLaunchOutput) return+ void session.recordOutput(data).then(+ () =>+ broadcast(session, {+ type: 'data',+ name: session.name,+ data,+ generation: session.generation+ }),+ (e) => {+ // Delivery is still preferable to silently losing real PTY bytes if the screen mirror+ // itself ever rejects. The queue recovers for later writes; a capture may omit this one.+ log(`terminal mirror write failed name=${session.name}: ${String(e)}`)+ broadcast(session, {+ type: 'data',+ name: session.name,+ data,+ generation: session.generation+ })+ }+ )+ })+ session.proc.onExit(({ exitCode }) => {+ session.observeProcessExit(exitCode)+ void endSession(session, exitCode)+ })+ }++ async function launchProcessReady(session: HostSession): Promise<boolean> {+ const command = await readPaneCommand(session.proc.pid)+ if (!command) return false+ const liveName = command.replace(/\\/g, '/').split('/').pop()?.toLowerCase() ?? ''+ return Boolean(liveName && liveName !== session.shellExecutableName)+ }++ async function handleAttach(+ req: Extract<SessionHostRequest, { cmd: 'attach' }>,+ socket: net.Socket+ ): Promise<AttachResult> {+ return generationCoordinator.run<AttachResult>(req.name, async (existing) => {+ if (ending.has(req.name)) {+ throw new Error(`session '${req.name}' is ending and cannot be attached`)+ }+ if (existing && !existing.exited) {+ if (req.replacementToken) {+ if (existing.createdByReplacementToken !== req.replacementToken) {+ throw new Error(+ `reserved replacement '${req.name}' cannot attach a different live generation`+ )+ }+ if (!existing.matchesReplacementReplay(req.spawn, req.scrollback)) {+ throw new Error(+ `reserved replacement '${req.name}' replay changed its trusted launch plan`+ )+ }+ }+ // Restore this connection's flow + geometry before taking the screen. A reconnect carrying+ // `paused` must never receive bytes in the gap before its explicit ticket is reasserted.+ // Live delivery still starts only AFTER the barrier+snapshot, so a pending chunk cannot be+ // delivered to this socket and then appear again in the warm screen.+ const attachment = await existing.prepareAttachment(+ socket,+ req.spawn.cols,+ req.spawn.rows,+ req.paused === true+ )+ try {+ const screen = await existing.serialize()+ if (!attachment.isCurrent()) {+ await attachment.rollback()+ throw new Error('attach cancelled before activation')+ }+ // The process can exit while the async emulator drains. Retain this name claim and cross+ // its retirement barrier again; recursive attach would deadlock or race another waiter.+ if (existing.exited || sessions.get(req.name) !== existing) {+ await attachment.rollback()+ if (!attachment.isCurrent()) throw new Error('attach cancelled during retry')+ return RETRY_SESSION_GENERATION+ }+ if (!attachment.commit()) throw new Error('attach cancelled before activation')+ const initialLaunch = req.replacementToken+ ? await existing.executeInitialLaunch(req.spawn, () => launchProcessReady(existing))+ : undefined+ log(`attach (warm) name=${req.name} subscribers=${existing.subscribers.size}`)+ return {+ // A replay of the same consumed replacement token replays the original cold result;+ // this is not an ordinary warm attach even though the generation now exists.+ fresh: Boolean(req.replacementToken),+ screen: screen || undefined,+ generation: existing.generation,+ launchDialect: existing.launchDialect,+ initialLaunchStatus: initialLaunch?.status+ }+ } catch (error) {+ await attachment.rollback()+ throw error+ }+ }++ const reservation = activeReplacementReservation(req.name)+ if (reservation && req.replacementToken !== reservation.token) {+ scheduleGraceExitIfEmpty()+ throw new Error(`session '${req.name}' is reserved for confirmed replacement`)+ }+ if (!reservation && req.replacementToken) {+ scheduleGraceExitIfEmpty()+ throw new Error(`replacement reservation for session '${req.name}' is no longer valid`)+ }+ // Consume before construction: a resolver/spawn failure releases the name for recovery.+ if (reservation) replacementReservations.delete(req.name)+ let session: HostSession+ try {+ session = new HostSession(req.name, req.spawn, req.scrollback, reservation?.token)+ } catch (error) {+ scheduleGraceExitIfEmpty()+ log(`spawn failed name=${req.name} category=profile-start-failed detail=${String(error)}`)+ // Executable, argv, cwd and native process details are trusted-core/private state. The wire+ // carries only a stable actionable category; full diagnostics stay in the host-local log.+ throw new Error('session-host could not start the requested terminal profile')+ }+ // prepareAttachment books `paused` synchronously before its first await. Do that before the+ // process is wired for output so a reconnect cannot leak initial bytes before the ticket.+ const preparing = session.prepareAttachment(+ socket,+ req.spawn.cols,+ req.spawn.rows,+ req.paused === true+ )+ sessions.set(req.name, session)+ wireSession(session)+ try {+ const attachment = await preparing+ if (+ session.exited ||+ sessions.get(req.name) !== session ||+ !attachment.isCurrent() ||+ !attachment.commit()+ ) {+ await attachment.rollback()+ throw new Error('attach cancelled before activation')+ }+ } catch (error) {+ if (session.exited) {+ await session.ending+ } else if (sessions.get(req.name) === session) {+ await killHostSession(session, beginKillRetirement)+ }+ throw error+ }+ log(`attach (cold) name=${req.name} pid=${session.proc.pid}`)+ const initialLaunch = await session.executeInitialLaunch(req.spawn, () =>+ launchProcessReady(session)+ )+ return {+ fresh: true,+ generation: session.generation,+ launchDialect: session.launchDialect,+ initialLaunchStatus: initialLaunch?.status+ }+ })+ }++ async function handleAttachExisting(+ req: Extract<SessionHostRequest, { cmd: 'attachExisting' }>,+ socket: net.Socket+ ): Promise<AttachResult> {+ return generationCoordinator.run<AttachResult>(req.name, async (existing) => {+ if (ending.has(req.name)) {+ throw new Error(`session '${req.name}' is ending and cannot be attached`)+ }+ if (!existing || existing.exited) {+ scheduleGraceExitIfEmpty()+ throw new Error(`no existing session '${req.name}'`)+ }+ if (req.expectedGeneration && req.expectedGeneration !== existing.generation) {+ throw new Error(`session '${req.name}' was replaced by a different generation`)+ }+ const attachment = await existing.prepareExistingAttachment(+ socket,+ req.paused === true,+ req.cols,+ req.rows+ )+ try {+ const screen = await existing.serialize()+ if (!attachment.isCurrent()) {+ await attachment.rollback()+ throw new Error('attachExisting cancelled before activation')+ }+ if (existing.exited || sessions.get(req.name) !== existing) {+ await attachment.rollback()+ if (!attachment.isCurrent()) throw new Error('attachExisting cancelled during retry')+ return RETRY_SESSION_GENERATION+ }+ if (!attachment.commit()) throw new Error('attachExisting cancelled before activation')+ log(`attach-existing name=${req.name} subscribers=${existing.subscribers.size}`)+ return {+ fresh: false,+ screen: screen || undefined,+ generation: existing.generation,+ launchDialect: existing.launchDialect+ }+ } catch (error) {+ await attachment.rollback()+ throw error+ }+ })+ }++ async function handleKill(+ name: string,+ operationId: string,+ expectedGeneration: string | undefined,+ reserveReplacement: boolean+ ): Promise<KillSessionResult> {+ validateKillOperationId(operationId)+ pruneCompletedKills()+ const completed = completedKillIds.get(operationId)+ if (completed) {+ if (completed.name !== name) throw new Error('kill operation id belongs to another session')+ if (completed.reserveReplacement !== reserveReplacement) {+ throw new Error('kill operation retry changed replacement mode')+ }+ if (completed.expectedGeneration !== expectedGeneration) {+ throw new Error('kill operation retry changed expected generation')+ }+ if (!reserveReplacement) return {}+ const current = sessions.get(name)+ if (current && !current.exited) {+ throw new Error(`session '${name}' was replaced by a different generation`)+ }+ const reservation = activeReplacementReservation(name)+ if (reservation && reservation.token !== operationId) {+ throw new Error(`session '${name}' is already restarting`)+ }+ // Refresh a same-operation reservation that expired while the client was uncertain.+ setReplacementReservation(name, operationId)+ return { replacementToken: operationId }+ }+ const byId = inProgressKillIds.get(operationId)+ if (byId) {+ if (byId.name !== name) throw new Error('kill operation id belongs to another session')+ if (byId.operation.reserveReplacement !== reserveReplacement) {+ throw new Error('kill operation retry changed replacement mode')+ }+ if (byId.operation.expectedGeneration !== expectedGeneration) {+ throw new Error('kill operation retry changed expected generation')+ }+ return byId.operation.promise+ }++ const alreadyEnding = ending.get(name)+ if (alreadyEnding) {+ // Only the same operation id is a retry. A second client must not join the destructive+ // operation and then falsely believe its own id owns the single replacement reservation.+ throw new Error(`session '${name}' is already restarting`)+ }++ let session = sessions.get(name)+ if (session && (session.exited || session.retiring)) {+ // Natural exit keeps the generation registered through its output/exit publication barrier.+ // Absence is not authoritative until that exact generation has finished retiring.+ if (!session.ending) throw new Error(`ending session '${name}' has no retirement barrier`)+ await session.ending+ session = sessions.get(name)+ }+ if (!session || session.exited) {+ const reservation = activeReplacementReservation(name)+ if (reserveReplacement && reservation && reservation.token !== operationId) {+ throw new Error(`session '${name}' is already restarting`)+ }+ if (reserveReplacement) setReplacementReservation(name, operationId)+ rememberCompletedKill(operationId, name, reserveReplacement, expectedGeneration)+ return { replacementToken: reserveReplacement ? operationId : undefined }+ }+ if (expectedGeneration === undefined) {+ // In v2, undefined after the client's immediate probe is an explicit expected-absence+ // observation, not name-only permission. A later generation is outside this operation even+ // after the completed-op cache expires: generic delete confirms its observed target was+ // already absent; a requested lease rejects because another app won the name.+ if (reserveReplacement) {+ throw new Error(`session '${name}' became live before its replacement lease was acquired`)+ }+ rememberCompletedKill(operationId, name, false, undefined)+ return {}+ }+ if (expectedGeneration !== undefined && expectedGeneration !== session.generation) {+ // A different opaque generation confirms the requested process is already gone, but that+ // live replacement belongs to somebody else and must not be reserved or terminated.+ if (reserveReplacement) {+ throw new Error(`session '${name}' was replaced by a different generation`)+ }+ rememberCompletedKill(operationId, name, false, expectedGeneration)+ return {}+ }++ let resolve!: (result: KillSessionResult) => void+ let reject!: (error: Error) => void+ const promise = new Promise<KillSessionResult>((done, fail) => {+ resolve = done+ reject = fail+ })+ const operation: EndingOperation = {+ session,+ promise,+ resolve,+ reject,+ operationIds: new Set([operationId]),+ reserveReplacement,+ expectedGeneration+ }+ // Store before either termination mechanism: node-pty may emit onExit synchronously.+ ending.set(name, operation)+ inProgressKillIds.set(operationId, { name, operation })++ const failOperation = (error: unknown): void => {+ if (ending.get(name) !== operation) return // real exit already confirmed and resolved it+ ending.delete(name)+ for (const id of operation.operationIds) inProgressKillIds.delete(id)+ operation.reject(error instanceof Error ? error : new Error(String(error)))+ }++ if (process.platform === 'win32') {+ // node-pty defers WindowsTerminal.kill() until first output. taskkill owns the process tree+ // independently, then endSession acknowledges only after the PID is confirmed absent.+ void terminateWindowsProcessTree(session.proc.pid).then(+ () => {+ if (sessions.get(name) !== session || session.exited) return+ try {+ session.releaseWindowsPtyAfterExternalTreeKill()+ // No manual endSession here. Closing the ConPTY handle must produce node-pty's real+ // onExit, which is the proof that shell descendants *and* host-parented conhost are+ // gone. If it never arrives, the client times out uncertain instead of receiving a+ // false destructive acknowledgement.+ void beginKillRetirement(session).catch(failOperation)+ } catch (error) {+ log(`ConPTY release failed name=${name}: ${String(error)}`)+ failOperation(new Error('session-host could not confirm terminal process termination'))+ }+ },+ (error) => {+ log(`process-tree termination failed name=${name}: ${String(error)}`)+ failOperation(new Error('session-host could not confirm terminal process termination'))+ }+ )+ } else {+ try {+ session.proc.kill()+ void beginKillRetirement(session).catch(failOperation)+ } catch (error) {+ failOperation(error)+ }+ }+ return promise+ }++ async function dispatch(+ req: SessionHostRequest,+ socket: net.Socket,+ clientProtocolVersion: 1 | 2+ ): Promise<{ ok: true; result?: unknown } | { ok: false; error: string }> {+ switch (req.cmd) {+ case 'attach':+ return { ok: true, result: await handleAttach(req, socket) }+ case 'attachExisting':+ if (clientProtocolVersion === 1) {+ return { ok: false, error: 'attachExisting requires session-host protocol v2' }+ }+ return { ok: true, result: await handleAttachExisting(req, socket) }+ case 'hasSession':+ {+ const session = sessions.get(req.name)+ const result: HasSessionResult =+ session && !session.exited+ ? { exists: true, generation: session.generation }+ : { exists: false }+ return {+ ok: true,+ result+ }+ }+ case 'write': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: false, error: 'no such session' }+ if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }+ s.proc.write(req.data)+ return { ok: true }+ }+ case 'resize': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: false, error: 'no such session' }+ if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }+ await s.resizeFor(socket, req.cols, req.rows)+ return { ok: true }+ }+ case 'pause': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: false, error: 'no such session' }+ if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }+ s.pauseFor(socket)+ return { ok: true }+ }+ case 'resume': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: false, error: 'no such session' }+ if (!s.subscribers.has(socket)) return { ok: false, error: 'not attached to session' }+ s.resumeFor(socket)+ return { ok: true }+ }+ case 'sendKeys': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: false, error: 'no such session' }+ s.proc.write(req.text + (req.enter ? '\r' : ''))+ return { ok: true }+ }+ case 'paneCommand': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: true, result: { command: null } satisfies PaneCommandResult }+ const command = await readPaneCommand(s.proc.pid)+ return { ok: true, result: { command } satisfies PaneCommandResult }+ }+ case 'capture': {+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: true, result: { text: '' } satisfies CaptureResult }+ const text = await s.serialize(req.full ? undefined : 200)+ if (s.exited || sessions.get(req.name) !== s) {+ return { ok: true, result: { text: '' } satisfies CaptureResult }+ }+ return { ok: true, result: { text } satisfies CaptureResult }+ }+ case 'executeLaunch': {+ if (clientProtocolVersion === 1) {+ return { ok: false, error: 'opaque launch requires session-host protocol v2' }+ }+ const s = sessions.get(req.name)+ if (!s || s.exited) return { ok: false, error: 'no such session' }+ if (req.generation !== s.generation) {+ return { ok: false, error: `session '${req.name}' was replaced by another generation` }+ }+ const result = await s.executeLaunch(+ req.launchId,+ req.command,+ req.stdinAfterStart,+ () => launchProcessReady(s)+ )+ return { ok: true, result }+ }+ case 'killSession': {+ // Do not acknowledge merely because kill() was requested. The per-name promise resolves+ // only when the real node-pty onExit path has removed/disposed the generation. A retry on+ // another socket coalesces here, and a retry after completion sees absence as success.+ const raw = req as Extract<SessionHostRequest, { cmd: 'killSession' }> & {+ operationId?: unknown+ expectedGeneration?: unknown+ reserveReplacement?: unknown+ }+ if (clientProtocolVersion === 1 && raw.reserveReplacement === true) {+ return { ok: false, error: 'replacement reservation requires session-host protocol v2' }+ }+ const operationId =+ clientProtocolVersion === 2 && typeof raw.operationId === 'string'+ ? raw.operationId+ : crypto.randomUUID()+ const expectedGeneration =+ clientProtocolVersion === 2 && typeof raw.expectedGeneration === 'string'+ ? raw.expectedGeneration+ : sessions.get(req.name)?.generation+ const reserveReplacement =+ clientProtocolVersion === 2 && raw.reserveReplacement === true+ const result = await handleKill(+ req.name,+ operationId,+ expectedGeneration,+ reserveReplacement+ )+ return { ok: true, result }+ }+ case 'detach': {+ await sessions.get(req.name)?.detach(socket)+ return { ok: true }+ }+ case 'listSessions':+ return { ok: true, result: { names: [...sessions.keys()] } satisfies ListSessionsResult }+ case 'ping':+ return { ok: true }+ default:+ return { ok: false, error: `unknown command` }+ }+ }++ const liveSockets = new Set<net.Socket>()+ const server = net.createServer((socket) => {+ liveSockets.add(socket)+ let authed = false+ let clientProtocolVersion: 1 | 2 | null = null+ const framer = new LineFramer()+ const requestQueue = new SessionHostSocketRequestQueue()+ const dispatchAndRespond = async (req: SessionHostRequest): Promise<void> => {+ if (socket.destroyed) return+ try {+ const res = await dispatch(req, socket, clientProtocolVersion ?? 1)+ writeSessionHostFrame(+ socket,+ encodeFrame({ id: req.id, ...res }),+ sessions.values()+ )+ } catch (e) {+ writeSessionHostFrame(+ socket,+ encodeFrame({+ id: req.id,+ ok: false,+ error: e instanceof Error ? e.message : String(e)+ }),+ sessions.values()+ )+ }+ }+ socket.on('data', (chunk: Buffer) => {+ const frames = framer.push<SessionHostRequest>(chunk.toString('utf8'))+ for (const req of frames) {+ if (!authed) {+ const requestedVersion =+ req.cmd === 'hello'+ ? (req as { protocolVersion?: unknown }).protocolVersion+ : undefined+ if (+ req.cmd === 'hello' &&+ req.token === token &&+ (requestedVersion === undefined ||+ requestedVersion === 1 ||+ requestedVersion === currentProtocolVersion())+ ) {+ authed = true+ clientProtocolVersion =+ requestedVersion === undefined || requestedVersion === 1 ? 1 : 2+ writeSessionHostFrame(+ socket,+ encodeFrame(+ clientProtocolVersion === 1+ ? { id: req.id, ok: true }+ : {+ id: req.id,+ ok: true,+ result: { protocolVersion: currentProtocolVersion() }+ }+ ),+ sessions.values()+ )+ } else {+ const error =+ req.cmd === 'hello' && req.token === token+ ? `incompatible session-host protocol: expected ${currentProtocolVersion()}`+ : 'unauthorized'+ writeSessionHostFrame(+ socket,+ encodeFrame({ id: req.id, ok: false, error }),+ sessions.values()+ )+ socket.destroy()+ }+ continue+ }+ if (req.cmd === 'hello') {+ writeSessionHostFrame(+ socket,+ encodeFrame(+ clientProtocolVersion === 1+ ? { id: req.id, ok: true }+ : {+ id: req.id,+ ok: true,+ result: { protocolVersion: currentProtocolVersion() }+ }+ ),+ sessions.values()+ )+ continue+ }+ if ('name' in req) void requestQueue.enqueue(req.name, () => dispatchAndRespond(req))+ else void dispatchAndRespond(req)+ }+ })+ socket.on('drain', () => drainSessionHostTransport(socket, sessions.values()))+ socket.on('close', () => {+ liveSockets.delete(socket)+ // A connection dropping is a DETACH, never a kill — sessions belong to the host, not to+ // any one connection. Mirrors tmux: closing a client's terminal only ends that client.+ // `detach` also returns this socket's pause ticket; without that second half, a crashed+ // viewer can leave the global node-pty actuator paused forever for every healthy viewer.+ for (const session of sessions.values()) {+ void session.detach(socket).catch((e) =>+ log(`detach cleanup failed name=${session.name}: ${String(e)}`)+ )+ }+ })+ socket.on('error', () => {+ /* the 'close' handler above still runs and does the real cleanup */+ })+ })++ let abortingStartup = false+ function abortListeningStartup(reason: string, error: unknown): void {+ if (abortingStartup) return+ abortingStartup = true+ log(`fatal: ${reason}: ${String(error)}`)+ // `listen` has already succeeded when token/state publication runs. Stop accepting first and+ // destroy anything that reached the tiny pre-publication window, then remove every artifact+ // owned behind our exclusive startup lock. The uncaughtException logger below deliberately+ // keeps the process alive, so startup failures must terminate through this explicit path.+ for (const socket of liveSockets) socket.destroy()+ const finish = (): void => {+ cleanupFiles()+ process.exit(1)+ }+ try {+ server.close(finish)+ } catch {+ finish()+ }+ }++ server.on('error', (err: NodeJS.ErrnoException) => {+ log(`listen error: ${err.code ?? err.message}`)+ // We hold the state-file lock, so a genuine EADDRINUSE here means a PRIOR host (from before+ // this file existed, or one that crashed after binding but before this run started) is still+ // bound. Give the probe one more honest look before giving up.+ if (err.code === 'EADDRINUSE') {+ void probeExisting(paths.statePath, paths.endpoint, paths.tokenPath).then(+ (alive) => {+ if (alive) process.exit(0)+ cleanupFiles()+ process.exit(1)+ },+ (error) => {+ log(`fatal: ownership probe after EADDRINUSE failed: ${String(error)}`)+ cleanupFiles()+ process.exit(1)+ }+ )+ return+ }+ cleanupFiles()+ process.exit(1)+ })++ const token = crypto.randomBytes(32).toString('hex')+ server.listen(paths.endpoint, () => {+ try {+ fs.writeFileSync(paths.tokenPath, token, { mode: 0o600 })+ } catch (e) {+ abortListeningStartup('could not write token file', e)+ return+ }+ const state: SessionHostState = {+ pid: process.pid,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: Date.now(),+ protocolVersion: currentProtocolVersion()+ }+ // Replace the empty startup-lock file atomically from a temp owned by THIS process. A fixed+ // `.tmp` lets racing/stale-reclaim hosts publish or remove one another's bytes; a bare rename+ // also loses the boot on Windows when a scanner briefly holds the state file open.+ try {+ publishSessionHostState(paths.statePath, JSON.stringify(state))+ } catch (e) {+ abortListeningStartup('could not publish state file', e)+ return+ }+ log(`listening pid=${process.pid} endpoint=${paths.endpoint}`)+ scheduleGraceExitIfEmpty() // a host with zero sessions ever attached still exits eventually+ })++ // Detaching every client (app quit) is not a lifecycle event here at all — there is no+ // "client" concept at the process level, only sockets, and their 'close' handler above already+ // does the right thing. Nothing to hook for that case.++ process.on('uncaughtException', (e) => log(`uncaughtException: ${String(e)}`))+ process.on('unhandledRejection', (e) => log(`unhandledRejection: ${String(e)}`))+}++void main()diff --git a/src/session-host/kill-session.test.ts b/src/session-host/kill-session.test.tsnew file mode 100644index 000000000..c3bc57a29--- /dev/null+++ b/src/session-host/kill-session.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it, vi } from 'vitest'+import type { HostSession } from './session'+import { killHostSession } from './kill-session'++describe('session-host explicit kill truth', () => {+ it('propagates a process kill failure without retiring the live generation', async () => {+ const failure = new Error('synthetic access denied')+ const session = {+ exited: false,+ proc: {+ kill: vi.fn(() => {+ throw failure+ })+ }+ } as unknown as HostSession+ const beginRetirement = vi.fn(async () => {})++ await expect(killHostSession(session, beginRetirement)).rejects.toBe(failure)+ expect(beginRetirement).not.toHaveBeenCalled()+ })++ it('keeps the kill request pending until observed exit retirement resolves', async () => {+ let releaseRetirement!: () => void+ const session = {+ exited: false,+ retiring: false,+ proc: { kill: vi.fn() }+ } as unknown as HostSession+ const beginRetirement = vi.fn((value: HostSession) => {+ value.retiring = true+ return new Promise<void>((resolve) => {+ releaseRetirement = resolve+ })+ })++ let settled = false+ const killing = killHostSession(session, beginRetirement).then(() => {+ settled = true+ })+ await Promise.resolve()+ expect(session.proc.kill).toHaveBeenCalledOnce()+ expect(beginRetirement).toHaveBeenCalledWith(session)+ expect(session.retiring).toBe(true)+ expect(settled).toBe(false)++ releaseRetirement()+ await killing+ expect(settled).toBe(true)+ })++ it('awaits the existing retirement barrier without signalling twice', async () => {+ const session = {+ exited: false,+ retiring: true,+ proc: { kill: vi.fn() }+ } as unknown as HostSession+ const beginRetirement = vi.fn(async () => {})++ await expect(killHostSession(session, beginRetirement)).resolves.toBeUndefined()+ expect(session.proc.kill).not.toHaveBeenCalled()+ expect(beginRetirement).toHaveBeenCalledWith(session)+ })+})diff --git a/src/session-host/kill-session.ts b/src/session-host/kill-session.tsnew file mode 100644index 000000000..e3c7d01e8--- /dev/null+++ b/src/session-host/kill-session.ts@@ -0,0 +1,12 @@+import type { HostSession } from './session'++/** Request a real process kill before entering the one retirement path. A thrown kill is unknown,+ * not evidence that the process is already dead: propagating keeps the generation registered and+ * prevents a false successful deletion of a still-running unmanaged PTY. */+export async function killHostSession(+ session: HostSession,+ beginRetirement: (session: HostSession) => Promise<void>+): Promise<void> {+ if (!session.exited && !session.retiring) session.proc.kill()+ await beginRetirement(session)+}diff --git a/src/session-host/paths.ts b/src/session-host/paths.tsnew file mode 100644index 000000000..36c085324--- /dev/null+++ b/src/session-host/paths.ts@@ -0,0 +1,59 @@+// Pure path resolution for the session host, shared by the standalone host process AND the+// Electron-main client/launcher (src/core/session-host-client.ts, session-host-launcher.ts).+// Deterministic from `userDataDir` alone — neither side ever has to ask the other "where are+// you", which is what lets a second app instance in the startup race (see host.ts) find the+// winner without any prior handshake.++import path from 'path'+import os from 'os'+import { createHash } from 'crypto'+import { SESSION_HOST_PROTOCOL_VERSION } from './protocol'++/** Short, filesystem/pipe-name-safe fingerprint of the userData dir, so a dev checkout running+ * beside a packaged install (different userData dirs) never collides on one endpoint. */+function fingerprint(userDataDir: string): string {+ return createHash('sha256').update(userDataDir).digest('hex').slice(0, 16)+}++export interface SessionHostPaths {+ /** Where the client connects and the host binds: a Windows named pipe, or a POSIX unix socket+ * file. Sockets live in the OS temp dir rather than userData — AF_UNIX paths are capped at+ * ~104-108 bytes on many platforms, and userData can easily be deeper than that. */+ endpoint: string+ /**+ * Exclusive-create race gate for host STARTUP (see host.ts's `main()`), and — once the host is+ * actually listening — the informational state file a later launcher reads to find a running+ * host without probing blind: `{pid, endpoint, tokenPath, startedAt, protocolVersion}`.+ */+ statePath: string+ /** Bearer token, written 0600 by the host, read by every client before its first request.+ * Never placed on a command line or in an environment variable a `ps`/`/proc` listing could+ * expose — see the node-identity incident this repo already carries a scar from+ * (docs/node-identity.md), which is exactly the mistake this file exists to not repeat. */+ tokenPath: string+}++export function sessionHostPaths(userDataDir: string): SessionHostPaths {+ const fp = fingerprint(userDataDir)+ const endpoint =+ process.platform === 'win32'+ ? `\\\\.\\pipe\\nodeterm-session-host-${fp}`+ : path.join(os.tmpdir(), `nodeterm-session-host-${fp}.sock`)+ return {+ endpoint,+ statePath: path.join(userDataDir, 'session-host.json'),+ tokenPath: path.join(userDataDir, 'session-host.token')+ }+}++export interface SessionHostState {+ pid: number+ endpoint: string+ tokenPath: string+ startedAt: number+ protocolVersion: number+}++export function currentProtocolVersion(): number {+ return SESSION_HOST_PROTOCOL_VERSION+}diff --git a/src/session-host/process-tree.ts b/src/session-host/process-tree.tsnew file mode 100644index 000000000..c7f0ff27d--- /dev/null+++ b/src/session-host/process-tree.ts@@ -0,0 +1,109 @@+import { execFile } from 'child_process'++/**+ * The `#{pane_current_command}` equivalent for a backend with no tmux underneath it. tmux tracks+ * this by watching the pane's foreground process GROUP; we have no such kernel hook here, so this+ * WALKS THE DESCENDANTS of the pty's own child pid and reports the deepest live one.+ *+ * This is a deliberately small, standalone reader rather than a reuse of+ * `src/core/session-memory.ts`'s process-table reader: that module queries `pid,ppid,rss` (for+ * memory accounting) and has no Windows branch at all yet, so there is nothing here to actually+ * reuse without querying a THIRD column (`comm`/`Name`) it does not fetch — this is the "cannot,+ * so wrote a second (much smaller) one" case CLAUDE.md's guidance for this task allows for.+ *+ * The in-place agent restart feature (CLAUDE.md, "Restart agent (resume)") only cares about ONE+ * distinction — "is a SHELL back in charge of this pane, or is something else still running" — so+ * imprecision below that bar (which of several MCP-server children counts as "the" foreground+ * process) is harmless: every non-shell answer reads the same way to that caller. Documented as a+ * known limitation in docs/windows-session-host.md rather than pretended away.+ */++interface ProcRow {+ pid: number+ ppid: number+ name: string+}++function indexRows(rows: readonly ProcRow[]): {+ table: Map<number, ProcRow>+ kids: Map<number, number[]>+} {+ const table = new Map<number, ProcRow>()+ const kids = new Map<number, number[]>()+ for (const r of rows) {+ table.set(r.pid, r)+ const list = kids.get(r.ppid)+ if (list) list.push(r.pid)+ else kids.set(r.ppid, [r.pid])+ }+ return { table, kids }+}++function readWin32(): Promise<ProcRow[]> {+ return new Promise((resolve) => {+ // -NoProfile/-NonInteractive: this runs unattended and can be polled every ~250ms while a+ // restart is in progress — sourcing a user PowerShell profile here would be exactly the+ // "100-800ms per lookup" mistake exec-path.ts documents for the POSIX login-shell PATH probe.+ execFile(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name | ConvertTo-Json -Compress'+ ],+ { timeout: 5000, maxBuffer: 16 * 1024 * 1024, windowsHide: true },+ (err, stdout) => {+ if (err || !stdout) return resolve([])+ try {+ const parsed = JSON.parse(stdout) as unknown+ const arr = Array.isArray(parsed) ? parsed : [parsed]+ const rows = arr+ .map((r) => {+ const o = r as { ProcessId?: unknown; ParentProcessId?: unknown; Name?: unknown }+ return { pid: Number(o.ProcessId), ppid: Number(o.ParentProcessId), name: String(o.Name ?? '') }+ })+ .filter((r) => Number.isFinite(r.pid) && Number.isFinite(r.ppid))+ resolve(rows)+ } catch {+ resolve([])+ }+ }+ )+ })+}++function readPosix(): Promise<ProcRow[]> {+ return new Promise((resolve) => {+ execFile('ps', ['-eo', 'pid,ppid,comm'], { timeout: 5000, maxBuffer: 16 * 1024 * 1024 }, (err, stdout) => {+ if (err || !stdout) return resolve([])+ const rows: ProcRow[] = []+ for (const line of stdout.split('\n')) {+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/)+ if (!m) continue+ rows.push({ pid: Number(m[1]), ppid: Number(m[2]), name: m[3] })+ }+ resolve(rows)+ })+ })+}++/** The deepest live descendant of `rootPid` (the pty's own child), by name — or null when the+ * process table couldn't be read or `rootPid` is no longer in it (the session just exited). */+export async function paneCommand(rootPid: number): Promise<string | null> {+ const rows = process.platform === 'win32' ? await readWin32() : await readPosix()+ if (rows.length === 0) return null+ const { table, kids } = indexRows(rows)+ if (!table.has(rootPid)) return null+ let deepest = rootPid+ const seen = new Set<number>([rootPid])+ const stack = [...(kids.get(rootPid) ?? [])]+ while (stack.length > 0) {+ const pid = stack.pop() as number+ if (seen.has(pid)) continue+ seen.add(pid)+ if (table.has(pid)) deepest = pid+ for (const k of kids.get(pid) ?? []) stack.push(k)+ }+ return table.get(deepest)?.name || null+}diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.tsnew file mode 100644index 000000000..9d4886155--- /dev/null+++ b/src/session-host/protocol.ts@@ -0,0 +1,227 @@+// Wire protocol between the standalone session-host process and its Node clients (today: the+// desktop main process — see src/core/session-host-client.ts). Newline-delimited JSON over a+// local named pipe (Windows) or unix domain socket (POSIX/WSL/etc).+//+// This module is pure TypeScript with no Electron/Node-native imports so it can be bundled into+// BOTH the standalone host process (out/session-host/host.cjs, built with esbuild — see+// scripts nothing, just the `host:build` npm script) and the Electron main process bundle+// (electron-vite). See docs/windows-session-host.md for the architecture this implements.++/** Bumped whenever a request/response/event SHAPE changes. Carried in the host's state file and+ * enforced by the client before hello, so a newly packaged client cannot reuse a long-lived host+ * whose attach/flow contract predates its own. */+export const SESSION_HOST_PROTOCOL_VERSION = 2++/** Concrete parser owned by the live terminal generation. Kept in the host so a new renderer/main+ * process can safely encode a delayed launch without re-guessing from a stale profile id. */+export type SessionHostShellDialect = 'posix' | 'pwsh' | 'windows-powershell' | 'cmd'++/** Exactly what node-pty needs to spawn — passed on `attach` so the host never has to compute cwd+ * resolution, PATH, hook env, etc. itself. The CLIENT (pty-manager.ts, which already resolves all+ * of this for the tmux/plain-shell paths) is the one source of truth for that logic. */+export interface SessionHostSpawnOptions {+ cwd: string+ shell: string+ args: string[]+ env: Record<string, string>+ cols: number+ rows: number+ /** Required for trusted v2 profile launches; omitted only by legacy/test callers that will not+ * execute an opaque launch intent on this generation. */+ launchDialect?: SessionHostShellDialect+ /** Optional trusted cold-start launch. The host inserts this id into the new generation's+ * exactly-once ledger before typing any input and completes it before acknowledging attach. */+ initialLaunch?: {+ launchId: string+ command: string+ stdinAfterStart?: string+ }+}++/** Client → host requests. Every request carries a monotonic `id`; the host echoes it on the+ * matching response so replies can be correlated over one shared, long-lived connection — the+ * same idiom `ControlModeClient` uses for tmux control-mode, minus the positional-FIFO fragility+ * (JSON here carries its own id, so an out-of-order reply is still recoverable). */+export type SessionHostRequest =+ | { id: number; cmd: 'hello'; token: string; protocolVersion: number }+ | {+ id: number+ cmd: 'attach'+ name: string+ spawn: SessionHostSpawnOptions+ /** Cap on both the emulator's live scrollback buffer and how much `capture`'s `full: true`+ * returns — mirrors `settings.tmuxScrollback` / tmux's own `history-limit`. */+ scrollback: number+ /** Capability established by a confirmed kill. Required to cold-create that reserved name;+ * other authenticated app clients cannot steal the replacement window. */+ replacementToken?: string+ /** The reconnecting connection already owes an explicit flow pause. Restored before the+ * screen barrier and live subscriber activation, so no output leaks through reconnect. */+ paused?: boolean+ }+ /** Warm attach that is atomic with the host's existence check. It deliberately carries no+ * spawn plan: absence/exit is an error and can never recreate a session with stale settings. */+ | {+ id: number+ cmd: 'attachExisting'+ name: string+ /** When known, prevents a same-name replacement from satisfying a stale warm attach. */+ expectedGeneration?: string+ /** Optional aggregate reconnect state. Older v2 clients omit it; the host then reuses the+ * generation's current geometry while retaining the no-spawn/expected-generation guard. */+ cols?: number+ rows?: number+ paused?: boolean+ }+ | { id: number; cmd: 'hasSession'; name: string }+ | { id: number; cmd: 'write'; name: string; data: string }+ | { id: number; cmd: 'resize'; name: string; cols: number; rows: number }+ | { id: number; cmd: 'pause'; name: string }+ | { id: number; cmd: 'resume'; name: string }+ | { id: number; cmd: 'sendKeys'; name: string; text: string; enter: boolean }+ | { id: number; cmd: 'paneCommand'; name: string }+ | { id: number; cmd: 'capture'; name: string; full: boolean }+ | {+ id: number+ cmd: 'executeLaunch'+ name: string+ /** Exact host process generation returned by attach/attachExisting. */+ generation: string+ /** Machine-local UUID v4. Host deduplication is scoped to this generation. */+ launchId: string+ /** Core-private, already validated and rendered input. Never returned on the wire. */+ command: string+ stdinAfterStart?: string+ }+ | {+ id: number+ cmd: 'killSession'+ name: string+ /** Stable across client reconnect/retry. The host caches completed operations so a lost+ * acknowledgement can never kill a newer same-name generation (multi-client ABA). */+ operationId: string+ /** Exact process generation observed by attach/hasSession. A different current generation+ * proves the requested target is already gone and must not be killed. */+ expectedGeneration?: string+ /** Confirmed recycle reserves the now-empty name for the same client operation. Generic+ * deletion leaves no token and does not block a later ordinary create/undo. */+ reserveReplacement: boolean+ }+ | { id: number; cmd: 'detach'; name: string }+ | { id: number; cmd: 'listSessions' }+ | { id: number; cmd: 'ping' }++/** Host → client response to a request, correlated by `id`. */+export type SessionHostResponse =+ | { id: number; ok: true; result?: unknown }+ | { id: number; ok: false; error: string }++/** Host → client PUSH frames — not correlated to any request id; delivered for as long as this+ * connection is a subscriber of `name` (see `attach` / `detach`). */+export type SessionHostEvent =+ | { type: 'data'; name: string; data: string; generation?: string }+ | {+ type: 'exit'+ name: string+ exitCode: number+ generation?: string+ }++export type SessionHostFrame = SessionHostResponse | SessionHostEvent++/**+ * `SessionHostRequest` minus `id`, DISTRIBUTED over the union rather than collapsed by a plain+ * `Omit<SessionHostRequest, 'id'>` — a bare `Omit` on a discriminated union only keeps properties+ * common to every member (here, just `cmd`), silently dropping every command-specific field like+ * `name`/`data`/`token`. The client builds requests against this type before assigning a real id.+ */+export type SessionHostRequestBody = SessionHostRequest extends infer T+ ? T extends { id: number }+ ? Omit<T, 'id'>+ : never+ : never++export function isEventFrame(f: SessionHostFrame): f is SessionHostEvent {+ return (f as SessionHostEvent).type === 'data' || (f as SessionHostEvent).type === 'exit'+}++/** Result payload shapes, `result` on a successful response — documented here rather than typed+ * as a discriminated union on `SessionHostResponse` itself, so the response type stays simple to+ * parse off the wire; callers cast `result` to the shape their own command implies. */+export interface AttachResult {+ /** True when no session existed for this name and one was spawned just now — a cold start+ * (first open, or a fresh host after the previous one died / the machine rebooted). False =+ * warm reattach to a session that was already running (in THIS host process, which may have+ * outlived several app restarts already). */+ fresh: boolean+ /**+ * The reconstructed screen — an xterm.js `SerializeAddon` dump (colors/attributes, private-mode+ * restore, alt-buffer switch and cursor placement all included — see terminal-emulator.ts).+ * Present on an ordinary warm attach, or on an idempotent replay of a consumed replacement token,+ * when the session has painted anything since it started; absent (never an empty string)+ * otherwise, mirroring `PtyCreateResult.screen`'s own contract ("guaranteed non-empty when+ * present").+ */+ screen?: string+ /** Opaque identity for the exact host-owned process behind this attachment. */+ /** Required by protocol v2; absent only while interoperating with a live legacy v1 host. */+ generation?: string+ /** Exact live parser. Required for generation-safe opaque launch execution. */+ launchDialect?: SessionHostShellDialect+ /** Sanitized outcome for an atomic cold-start launch; no rendered input is reflected. */+ initialLaunchStatus?: 'executed' | 'already-executed'+}+export interface HasSessionResult {+ exists: boolean+ /** Required with exists:true in v2; legacy v1 hosts do not provide it. */+ generation?: string+}+export interface KillSessionResult {+ /** Present only for a reserveReplacement operation that currently owns the name reservation. */+ replacementToken?: string+}+export interface ExecuteLaunchResult {+ /** No private command/input details are ever reflected to callers. */+ status: 'executed' | 'already-executed'+}+export interface PaneCommandResult {+ command: string | null+}+export interface CaptureResult {+ text: string+}+export interface ListSessionsResult {+ names: string[]+}++/**+ * Splits a byte stream on `\n` into complete JSON lines, buffering a line that arrived split+ * across TCP/pipe chunks — the whole reason a delimiter-based framing needs a stateful parser+ * instead of `JSON.parse(chunk)`. Shared by both ends so the framing rule is written exactly once.+ */+export class LineFramer {+ private buf = ''+ /** Feed a raw chunk; returns every complete frame it now contains, in arrival order. A+ * malformed line is DROPPED rather than thrown — one corrupt frame must never wedge every+ * frame that follows it on the same connection. */+ push<T>(chunk: string): T[] {+ this.buf += chunk+ const lines = this.buf.split('\n')+ this.buf = lines.pop() ?? ''+ const out: T[] = []+ for (const line of lines) {+ const trimmed = line.trim()+ if (!trimmed) continue+ try {+ out.push(JSON.parse(trimmed) as T)+ } catch {+ // one corrupt line — drop it and keep reading the rest of the stream+ }+ }+ return out+ }+}++export function encodeFrame(frame: unknown): string {+ return JSON.stringify(frame) + '\n'+}diff --git a/src/session-host/session.test.ts b/src/session-host/session.test.tsnew file mode 100644index 000000000..4fb74a1d9--- /dev/null+++ b/src/session-host/session.test.ts@@ -0,0 +1,544 @@+import { describe, expect, it, vi } from 'vitest'+import type { Socket } from 'net'+import type { IPty } from 'node-pty'+import {+ HostSession,+ SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES,+ SESSION_EMULATOR_OUTPUT_LOW_WATER_BYTES+} from './session'+import type { TerminalEmulator } from './terminal-emulator'+import type { SessionHostSpawnOptions } from './protocol'++const SPAWN: SessionHostSpawnOptions = {+ shell: 'unused-in-tests',+ args: [],+ cwd: '.',+ env: {},+ cols: 80,+ rows: 24+}++function fakeProc(): {+ value: IPty+ pause: ReturnType<typeof vi.fn>+ resume: ReturnType<typeof vi.fn>+ resize: ReturnType<typeof vi.fn>+} {+ const pause = vi.fn()+ const resume = vi.fn()+ const resize = vi.fn()+ return {+ value: {+ pid: 42,+ pause,+ resume,+ resize+ } as unknown as IPty,+ pause,+ resume,+ resize+ }+}++function inertTerm(): TerminalEmulator {+ return {+ write: vi.fn(async () => {}),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+}+describe('HostSession terminal-output ordering', () => {+ it('waits for every prior asynchronous xterm write before serializing', async () => {+ const proc = fakeProc()+ const applied: string[] = []+ const releases: Array<() => void> = []+ const serialize = vi.fn(() => applied.join(''))+ const write = vi.fn(+ (data: string) =>+ new Promise<void>((resolve) => {+ releases.push(() => {+ applied.push(data)+ resolve()+ })+ })+ )+ const term = {+ write,+ serialize,+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('ordered', SPAWN, 100, { proc: proc.value, term })++ const first = session.recordOutput('first')+ const second = session.recordOutput('second')+ const snapshot = session.serialize()++ await Promise.resolve()+ expect(write).toHaveBeenCalledTimes(1)+ expect(serialize).not.toHaveBeenCalled()++ releases[0]()+ await first+ await Promise.resolve()+ expect(write).toHaveBeenCalledTimes(2)+ expect(serialize).not.toHaveBeenCalled()++ releases[1]()+ await second+ await expect(snapshot).resolves.toBe('firstsecond')+ expect(serialize).toHaveBeenCalledTimes(1)+ })++ it('recovers the ordering tail after one mirror write rejects', async () => {+ const proc = fakeProc()+ const applied: string[] = []+ const term = {+ write: vi.fn(async (data: string) => {+ if (data === 'bad') throw new Error('synthetic mirror rejection')+ applied.push(data)+ }),+ serialize: vi.fn(() => applied.join('')),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('recover', SPAWN, 100, { proc: proc.value, term })++ await expect(session.recordOutput('bad')).rejects.toThrow('synthetic mirror rejection')+ await expect(session.recordOutput('good')).resolves.toBeUndefined()+ await expect(session.serialize()).resolves.toBe('good')+ })+})++describe('HostSession connection-scoped pause ownership', () => {+ it('resumes only after the last pausing connection returns its ticket', () => {+ const proc = fakeProc()+ const term = {+ write: vi.fn(async () => {}),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('flow', SPAWN, 100, { proc: proc.value, term })+ const a = {} as Socket+ const b = {} as Socket+ const stranger = {} as Socket+ session.subscribers.add(a)+ session.subscribers.add(b)++ session.pauseFor(a)+ session.pauseFor(a) // a re-asserted high-water pause is idempotent+ session.pauseFor(b)+ expect(proc.pause).toHaveBeenCalledTimes(1)++ session.resumeFor(stranger) // a socket cannot release another socket's pause+ session.resumeFor(a)+ expect(proc.resume).not.toHaveBeenCalled()++ session.resumeFor(b)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ session.resumeFor(b)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('returns a crashed connection\'s pause ticket during detach without disturbing peers', async () => {+ const proc = fakeProc()+ const term = {+ write: vi.fn(async () => {}),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('disconnect', SPAWN, 100, { proc: proc.value, term })+ const crashed = {} as Socket+ const healthy = {} as Socket+ session.subscribers.add(crashed)+ session.subscribers.add(healthy)++ session.pauseFor(crashed)+ session.pauseFor(healthy)+ await session.detach(crashed)+ expect(session.subscribers.has(crashed)).toBe(false)+ expect(session.subscribers.has(healthy)).toBe(true)+ expect(proc.resume).not.toHaveBeenCalled()++ await session.detach(healthy)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('keeps explicit and transport ownership independent and gates strangers', () => {+ const proc = fakeProc()+ const session = new HostSession('owner-kinds', SPAWN, 100, {+ proc: proc.value,+ term: inertTerm()+ })+ const subscriber = {} as Socket+ const stranger = {} as Socket+ session.subscribers.add(subscriber)++ session.pauseFor(subscriber)+ session.pauseTransportFor(subscriber)+ session.pauseFor(stranger)+ session.pauseTransportFor(stranger)+ expect(proc.pause).toHaveBeenCalledTimes(1)++ session.resumeTransportFor(subscriber)+ session.resumeFor(stranger)+ expect(proc.resume).not.toHaveBeenCalled()+ session.resumeFor(subscriber)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('books reconnect pause synchronously before a pending output barrier', async () => {+ const proc = fakeProc()+ let releaseOutput!: () => void+ const term = {+ write: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ releaseOutput = resolve+ })+ ),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('paused-reconnect', SPAWN, 100, { proc: proc.value, term })+ const socket = {} as Socket+ const output = session.recordOutput('pending')++ const preparing = session.prepareAttachment(socket, SPAWN.cols, SPAWN.rows, true)+ expect(proc.pause).toHaveBeenCalledTimes(1)+ expect(session.subscribers.has(socket)).toBe(false)+ await Promise.resolve()+ releaseOutput()+ await output+ const transaction = await preparing+ await transaction.rollback()+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('inherits an already-backed-up transport on commit and releases it on detach', async () => {+ const proc = fakeProc()+ const session = new HostSession('pre-backed-up', SPAWN, 100, {+ proc: proc.value,+ term: inertTerm()+ })+ const socket = { writableNeedDrain: true } as Socket+ const transaction = await session.prepareAttachment(+ socket,+ SPAWN.cols,+ SPAWN.rows,+ false+ )++ expect(transaction.commit()).toBe(true)+ expect(proc.pause).toHaveBeenCalledTimes(1)+ await session.detach(socket)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })+})++describe('HostSession per-socket geometry', () => {+ it('applies the componentwise minimum before snapshot and grows when the smaller owner leaves', async () => {+ const proc = fakeProc()+ let geometry = { cols: SPAWN.cols, rows: SPAWN.rows }+ const term = {+ write: vi.fn(async () => {}),+ serialize: vi.fn(() => `${geometry.cols}x${geometry.rows}`),+ resize: vi.fn((cols: number, rows: number) => {+ geometry = { cols, rows }+ }),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('geometry', SPAWN, 100, { proc: proc.value, term })+ const wide = {} as Socket+ const narrow = {} as Socket++ const wideAttach = await session.prepareAttachment(wide, 100, 50, false)+ wideAttach.commit()+ const narrowAttach = await session.prepareAttachment(narrow, 80, 60, false)++ // The warm snapshot sees the effective 80x50 cross-product before live delivery starts.+ await expect(session.serialize()).resolves.toBe('80x50')+ expect(session.subscribers.has(narrow)).toBe(false)+ narrowAttach.commit()+ expect(proc.resize).toHaveBeenLastCalledWith(80, 50)++ await session.detach(narrow)+ expect(proc.resize).toHaveBeenLastCalledWith(100, 50)+ await expect(session.serialize()).resolves.toBe('100x50')+ })++ it('overwrites a reconnecting socket claim and rolls a failed attach back exactly', async () => {+ const proc = fakeProc()+ const term = inertTerm()+ const session = new HostSession('reconnect-geometry', SPAWN, 100, { proc: proc.value, term })+ const socket = {} as Socket++ const initial = await session.prepareAttachment(socket, 100, 40, false)+ initial.commit()+ const retry = await session.prepareAttachment(socket, 40, 10, true)+ expect(proc.pause).toHaveBeenCalledTimes(1)+ await retry.rollback()++ expect(session.subscribers.has(socket)).toBe(true)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ expect(proc.resize).toHaveBeenLastCalledWith(100, 40)+ })++ it('ignores a resize claim from a non-subscriber', async () => {+ const proc = fakeProc()+ const term = inertTerm()+ const session = new HostSession('resize-membership', SPAWN, 100, {+ proc: proc.value,+ term+ })++ await session.resizeFor({} as Socket, 10, 5)+ expect(proc.resize).not.toHaveBeenCalled()+ expect(term.resize).not.toHaveBeenCalled()+ })++ it('cancels a delayed attach on detach instead of resurrecting its socket or claim', async () => {+ const proc = fakeProc()+ let releaseOutput!: () => void+ const term = {+ write: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ releaseOutput = resolve+ })+ ),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('cancelled-attach', SPAWN, 100, { proc: proc.value, term })+ const cancelled = {} as Socket+ const replacement = {} as Socket++ const output = session.recordOutput('real-output-barrier')+ await Promise.resolve()+ const preparing = session.prepareAttachment(cancelled, 40, 10, true)+ let prepared = false+ void preparing.then(() => {+ prepared = true+ })+ await Promise.resolve()+ expect(prepared).toBe(false)+ const detaching = session.detach(cancelled)+ releaseOutput()+ await output+ const transaction = await preparing+ expect(transaction.commit()).toBe(false)+ await detaching+ expect(session.subscribers.has(cancelled)).toBe(false)+ expect(proc.resume).toHaveBeenCalledTimes(1)++ const replacementTransaction = await session.prepareAttachment(replacement, 100, 50, false)+ expect(replacementTransaction.commit()).toBe(true)+ expect(proc.resize).toHaveBeenLastCalledWith(100, 50)+ })++ it('retries an identical geometry after the emulator rejected its first resize', async () => {+ const proc = fakeProc()+ let attempts = 0+ const term = {+ write: vi.fn(async () => {}),+ serialize: vi.fn(() => ''),+ resize: vi.fn(() => {+ attempts+++ if (attempts === 1) throw new Error('synthetic resize failure')+ }),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('resize-retry', SPAWN, 100, { proc: proc.value, term })+ const socket = {} as Socket+ const attached = await session.prepareAttachment(socket, SPAWN.cols, SPAWN.rows, false)+ attached.commit()++ const first = session.resizeFor(socket, 100, 40)+ const identicalFollower = session.resizeFor(socket, 100, 40)+ await expect(first).rejects.toThrow('synthetic resize failure')+ await expect(identicalFollower).rejects.toThrow('synthetic resize failure')+ await expect(session.resizeFor(socket, 100, 40)).resolves.toBeUndefined()+ expect(term.resize).toHaveBeenCalledTimes(2)+ expect(proc.resize).toHaveBeenCalledTimes(2)+ })++ it('rejects non-finite geometry without poisoning a healthy peer claim', async () => {+ const proc = fakeProc()+ const term = inertTerm()+ const session = new HostSession('finite-geometry', SPAWN, 100, { proc: proc.value, term })+ const wide = {} as Socket+ const narrow = {} as Socket+ const wideAttach = await session.prepareAttachment(wide, 100, 50, false)+ wideAttach.commit()+ const narrowAttach = await session.prepareAttachment(narrow, 80, 40, false)+ narrowAttach.commit()++ await expect(session.resizeFor(wide, Number.POSITIVE_INFINITY, 30)).rejects.toThrow(+ 'finite positive integer'+ )+ await session.detach(narrow)+ expect(proc.resize).toHaveBeenLastCalledWith(100, 50)+ await expect(session.serialize()).resolves.toBe('')+ })+})++describe('HostSession emulator output watermarks', () => {+ it('pauses at 4 MiB and resumes only after the queued tail drains to 1 MiB', async () => {+ const proc = fakeProc()+ const releases: Array<() => void> = []+ const applied: number[] = []+ const term = {+ write: vi.fn(+ (data: string) =>+ new Promise<void>((resolve) => {+ releases.push(() => {+ applied.push(data.length)+ resolve()+ })+ })+ ),+ serialize: vi.fn(() => applied.join(',')),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('bounded-tail', SPAWN, 100, { proc: proc.value, term })+ const first = session.recordOutput('a'.repeat(2 * 1024 * 1024))+ const second = session.recordOutput('b'.repeat(1024 * 1024))+ const third = session.recordOutput('c'.repeat(1024 * 1024))+ const snapshot = session.serialize()++ expect(SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES).toBe(4 * 1024 * 1024)+ expect(SESSION_EMULATOR_OUTPUT_LOW_WATER_BYTES).toBe(1024 * 1024)+ expect(proc.pause).toHaveBeenCalledTimes(1)+ await Promise.resolve()+ releases[0]()+ await first+ expect(proc.resume).not.toHaveBeenCalled() // 2 MiB still queued++ await Promise.resolve()+ releases[1]()+ await second+ expect(proc.resume).toHaveBeenCalledTimes(1) // exactly 1 MiB remains+ expect(term.serialize).not.toHaveBeenCalled()++ await Promise.resolve()+ releases[2]()+ await third+ await expect(snapshot).resolves.toBe('2097152,1048576,1048576')+ })++ it('counts UTF-8 bytes rather than JavaScript code units', async () => {+ const proc = fakeProc()+ let release!: () => void+ const term = {+ write: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ release = resolve+ })+ ),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('utf8-tail', SPAWN, 100, { proc: proc.value, term })++ const write = session.recordOutput('💥'.repeat(SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES / 4))+ expect(proc.pause).toHaveBeenCalledTimes(1)+ await Promise.resolve()+ release()+ await write+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('does not let transport or explicit drains release the emulator owner', async () => {+ const proc = fakeProc()+ let release!: () => void+ const term = {+ write: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ release = resolve+ })+ ),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('three-owners', SPAWN, 100, { proc: proc.value, term })+ const socket = {} as Socket+ session.subscribers.add(socket)++ session.pauseFor(socket)+ session.pauseTransportFor(socket)+ const write = session.recordOutput('x'.repeat(SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES))+ session.resumeTransportFor(socket)+ session.resumeFor(socket)+ expect(proc.resume).not.toHaveBeenCalled()++ await Promise.resolve()+ release()+ await write+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('does not let the emulator low-water drain release an explicit owner', async () => {+ const proc = fakeProc()+ let release!: () => void+ const term = {+ write: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ release = resolve+ })+ ),+ serialize: vi.fn(() => ''),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('explicit-after-emulator', SPAWN, 100, {+ proc: proc.value,+ term+ })+ const socket = {} as Socket+ session.subscribers.add(socket)+ session.pauseFor(socket)+ const write = session.recordOutput('x'.repeat(SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES))++ await Promise.resolve()+ release()+ await write+ expect(proc.resume).not.toHaveBeenCalled()+ session.resumeFor(socket)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ })++ it('releases a rejected chunk\'s bytes and heals the ordering tail', async () => {+ const proc = fakeProc()+ const applied: string[] = []+ const term = {+ write: vi.fn(async (data: string) => {+ if (data.startsWith('bad')) throw new Error('synthetic flood rejection')+ applied.push(data)+ }),+ serialize: vi.fn(() => applied.join('')),+ resize: vi.fn(),+ dispose: vi.fn()+ } as unknown as TerminalEmulator+ const session = new HostSession('rejected-tail', SPAWN, 100, { proc: proc.value, term })++ await expect(+ session.recordOutput('bad'.padEnd(SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES, '!'))+ ).rejects.toThrow('synthetic flood rejection')+ expect(proc.pause).toHaveBeenCalledTimes(1)+ expect(proc.resume).toHaveBeenCalledTimes(1)+ await expect(session.recordOutput('good')).resolves.toBeUndefined()+ await expect(session.serialize()).resolves.toBe('good')+ })+})diff --git a/src/session-host/session.ts b/src/session-host/session.tsnew file mode 100644index 000000000..eb9e215ce--- /dev/null+++ b/src/session-host/session.ts@@ -0,0 +1,714 @@+import type { Socket } from 'net'+import { createHash, randomUUID } from 'crypto'+import * as pty from 'node-pty'+import { TerminalEmulator } from './terminal-emulator'+import type {+ ExecuteLaunchResult,+ SessionHostShellDialect,+ SessionHostSpawnOptions+} from './protocol'++const MAX_LAUNCH_LEDGER_ENTRIES = 256+const SHELL_QUIET_MS = 200+const SHELL_QUIET_CAP_MS = 1_500+const POST_LAUNCH_READY_CAP_MS = 5_000+const LAUNCH_READINESS_POLL_MS = 100+const VERIFY_TIMEOUT_MS = 2_000+const DELIVERY_ATTEMPTS = 3+const ECHO_TAIL_CHARS = 24+const KILL_LINE = '\x15'+const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i+// eslint-disable-next-line no-control-regex+const ESC_SEQ = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g++function cleanEcho(chunk: string): string {+ // eslint-disable-next-line no-control-regex+ return chunk.replace(ESC_SEQ, '').replace(/[\r\n]/g, '')+}++interface LaunchLedgerEntry {+ fingerprint: string+ outcome: Promise<{ ok: true } | { ok: false }>+}++interface HostSessionOverrides {+ proc?: pty.IPty+ term?: TerminalEmulator+}++function launchFingerprint(command: string, stdinAfterStart: string | undefined): string {+ const hash = createHash('sha256')+ hash.update(command, 'utf8')+ hash.update('\0', 'utf8')+ if (stdinAfterStart !== undefined) hash.update(stdinAfterStart, 'utf8')+ return hash.digest('hex')+}++function replacementAttachFingerprint(+ spawn: SessionHostSpawnOptions,+ scrollback: number+): string {+ const canonical = {+ cwd: spawn.cwd,+ shell: spawn.shell,+ args: [...spawn.args],+ env: Object.fromEntries(Object.entries(spawn.env).sort(([a], [b]) => a.localeCompare(b))),+ cols: spawn.cols,+ rows: spawn.rows,+ launchDialect: spawn.launchDialect ?? null,+ initialLaunch: spawn.initialLaunch ?? null,+ scrollback+ }+ return createHash('sha256').update(JSON.stringify(canonical), 'utf8').digest('hex')+}++/** Pause before the asynchronous headless terminal retains more than this many queued UTF-8+ * bytes. node-pty can still have a bounded amount already in flight, but it cannot keep feeding an+ * unbounded promise chain while xterm is behind. */+export const SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES = 4 * 1024 * 1024+/** Resume only after the queued emulator tail drains this far, leaving hysteresis so a producer+ * hovering around the high-water boundary cannot chatter node-pty's global pause actuator. */+export const SESSION_EMULATOR_OUTPUT_LOW_WATER_BYTES = 1 * 1024 * 1024++interface Geometry {+ cols: number+ rows: number+}++interface HostSessionOverrides {+ proc?: pty.IPty+ term?: TerminalEmulator+}++interface AttachmentState {+ geometry?: Geometry+ explicitPaused: boolean+ subscribed: boolean+}++/** A warm attach must temporarily claim geometry and (on reconnect) restore its explicit pause+ * before reading a screen. The transaction makes a failed/retried attach restore only its own+ * prior socket state instead of leaking a claim or erasing an already-live duplicate attach. */+export interface PreparedHostAttachment {+ isCurrent(): boolean+ /** False means a concurrent detach/close cancelled this exact socket+name transaction. */+ commit(): boolean+ rollback(): Promise<void>+}++function normalizedGeometry(cols: number, rows: number): Geometry {+ if (+ !Number.isInteger(cols) ||+ !Number.isFinite(cols) ||+ cols <= 0 ||+ !Number.isInteger(rows) ||+ !Number.isFinite(rows) ||+ rows <= 0+ ) {+ throw new Error('terminal geometry must use finite positive integer cols and rows')+ }+ return { cols, rows }+}++/**+ * One persisted session, owned by the host process for as long as it lives — this is the+ * Windows-and-anywhere-else-tmux-is-missing analogue of a tmux session: it survives every+ * connecting client detaching, and outlives the app that spawned it.+ */+export class HostSession {+ readonly name: string+ /** Opaque identity for this exact process generation. Same-name replacement gets a new value. */+ readonly generation = randomUUID()+ readonly launchDialect?: SessionHostShellDialect+ readonly shellExecutableName: string+ /** Operation that created this generation after consuming a replacement lease. Retained only+ * with the live generation so a lost attach reply can be replayed idempotently with that token. */+ readonly createdByReplacementToken?: string+ private readonly replacementFingerprint: string+ readonly proc: pty.IPty+ private readonly term: TerminalEmulator+ /** The tail of every emulator mutation accepted so far. `@xterm/headless` applies writes+ * asynchronously, so warm attach/capture/resize/exit all cross this barrier. Rejections heal the+ * shared tail while the individual recordOutput caller still observes its own failure. */+ private outputTail: Promise<void> = Promise.resolve()+ private queuedOutputBytes = 0+ /** Explicit protocol flow and named-pipe transport flow drain independently. Collapsing them by+ * socket lets a `drain` event cancel a renderer pause that is still owed. */+ private readonly explicitPauseOwners = new Set<Socket>()+ private readonly transportPauseOwners = new Set<Socket>()+ /** The emulator queue is session-global, not owned by a connection. */+ private emulatorPauseOwner = false+ /** Each app connection contributes one componentwise geometry claim. The effective PTY size is+ * the minimum across live claims so every viewer fits; removing the smallest claim grows it. */+ private readonly geometryClaims = new Map<Socket, Geometry>()+ /** A detach/close increments the socket epoch before clearing state. A delayed prepare/rollback+ * from the prior epoch can then observe cancellation instead of resurrecting a ghost socket. */+ private readonly attachmentEpochs = new WeakMap<Socket, number>()+ private appliedGeometry: Geometry+ /** Consecutive callers asking for the same effective target share one acknowledgement. If that+ * actuator attempt fails, every waiter sees the failure; a later exact retry starts a new one. */+ private pendingGeometry: { key: string; promise: Promise<void> } | null = null+ /** Sockets currently receiving `data`/`exit` push frames for this session — the same "N+ * subscribers, one underlying process" shape `pty-manager.ts` already implements for tmux+ * co-attach, one level further down the stack. */+ readonly subscribers = new Set<Socket>()+ readonly createdAt = Date.now()+ /** Set once, by whichever path (natural pty exit or an explicit `killSession`) ends this+ * session first — guards against double-dispose/double-broadcast when both could race. */+ exited = false+ /** Generation-local exactly-once ledger. Promise insertion happens before command delivery, so+ * another app process repeating a launch whose first reply was lost observes the same result. */+ private readonly launchLedger = new Map<string, LaunchLedgerEntry>()+ /** Different launch ids must not type over one another in the same interactive prompt. */+ private launchQueue: Promise<void> = Promise.resolve()+ /** While trusted private input is being echo-verified, host.ts must neither broadcast it nor+ * write it into the reconstructable emulator screen. */+ private privateLaunchOutput = false++ get suppressingPrivateLaunchOutput(): boolean {+ return this.privateLaunchOutput+ }++ /** True once a successful explicit kill has claimed the name but before node-pty proves process+ * death with onExit. Same-name attach waits behind `ending` instead of joining this generation. */+ retiring = false+ /** Shared completion for the natural-exit / explicit-kill race. A second caller waits for the+ * first caller's output drain instead of acknowledging while teardown is still in flight. */+ ending: Promise<void> | null = null+ private processExitCode: number | null = null+ private readonly processExit: Promise<number>+ private resolveProcessExit!: (exitCode: number) => void+ constructor(+ name: string,+ spawn: SessionHostSpawnOptions,+ scrollback: number,+ createdByReplacementTokenOrOverrides?: string | HostSessionOverrides,+ maybeOverrides?: HostSessionOverrides+ ) {+ const createdByReplacementToken =+ typeof createdByReplacementTokenOrOverrides === 'string'+ ? createdByReplacementTokenOrOverrides+ : undefined+ const overrides =+ typeof createdByReplacementTokenOrOverrides === 'object'+ ? createdByReplacementTokenOrOverrides+ : maybeOverrides+ this.name = name+ this.launchDialect = spawn.launchDialect+ this.shellExecutableName = (spawn.shell.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase()+ this.createdByReplacementToken = createdByReplacementToken+ this.replacementFingerprint = replacementAttachFingerprint(spawn, scrollback)+ this.processExit = new Promise<number>((resolve) => {+ this.resolveProcessExit = resolve+ })+ this.appliedGeometry = normalizedGeometry(spawn.cols, spawn.rows)+ this.proc =+ overrides?.proc ??+ pty.spawn(spawn.shell, spawn.args, {+ name: 'xterm-256color',+ cols: this.appliedGeometry.cols,+ rows: this.appliedGeometry.rows,+ cwd: spawn.cwd,+ env: spawn.env+ })+ this.term =+ overrides?.term ??+ new TerminalEmulator({+ cols: this.appliedGeometry.cols,+ rows: this.appliedGeometry.rows,+ scrollback+ })+ }++ /** Queue one PTY-output chunk into the headless emulator, preserving arrival order and bounding+ * the retained byte tail. Accounting happens before chaining because promises not yet started+ * still retain their chunk strings and therefore count against the memory bound. */+ recordOutput(data: string): Promise<void> {+ const bytes = Buffer.byteLength(data, 'utf8')+ this.queuedOutputBytes += bytes+ if (this.queuedOutputBytes >= SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES) {+ this.setEmulatorPause(true)+ }++ const applied = this.outputTail.then(() => this.term.write(data))+ const settled = applied.finally(() => {+ this.queuedOutputBytes = Math.max(0, this.queuedOutputBytes - bytes)+ if (this.queuedOutputBytes <= SESSION_EMULATOR_OUTPUT_LOW_WATER_BYTES) {+ this.setEmulatorPause(false)+ }+ })+ this.outputTail = settled.catch(() => {})+ return settled+ }++ /** Wait until every PTY-output chunk observed before this call has reached xterm. */+ settleOutput(): Promise<void> {+ return this.outputTail+ }++ /** Record the one authoritative process-death observation. A kill syscall returning is not this+ * event; only node-pty's onExit resolves the barrier and permits retirement acknowledgement. */+ observeProcessExit(exitCode: number): void {+ if (this.processExitCode !== null) return+ this.processExitCode = exitCode+ this.exited = true+ this.resolveProcessExit(exitCode)+ }++ waitForProcessExit(): Promise<number> {+ return this.processExit+ }++ /** Serialize only after prior asynchronous writes and geometry changes have landed. */+ async serialize(scrollback?: number): Promise<string> {+ await this.outputTail+ return this.term.serialize(scrollback)+ }++ /** Stage an attach's explicit flow state and per-socket geometry before the warm screen barrier.+ * The returned commit is the only operation that activates live delivery. */+ async prepareAttachment(+ socket: Socket,+ cols: number,+ rows: number,+ paused: boolean+ ): Promise<PreparedHostAttachment> {+ const epoch = (this.attachmentEpochs.get(socket) ?? 0) + 1+ this.attachmentEpochs.set(socket, epoch)+ const previous: AttachmentState = {+ geometry: this.geometryClaims.get(socket),+ explicitPaused: this.explicitPauseOwners.has(socket),+ subscribed: this.subscribers.has(socket)+ }+ this.setSocketPauseOwner(this.explicitPauseOwners, socket, paused)+ try {+ await this.setGeometryClaim(socket, cols, rows)+ } catch (error) {+ await this.restoreAttachment(socket, previous, epoch)+ throw error+ }++ let finished = false+ return {+ isCurrent: () => this.attachmentEpochs.get(socket) === epoch && !socket.destroyed,+ commit: () => {+ if (finished) return false+ finished = true+ if (this.attachmentEpochs.get(socket) !== epoch || socket.destroyed) return false+ this.subscribers.add(socket)+ // A response written before this attach may already have filled the socket. The new+ // session must inherit that socket-wide transport ticket before any live frame can add to+ // the same queue.+ if (socket.writableNeedDrain) this.setSocketPauseOwner(this.transportPauseOwners, socket, true)+ return true+ },+ rollback: async () => {+ if (finished) return+ finished = true+ await this.restoreAttachment(socket, previous, epoch)+ }+ }+ }++ /** Warm no-spawn attach used by a generation-checked reconnect. New clients carry their current+ * aggregate geometry; older v2 clients safely reuse the generation's last applied size. */+ prepareExistingAttachment(+ socket: Socket,+ paused: boolean,+ cols?: number,+ rows?: number+ ): Promise<PreparedHostAttachment> {+ if ((cols === undefined) !== (rows === undefined)) {+ throw new Error('existing attachment geometry requires both cols and rows')+ }+ const geometry =+ cols === undefined || rows === undefined ? this.appliedGeometry : normalizedGeometry(cols, rows)+ return this.prepareAttachment(socket, geometry.cols, geometry.rows, paused)+ }++ /** Update only the requesting subscriber's geometry claim. */+ async resizeFor(socket: Socket, cols: number, rows: number): Promise<void> {+ if (!this.subscribers.has(socket)) return+ await this.setGeometryClaim(socket, cols, rows)+ }++ pauseFor(socket: Socket): void {+ if (!this.subscribers.has(socket)) return+ this.setSocketPauseOwner(this.explicitPauseOwners, socket, true)+ }++ resumeFor(socket: Socket): void {+ if (!this.subscribers.has(socket)) return+ this.setSocketPauseOwner(this.explicitPauseOwners, socket, false)+ }++ pauseTransportFor(socket: Socket): void {+ if (!this.subscribers.has(socket)) return+ this.setSocketPauseOwner(this.transportPauseOwners, socket, true)+ }++ resumeTransportFor(socket: Socket): void {+ this.setSocketPauseOwner(this.transportPauseOwners, socket, false)+ }++ /** A protocol detach and a transport close mean the same thing for ownership: this socket can+ * never return either flow ticket or its geometry claim, so release all three unconditionally. */+ async detach(socket: Socket): Promise<void> {+ this.attachmentEpochs.set(socket, (this.attachmentEpochs.get(socket) ?? 0) + 1)+ const wasPaused = this.hasPauseOwner()+ this.subscribers.delete(socket)+ this.explicitPauseOwners.delete(socket)+ this.transportPauseOwners.delete(socket)+ this.reconcileProcFlow(wasPaused)+ if (!this.geometryClaims.delete(socket)) return+ await this.applyEffectiveGeometry()+ }++ async executeInitialLaunch(+ spawn: SessionHostSpawnOptions,+ readinessProbe?: () => Promise<boolean>+ ): Promise<ExecuteLaunchResult | undefined> {+ const initial = spawn.initialLaunch+ if (!initial) return undefined+ return this.executeLaunch(+ initial.launchId,+ initial.command,+ initial.stdinAfterStart,+ readinessProbe+ )+ }++ matchesReplacementReplay(spawn: SessionHostSpawnOptions, scrollback: number): boolean {+ return this.replacementFingerprint === replacementAttachFingerprint(spawn, scrollback)+ }++ dispose(): void {+ this.explicitPauseOwners.clear()+ this.transportPauseOwners.clear()+ this.emulatorPauseOwner = false+ this.geometryClaims.clear()+ this.term.dispose()+ }++ async executeLaunch(+ launchId: string,+ command: string,+ stdinAfterStart?: string,+ readinessProbe?: () => Promise<boolean>+ ): Promise<ExecuteLaunchResult> {+ if (!this.launchDialect) {+ throw new Error('session-host terminal has no trusted launch dialect')+ }+ if (!UUID_V4.test(launchId)) throw new Error('session-host launch id is invalid')+ if (!command || command.length > 128 * 1024 || command.includes('\0')) {+ throw new Error('session-host launch input is invalid')+ }+ if (+ stdinAfterStart !== undefined &&+ (stdinAfterStart.length > 1024 * 1024 || stdinAfterStart.includes('\0'))+ ) {+ throw new Error('session-host launch follow-up input is invalid')+ }+ const fingerprint = launchFingerprint(command, stdinAfterStart)+ const existing = this.launchLedger.get(launchId)+ if (existing) {+ if (existing.fingerprint !== fingerprint) {+ throw new Error('session-host launch id was reused with different input')+ }+ const outcome = await existing.outcome+ if (!outcome.ok) throw new Error('session-host launch delivery previously failed')+ return { status: 'already-executed' }+ }++ // Never evict within a live generation. Eviction would make an old lost-reply retry execute a+ // second time; at the bounded cap, fail new ids closed until this generation ends.+ if (this.launchLedger.size >= MAX_LAUNCH_LEDGER_ENTRIES) {+ throw new Error('session-host launch ledger is full for this terminal generation')+ }++ const execution = this.launchQueue+ .catch(() => {+ // A failed older launch must not poison the serialization queue for a distinct id.+ })+ .then(() => this.deliverLaunch(command, stdinAfterStart, readinessProbe))+ const outcome = execution.then(+ () => ({ ok: true }) as const,+ () => ({ ok: false }) as const+ )+ const entry: LaunchLedgerEntry = { fingerprint, outcome }+ // Insert before the queued work can begin. This is the exactly-once commit point.+ this.launchLedger.set(launchId, entry)+ this.launchQueue = execution.catch(() => {})+ const result = await outcome+ if (!result.ok) throw new Error('session-host launch delivery failed')+ return { status: 'executed' }+ }++ private async deliverLaunch(+ command: string,+ stdinAfterStart?: string,+ readinessProbe?: () => Promise<boolean>+ ): Promise<void> {+ await this.waitForOutputQuiet(SHELL_QUIET_CAP_MS)+ await this.deliverVerifiedCommand(command)+ if (stdinAfterStart !== undefined) {+ // Time/quiet alone is not readiness: a short-lived failed agent can already have returned to+ // the shell prompt. Require the host's process-tree probe to observe a non-shell descendant+ // before literal follow-up input is allowed anywhere near the terminal.+ if (!readinessProbe) throw new Error('session-host has no launch readiness probe')+ await this.waitForLaunchReadiness(readinessProbe)+ await this.waitForOutputQuiet(SHELL_QUIET_MS)+ if (this.exited) throw new Error('session-host terminal exited during launch delivery')+ try {+ this.privateLaunchOutput = true+ this.proc.write(stdinAfterStart)+ this.proc.write('\r')+ // Keep any asynchronous terminal echo private through one bounded settle window.+ await this.waitForOutputQuiet(SHELL_QUIET_CAP_MS)+ } catch {+ throw new Error('session-host could not deliver launch follow-up input')+ } finally {+ this.privateLaunchOutput = false+ }+ }+ }++ private async waitForLaunchReadiness(probe: () => Promise<boolean>): Promise<void> {+ const deadline = Date.now() + POST_LAUNCH_READY_CAP_MS+ while (!this.exited && Date.now() < deadline) {+ try {+ if (await probe()) return+ } catch {+ // A failed read is uncertainty, never readiness. Keep polling within the fixed bound.+ }+ await new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, LAUNCH_READINESS_POLL_MS)+ timer.unref?.()+ })+ }+ if (this.exited) throw new Error('session-host terminal exited during launch delivery')+ throw new Error('session-host could not confirm launched agent readiness')+ }++ private waitForOutputQuiet(capMs: number): Promise<void> {+ if (this.exited) return Promise.reject(new Error('session-host terminal exited during launch delivery'))+ return new Promise<void>((resolve, reject) => {+ let done = false+ let quietTimer: ReturnType<typeof setTimeout> | undefined+ let dataSub: { dispose(): void } | undefined+ let exitSub: { dispose(): void } | undefined+ const capTimer = setTimeout(() => finish(), capMs)+ capTimer.unref?.()+ const cleanup = (): void => {+ clearTimeout(capTimer)+ if (quietTimer) clearTimeout(quietTimer)+ dataSub?.dispose()+ exitSub?.dispose()+ }+ const finish = (error?: Error): void => {+ if (done) return+ done = true+ cleanup()+ if (error) reject(error)+ else resolve()+ }+ dataSub = this.proc.onData(() => {+ if (quietTimer) clearTimeout(quietTimer)+ quietTimer = setTimeout(() => finish(), SHELL_QUIET_MS)+ quietTimer.unref?.()+ })+ exitSub = this.proc.onExit(() =>+ finish(new Error('session-host terminal exited during launch delivery'))+ )+ })+ }++ private deliverVerifiedCommand(command: string): Promise<void> {+ if (this.exited) return Promise.reject(new Error('session-host terminal exited during launch delivery'))+ return new Promise<void>((resolve, reject) => {+ this.privateLaunchOutput = true+ let done = false+ let attempt = 0+ let echoed = ''+ let timer: ReturnType<typeof setTimeout> | undefined+ let dataSub: { dispose(): void } | undefined+ let exitSub: { dispose(): void } | undefined+ const cleanup = (): void => {+ if (timer) clearTimeout(timer)+ dataSub?.dispose()+ exitSub?.dispose()+ }+ const finish = (error?: Error): void => {+ if (done) return+ done = true+ this.privateLaunchOutput = false+ cleanup()+ if (error) reject(error)+ else resolve()+ }+ const write = (data: string): boolean => {+ try {+ this.proc.write(data)+ return true+ } catch {+ finish(new Error('session-host could not deliver launch input'))+ return false+ }+ }+ const submit = (): void => {+ if (!write('\r')) return+ finish()+ }+ const tryOnce = (): void => {+ if (done) return+ attempt+++ echoed = ''+ timer = setTimeout(() => {+ if (done) return+ if (attempt >= DELIVERY_ATTEMPTS) {+ // Never submit an unverified/mangled command. Clear it so the terminal remains+ // recoverable, cache the fixed failure, and let explicit user action decide next.+ write(KILL_LINE)+ finish(new Error('session-host could not verify launch command delivery'))+ return+ }+ if (!write(KILL_LINE)) return+ tryOnce()+ }, VERIFY_TIMEOUT_MS)+ timer.unref?.()+ write(command)+ }+ dataSub = this.proc.onData((chunk) => {+ if (done) return+ echoed = (echoed + cleanEcho(chunk)).slice(-Math.max(command.length + 256, 512))+ if (echoed.includes(command.slice(-ECHO_TAIL_CHARS))) submit()+ })+ exitSub = this.proc.onExit(() =>+ finish(new Error('session-host terminal exited during launch delivery'))+ )+ tryOnce()+ })+ }++ /** Release node-pty's Windows ConPTY handle after the independently verified `/T /F` process+ * tree termination. `WindowsTerminal.kill()` cannot be used here: node-pty defers that public+ * method until the first output byte, so a valid silent process would keep its host-parented+ * conhost alive forever. The internal agent call is the narrow upstream-compatible primitive+ * that closes the ConPTY handle; the host still waits for this pty's real `onExit` before ack. */+ releaseWindowsPtyAfterExternalTreeKill(): void {+ if (process.platform !== 'win32') {+ throw new Error('external ConPTY release is Windows-only')+ }+ const internal = this.proc as unknown as {+ _close?: () => void+ _agent?: { kill?: () => void }+ }+ if (typeof internal._close !== 'function' || typeof internal._agent?.kill !== 'function') {+ throw new Error('installed node-pty does not expose the required ConPTY release primitive')+ }+ internal._close()+ internal._agent.kill()+ }++ private async restoreAttachment(+ socket: Socket,+ previous: AttachmentState,+ epoch: number+ ): Promise<void> {+ if (this.attachmentEpochs.get(socket) !== epoch) return+ const wasPaused = this.hasPauseOwner()+ if (previous.explicitPaused) this.explicitPauseOwners.add(socket)+ else this.explicitPauseOwners.delete(socket)+ if (previous.subscribed) this.subscribers.add(socket)+ else this.subscribers.delete(socket)+ this.reconcileProcFlow(wasPaused)++ if (previous.geometry) this.geometryClaims.set(socket, previous.geometry)+ else this.geometryClaims.delete(socket)+ await this.applyEffectiveGeometry()+ }++ private setGeometryClaim(socket: Socket, cols: number, rows: number): Promise<void> {+ this.geometryClaims.set(socket, normalizedGeometry(cols, rows))+ return this.applyEffectiveGeometry()+ }++ private applyEffectiveGeometry(): Promise<void> {+ const requested = this.effectiveGeometry()+ const key = requested ? `${requested.cols}x${requested.rows}` : 'unclaimed'+ if (this.pendingGeometry?.key === key) return this.pendingGeometry.promise+ // Recompute inside the serialized emulator tail, not when the request arrives. Concurrent+ // resize/detach calls can change the claim ledger while an earlier xterm write is pending; a+ // captured target would land stale after the newer operation. `appliedGeometry` advances only+ // after both real actuators succeed, so identical waiters share a real failure and a later+ // exact retry cannot false-no-op on a marker that never reached the terminal.+ const reconciled = this.outputTail.then(() => {+ const target = this.effectiveGeometry()+ if (!target) return+ if (+ target.cols === this.appliedGeometry.cols &&+ target.rows === this.appliedGeometry.rows+ ) {+ return+ }+ this.proc.resize(target.cols, target.rows)+ this.term.resize(target.cols, target.rows)+ this.appliedGeometry = target+ })+ const pending = { key, promise: reconciled }+ this.pendingGeometry = pending+ void reconciled.then(+ () => {+ if (this.pendingGeometry === pending) this.pendingGeometry = null+ },+ () => {+ if (this.pendingGeometry === pending) this.pendingGeometry = null+ }+ )+ this.outputTail = reconciled.catch(() => {})+ return reconciled+ }++ private effectiveGeometry(): Geometry | null {+ if (this.geometryClaims.size === 0) return null+ let cols = Number.MAX_SAFE_INTEGER+ let rows = Number.MAX_SAFE_INTEGER+ for (const claim of this.geometryClaims.values()) {+ cols = Math.min(cols, claim.cols)+ rows = Math.min(rows, claim.rows)+ }+ return { cols, rows }+ }++ private hasPauseOwner(): boolean {+ return (+ this.emulatorPauseOwner ||+ this.explicitPauseOwners.size > 0 ||+ this.transportPauseOwners.size > 0+ )+ }++ private setSocketPauseOwner(owners: Set<Socket>, socket: Socket, held: boolean): void {+ const wasPaused = this.hasPauseOwner()+ if (held) owners.add(socket)+ else owners.delete(socket)+ this.reconcileProcFlow(wasPaused)+ }++ private setEmulatorPause(held: boolean): void {+ const wasPaused = this.hasPauseOwner()+ this.emulatorPauseOwner = held+ this.reconcileProcFlow(wasPaused)+ }++ private reconcileProcFlow(wasPaused: boolean): void {+ const isPaused = this.hasPauseOwner()+ if (wasPaused === isPaused) return+ try {+ if (isPaused) this.proc.pause()+ else this.proc.resume()+ } catch {+ /* pty may have exited between the session lookup and the actuator call */+ }+ }+}diff --git a/src/session-host/socket-flow.test.ts b/src/session-host/socket-flow.test.tsnew file mode 100644index 000000000..c0e00b683--- /dev/null+++ b/src/session-host/socket-flow.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from 'vitest'+import type { Socket } from 'net'+import type { HostSession } from './session'+import { drainSessionHostTransport, writeSessionHostFrame } from './socket-flow'++function fakeSession(socket?: Socket): {+ value: HostSession+ pauseTransportFor: ReturnType<typeof vi.fn>+ resumeTransportFor: ReturnType<typeof vi.fn>+} {+ const pauseTransportFor = vi.fn()+ const resumeTransportFor = vi.fn()+ return {+ value: {+ subscribers: new Set(socket ? [socket] : []),+ pauseTransportFor,+ resumeTransportFor+ } as unknown as HostSession,+ pauseTransportFor,+ resumeTransportFor+ }+}++describe('session-host socket transport flow', () => {+ it('books write(false) against every session sharing that socket and drains only those owners', () => {+ const socket = {+ write: vi.fn(() => false),+ destroy: vi.fn()+ } as unknown as Socket+ const first = fakeSession(socket)+ const second = fakeSession(socket)+ const unrelated = fakeSession()++ writeSessionHostFrame(socket, 'frame\n', [first.value, unrelated.value, second.value])+ expect(first.pauseTransportFor).toHaveBeenCalledOnce()+ expect(second.pauseTransportFor).toHaveBeenCalledOnce()+ expect(unrelated.pauseTransportFor).not.toHaveBeenCalled()++ drainSessionHostTransport(socket, [first.value, unrelated.value, second.value])+ expect(first.resumeTransportFor).toHaveBeenCalledOnce()+ expect(second.resumeTransportFor).toHaveBeenCalledOnce()+ expect(unrelated.resumeTransportFor).not.toHaveBeenCalled()+ })++ it('does not book a transport owner for a write accepted immediately', () => {+ const socket = {+ write: vi.fn(() => true),+ destroy: vi.fn()+ } as unknown as Socket+ const session = fakeSession(socket)++ writeSessionHostFrame(socket, 'frame\n', [session.value])+ expect(session.pauseTransportFor).not.toHaveBeenCalled()+ })++ it('destroys a socket whose write throws instead of trying to send a second frame', () => {+ const socket = {+ write: vi.fn(() => {+ throw new Error('socket closed during write')+ }),+ destroy: vi.fn()+ } as unknown as Socket+ const session = fakeSession(socket)++ expect(() => writeSessionHostFrame(socket, 'frame\n', [session.value])).not.toThrow()+ expect(socket.destroy).toHaveBeenCalledOnce()+ expect(socket.write).toHaveBeenCalledOnce()+ expect(session.pauseTransportFor).not.toHaveBeenCalled()+ })+})diff --git a/src/session-host/socket-flow.ts b/src/session-host/socket-flow.tsnew file mode 100644index 000000000..29b14db92--- /dev/null+++ b/src/session-host/socket-flow.ts@@ -0,0 +1,34 @@+import type { Socket } from 'net'+import type { HostSession } from './session'++/** Write one accepted-connection frame without mistaking named-pipe backpressure for delivery+ * failure. A net.Socket queue is shared by every session on that connection, so the first false+ * return books a transport pause against every subscribed session, not only the frame's source. */+export function writeSessionHostFrame(+ socket: Socket,+ frame: string,+ sessions: Iterable<HostSession>+): void {+ try {+ if (socket.write(frame)) return+ } catch {+ // A synchronous send failure is a dead transport, not a failed dispatch that should generate+ // a second response. Destroying it funnels all ownership cleanup through the close handler.+ socket.destroy()+ return+ }+ for (const session of sessions) {+ if (session.subscribers.has(socket)) session.pauseTransportFor(socket)+ }+}++/** A socket drain returns only the named-pipe transport ticket. Explicit renderer flow and the+ * session-global emulator queue have independent drain events and remain held. */+export function drainSessionHostTransport(+ socket: Socket,+ sessions: Iterable<HostSession>+): void {+ for (const session of sessions) {+ if (session.subscribers.has(socket)) session.resumeTransportFor(socket)+ }+}diff --git a/src/session-host/socket-request-queue.test.ts b/src/session-host/socket-request-queue.test.tsnew file mode 100644index 000000000..63fc78af7--- /dev/null+++ b/src/session-host/socket-request-queue.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it, vi } from 'vitest'+import { SessionHostSocketRequestQueue } from './socket-request-queue'++describe('session-host per-socket request ordering', () => {+ it('does not let a same-name detach overtake a delayed attach', async () => {+ const queue = new SessionHostSocketRequestQueue()+ const order: string[] = []+ let releaseAttach!: () => void+ const attach = queue.enqueue(+ 'same-name',+ () =>+ new Promise<void>((resolve) => {+ order.push('attach-start')+ releaseAttach = () => {+ order.push('attach-finish')+ resolve()+ }+ })+ )+ const detachTask = vi.fn(async () => {+ order.push('detach')+ })+ const detach = queue.enqueue('same-name', detachTask)++ await Promise.resolve()+ await Promise.resolve()+ expect(order).toEqual(['attach-start'])+ expect(detachTask).not.toHaveBeenCalled()+ releaseAttach()+ await Promise.all([attach, detach])+ expect(order).toEqual(['attach-start', 'attach-finish', 'detach'])+ })++ it('keeps different session names concurrent', async () => {+ const queue = new SessionHostSocketRequestQueue()+ let releaseFirst!: () => void+ const first = queue.enqueue(+ 'first',+ () =>+ new Promise<void>((resolve) => {+ releaseFirst = resolve+ })+ )+ const second = vi.fn(async () => {})++ await queue.enqueue('second', second)+ expect(second).toHaveBeenCalledOnce()+ releaseFirst()+ await first+ })+})diff --git a/src/session-host/socket-request-queue.ts b/src/session-host/socket-request-queue.tsnew file mode 100644index 000000000..e65ced598--- /dev/null+++ b/src/session-host/socket-request-queue.ts@@ -0,0 +1,22 @@+/** Preserve wire order for commands targeting the same session on one socket. Dispatch itself is+ * asynchronous (warm snapshots and geometry barriers await), so merely iterating parsed frames in+ * order lets a later detach run before the earlier attach has even prepared its claim. Different+ * names keep independent lanes and therefore retain the protocol's intended concurrency. */+export class SessionHostSocketRequestQueue {+ private readonly tails = new Map<string, Promise<void>>()++ enqueue(name: string, task: () => Promise<void>): Promise<void> {+ const previous = this.tails.get(name) ?? Promise.resolve()+ const current = previous.catch(() => {}).then(task)+ this.tails.set(name, current)+ void current.then(+ () => this.release(name, current),+ () => this.release(name, current)+ )+ return current+ }++ private release(name: string, current: Promise<void>): void {+ if (this.tails.get(name) === current) this.tails.delete(name)+ }+}diff --git a/src/session-host/startup-failure.test.ts b/src/session-host/startup-failure.test.tsnew file mode 100644index 000000000..8fff5c446--- /dev/null+++ b/src/session-host/startup-failure.test.ts@@ -0,0 +1,221 @@+import { afterEach, describe, expect, it } from 'vitest'+import { spawn, type ChildProcess } from 'child_process'+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync+} from 'fs'+import net from 'net'+import os from 'os'+import path from 'path'+import { build, type Plugin } from 'esbuild'+import { sessionHostPaths } from './paths'+import { SESSION_HOST_PROTOCOL_VERSION } from './protocol'++interface ExitOutcome {+ code: number | null+ signal: NodeJS.Signals | null+ timedOut: boolean+}++function waitForExit(child: ChildProcess, timeoutMs: number): Promise<ExitOutcome> {+ return new Promise((resolve) => {+ let timedOut = false+ const timer = setTimeout(() => {+ timedOut = true+ child.kill()+ }, timeoutMs)+ child.once('exit', (code, signal) => {+ clearTimeout(timer)+ resolve({ code, signal, timedOut })+ })+ })+}++function endpointAcceptsConnections(endpoint: string): Promise<boolean> {+ return new Promise((resolve) => {+ const socket = net.connect(endpoint)+ let settled = false+ const finish = (connected: boolean): void => {+ if (settled) return+ settled = true+ socket.destroy()+ resolve(connected)+ }+ socket.once('connect', () => finish(true))+ socket.once('error', () => finish(false))+ socket.setTimeout(500, () => finish(false))+ })+}++function failureInjectionPlugin(): Plugin {+ return {+ name: 'session-host-startup-failure',+ setup(bundle) {+ bundle.onResolve({ filter: /^\.\/state-file$/ }, () => ({+ path: 'injected-state-file',+ namespace: 'startup-failure'+ }))+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({+ path: 'node-pty',+ namespace: 'startup-failure'+ }))+ bundle.onLoad(+ { filter: /^injected-state-file$/, namespace: 'startup-failure' },+ () => ({+ loader: 'js',+ contents: `+ export function publishSessionHostState() {+ const error = new Error('injected state publication failure')+ error.code = 'ENOSPC'+ throw error+ }+ `+ })+ )+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'startup-failure' }, () => ({+ loader: 'js',+ contents: `export function spawn() { throw new Error('node-pty must not spawn') }`+ }))+ }+ }+}++function inertPtyPlugin(): Plugin {+ return {+ name: 'session-host-inert-pty',+ setup(bundle) {+ bundle.onResolve({ filter: /^node-pty$/ }, () => ({+ path: 'node-pty',+ namespace: 'startup-failure'+ }))+ bundle.onLoad({ filter: /^node-pty$/, namespace: 'startup-failure' }, () => ({+ loader: 'js',+ contents: `export function spawn() { throw new Error('node-pty must not spawn') }`+ }))+ }+ }+}++async function buildAndStartHost(+ fixtureDir: string,+ dataDir: string,+ plugins: Plugin[]+): Promise<{ child: ChildProcess; bundlePath: string }> {+ const bundlePath = path.join(fixtureDir, 'host.cjs')+ await build({+ absWorkingDir: process.cwd(),+ entryPoints: ['src/session-host/host.ts'],+ outfile: bundlePath,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ plugins,+ logLevel: 'silent'+ })+ return {+ bundlePath,+ child: spawn(process.execPath, [bundlePath, dataDir], {+ cwd: process.cwd(),+ stdio: 'ignore',+ windowsHide: true+ })+ }+}++const cleanupPaths: string[] = []+afterEach(() => {+ for (const target of cleanupPaths.splice(0)) rmSync(target, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+})++describe('session-host startup publication failure', () => {+ it('exits nonzero and leaves no listener, token, or startup lock behind', async () => {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-process-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [failureInjectionPlugin()])++ const outcome = await waitForExit(child, 5_000)++ expect(outcome.timedOut).toBe(false)+ expect(outcome.signal).toBeNull()+ expect(outcome.code).not.toBeNull()+ expect(outcome.code).not.toBe(0)+ expect(existsSync(paths.statePath)).toBe(false)+ expect(existsSync(paths.tokenPath)).toBe(false)+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(false)+ }, 15_000)+})++describe('session-host startup ownership reads', () => {+ it('does not reclaim a corrupt state file as though it were absent', async () => {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-corrupt-state-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ const original = '{broken ownership state'+ writeFileSync(paths.statePath, original)+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [inertPtyPlugin()])++ const outcome = await waitForExit(child, 5_000)++ expect(outcome.timedOut).toBe(false)+ expect(outcome.code).not.toBe(0)+ expect(readFileSync(paths.statePath, 'utf8')).toBe(original)+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(false)+ }, 15_000)++ it('does not reclaim valid ownership whose token is empty/unreadable', async () => {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-empty-token-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ const state = JSON.stringify({+ pid: 42,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: 1234,+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ writeFileSync(paths.statePath, state)+ writeFileSync(paths.tokenPath, '')+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [inertPtyPlugin()])++ const outcome = await waitForExit(child, 5_000)++ expect(outcome.timedOut).toBe(false)+ expect(outcome.code).not.toBe(0)+ expect(readFileSync(paths.statePath, 'utf8')).toBe(state)+ expect(readFileSync(paths.tokenPath, 'utf8')).toBe('')+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(false)+ }, 15_000)++ it('leaves a directory occupying the ownership path untouched', async () => {+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-state-dir-'))+ cleanupPaths.push(fixtureDir)+ const dataDir = path.join(fixtureDir, 'user-data')+ mkdirSync(dataDir)+ const paths = sessionHostPaths(dataDir)+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)+ mkdirSync(paths.statePath)+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [inertPtyPlugin()])++ const outcome = await waitForExit(child, 5_000)++ expect(outcome.timedOut).toBe(false)+ expect(outcome.code).not.toBe(0)+ expect(statSync(paths.statePath).isDirectory()).toBe(true)+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(false)+ }, 15_000)+})diff --git a/src/session-host/state-file.test.ts b/src/session-host/state-file.test.tsnew file mode 100644index 000000000..8b14f4e24--- /dev/null+++ b/src/session-host/state-file.test.ts@@ -0,0 +1,108 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import {+ publishSessionHostState,+ renameSessionHostStateAtomic,+ sessionHostStateTempName+} from './state-file'++function codedError(code: string): NodeJS.ErrnoException {+ const error: NodeJS.ErrnoException = new Error(`${code}: injected`)+ error.code = code+ return error+}++let dir: string+beforeEach(() => {+ dir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-state-'))+})+afterEach(() => {+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })+})++describe('session-host state publication', () => {+ it('keeps process identity visible in otherwise unique temp paths', () => {+ const target = path.join(dir, 'session-host.json')+ const a = sessionHostStateTempName(target, { pid: 101, sequence: 1, uuid: () => 'uuid-a' })+ const b = sessionHostStateTempName(target, { pid: 202, sequence: 1, uuid: () => 'uuid-b' })++ expect(a).not.toBe(b)+ expect(a).toContain('.101.')+ expect(b).toContain('.202.')+ expect(a.endsWith('.tmp')).toBe(true)+ expect(b.endsWith('.tmp')).toBe(true)+ })+ it('gives colliding PID namespaces and module counters different temp paths', () => {+ const target = path.join(dir, 'session-host.json')+ const sameNamespace = { pid: 1, sequence: 1 }+ const defaultUuidA = sessionHostStateTempName(target, sameNamespace)+ const defaultUuidB = sessionHostStateTempName(target, sameNamespace)+ expect(defaultUuidA).not.toBe(defaultUuidB)+ const a = sessionHostStateTempName(target, { ...sameNamespace, uuid: () => 'uuid-a' })+ const b = sessionHostStateTempName(target, { ...sameNamespace, uuid: () => 'uuid-b' })++ expect(a).not.toBe(b)+ expect(a).toContain('.1.1.uuid-a.tmp')+ expect(b).toContain('.1.1.uuid-b.tmp')+ expect(a.endsWith('.tmp')).toBe(true)+ expect(b.endsWith('.tmp')).toBe(true)+ })++ it('retries transient Windows sharing violations before atomically replacing the lock file', () => {+ const target = path.join(dir, 'session-host.json')+ writeFileSync(target, '') // the exclusive-create startup lock this publication replaces+ let attempts = 0+ const waits: number[] = []++ publishSessionHostState(target, '{"pid":42}', {+ rename: (from, to) => {+ if (++attempts <= 2) throw codedError('EPERM')+ renameSync(from, to)+ },+ wait: (ms) => waits.push(ms)+ })++ expect(attempts).toBe(3)+ expect(waits).toEqual([10, 25])+ expect(readFileSync(target, 'utf8')).toBe('{"pid":42}')+ expect(readdirSync(dir).filter((name) => name.endsWith('.tmp'))).toEqual([])+ })++ it('leaves the old lock/state intact and removes its own temp on a permanent failure', () => {+ const target = path.join(dir, 'session-host.json')+ writeFileSync(target, 'old-state')++ expect(() =>+ publishSessionHostState(target, 'replacement', {+ rename: () => {+ throw codedError('ENOSPC')+ },+ wait: () => {+ throw new Error('a permanent failure must not spend the retry budget')+ }+ })+ ).toThrow(/ENOSPC/)+ expect(readFileSync(target, 'utf8')).toBe('old-state')+ expect(readdirSync(dir).filter((name) => name.endsWith('.tmp'))).toEqual([])+ })+})++describe('renameSessionHostStateAtomic', () => {+ it('does not let one unfixable result block startup forever', () => {+ let attempts = 0+ expect(() =>+ renameSessionHostStateAtomic('tmp', 'target', {+ rename: () => {+ attempts+++ throw codedError('ENOENT')+ },+ wait: () => {+ throw new Error('ENOENT must not wait')+ }+ })+ ).toThrow(/ENOENT/)+ expect(attempts).toBe(1)+ })+})diff --git a/src/session-host/state-file.ts b/src/session-host/state-file.tsnew file mode 100644index 000000000..a2a12fbb7--- /dev/null+++ b/src/session-host/state-file.ts@@ -0,0 +1,96 @@+// Session-host-local atomic publication. This standalone bundle deliberately imports neither+// src/core nor Electron, so it cannot reuse core/fs-atomic.ts without breaking the process+// boundary documented in docs/windows-session-host.md. Keep this small twin behavior-identical:+// unique temp ownership, bounded Windows sharing-violation retries, cleanup on every failure.++import { renameSync, rmSync, writeFileSync } from 'fs'+import { randomUUID } from 'crypto'++const TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EACCES', 'EBUSY'])+const RETRY_DELAYS_MS = [10, 25, 75, 200]+const SLEEP_SLOT = new Int32Array(new SharedArrayBuffer(4))+let tempSequence = 0++function codeOf(error: unknown): string {+ return typeof error === 'object' && error && 'code' in error+ ? String((error as { code: unknown }).code)+ : ''+}++export interface SessionHostTempNameOptions {+ /** Deterministic seams for the collision gate; production leaves all three undefined. */+ pid?: number+ sequence?: number+ uuid?: () => string+}++/** The UUID separates PID namespaces, worker isolates, and PID reuse. PID/counter remain useful+ * ownership metadata. A fixed `<state>.tmp` lets a second startup publish or remove the first+ * one's bytes, especially after a stale-lock reclaim. */+export function sessionHostStateTempName(+ target: string,+ opts: SessionHostTempNameOptions = {}+): string {+ const pid = opts.pid ?? process.pid+ const sequence = opts.sequence ?? ++tempSequence+ const uuid = opts.uuid ?? randomUUID+ return `${target}.${pid}.${sequence}.${uuid()}.tmp`+}++export function renameSessionHostStateAtomic(+ tmp: string,+ target: string,+ deps: {+ rename?: (from: string, to: string) => void+ wait?: (ms: number) => void+ } = {}+): void {+ const rename = deps.rename ?? renameSync+ const wait = deps.wait ?? ((ms: number) => Atomics.wait(SLEEP_SLOT, 0, 0, ms))+ for (let attempt = 0; ; attempt++) {+ try {+ rename(tmp, target)+ return+ } catch (error) {+ if (+ attempt >= RETRY_DELAYS_MS.length ||+ !TRANSIENT_RENAME_CODES.has(codeOf(error))+ ) {+ throw error+ }+ wait(RETRY_DELAYS_MS[attempt])+ }+ }+}++/** Publish the fully-written state as one rename. The old state/lock file stays intact on any+ * failure, and this process removes only the unique temp file it owns. */+export function publishSessionHostState(+ target: string,+ json: string,+ deps: {+ tempName?: (target: string) => string+ write?: (path: string, data: string) => void+ rename?: (from: string, to: string) => void+ remove?: (path: string) => void+ wait?: (ms: number) => void+ } = {}+): void {+ const tmp = (deps.tempName ?? sessionHostStateTempName)(target)+ const write =+ deps.write ??+ ((file: string, data: string) =>+ writeFileSync(file, data, { encoding: 'utf8', mode: 0o600 }))+ const remove = deps.remove ?? ((file: string) => rmSync(file, { force: true }))+ try {+ write(tmp, json)+ renameSessionHostStateAtomic(tmp, target, { rename: deps.rename, wait: deps.wait })+ } catch (error) {+ try {+ remove(tmp)+ } catch {+ /* best effort: never replace the original publication error with temp cleanup noise */+ }+ throw error+ }+}diff --git a/src/session-host/terminal-emulator.ts b/src/session-host/terminal-emulator.tsnew file mode 100644index 000000000..bceb5c521--- /dev/null+++ b/src/session-host/terminal-emulator.ts@@ -0,0 +1,89 @@+import { Terminal, type ITerminalAddon } from '@xterm/headless'+import { SerializeAddon } from '@xterm/addon-serialize'++// @xterm/addon-serialize's published types are written against @xterm/xterm's (browser) Terminal,+// which has a superset of DOM-specific members @xterm/headless's Terminal lacks. The addon only+// ever touches buffer/modes/cols/rows at runtime — all present on the headless Terminal — so this+// is a real type mismatch between two packages that are runtime-compatible, not a runtime risk.++/**+ * One session's server-side screen. This is the piece that makes the session host able to+ * reconstruct a fresh client's screen on attach WITHOUT itself being a "painter" the way a real+ * tmux client is — see docs/windows-session-host.md ("The seeding trap") before touching any of+ * this, and CLAUDE.md's "Seeding a fresh xterm" section for why a tmux-shaped answer here+ * (seed nothing on warm attach) would ship a blank terminal or duplicated screens depending on+ * which half you got wrong.+ *+ * MODE RESTORATION, VERIFIED NOT ASSUMED: xterm.js's own `SerializeAddon` already restores most+ * DEC private modes as part of its `serialize()` output (bracketed paste, application cursor+ * keys, origin mode, insert mode, reverse-wraparound, send-focus, wraparound, and — when the+ * active buffer is the alternate screen — the `?1049h` switch). Read directly from the compiled+ * `_serializeModes()` in `node_modules/@xterm/addon-serialize/lib/addon-serialize.js` rather than+ * assumed from the docs. It does NOT emit `CSI ?1006h` (SGR extended mouse coordinates) — there+ * is no separate field on the public `IModes` API for it to read; `modes.mouseTrackingMode` only+ * says which tracking PROTOCOL is on (x10/vt200/drag/any), not the coordinate ENCODING. This app+ * always turns mouse tracking on together with SGR (`CO_ATTACH_MOUSE_SEQ` in the renderer mirrors+ * real tmux's `mouse on`, which always pairs `?1000h`/`?1002h` with `?1006h`), so that one+ * sequence is appended by hand below whenever tracking is active. If a future xterm.js version+ * starts emitting it itself, appending it twice is a harmless idempotent DECSET, not a bug.+ */+export class TerminalEmulator {+ private readonly term: Terminal+ private readonly serializer: SerializeAddon+ private readonly defaultScrollback: number++ constructor(opts: { cols: number; rows: number; scrollback: number }) {+ this.defaultScrollback = Math.max(0, opts.scrollback)+ this.term = new Terminal({+ cols: Math.max(1, opts.cols),+ rows: Math.max(1, opts.rows),+ scrollback: this.defaultScrollback,+ allowProposedApi: true+ })+ this.serializer = new SerializeAddon()+ this.term.loadAddon(this.serializer as unknown as ITerminalAddon)+ }++ /**+ * Feed one chunk of PTY output. Resolves once xterm has fully applied it — `Terminal.write`'s+ * own write queue can defer processing of a large chunk past the current tick, and a caller+ * that called `serialize()` without waiting for this would race a partially-applied write (the+ * screen it hands back could be missing the tail of what just arrived).+ */+ write(data: string): Promise<void> {+ return new Promise((resolve) => this.term.write(data, resolve))+ }++ resize(cols: number, rows: number): void {+ if (cols > 0 && rows > 0) this.term.resize(cols, rows)+ }++ /**+ * The reconstructed screen: serialized content (scrollback capped at `scrollback`, defaulting+ * to this emulator's construction-time cap — smaller for `captureSession`'s "recent lines"+ * callers) plus the mode-restore/alt-buffer/cursor tail `SerializeAddon` already produces, with+ * the SGR-mouse gap above patched in by hand. Returns '' for a session that has never painted+ * anything (a cold session moments after spawn) — callers treat '' the same way the rest of+ * this app already treats an empty tmux capture: "nothing to seed", never a screen reset.+ */+ serialize(scrollback = this.defaultScrollback): string {+ let out = this.serializer.serialize({ scrollback: Math.max(0, scrollback) })+ if (this.term.modes.mouseTrackingMode !== 'none' && !out.includes('\x1b[?1006h')) {+ out += '\x1b[?1006h'+ }+ return out+ }++ dispose(): void {+ try {+ this.serializer.dispose()+ } catch {+ /* already disposed */+ }+ try {+ this.term.dispose()+ } catch {+ /* already disposed */+ }+ }+}diff --git a/src/session-host/windows-conpty.ts b/src/session-host/windows-conpty.tsnew file mode 100644index 000000000..330abc063--- /dev/null+++ b/src/session-host/windows-conpty.ts@@ -0,0 +1,233 @@+import fs from 'fs'+import type { Socket } from 'net'+import type { IPty } from 'node-pty'++export const SUPPORTED_WINDOWS_CONPTY_NODE_PTY_VERSION = '1.1.0'++const SAFE_CLOSE_ERROR = 'session-host could not safely close the Windows terminal'++type PrivateConptyNative = {+ startProcess: (...args: unknown[]) => unknown+ connect: (...args: unknown[]) => unknown+ resize: (...args: unknown[]) => unknown+ clear: (...args: unknown[]) => unknown+ /** Patched node-pty 1.1.0 returns true only when it found and closed this exact HPCON. */+ kill: (ptyId: number, useConptyDll: boolean) => unknown+}++type PrivateWindowsPtyAgent = {+ constructor: { name?: unknown }+ _useConpty: boolean+ _useConptyDll: boolean+ _pty: number+ _ptyNative: PrivateConptyNative+ _inSocket: Socket+ _outSocket: Socket+ _conoutSocketWorker: {+ constructor: { name?: unknown }+ _worker: { terminate: () => unknown }+ _drainTimeout?: ReturnType<typeof setTimeout>+ _isDisposed: boolean+ }+}++type PrivateWindowsTerminal = {+ constructor: { name?: unknown }+ _pty: number+ _isReady: boolean+ _deferreds: unknown[]+ _agent: PrivateWindowsPtyAgent+ _close: () => void+}++type CloseState = {+ terminal: PrivateWindowsTerminal+ release?: Promise<void>+}++const closeStates = new WeakMap<object, CloseState>()++function fail(): never {+ // This exception can cross the session-host protocol. Keep executable paths, argv, PIDs and+ // private-property diagnostics out of it; callers may add private local logging separately.+ throw new Error(SAFE_CLOSE_ERROR)+}++function isRecord(value: unknown): value is Record<PropertyKey, unknown> {+ return typeof value === 'object' && value !== null+}++let installedNodePtyVersion: string | undefined++function nodePtyVersion(): string {+ if (installedNodePtyVersion !== undefined) return installedNodePtyVersion+ try {+ const packagePath = require.resolve('node-pty/package.json')+ const parsed = JSON.parse(fs.readFileSync(packagePath, 'utf8')) as unknown+ if (!isRecord(parsed) || typeof parsed.version !== 'string') fail()+ installedNodePtyVersion = parsed.version+ return parsed.version+ } catch {+ fail()+ }+}++function hasNativeFunction(+ native: Record<PropertyKey, unknown>,+ name: keyof PrivateConptyNative+): boolean {+ return typeof native[name] === 'function'+}++function exactWindowsConpty(proc: IPty): PrivateWindowsTerminal {+ if (process.platform !== 'win32') fail()+ if (nodePtyVersion() !== SUPPORTED_WINDOWS_CONPTY_NODE_PTY_VERSION) fail()+ if (!isRecord(proc) || proc.constructor?.name !== 'WindowsTerminal') fail()++ const agent = proc._agent+ if (!isRecord(agent) || agent.constructor?.name !== 'WindowsPtyAgent') fail()+ if (agent._useConpty !== true || typeof agent._useConptyDll !== 'boolean') fail()+ if (typeof agent._pty !== 'number' || !Number.isSafeInteger(agent._pty) || agent._pty <= 0) {+ fail()+ }+ if (+ typeof proc._pty !== 'number' ||+ !Number.isSafeInteger(proc._pty) ||+ proc._pty !== agent._pty+ ) {+ fail()+ }+ if (typeof proc._isReady !== 'boolean' || !Array.isArray(proc._deferreds)) fail()++ const native = agent._ptyNative+ if (!isRecord(native)) fail()+ if (+ !hasNativeFunction(native, 'startProcess') ||+ !hasNativeFunction(native, 'connect') ||+ !hasNativeFunction(native, 'resize') ||+ !hasNativeFunction(native, 'clear') ||+ !hasNativeFunction(native, 'kill')+ ) {+ fail()+ }+ if (+ !isRecord(agent._inSocket) ||+ typeof agent._inSocket.destroy !== 'function' ||+ typeof agent._inSocket.once !== 'function' ||+ !isRecord(agent._outSocket) ||+ typeof agent._outSocket.destroy !== 'function' ||+ typeof agent._outSocket.once !== 'function'+ ) {+ fail()+ }+ const conout = agent._conoutSocketWorker+ if (+ !isRecord(conout) ||+ conout.constructor?.name !== 'ConoutConnection' ||+ typeof conout._isDisposed !== 'boolean' ||+ !isRecord(conout._worker) ||+ typeof conout._worker.terminate !== 'function' ||+ typeof proc._close !== 'function'+ ) {+ fail()+ }+ return proc as unknown as PrivateWindowsTerminal+}++/**+ * Close one node-pty 1.1.0 Windows pseudoconsole by its native PTY id, even before the first+ * output byte. This deliberately bypasses `WindowsTerminal.kill()` (which is deferred until first+ * data) and `WindowsPtyAgent.kill()` (which starts asynchronous console-process enumeration).+ *+ * The repository's version-pinned native patch changes `conpty.kill` to return `true` only after+ * it found this exact baton and synchronously called ClosePseudoConsole for its HPCON. `undefined`+ * is the stock 1.1.0 behavior and is rejected: it cannot distinguish a close from the shell-exit+ * race that already deleted the baton. The caller must still wait for the exact recorded process+ * identities to disappear before acknowledging a destructive operation.+ */+export function closeExactWindowsConpty(proc: IPty): void {+ const terminal = exactWindowsConpty(proc)+ if (closeStates.has(terminal as unknown as object)) fail()+ const agent = terminal._agent+ let closed: unknown+ try {+ closed = agent._ptyNative.kill.call(+ agent._ptyNative,+ agent._pty,+ agent._useConptyDll+ )+ } catch {+ fail()+ }+ if (closed !== true) fail()+ closeStates.set(terminal as unknown as object, { terminal })+}++function socketClosed(socket: Socket): Promise<void> {+ if (socket.destroyed) return Promise.resolve()+ return new Promise<void>((resolve, reject) => {+ const onClose = (): void => {+ cleanup()+ resolve()+ }+ const onError = (): void => {+ cleanup()+ reject(new Error(SAFE_CLOSE_ERROR))+ }+ const cleanup = (): void => {+ socket.removeListener('close', onClose)+ socket.removeListener('error', onError)+ }+ socket.once('close', onClose)+ socket.once('error', onError)+ try {+ socket.destroy()+ } catch {+ cleanup()+ reject(new Error(SAFE_CLOSE_ERROR))+ }+ })+}++function isPromiseLike(value: unknown): value is PromiseLike<unknown> {+ return isRecord(value) && typeof value.then === 'function'+}++/**+ * Finish the exact ConPTY's private transport teardown after the caller has independently proven+ * the shell process tree absent. The output socket is destroyed last because its `close` event is+ * node-pty's public `onExit`; by then the input handle and the exact ConoutConnection worker are+ * already gone, so a host cannot acknowledge through `onExit` while those resources remain live.+ */+export function releaseExactWindowsConpty(proc: IPty): Promise<void> {+ const state = closeStates.get(proc as unknown as object)+ if (!state || state.terminal !== (proc as unknown as PrivateWindowsTerminal)) {+ return Promise.reject(new Error(SAFE_CLOSE_ERROR))+ }+ if (state.release) return state.release++ state.release = (async () => {+ const terminal = state.terminal+ const agent = terminal._agent+ const conout = agent._conoutSocketWorker+ try {+ terminal._close()+ await socketClosed(agent._inSocket)++ if (conout._drainTimeout !== undefined) {+ clearTimeout(conout._drainTimeout)+ conout._drainTimeout = undefined+ }+ conout._isDisposed = true+ const terminated = conout._worker.terminate()+ if (!isPromiseLike(terminated)) fail()+ await terminated++ // This is the public exit-event commit point. Keep it after every awaited private cleanup.+ await socketClosed(agent._outSocket)+ } catch {+ fail()+ }+ })()+ return state.release+}diff --git a/src/session-host/windows-process-tree.test.ts b/src/session-host/windows-process-tree.test.tsnew file mode 100644index 000000000..c8db221ec--- /dev/null+++ b/src/session-host/windows-process-tree.test.ts@@ -0,0 +1,138 @@+import { spawn } from 'child_process'+import { describe, expect, it } from 'vitest'+import {+ WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS,+ terminateWindowsProcessTree+} from './windows-process-tree'++/**+ * The Windows kill path had no test of its own, on the platform this app ships to.+ *+ * It is what `host.ts` actually calls to end a session — node-pty defers WindowsTerminal.kill()+ * until a terminal's first output, so a silent process would otherwise stay alive forever — and its+ * doc comment makes a strong safety claim: "success is acknowledged only after the root PID is also+ * observed absent. A timeout is always rejection." Nothing verified that. The one test that reaches+ * this path (host-routing's kill-acknowledgement case) is skipped on win32 precisely because it+ * fakes node-pty, which the Windows branch never calls.+ *+ * These use a REAL child process, because the claim being checked is about a real process actually+ * being gone. A fake cannot disagree with the implementation about that.+ */+describe('terminateWindowsProcessTree', () => {+ const alive = (pid: number): boolean => {+ try {+ process.kill(pid, 0)+ return true+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'+ }+ }++ // `ping.exe` directly, never `cmd.exe /c ping`. The wrapper is what the first version of this+ // file used, and `child.kill()` then ends cmd while leaving ping running for its full 30 seconds+ // — measured, not assumed: one orphan survived every kill. That is precisely the failure the+ // function under test exists to prevent, so a test for it that leaks processes is worse than+ // funny; a suite that spawns real shells elsewhere then competes with the litter. }++ it('refuses to run at all off Windows, rather than pretending to have killed something', async () => {+ if (process.platform === 'win32') return+ await expect(terminateWindowsProcessTree(999_999)).rejects.toThrow(/unavailable on this platform/)+ })++ it('refuses an invalid pid and its own process, before touching taskkill', async () => {+ // These guards run before the platform-specific work, so they hold everywhere and are the+ // cheapest place to prove the helper cannot be aimed at the host itself.+ await expect(terminateWindowsProcessTree(process.pid)).rejects.toThrow(/Refusing to terminate/)+ await expect(terminateWindowsProcessTree(0)).rejects.toThrow(/Refusing to terminate/)+ await expect(terminateWindowsProcessTree(-1)).rejects.toThrow(/Refusing to terminate/)+ await expect(terminateWindowsProcessTree(1.5)).rejects.toThrow(/Refusing to terminate/)+ })++ it.skipIf(process.platform !== 'win32')(+ 'kills a real silent process and reports only after it is gone',+ async () => {+ // A process that produces no early output: `ping -n` just waits, which is the exact shape+ // this helper exists for, because node-pty defers its own kill() until a first write.+ const child = spawn('ping.exe', ['-n', '30', '127.0.0.1'], {+ windowsHide: true,+ stdio: 'ignore'+ })+ const pid = child.pid+ expect(pid).toBeTypeOf('number')+ expect(alive(pid as number)).toBe(true)++ await terminateWindowsProcessTree(pid as number)+ expect(alive(pid as number)).toBe(false)+ },+ WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS + 20_000+ )++ it.skipIf(process.platform !== 'win32')(+ 'does not report success until the pid is actually observed absent',+ async () => {+ // The claim the source makes, now actually held to it. The injected probe reports the+ // process alive for the first few polls and only then absent, which is the race the loop+ // exists for and which cannot be produced by killing a real child — taskkill /F has already+ // finished by the time the promise would settle.+ const child = spawn('ping.exe', ['-n', '30', '127.0.0.1'], {+ windowsHide: true,+ stdio: 'ignore'+ })+ const pid = child.pid as number+ let polls = 0+ const laggingProbe = (): boolean => {+ polls += 1+ return polls <= 4+ }++ const started = Date.now()+ await terminateWindowsProcessTree(pid, laggingProbe)+ const waited = Date.now() - started++ // It polled until the probe said absent, rather than resolving on taskkill's return.+ expect(polls).toBeGreaterThan(4)+ // Four extra polls at the 25 ms cadence cannot have taken no time at all.+ expect(waited).toBeGreaterThanOrEqual(80)+ },+ WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS + 20_000+ )++ it.skipIf(process.platform !== 'win32')(+ 'rejects when the tree never goes away, rather than acknowledging a kill it cannot prove',+ async () => {+ // A timeout is always rejection — the other half of the same sentence in the source.+ const child = spawn('ping.exe', ['-n', '30', '127.0.0.1'], {+ windowsHide: true,+ stdio: 'ignore'+ })+ const pid = child.pid as number+ try {+ await expect(terminateWindowsProcessTree(pid, () => true)).rejects.toThrow(+ /is still alive after/+ )+ } finally {+ child.kill()+ }+ },+ WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS + 30_000+ )++ // The absence poll is now genuinely guarded: neutering the loop to `while (false)` turns the two+ // tests above red. It was not, before the `isAlive` seam existed — a test written against a real+ // child passed either way, because `taskkill /F` has already finished by the time the promise+ // settles. That is the whole reason the seam is there, and why it was worth a production+ // parameter that production never passes: without it, this file could only ever have documented+ // the gap instead of closing it.+ it.skipIf(process.platform !== 'win32')(+ 'rejects for a pid that does not exist rather than reporting a kill it never made',+ async () => {+ // taskkill fails for an unknown pid, and the helper never converts an execution error into+ // success — the comment in the source says so, and this is what holds it to it.+ const child = spawn('cmd.exe', ['/c', 'exit'], { windowsHide: true, stdio: 'ignore' })+ const pid = child.pid as number+ await new Promise<void>((resolve) => child.once('exit', () => resolve()))+ await expect(terminateWindowsProcessTree(pid)).rejects.toThrow(/termination failed for PID/)+ },+ 30_000+ )+})diff --git a/src/session-host/windows-process-tree.ts b/src/session-host/windows-process-tree.tsnew file mode 100644index 000000000..951f711fa--- /dev/null+++ b/src/session-host/windows-process-tree.ts@@ -0,0 +1,88 @@+import { execFile } from 'child_process'+import fs from 'fs'+import path from 'path'++export const WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS = 8_000++function processExists(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'+ }+}++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}++/**+ * Force-terminate a Windows process tree independently of node-pty's `WindowsTerminal.kill()`.+ * node-pty defers that method until its first output marks the terminal ready, so a valid silent+ * process can otherwise remain alive forever. `taskkill /T /F` owns tree traversal; success is+ * acknowledged only after the root PID is also observed absent. A timeout is always rejection.+ * `isAlive` is a parameter only because a spy cannot be attached to an ESM namespace export,+ * so a test has no other way to hold this to its own claim: that success is reported only after+ * the root pid is observed absent. Production never passes it. Without the seam the poll loop can+ * be deleted outright and every test stays green, because `taskkill /F` on a plain child has+ * already finished by the time the promise settles — the loop earns its keep only in the race+ * where taskkill returns before the kernel reaps the tree, and that race cannot be forced from+ * outside. Injecting it rather than exporting a mutable hook keeps the seam typed and visible,+ * the same trade `renameAtomicSync` makes in core/fs-atomic.ts and for the same reason.+ */+export async function terminateWindowsProcessTree(+ pid: number,+ isAlive: (candidate: number) => boolean = processExists+): Promise<void> {+ // The pid guards come BEFORE the platform check so they hold on every platform — the test+ // proves on POSIX that this helper can never be aimed at the host process, which a+ // platform-first ordering would leave unprovable anywhere but Windows.+ if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid) {+ throw new Error(`Refusing to terminate invalid Windows process id ${String(pid)}`)+ }+ if (process.platform !== 'win32') {+ throw new Error('Windows process-tree termination is unavailable on this platform')+ }++ const systemRoot = process.env.SystemRoot+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) {+ throw new Error('Cannot resolve the trusted Windows SystemRoot')+ }+ const taskkillPath = path.win32.join(systemRoot, 'System32', 'taskkill.exe')+ if (!path.win32.isAbsolute(taskkillPath) || !fs.existsSync(taskkillPath)) {+ throw new Error('Cannot resolve the trusted Windows taskkill executable')+ }++ const deadline = Date.now() + WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS+ const taskkillError = await new Promise<Error | null>((resolve) => {+ execFile(+ taskkillPath,+ ['/PID', String(pid), '/T', '/F'],+ {+ windowsHide: true,+ timeout: WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS,+ maxBuffer: 64 * 1024+ },+ (error) => resolve(error)+ )+ })++ // Do not turn root absence into proof that `/T` killed every descendant: taskkill can remove+ // the root and still fail on a protected child. A concurrent natural exit is resolved by the+ // host's real onExit path; this helper never converts an execution error into success.+ if (taskkillError) {+ throw new Error(+ `Windows process-tree termination failed for PID ${pid}: ${taskkillError.message}`+ )+ }+ while (isAlive(pid)) {+ if (Date.now() >= deadline) {+ throw new Error(+ `Windows process tree for PID ${pid} is still alive after ` ++ `${WINDOWS_PROCESS_TREE_TERMINATION_TIMEOUT_MS}ms`+ )+ }+ await delay(25)+ }+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex e0827ec10..d6ddbebe3 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -12,6 +12,8 @@ export const IPC = {* on every canvas, so co-viewers get the restart notice (`ptyRecycled`) instead of the* permanent, un-respawnable `ptyClosed`. */ptyRecycle: 'pty:recycle',+ /** Desktop-only awaited recycle path used after an explicit destructive-action confirmation. */+ ptyRecycleConfirmed: 'pty:recycle-confirmed',ptyGenerateName: 'pty:generate-name',ptyGenerateGroupName: 'pty:generate-group-name',ptyCapture: 'pty:capture',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 6e0059745..609989b7b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -15,6 +15,65 @@ import type {ModelGatewaySettings} from './agents/model-gateway'+/** Profile-switch replacement intent. The trusted core validates and re-resolves it before teardown. */+export interface PtyRecycleTarget {+ profileId: string+ cwd: string+}++/**+ * A shell-independent request to start or resume an agent.+ *+ * The renderer deliberately does not turn this into a command line: the trusted core validates+ * the semantic fields, resolves the current machine-local agent configuration, and encodes the+ * launch for the concrete shell that owns the live session. In particular, `auto` is not a shell+ * dialect until immediately before a Windows profile is spawned.+ */+export type AgentLaunchIntent =+ | {+ kind: 'agent'+ action: 'start'+ agentId: AgentId+ /** Initial prompt for a new conversation. The core rejects control-bearing values. */+ prompt?: string+ /** Already version/policy-gated starting mode. The core re-validates it at execution. */+ permissionMode?: AgentPermissionMode+ /** Optional provider id minted for this first launch; never reused as a resume id. */+ newSessionId?: string+ }+ | {+ kind: 'agent'+ action: 'resume'+ agentId: AgentId+ /** Existing provider id. Required for resume and runtime-validated by the trusted core. */+ sessionId: string+ /** Starting mode for the reconstructed CLI, where the selected agent supports it. */+ permissionMode?: AgentPermissionMode+ }++/**+ * One locally-authorized launch held behind canvas dependencies.+ *+ * `shell-command` is the explicit `open-terminal --cmd` compatibility path. It is opaque shell+ * source, not something the app can safely parse back into argv. The whole PendingLaunch is+ * machine-local and must be stripped from shared project files, exports, and inbound mutations.+ */+export type TerminalLaunchIntent =+ | AgentLaunchIntent+ | { kind: 'shell-command'; command: string }++export type LaunchIntentFailureReason =+ | 'invalid-intent'+ | 'agent-unavailable'+ | 'unsupported-shell'+ | 'session-unavailable'+ | 'delivery-failed'++/** Opaque execution outcome. It must never contain a rendered command, executable, or argv. */+export type LaunchIntentExecutionResult =+ | { ok: true }+ | { ok: false; reason: LaunchIntentFailureReason; message: string }+export interface PtyCreateOptions {shell?: string/** Arguments for `shell` when it is run as the session program (e.g. ssh args). */diff --git a/tsconfig.node.json b/tsconfig.node.jsonindex b0e1807c0..507fbda93 100644--- a/tsconfig.node.json+++ b/tsconfig.node.json@@ -21,6 +21,7 @@"src/preload/**/*","src/shared/**/*","src/core/**/*",- "src/server/**/*"+ "src/server/**/*",+ "src/session-host/**/*"]}diff --git a/vitest.config.ts b/vitest.config.tsindex acd805256..a3fa8827d 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -11,6 +11,7 @@ export default defineConfig({// .tsx too: component tests (jsdom via a per-file pragma; everything else stays node).'src/renderer/**/*.test.{ts,tsx}','src/server/**/*.test.ts',+ 'src/session-host/**/*.test.ts','test/server/**/*.test.ts','test/remote/**/*.test.ts',// Opt-in end-to-end tests against a real sshd in Docker. They self-skip unless