Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(windows): run terminals on node-pty's bundled ConPTY so fullscreen TUIs scroll
review51e710e890ca
diff --git a/CLAUDE.md b/CLAUDE.mdindex d8c90ca83..17c8262ec 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -52,6 +52,13 @@ means — and what you may assume when writing a feature — is three tiers, not`gateEntriesForPlatform` marks those entries unsupported with `RUN_WINDOWS_REASON` (browserconfigs and browser-only compounds still run), and the add menu / Dock disable the row (the palette hides it)from the core's own platform (`useCoreIsWindows`). A pwsh launcher is the follow-up.+- **Windows terminals run on node-pty's BUNDLED ConPTY when it is installed**+ (`windowsConptySpawnOptions`, `src/core/windows-conpty-dll.ts`, spread into both `pty.spawn`+ sites). Windows 10's inbox ConPTY swallows mouse-tracking and alternate-screen modes, so a+ fullscreen TUI could not be scrolled. The DLL is looked up exactly where node-pty's native loader+ looks (beside the loaded `conpty.node`), restaged after `electron-rebuild` wipes `build/`+ (`scripts/stage-conpty-dll.mjs`), and missing ⇒ the inbox ConPTY. Details + device checklist:+ docs/windows-session-host.md, "Which ConPTY".- **New code is platform-neutral by default.** Do not hardcode POSIX assumptions. Publish filesthrough `renameAtomic`/`writeFileAtomic` (`src/core/fs-atomic.ts`), not a bare `fs.rename` — theguard test (`fs-atomic.guard.test.ts`) enforces this. Resolve path separators / absolute-pathdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4d3135114..3a8beda69 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -30,6 +30,9 @@ Run `npm run rebuild`. node-pty 1.1.0 leaks a pty device per spawn on macOSconhost alive per killed session (its exit thread deletes the ConPTY baton without closing theHPCON); we patch both sources before `electron-rebuild` compiles them, and that test guards thepatches surviving upgrades.+After the rebuild, `scripts/stage-conpty-dll.mjs` copies node-pty's bundled `conpty.dll` ++`OpenConsole.exe` back beside `build/Release/conpty.node` on Windows (the rebuild deletes them);+without them Windows terminals fall back to the inbox ConPTY, where a fullscreen TUI cannot scroll.## Where code goesdiff --git a/docs/windows-session-host.md b/docs/windows-session-host.mdindex 25cebacfb..99a12334a 100644--- a/docs/windows-session-host.md+++ b/docs/windows-session-host.md@@ -276,6 +276,51 @@ Because all of this rides inside the `screen` string itself (as real escape sequrenderer writes verbatim), **`PtyCreateResult.coAttachMouse` is never set for a session-hostsession** — there is nothing left for that separate flag to carry.+### Which ConPTY: node-pty's bundled one, inbox as the fallback++The restoration above only has something to restore if the modes ever reach an emulator. On+**Windows 10** (the 19041 servicing line, 22H2 = build 19045 included) the OS inbox ConPTY does not+pass the DEC private mouse-tracking modes (`?1000h`/`?1002h`/`?1006h`) or the alternate screen+(`?1049h`) through to the terminal on its far side: it consumes them and repaints the screen in+place. So neither the host's headless emulator nor the renderer's xterm ever enters mouse-tracking+mode, xterm never forwards a wheel event to the pty, and — because ConPTY repaints rather than+scrolls — xterm's own scrollback stays empty. In a full-screen TUI (Claude Code with+`/tui fullscreen`) the wheel and the trackpad do nothing and earlier conversation is unreachable.+The canvas is not involved: the terminal container is already `nodrag nowheel`.++node-pty 1.1.0 ships a newer ConPTY (`conpty.dll` + `OpenConsole.exe`, from the Windows Terminal+project) and uses it instead of the OS one when spawned with `useConptyDll: true`. Both spawn sites+— the session host (`src/session-host/session.ts`) and the PtyManager's direct `pty.spawn`+(`src/core/pty-manager.ts`) — spread ONE helper, `windowsConptySpawnOptions()`+(`src/core/windows-conpty-dll.ts`):++- **Where node-pty looks, exactly.** Not `third_party/`: the native `LoadConptyDll`+ (`src/win/conpty.cc`) loads `<directory of the loaded conpty.node>\conpty\conpty.dll`, and+ `conpty.node` is the first one `loadNativeModule` (`lib/utils.js`) finds among `build/Release`,+ `build/Debug`, `prebuilds/<platform>-<arch>`, each tried relative to `lib/..` then `lib/.`. The+ helper walks the same list, stops at the first `conpty.node`, and answers `{ useConptyDll: true }`+ only when BOTH files sit in its `conpty\` subfolder. A DLL missing there is a THROWN spawn in+ node-pty ("Cannot find conpty.dll at …"), not a fallback, which is why the helper checks first.+- **Fail-open.** Any other platform, a missing file, a resolve or fs error ⇒ `{}` — the inbox+ ConPTY, and spawn options byte-identical to before. It never throws. Off Windows it touches no+ file at all.+- **The files must be STAGED, because our build deletes them.** node-pty's own post-install copies+ `third_party/conpty/<version>/win10-<arch>/` into `build/Release/conpty/`, but our postinstall then+ runs `electron-rebuild -f`, i.e. `node-gyp rebuild`, whose `clean` removes `build/`. The rebuilt+ `build/Release/conpty.node` is the one node-pty loads, so `scripts/stage-conpty-dll.mjs` runs after+ electron-rebuild (postinstall and `npm run rebuild`) and copies the two files back beside it+ (Windows only; x64 and arm64 — the arches node-pty bundles). Without it every Windows build would+ quietly run on the inbox ConPTY.+- **Packaging.** The main process gets them through `asarUnpack` (`**/node_modules/node-pty/**`).+ The session host's own node-pty copy (`build.win.extraResources`) is an allowlist, and now names+ `build/Release/conpty/conpty.dll` and `build/Release/conpty/OpenConsole.exe`; the staged host+ runtime copies `resources/session-host/**` recursively, so they reach it unchanged.+- The native close path already handles both values: the Windows leg of+ `scripts/patch-node-pty.mjs` patches the `useConptyDll` branches, and+ `src/session-host/windows-conpty.ts` reads `_useConptyDll` instead of assuming one.++Unverified on a device (no Windows machine here): see "ConPTY selection — device checklist" below.+### Output ordering, flow ownership, and geometry`@xterm/headless` applies `Terminal.write()` asynchronously. A PTY data callback therefore does@@ -1051,6 +1096,34 @@ P5. **Eco on Windows**, with pwsh and with cmd as the default shell: idle → `/shell alone. Repeat with a native `claude.exe` and an npm `claude.cmd`; a node with an MCP child(`node` → `cmd /c` → `node`) is not misread as a shell; a `blocked` node is never exited.+### ConPTY selection (bundled `conpty.dll`) — device checklist++Written and unit-tested on Linux; nothing below has run on Windows yet. Run each on **Windows 10+22H2 (19045)** and on **Windows 11**, packaged build:++C1. **Which ConPTY ran.** Task Manager → Details while a terminal is open: an `OpenConsole.exe`+ whose path is under the install (main process) or `%LOCALAPPDATA%\nodeterm\session-host\…`+ (session host), and no inbox `conhost.exe` for that terminal.+C2. **Fullscreen Claude wheel scroll, in a canvas node.** Claude Code with `/tui fullscreen`, a long+ conversation: mouse wheel and trackpad scroll the conversation; earlier turns are reachable.+C3. **The same in the kanban card modal** (its co-attached viewer), including right after opening+ the modal without pressing a key.+C4. **vim / htop mouse.** Click to place the cursor in vim with `:set mouse=a`; click a process in+ htop (or another mouse-aware TUI); wheel scrolls inside them.+C5. **Plain shell scrollback still works.** In pwsh and cmd, run something that prints a few+ hundred lines: the wheel scrolls xterm's own history as before, and Shift-drag selection copies.+C6. **Warm reattach after an app restart.** Quit and relaunch with a fullscreen Claude and a vim+ open: both reattach warm (`attach (warm)` in `session-host.log`) and the wheel still works+ without a keystroke (mouse modes restored from the host's serialized screen).+C7. **Teardown leaves no `OpenConsole.exe`.** Close a node with ×, End session, an Eco exit cycle,+ and quitting the session host for an update: after each, no orphan `OpenConsole.exe` remains in+ Task Manager, and `conpty.kill` still reports positive proof (no `could not safely close` line).+C8. **Fallback.** Delete `build\Release\conpty\conpty.dll` from a packaged install's session-host+ copy: terminals still open (inbox ConPTY), they just lose C2.+C9. **P4 with `useConptyDll`.** The per-session session-host cost of P4 above, measured again with+ the bundled ConPTY — `OpenConsole.exe` replaces `conhost.exe`, and the memory panel's host line+ must still count it (P3's parentage check, for `OpenConsole.exe`).+### Earlier itemsThe real Windows x64 installer must still be exercised through the required cheap headless route:diff --git a/package.json b/package.jsonindex 7b779f8a8..b82fcecde 100644--- a/package.json+++ b/package.json@@ -22,7 +22,7 @@"test": "vitest run","test:unit": "vitest run test/remote","diagnose:agents": "node scripts/agent-session-scan.mjs",- "rebuild": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper",+ "rebuild": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper && node scripts/stage-conpty-dll.mjs","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 --external:ssh2 --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",@@ -34,7 +34,7 @@"dist:win": "npm run make-icon && npm run build && electron-builder --win --x64 --publish never -c.extraMetadata.nodeTermUpdates=disabled","dist:win:release": "npm run make-icon && npm run build && electron-builder --win --x64 --publish never -c.extraMetadata.nodeTermUpdates=manual","release": "npm run make-icon && npm run build && sh -c 'electron-builder --mac --arm64 --x64 --publish never; s=$?; npm run rebuild; exit $s'",- "postinstall": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper"+ "postinstall": "node scripts/patch-node-pty.mjs && electron-rebuild -f -w node-pty,smart-whisper && node scripts/stage-conpty-dll.mjs"},"build": {"appId": "com.nodeterm.app",@@ -150,7 +150,9 @@"!lib/**/*.test.js","build/Release/*.node","build/Release/*.exe",- "build/Release/*.dll"+ "build/Release/*.dll",+ "build/Release/conpty/conpty.dll",+ "build/Release/conpty/OpenConsole.exe"]}],diff --git a/scripts/stage-conpty-dll.mjs b/scripts/stage-conpty-dll.mjsnew file mode 100644index 000000000..20dcf4f5e--- /dev/null+++ b/scripts/stage-conpty-dll.mjs@@ -0,0 +1,69 @@+#!/usr/bin/env node+/**+ * stage-conpty-dll.mjs — put node-pty's bundled ConPTY (`conpty.dll` + `OpenConsole.exe`) beside+ * the electron-rebuilt `conpty.node`, on Windows only.+ *+ * WHY: node-pty's native `LoadConptyDll` (src/win/conpty.cc) looks for+ * `<directory of the loaded conpty.node>\conpty\conpty.dll` when spawned with+ * `useConptyDll: true`. node-pty's own post-install.js copies the files from+ * `third_party/conpty/<version>/win10-<arch>/` into `build/Release/conpty/` — but our postinstall+ * then runs `electron-rebuild -f`, which is `node-gyp rebuild`, whose `clean` step deletes the+ * whole `build/` directory. The rebuilt `build/Release/conpty.node` is the one node-pty loads+ * (build/Release is tried before prebuilds/), so without this step the sidecar is gone and+ * `src/core/windows-conpty-dll.ts` falls back to the OS inbox ConPTY — which on Windows 10 does+ * not pass mouse-tracking / alternate-screen modes through (see docs/windows-session-host.md).+ *+ * Runs AFTER electron-rebuild (postinstall + rebuild). A no-op off Windows, when the rebuilt module+ * is absent, or when the arch has no bundled ConPTY. Never fails the install: the runtime helper+ * already degrades to the inbox ConPTY when the files are missing.+ */+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++export const CONPTY_FILES = ['conpty.dll', 'OpenConsole.exe']+const SUPPORTED_ARCH = ['x64', 'arm64']++/**+ * @param {{ ptyDir: string, platform?: string, arch?: string, fsImpl?: typeof fs }} opts+ * @returns {{ staged: boolean, reason: string }}+ */+export function stageConptyDll({ ptyDir, platform = process.platform, arch, fsImpl = fs }) {+ if (platform !== 'win32') return { staged: false, reason: 'not Windows' }+ const windowsArch = arch ?? process.env.npm_config_arch ?? process.arch+ if (!SUPPORTED_ARCH.includes(windowsArch)) {+ return { staged: false, reason: `no bundled ConPTY for ${windowsArch}` }+ }+ const releaseDir = path.join(ptyDir, 'build', 'Release')+ if (!fsImpl.existsSync(path.join(releaseDir, 'conpty.node'))) {+ return { staged: false, reason: 'build/Release/conpty.node not built' }+ }+ const conptyRoot = path.join(ptyDir, 'third_party', 'conpty')+ if (!fsImpl.existsSync(conptyRoot)) return { staged: false, reason: 'third_party/conpty missing' }+ // node-pty's own post-install takes the first (and only) version folder; do the same.+ const versionFolder = fsImpl.readdirSync(conptyRoot).sort()[0]+ if (!versionFolder) return { staged: false, reason: 'third_party/conpty is empty' }+ const sourceDir = path.join(conptyRoot, versionFolder, `win10-${windowsArch}`)+ const destDir = path.join(releaseDir, 'conpty')+ for (const f of CONPTY_FILES) {+ if (!fsImpl.existsSync(path.join(sourceDir, f))) {+ return { staged: false, reason: `missing ${path.join(sourceDir, f)}` }+ }+ }+ fsImpl.mkdirSync(destDir, { recursive: true })+ for (const f of CONPTY_FILES) fsImpl.copyFileSync(path.join(sourceDir, f), path.join(destDir, f))+ return { staged: true, reason: `copied ${versionFolder}/win10-${windowsArch}` }+}++const invokedDirectly =+ process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)+if (invokedDirectly) {+ const ptyDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'node_modules', 'node-pty')+ try {+ const r = stageConptyDll({ ptyDir })+ console.log(`[stage-conpty-dll] ${r.staged ? 'staged' : 'skipped'}: ${r.reason}`)+ } catch (err) {+ // Never fail the install: the runtime falls back to the inbox ConPTY.+ console.warn(`[stage-conpty-dll] could not stage the bundled ConPTY: ${err && err.message}`)+ }+}diff --git a/scripts/stage-conpty-dll.test.ts b/scripts/stage-conpty-dll.test.tsnew file mode 100644index 000000000..4016d0290--- /dev/null+++ b/scripts/stage-conpty-dll.test.ts@@ -0,0 +1,71 @@+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'+import { testTmpDir } from '../src/core/test-tmp'+// @ts-expect-error -- plain .mjs build script, no type declarations+import { stageConptyDll } from './stage-conpty-dll.mjs'++const PKG = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8'))++function fakePty(opts: { built?: boolean; arches?: string[] } = {}): string {+ const dir = testTmpDir('nt-stage-conpty-')+ const write = (rel: string): void => {+ const p = path.join(dir, rel)+ fs.mkdirSync(path.dirname(p), { recursive: true })+ fs.writeFileSync(p, rel)+ }+ if (opts.built !== false) write('build/Release/conpty.node')+ for (const arch of opts.arches ?? ['x64', 'arm64']) {+ write(`third_party/conpty/1.23.251008001/win10-${arch}/conpty.dll`)+ write(`third_party/conpty/1.23.251008001/win10-${arch}/OpenConsole.exe`)+ }+ return dir+}++describe('stage-conpty-dll', () => {+ it('copies conpty.dll + OpenConsole.exe beside the rebuilt conpty.node on win32 (where node-pty looks)', () => {+ const dir = fakePty()+ expect(stageConptyDll({ ptyDir: dir, platform: 'win32', arch: 'arm64' }).staged).toBe(true)+ for (const f of ['conpty.dll', 'OpenConsole.exe']) {+ expect(fs.readFileSync(path.join(dir, 'build/Release/conpty', f), 'utf8')).toBe(+ `third_party/conpty/1.23.251008001/win10-arm64/${f}`+ )+ }+ })++ it('is a no-op off Windows, without a built module, or for an arch with no bundled ConPTY', () => {+ const linux = fakePty()+ expect(stageConptyDll({ ptyDir: linux, platform: 'linux', arch: 'x64' }).staged).toBe(false)+ expect(fs.existsSync(path.join(linux, 'build/Release/conpty'))).toBe(false)++ const unbuilt = fakePty({ built: false })+ expect(stageConptyDll({ ptyDir: unbuilt, platform: 'win32', arch: 'x64' }).staged).toBe(false)++ const ia32 = fakePty()+ expect(stageConptyDll({ ptyDir: ia32, platform: 'win32', arch: 'ia32' }).staged).toBe(false)+ })++ it('stages nothing when the arch folder is incomplete', () => {+ const dir = fakePty({ arches: ['arm64'] })+ expect(stageConptyDll({ ptyDir: dir, platform: 'win32', arch: 'x64' }).staged).toBe(false)+ expect(fs.existsSync(path.join(dir, 'build/Release/conpty'))).toBe(false)+ })++ it('runs AFTER electron-rebuild in both postinstall and rebuild (node-gyp rebuild wipes build/)', () => {+ for (const name of ['postinstall', 'rebuild']) {+ const cmd: string = PKG.scripts[name]+ const rebuild = cmd.indexOf('electron-rebuild')+ const stage = cmd.indexOf('node scripts/stage-conpty-dll.mjs')+ expect(rebuild, name).toBeGreaterThanOrEqual(0)+ expect(stage, `${name} must stage the bundled ConPTY`).toBeGreaterThan(rebuild)+ }+ })++ it("ships the staged ConPTY in the Windows session host's node-pty copy", () => {+ const resources: Array<{ from: string; to: string; filter?: string[] }> = PKG.build.win.extraResources+ const nodePty = resources.find((r) => r.to === 'session-host/node_modules/node-pty')+ expect(nodePty?.filter).toEqual(+ expect.arrayContaining(['build/Release/conpty/conpty.dll', 'build/Release/conpty/OpenConsole.exe'])+ )+ })+})diff --git a/src/core/pty-conpty-spawn.test.ts b/src/core/pty-conpty-spawn.test.tsnew file mode 100644index 000000000..dea0b3222--- /dev/null+++ b/src/core/pty-conpty-spawn.test.ts@@ -0,0 +1,75 @@+/**+ * The PtyManager's direct `pty.spawn` (the non-session-host branch) must spread the Windows ConPTY+ * option the shared helper decides — and add nothing when the helper answers `{}`, which is every+ * non-Windows platform. The helper's own decision is windows-conpty-dll.test.ts.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'+import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'+import { testTmpDir } from './test-tmp'++const spawned: Array<Record<string, unknown>> = []+let helperAnswer: { useConptyDll?: true } = {}++vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('./windows-conpty-dll', () => ({+ windowsConptySpawnOptions: () => helperAnswer+}))+vi.mock('node-pty', () => ({+ spawn: (_file: string, _args: string[], options: Record<string, unknown>) => {+ spawned.push(options)+ return {+ onData: () => {},+ onExit: () => {},+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 4321+ }+ }+}))+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++describe('pty create: ConPTY option on the direct spawn', () => {+ let fake: FakePlatform++ beforeEach(async () => {+ spawned.length = 0+ fake = fakePlatform({ userDataDir: testTmpDir('nodeterm-conpty-spawn-') })+ initPlatform(fake)+ const { PtyManager } = await import('./pty-manager')+ new PtyManager().registerIpc()+ })+ afterEach(() => resetPlatformForTests())++ const create = (persistKey: string) =>+ fake.handlers[IPC.ptyCreate](1, {+ cols: 80,+ rows: 24,+ persistKey,+ cwd: process.cwd()+ } as PtyCreateOptions) as Promise<PtyCreateResult>++ it('passes useConptyDll when the helper asks for the bundled ConPTY', async () => {+ helperAnswer = { useConptyDll: true }+ await create('node-a')+ expect(spawned).toHaveLength(1)+ expect(spawned[0]).toMatchObject({ name: 'xterm-256color', useConptyDll: true })+ })++ it('adds no key at all when the helper answers {}', async () => {+ helperAnswer = {}+ await create('node-b')+ expect(spawned).toHaveLength(1)+ expect('useConptyDll' in spawned[0]).toBe(false)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 054a99d38..f3bb53afc 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -69,6 +69,7 @@ import {import { RemoteSessionIndex, type SessionVerdict } from './remote-ssh/remote-session-index'import { isSshProgram, nativeExecFileAsync, nativeMux, resolveSshProgram, useNativeSsh } from './remote-ssh/native/native-runtime'import { NativeSshPty } from './remote-ssh/native/native-pty'+import { windowsConptySpawnOptions } from './windows-conpty-dll'import { remotePtySpawnGate, type SpawnSlot } from './remote-ssh/pty-spawn-gate'import type { SshConnection } from '../shared/ssh'import { recordPendingRemoteKill, type PendingRemoteKill } from './pending-remote-kills'@@ -4926,7 +4927,10 @@ export class PtyManager {cols: options.cols,rows: options.rows,cwd: spawnCwd,- env+ env,+ // Win32 only: node-pty's bundled ConPTY when present (see windows-conpty-dll.ts);+ // `{}` on every other platform, so the options are byte-identical there.+ ...windowsConptySpawnOptions()})} catch (err) {// node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno.diff --git a/src/core/windows-conpty-dll.test.ts b/src/core/windows-conpty-dll.test.tsnew file mode 100644index 000000000..0d0527c73--- /dev/null+++ b/src/core/windows-conpty-dll.test.ts@@ -0,0 +1,122 @@+import { describe, it, expect } from 'vitest'+import path from 'path'+import { windowsConptySpawnOptions } from './windows-conpty-dll'++const ROOT = path.join('C:', 'app', 'node_modules', 'node-pty')+const rel = (...p: string[]): string => path.join(ROOT, ...p)++function existsFrom(files: string[]): (p: string) => boolean {+ const set = new Set(files.map((f) => path.normalize(f)))+ return (p) => set.has(path.normalize(p))+}++const BUILT = [+ rel('build', 'Release', 'conpty.node'),+ rel('build', 'Release', 'conpty', 'conpty.dll'),+ rel('build', 'Release', 'conpty', 'OpenConsole.exe')+]++describe('windowsConptySpawnOptions', () => {+ it('asks for the bundled ConPTY on win32 when conpty.dll AND OpenConsole.exe sit beside the loaded conpty.node', () => {+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'x64',+ nodePtyRoot: () => ROOT,+ exists: existsFrom(BUILT)+ })+ ).toEqual({ useConptyDll: true })+ })++ it('falls back to the inbox ConPTY when either file is missing', () => {+ for (const missing of BUILT.slice(1)) {+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'x64',+ nodePtyRoot: () => ROOT,+ exists: existsFrom(BUILT.filter((f) => f !== missing))+ })+ ).toEqual({})+ }+ })++ it('judges the sidecar of the conpty.node node-pty will LOAD, not a later candidate', () => {+ // build/Release wins in loadNativeModule; a DLL only beside the prebuild would not be found.+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'x64',+ nodePtyRoot: () => ROOT,+ exists: existsFrom([+ rel('build', 'Release', 'conpty.node'),+ rel('prebuilds', 'win32-x64', 'conpty.node'),+ rel('prebuilds', 'win32-x64', 'conpty', 'conpty.dll'),+ rel('prebuilds', 'win32-x64', 'conpty', 'OpenConsole.exe')+ ])+ })+ ).toEqual({})+ })++ it('uses the prebuild for the current arch when nothing was built', () => {+ const prebuilt = (arch: string): string[] => [+ rel('prebuilds', `win32-${arch}`, 'conpty.node'),+ rel('prebuilds', `win32-${arch}`, 'conpty', 'conpty.dll'),+ rel('prebuilds', `win32-${arch}`, 'conpty', 'OpenConsole.exe')+ ]+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'arm64',+ nodePtyRoot: () => ROOT,+ exists: existsFrom(prebuilt('arm64'))+ })+ ).toEqual({ useConptyDll: true })+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'arm64',+ nodePtyRoot: () => ROOT,+ exists: existsFrom(prebuilt('x64'))+ })+ ).toEqual({})+ })++ it('is {} on linux and darwin without touching the filesystem', () => {+ for (const platform of ['linux', 'darwin'] as const) {+ expect(+ windowsConptySpawnOptions({+ platform,+ nodePtyRoot: () => {+ throw new Error('must not resolve')+ },+ exists: () => {+ throw new Error('must not stat')+ }+ })+ ).toEqual({})+ }+ })++ it('never throws: an fs or resolve failure is the inbox ConPTY', () => {+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'x64',+ nodePtyRoot: () => ROOT,+ exists: () => {+ throw new Error('EACCES')+ }+ })+ ).toEqual({})+ expect(+ windowsConptySpawnOptions({+ platform: 'win32',+ arch: 'x64',+ nodePtyRoot: () => {+ throw new Error('Cannot find module')+ }+ })+ ).toEqual({})+ })+})diff --git a/src/core/windows-conpty-dll.ts b/src/core/windows-conpty-dll.tsnew file mode 100644index 000000000..ea7f66bd3--- /dev/null+++ b/src/core/windows-conpty-dll.ts@@ -0,0 +1,63 @@+import fs from 'fs'+import path from 'path'++/**+ * Which ConPTY a Windows terminal spawns on: the node-pty-BUNDLED one, when it is actually there.+ *+ * WHY: the inbox ConPTY of Windows 10 (the 19041 servicing line, 22H2 = 19045 included) does not+ * pass the DEC private mouse-tracking modes (?1000/?1002/?1006) or the alternate screen (?1049)+ * through to the terminal on the other end. xterm.js therefore never enters mouse-tracking mode,+ * never forwards a wheel event to the pty, and — because ConPTY repaints in place — has no+ * scrollback of its own either: in a full-screen TUI (Claude Code's `/tui fullscreen`) the wheel+ * does nothing and earlier conversation is unreachable. node-pty 1.1.0 ships a newer ConPTY+ * (`conpty.dll` + `OpenConsole.exe`) that is used instead of the OS one with `useConptyDll: true`.+ *+ * WHERE node-pty looks: NOT in `third_party/`. The native `LoadConptyDll` (src/win/conpty.cc)+ * resolves `<directory of the loaded conpty.node>\conpty\conpty.dll`, and `conpty.node` is the+ * first one `loadNativeModule` (lib/utils.js) finds among `build/Release`, `build/Debug`,+ * `prebuilds/<platform>-<arch>`, each tried relative to `lib/..` and then `lib/.`. A missing DLL+ * there is a THROWN spawn, not a fallback — so we only ask for it after seeing both files at that+ * exact place (`scripts/stage-conpty-dll.mjs` puts them next to the electron-rebuilt module).+ *+ * Fail-open by construction: any other platform, any missing file, any fs/resolve error ⇒ `{}`,+ * i.e. the inbox ConPTY and the spawn options byte-identical to before. Never throws.+ */+export interface ConptyDllDeps {+ platform?: NodeJS.Platform+ arch?: string+ /** node-pty's package root (the directory holding its package.json). */+ nodePtyRoot?: () => string+ exists?: (p: string) => boolean+}++const NATIVE_DIRS = (platform: string, arch: string): string[] => [+ 'build/Release',+ 'build/Debug',+ `prebuilds/${platform}-${arch}`+]++export function windowsConptySpawnOptions(deps: ConptyDllDeps = {}): { useConptyDll?: true } {+ const platform = deps.platform ?? process.platform+ if (platform !== 'win32') return {}+ try {+ const arch = deps.arch ?? process.arch+ const exists = deps.exists ?? ((p: string) => fs.existsSync(p))+ const root = (deps.nodePtyRoot ?? (() => path.dirname(require.resolve('node-pty/package.json'))))()+ const libDir = path.join(root, 'lib')+ for (const d of NATIVE_DIRS(platform, arch)) {+ for (const r of ['..', '.']) {+ const dir = path.join(libDir, r, d)+ if (!exists(path.join(dir, 'conpty.node'))) continue+ // This is the conpty.node node-pty will load, so its sidecar is the one that counts — a+ // DLL beside a later candidate would not be found by the native loader.+ const ok =+ exists(path.join(dir, 'conpty', 'conpty.dll')) &&+ exists(path.join(dir, 'conpty', 'OpenConsole.exe'))+ return ok ? { useConptyDll: true } : {}+ }+ }+ return {}+ } catch {+ return {}+ }+}diff --git a/src/session-host/session-conpty-spawn.test.ts b/src/session-host/session-conpty-spawn.test.tsnew file mode 100644index 000000000..53188384b--- /dev/null+++ b/src/session-host/session-conpty-spawn.test.ts@@ -0,0 +1,45 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++/**+ * The session host's real spawn (no `proc` override) must spread the Windows ConPTY option the+ * shared helper decides. node-pty and the helper are mocked: this pins the WIRING, the helper's+ * own decision is windows-conpty-dll.test.ts.+ */+const spawned: Array<Record<string, unknown>> = []+let helperAnswer: { useConptyDll?: true } = {}++vi.mock('node-pty', () => ({+ spawn: (_file: string, _args: string[], options: Record<string, unknown>) => {+ spawned.push(options)+ return { pid: 7, onData: () => {}, onExit: () => {}, write: () => {}, resize: () => {} }+ }+}))+vi.mock('../core/windows-conpty-dll', () => ({+ windowsConptySpawnOptions: () => helperAnswer+}))++const term = { write: async () => {}, serialize: () => '', resize: () => {}, dispose: () => {} }+const SPAWN = { shell: 'pwsh.exe', args: [], cwd: '.', env: {}, cols: 80, rows: 24 }++describe('HostSession spawn: ConPTY option', () => {+ beforeEach(() => {+ spawned.length = 0+ })++ it('passes useConptyDll when the helper asks for the bundled ConPTY', async () => {+ helperAnswer = { useConptyDll: true }+ const { HostSession } = await import('./session')+ new HostSession('s1', SPAWN, 100, { term: term as never })+ expect(spawned).toHaveLength(1)+ expect(spawned[0]).toMatchObject({ name: 'xterm-256color', useConptyDll: true })+ })++ it('adds nothing when the helper answers {} (non-Windows / inbox fallback)', async () => {+ helperAnswer = {}+ const { HostSession } = await import('./session')+ new HostSession('s2', SPAWN, 100, { term: term as never })+ expect(spawned).toHaveLength(1)+ expect('useConptyDll' in spawned[0]).toBe(false)+ expect(Object.keys(spawned[0]).sort()).toEqual(['cols', 'cwd', 'env', 'name', 'rows'])+ })+})diff --git a/src/session-host/session.ts b/src/session-host/session.tsindex 98b9b0cfd..3cb9520e6 100644--- a/src/session-host/session.ts+++ b/src/session-host/session.ts@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'crypto'import * as pty from 'node-pty'import { TerminalEmulator } from './terminal-emulator'import { CwdReportScanner } from './cwd-report'+import { windowsConptySpawnOptions } from '../core/windows-conpty-dll'import type {CaptureVisibleResult,ExecuteLaunchResult,@@ -245,7 +246,10 @@ export class HostSession {cols: this.appliedGeometry.cols,rows: this.appliedGeometry.rows,cwd: spawn.cwd,- env: spawn.env+ env: spawn.env,+ // Win32: node-pty's bundled ConPTY when it is installed (mouse + alt-screen modes reach+ // the emulator on Windows 10). `{}` everywhere else — byte-identical options.+ ...windowsConptySpawnOptions()})this.term =overrides?.term ??