Skip to content

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.

perf(windows): serve pane probes from one long-lived PowerShell worker

review78ac6e71fc1f
diff --git a/src/session-host/process-tree.test.ts b/src/session-host/process-tree.test.ts
index 5e6945de4..b41062cf1 100644
--- a/src/session-host/process-tree.test.ts
+++ b/src/session-host/process-tree.test.ts
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest'
-import { paneCommandFromRows, type ProcRow } from './process-tree'
+import {
+ createProcessTableReader,
+ paneCommandFromRows,
+ readWin32,
+ readWin32OneShot,
+ WIN32_PANE_TABLE_SCRIPT,
+ type ProcRow
+} from './process-tree'
+import { powershellArgs } from '../core/win32-powershell'
const row = (pid: number, ppid: number, name: string): ProcRow => ({ pid, ppid, name })
@@ -41,3 +49,86 @@ describe('paneCommandFromRows', () => {
expect(paneCommandFromRows([row(10, 1, 'node.exe'), row(20, 10, 'cmd.exe')], 10)).toBe('node.exe')
})
})
+
+describe('createProcessTableReader', () => {
+ it('ten concurrent reads share ONE table read', async () => {
+ let reads = 0
+ let release: (rows: ProcRow[]) => void = () => {}
+ const reader = createProcessTableReader(() => {
+ reads++
+ return new Promise<ProcRow[]>((r) => (release = r))
+ })
+ const all = Array.from({ length: 10 }, () => reader())
+ release([row(10, 1, 'pwsh.exe')])
+ const results = await Promise.all(all)
+ expect(reads).toBe(1)
+ expect(results.every((r) => r.length === 1)).toBe(true)
+ })
+
+ it('a settled read is never reused: the next call reads again (the exit poll needs two observations)', async () => {
+ let reads = 0
+ const reader = createProcessTableReader(async () => {
+ reads++
+ return [row(10, 1, 'pwsh.exe')]
+ })
+ await reader()
+ await reader()
+ expect(reads).toBe(2)
+ })
+
+ it('a failed or throwing read is [] and is not shared with later callers', async () => {
+ let reads = 0
+ const reader = createProcessTableReader(async () => {
+ reads++
+ if (reads === 1) throw new Error('boom')
+ return []
+ })
+ await expect(reader()).resolves.toEqual([])
+ await expect(reader()).resolves.toEqual([])
+ expect(reads).toBe(2)
+ })
+})
+
+describe('readWin32', () => {
+ const table = [{ ProcessId: 10, ParentProcessId: 1, Name: 'pwsh.exe' }]
+
+ it('answers from the probe worker without a one-shot PowerShell', async () => {
+ let oneShots = 0
+ const rows = await readWin32(
+ { request: async () => ({ kind: 'ok', result: table }) },
+ async () => {
+ oneShots++
+ return []
+ }
+ )
+ expect(rows).toEqual([row(10, 1, 'pwsh.exe')])
+ expect(oneShots).toBe(0)
+ })
+
+ it('a worker that cannot answer falls back to the one-shot read; a failed probe is a failed read', async () => {
+ const fallback = async (): Promise<ProcRow[]> => [row(1, 0, 'System')]
+ await expect(readWin32({ request: async () => ({ kind: 'unavailable' }) }, fallback)).resolves.toEqual([
+ row(1, 0, 'System')
+ ])
+ await expect(readWin32(null, fallback)).resolves.toEqual([row(1, 0, 'System')])
+ await expect(readWin32({ request: async () => ({ kind: 'failed' }) }, fallback)).resolves.toEqual([])
+ })
+
+ it('the one-shot read runs the ABSOLUTE System32 PowerShell, once', async () => {
+ const calls: Array<{ file: string; args: string[] }> = []
+ const rows = await readWin32OneShot(
+ (file, args, _opts, cb) => {
+ calls.push({ file, args })
+ cb(null, JSON.stringify(table[0]))
+ },
+ { SystemRoot: 'D:\\Win' }
+ )
+ expect(calls).toEqual([{ file: 'D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', args: powershellArgs(WIN32_PANE_TABLE_SCRIPT) }])
+ expect(rows).toEqual([row(10, 1, 'pwsh.exe')])
+ })
+
+ it('an unreadable one-shot reply is a failed read ([])', async () => {
+ await expect(readWin32OneShot((_f, _a, _o, cb) => cb(null, 'not json'), {})).resolves.toEqual([])
+ await expect(readWin32OneShot((_f, _a, _o, cb) => cb(new Error('timeout'), ''), {})).resolves.toEqual([])
+ })
+})
diff --git a/src/session-host/process-tree.ts b/src/session-host/process-tree.ts
index d9a7341ba..d8116b547 100644
--- a/src/session-host/process-tree.ts
+++ b/src/session-host/process-tree.ts
@@ -1,5 +1,7 @@
import { execFile } from 'child_process'
import { isShellCommand } from '../shared/agents/pane'
+import { powershellArgs, powershellExe } from '../core/win32-powershell'
+import { getWindowsProbeWorker, type WindowsProbeWorker } from './windows-probe-worker'
/**
* The `#{pane_current_command}` equivalent for a backend with no tmux underneath it. tmux tracks
@@ -40,32 +42,48 @@ function indexRows(rows: readonly ProcRow[]): {
return { table, kids }
}
-function readWin32(): Promise<ProcRow[]> {
+/** `Win32_Process` rows (`ProcessId`/`ParentProcessId`/`Name`) as ProcRows; malformed rows dropped. */
+export function win32ProcRows(parsed: unknown): ProcRow[] {
+ const arr = Array.isArray(parsed) ? parsed : parsed && typeof parsed === 'object' ? [parsed] : []
+ return 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))
+}
+
+export const WIN32_PANE_TABLE_SCRIPT =
+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name | ConvertTo-Json -Compress'
+
+type ExecFileLike = (
+ file: string,
+ args: string[],
+ options: { timeout: number; maxBuffer: number; windowsHide: boolean },
+ callback: (err: Error | null, stdout: string) => void
+) => unknown
+
+/**
+ * One powershell.exe for one table read — the original path, now the fallback when the probe
+ * worker cannot answer. -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.
+ * ABSOLUTE PowerShell path, never a bare `powershell.exe` resolved through the cwd and PATH (see
+ * core/win32-powershell.ts).
+ */
+export function readWin32OneShot(
+ run: ExecFileLike = execFile as unknown as ExecFileLike,
+ env: NodeJS.ProcessEnv = process.env
+): 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'
- ],
+ run(
+ powershellExe(env),
+ powershellArgs(WIN32_PANE_TABLE_SCRIPT),
{ 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)
+ resolve(win32ProcRows(JSON.parse(stdout)))
} catch {
resolve([])
}
@@ -74,6 +92,19 @@ function readWin32(): Promise<ProcRow[]> {
})
}
+/** The Windows table: through this process's long-lived probe worker (no PowerShell startup and no
+ * new process per read), else the one-shot read. A worker answer that is not a table is a failed
+ * read ([]), never "no processes". */
+export async function readWin32(
+ worker: Pick<WindowsProbeWorker, 'request'> | null = getWindowsProbeWorker(),
+ oneShot: () => Promise<ProcRow[]> = readWin32OneShot
+): Promise<ProcRow[]> {
+ const answer = worker ? await worker.request({ op: 'table' }) : null
+ if (answer?.kind === 'ok') return win32ProcRows(answer.result)
+ if (answer?.kind === 'failed') return []
+ return oneShot()
+}
+
function readPosix(): Promise<ProcRow[]> {
return new Promise((resolve) => {
execFile('ps', ['-eo', 'pid,ppid,comm'], { timeout: 5000, maxBuffer: 16 * 1024 * 1024 }, (err, stdout) => {
@@ -122,10 +153,37 @@ export function paneCommandFromRows(rows: readonly ProcRow[], rootPid: number):
return table.get(deepestNonShell ?? deepest)?.name || null
}
+/**
+ * Concurrent reads share ONE in-flight table read. N agent nodes asking at once (liveness polls on
+ * mount, a bulk restart) cost one PowerShell round trip instead of N.
+ *
+ * Deliberately NO time-based cache of a settled read: the restart/Eco exit poll accepts a changed
+ * reading only when it repeats on two CONSECUTIVE polls (agent-restart.ts), and a cached snapshot
+ * answering both polls would "confirm" a momentary child of a still-running CLI from a single
+ * observation — typing the resume line into a live agent. A failed read is never shared beyond the
+ * callers already waiting on it.
+ */
+export function createProcessTableReader(read: () => Promise<ProcRow[]>): () => Promise<ProcRow[]> {
+ let inFlight: Promise<ProcRow[]> | null = null
+ return () => {
+ if (inFlight) return inFlight
+ const p = read()
+ .catch((): ProcRow[] => [])
+ .finally(() => {
+ if (inFlight === p) inFlight = null
+ })
+ inFlight = p
+ return p
+ }
+}
+
+let sharedReader: (() => Promise<ProcRow[]>) | null = null
+
/** The pane-command answer for the pty's own child (`paneCommandFromRows`) — 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()
+ sharedReader ??= createProcessTableReader(() => (process.platform === 'win32' ? readWin32() : readPosix()))
+ const rows = await sharedReader()
if (rows.length === 0) return null
return paneCommandFromRows(rows, rootPid)
}
diff --git a/src/session-host/windows-pane-owner.test.ts b/src/session-host/windows-pane-owner.test.ts
index 730b271e1..cb13a8a74 100644
--- a/src/session-host/windows-pane-owner.test.ts
+++ b/src/session-host/windows-pane-owner.test.ts
@@ -1,6 +1,7 @@
-import { describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it } from 'vitest'
import { isAgentPane } from '../shared/agents/pane-owner-predicate'
import {
+ readWindowsConsoleOwner,
scriptCommandName,
windowsConsoleOwner,
windowsConsoleProbeScript,
@@ -102,3 +103,52 @@ describe('Windows console agent identity', () => {
expect(() => windowsConsoleProbeScript(-1)).toThrow()
})
})
+
+describe('readWindowsConsoleOwner through the probe worker', () => {
+ const real = process.platform
+ const setPlatform = (value: string): void => {
+ Object.defineProperty(process, 'platform', { value, configurable: true })
+ }
+ afterEach(() => setPlatform(real))
+
+ const snapshot = {
+ console: [10, 20],
+ processes: [root, agent]
+ }
+
+ it('answers from the worker snapshot', async () => {
+ setPlatform('win32')
+ const asked: unknown[] = []
+ const owner = await readWindowsConsoleOwner(10, 'gen-1', {
+ request: async (req) => {
+ asked.push(req)
+ return { kind: 'ok', result: snapshot }
+ }
+ })
+ expect(asked).toEqual([{ op: 'owner', pid: 10 }])
+ expect(owner?.command).toBe('opencode')
+ })
+
+ it('a probe the worker reports as failed, or a non-snapshot result, is null', async () => {
+ setPlatform('win32')
+ await expect(readWindowsConsoleOwner(10, 'gen-1', { request: async () => ({ kind: 'failed' }) })).resolves.toBeNull()
+ await expect(
+ readWindowsConsoleOwner(10, 'gen-1', { request: async () => ({ kind: 'ok', result: { console: 'x' } }) })
+ ).resolves.toBeNull()
+ })
+
+ it('an invalid pid is refused before the worker is asked; off Windows nothing runs', async () => {
+ setPlatform('win32')
+ let asked = 0
+ const worker = {
+ request: async () => {
+ asked++
+ return { kind: 'failed' as const }
+ }
+ }
+ await expect(readWindowsConsoleOwner(-1, 'gen-1', worker)).rejects.toThrow()
+ setPlatform('linux')
+ await expect(readWindowsConsoleOwner(10, 'gen-1', worker)).resolves.toBeNull()
+ expect(asked).toBe(0)
+ })
+})
diff --git a/src/session-host/windows-pane-owner.ts b/src/session-host/windows-pane-owner.ts
index 4c180843c..e9e2f7553 100644
--- a/src/session-host/windows-pane-owner.ts
+++ b/src/session-host/windows-pane-owner.ts
@@ -2,6 +2,9 @@ import { execFile } from 'child_process'
import { readFileSync } from 'fs'
import { win32 as winPath } from 'path'
import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
+import { powershellArgs, powershellExe } from '../core/win32-powershell'
+import { windowsConsoleProbeScript } from './windows-probe-script'
+import { getWindowsProbeWorker, type WindowsProbeWorker } from './windows-probe-worker'
/** Exact Windows console/process generation, not merely a reused PID or executable name. */
export function sameNativeProcess(before: PaneOwner | undefined, after: PaneOwner | null): boolean {
@@ -180,44 +183,49 @@ export function windowsConsoleOwner(
return null
}
-/** Probe only. The helper joins the console to read its process list, writes nothing into
- * it, and detaches in finally. The target PID is a validated integer, never shell text.
- * Do not log stdout: the result is an internal identity read. */
-export function windowsConsoleProbeScript(rootPid: number): string {
- if (!Number.isSafeInteger(rootPid) || rootPid <= 0) throw new Error('invalid console root PID')
- return `$ErrorActionPreference = 'Stop';
-Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class NtConsoleProbe { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool AttachConsole(uint pid); [DllImport("kernel32.dll", SetLastError=true)] public static extern uint GetConsoleProcessList([Out] uint[] ids, uint length); [DllImport("shell32.dll", SetLastError=true)] static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmd, out int count); [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p); public static string ScriptArg(string cmd) { if (String.IsNullOrEmpty(cmd)) return ""; int n; IntPtr p = CommandLineToArgvW(cmd, out n); if (p == IntPtr.Zero) return ""; try { if (n < 2) return ""; string a = Marshal.PtrToStringUni(Marshal.ReadIntPtr(p, IntPtr.Size)); return (a == null || a.StartsWith("-")) ? "" : a; } finally { LocalFree(p); } } }';
-$interpreters = @('node', 'nodejs', 'bun', 'deno', 'python', 'python3', 'ruby', 'perl');
-$self = $PID; $ids = @();
-try {
- [void][NtConsoleProbe]::FreeConsole();
- if (-not [NtConsoleProbe]::AttachConsole(${rootPid})) { throw 'console unavailable' };
- $buffer = New-Object 'System.UInt32[]' 1024;
- $count = [NtConsoleProbe]::GetConsoleProcessList($buffer, $buffer.Length);
- if ($count -eq 0 -or $count -gt $buffer.Length) { throw 'console identity unavailable' };
- for ($i = 0; $i -lt $count; $i++) { if ($buffer[$i] -ne $self) { $ids += [int]$buffer[$i] } };
-} finally { [void][NtConsoleProbe]::FreeConsole() };
-$rows = @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $self } | ForEach-Object {
- $row = @{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; executable = [string]$_.ExecutablePath; born = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }) };
- $exe = ([IO.Path]::GetFileNameWithoutExtension([string]$_.ExecutablePath)).ToLower();
- if (($ids -contains [int]$_.ProcessId) -and ($interpreters -contains $exe)) { $row.script = [NtConsoleProbe]::ScriptArg([string]$_.CommandLine) };
- $row
-});
-@{ console = @($ids); processes = $rows } | ConvertTo-Json -Depth 4 -Compress;`
+export { windowsConsoleProbeScript }
+
+/** A probe's JSON as a snapshot, or null when it is not one. */
+function asSnapshot(value: unknown): WindowsConsoleSnapshot | null {
+ if (!value || typeof value !== 'object') return null
+ const snapshot = value as WindowsConsoleSnapshot
+ if (!Array.isArray(snapshot.console) || !Array.isArray(snapshot.processes)) return null
+ return snapshot
}
-export async function readWindowsConsoleOwner(rootPid: number, generation: string): Promise<PaneOwner | null> {
- if (process.platform !== 'win32') return null
- const script = windowsConsoleProbeScript(rootPid)
+/** The original path: one powershell.exe for this probe. Now the fallback when the worker cannot
+ * answer. ABSOLUTE PowerShell path, never a bare name (see core/win32-powershell.ts). */
+function readOneShot(rootPid: number, generation: string, script: string): Promise<PaneOwner | null> {
return new Promise((resolve) => {
- execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script],
+ execFile(powershellExe(), powershellArgs(script),
{ timeout: 4000, maxBuffer: 4 * 1024 * 1024, windowsHide: true }, (error, stdout) => {
if (error) return resolve(null)
try {
- const snapshot = JSON.parse(stdout) as WindowsConsoleSnapshot
- if (!Array.isArray(snapshot.console) || !Array.isArray(snapshot.processes)) return resolve(null)
- resolve(windowsConsoleOwner(rootPid, generation, snapshot))
+ const snapshot = asSnapshot(JSON.parse(stdout))
+ resolve(snapshot ? windowsConsoleOwner(rootPid, generation, snapshot) : null)
} catch { resolve(null) }
})
})
}
+
+/**
+ * The console owner of `rootPid`'s console. Routed through this process's long-lived probe worker
+ * (windows-probe-worker.ts: the C# type is compiled once, not per probe); a worker that cannot
+ * answer falls back to the one-shot script, and a probe that FAILED in the worker is null, exactly
+ * as a failed one-shot run is.
+ */
+export async function readWindowsConsoleOwner(
+ rootPid: number,
+ generation: string,
+ worker: Pick<WindowsProbeWorker, 'request'> | null = getWindowsProbeWorker()
+): Promise<PaneOwner | null> {
+ if (process.platform !== 'win32') return null
+ const script = windowsConsoleProbeScript(rootPid) // validates the pid (throws) before anything runs
+ const answer = worker ? await worker.request({ op: 'owner', pid: rootPid }) : null
+ if (answer?.kind === 'ok') {
+ const snapshot = asSnapshot(answer.result)
+ return snapshot ? windowsConsoleOwner(rootPid, generation, snapshot) : null
+ }
+ if (answer?.kind === 'failed') return null
+ return readOneShot(rootPid, generation, script)
+}
diff --git a/src/session-host/windows-probe-script.ts b/src/session-host/windows-probe-script.ts
new file mode 100644
index 000000000..80f60c7f1
--- /dev/null
+++ b/src/session-host/windows-probe-script.ts
@@ -0,0 +1,98 @@
+// The PowerShell text behind the Windows pane probes: the one-shot console-owner script (one
+// powershell.exe per probe, the original path and now the fallback) and the long-lived probe
+// worker's script (windows-probe-worker.ts), which loads the same C# type ONCE and then answers
+// JSON-line requests on stdin. Both are built from the same pieces, so the two paths cannot read a
+// console differently.
+//
+// Every script here is a constant written in this repo. The only interpolated value is a process id
+// that has been validated as a safe positive integer; the worker receives its pids as JSON data on
+// stdin and re-validates them in PowerShell (`[int]`, `> 0`) — no request text is ever evaluated.
+
+/** `Add-Type` of the console probe. In Windows PowerShell 5.1 this runs csc and writes a temp
+ * assembly, which is the cost the worker pays once instead of per probe. */
+const PROBE_TYPE = `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class NtConsoleProbe { [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool AttachConsole(uint pid); [DllImport("kernel32.dll", SetLastError=true)] public static extern uint GetConsoleProcessList([Out] uint[] ids, uint length); [DllImport("shell32.dll", SetLastError=true)] static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmd, out int count); [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p); public static string ScriptArg(string cmd) { if (String.IsNullOrEmpty(cmd)) return ""; int n; IntPtr p = CommandLineToArgvW(cmd, out n); if (p == IntPtr.Zero) return ""; try { if (n < 2) return ""; string a = Marshal.PtrToStringUni(Marshal.ReadIntPtr(p, IntPtr.Size)); return (a == null || a.StartsWith("-")) ? "" : a; } finally { LocalFree(p); } } }';`
+
+const INTERPRETERS = `$interpreters = @('node', 'nodejs', 'bun', 'deno', 'python', 'python3', 'ruby', 'perl');`
+
+/** The console read itself, for the console whose root is `pidExpr` (a validated integer literal,
+ * or the worker's already-`[int]`-cast `$rootPid`). Ends in the JSON snapshot as its only output. */
+function ownerBody(pidExpr: string): string {
+ return `$self = $PID; $ids = @();
+try {
+ [void][NtConsoleProbe]::FreeConsole();
+ if (-not [NtConsoleProbe]::AttachConsole(${pidExpr})) { throw 'console unavailable' };
+ $buffer = New-Object 'System.UInt32[]' 1024;
+ $count = [NtConsoleProbe]::GetConsoleProcessList($buffer, $buffer.Length);
+ if ($count -eq 0 -or $count -gt $buffer.Length) { throw 'console identity unavailable' };
+ for ($i = 0; $i -lt $count; $i++) { if ($buffer[$i] -ne $self) { $ids += [int]$buffer[$i] } };
+} finally { [void][NtConsoleProbe]::FreeConsole() };
+$rows = @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $self } | ForEach-Object {
+ $row = @{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; executable = [string]$_.ExecutablePath; born = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }) };
+ $exe = ([IO.Path]::GetFileNameWithoutExtension([string]$_.ExecutablePath)).ToLower();
+ if (($ids -contains [int]$_.ProcessId) -and ($interpreters -contains $exe)) { $row.script = [NtConsoleProbe]::ScriptArg([string]$_.CommandLine) };
+ $row
+});
+@{ console = @($ids); processes = $rows } | ConvertTo-Json -Depth 4 -Compress;`
+}
+
+export function validProbePid(pid: number): boolean {
+ return Number.isSafeInteger(pid) && pid > 0
+}
+
+/** Probe only. The helper joins the console to read its process list, writes nothing into
+ * it, and detaches in finally. The target PID is a validated integer, never shell text.
+ * Do not log stdout: the result is an internal identity read. */
+export function windowsConsoleProbeScript(rootPid: number): string {
+ if (!validProbePid(rootPid)) throw new Error('invalid console root PID')
+ return `$ErrorActionPreference = 'Stop';
+${PROBE_TYPE}
+${INTERPRETERS}
+${ownerBody(String(rootPid))}`
+}
+
+/**
+ * The long-lived worker. Protocol, one JSON object per line each way:
+ * in : {"id":<int>,"op":"owner","pid":<int>} | {"id":<int>,"op":"table"}
+ * out: {"id":<int>,"ok":true,"result":<json>} | {"id":<int>,"ok":false}
+ * `ok:false` is the PROBE failing (no such console, CIM refused) — a definite answer. Anything else
+ * (no reply, a malformed line, the process dying) is the caller's cue to use the one-shot path.
+ *
+ * stdin/stdout are opened as raw UTF-8 streams BEFORE any probe runs: the probe Free/AttachConsoles,
+ * and holding the pipe handles up front keeps the protocol independent of whatever console the
+ * process is attached to at the moment (device-checklist item in docs/windows-session-host.md).
+ * The loop ends when stdin closes, so the worker dies with whoever spawned it.
+ */
+export const WINDOWS_PROBE_WORKER_SCRIPT = `$ErrorActionPreference = 'Stop';
+$ProgressPreference = 'SilentlyContinue';
+$ntUtf8 = New-Object System.Text.UTF8Encoding $false;
+$ntIn = New-Object System.IO.StreamReader([Console]::OpenStandardInput(), $ntUtf8);
+$ntOut = New-Object System.IO.StreamWriter([Console]::OpenStandardOutput(), $ntUtf8);
+$ntOut.AutoFlush = $true;
+${PROBE_TYPE}
+${INTERPRETERS}
+function NtOwner([int]$rootPid) {
+${ownerBody('$rootPid')}
+}
+function NtTable() {
+ ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process | ForEach-Object { @{ ProcessId = [int]$_.ProcessId; ParentProcessId = [int]$_.ParentProcessId; Name = [string]$_.Name } })
+}
+while ($true) {
+ $line = $ntIn.ReadLine();
+ if ($null -eq $line) { break };
+ $id = 0;
+ try {
+ $req = ConvertFrom-Json $line;
+ $id = [int]$req.id;
+ if ($req.op -eq 'owner') {
+ $target = [int]$req.pid;
+ if ($target -le 0) { throw 'invalid pid' };
+ $json = NtOwner $target
+ } elseif ($req.op -eq 'table') {
+ $json = NtTable
+ } else { throw 'unknown op' };
+ if (-not $json) { $json = 'null' };
+ $ntOut.WriteLine('{"id":' + $id + ',"ok":true,"result":' + $json + '}')
+ } catch {
+ $ntOut.WriteLine('{"id":' + $id + ',"ok":false}')
+ }
+}`
diff --git a/src/session-host/windows-probe-worker.test.ts b/src/session-host/windows-probe-worker.test.ts
new file mode 100644
index 000000000..6c97f96dc
--- /dev/null
+++ b/src/session-host/windows-probe-worker.test.ts
@@ -0,0 +1,226 @@
+// The probe worker, driven through a PassThrough fake child: runs on every CI host, spawns nothing.
+import { EventEmitter } from 'events'
+import { PassThrough } from 'stream'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { WindowsProbeWorker, getWindowsProbeWorker, type ProbeChild } from './windows-probe-worker'
+import { WINDOWS_PROBE_WORKER_SCRIPT, windowsConsoleProbeScript } from './windows-probe-script'
+
+interface FakeChild extends ProbeChild {
+ written: string[]
+ killed: boolean
+ reply(body: Record<string, unknown>): void
+ requests(): Array<{ id: number; op: string; pid?: number }>
+ exit(): void
+}
+
+function fakeChild(): FakeChild {
+ const events = new EventEmitter()
+ const stdin = new PassThrough()
+ const stdout = new PassThrough()
+ const written: string[] = []
+ stdin.on('data', (c: Buffer) => written.push(...String(c).split('\n').filter(Boolean)))
+ const child: FakeChild = {
+ stdin,
+ stdout,
+ written,
+ killed: false,
+ kill() {
+ child.killed = true
+ },
+ on(event, listener) {
+ events.on(event, listener)
+ return child
+ },
+ reply(body) {
+ stdout.write(JSON.stringify(body) + '\n')
+ },
+ requests() {
+ return written.map((l) => JSON.parse(l))
+ },
+ exit() {
+ events.emit('exit', 1)
+ }
+ }
+ return child
+}
+
+/** Let PassThrough deliver what was written. */
+const flush = async (): Promise<void> => {
+ for (let i = 0; i < 5; i++) await Promise.resolve()
+ await new Promise((r) => setImmediate(r))
+}
+
+describe('WindowsProbeWorker', () => {
+ let children: FakeChild[]
+ let worker: WindowsProbeWorker
+ const make = (over: Partial<ConstructorParameters<typeof WindowsProbeWorker>[0]> = {}): WindowsProbeWorker =>
+ new WindowsProbeWorker({
+ spawn: () => {
+ const c = fakeChild()
+ children.push(c)
+ return c
+ },
+ ...over
+ })
+
+ beforeEach(() => {
+ children = []
+ worker = make()
+ })
+ afterEach(() => {
+ worker.dispose()
+ vi.useRealTimers()
+ })
+
+ it('serves sequential probes from ONE child (the type is compiled once)', async () => {
+ for (let i = 0; i < 3; i++) {
+ const p = worker.request({ op: 'owner', pid: 10 + i })
+ await flush()
+ const req = children[0].requests()[i]
+ expect(req).toEqual({ id: req.id, op: 'owner', pid: 10 + i })
+ children[0].reply({ id: req.id, ok: true, result: { console: [], processes: [] } })
+ await expect(p).resolves.toEqual({ kind: 'ok', result: { console: [], processes: [] } })
+ }
+ expect(worker.spawnCount).toBe(1)
+ })
+
+ it('coalesces identical requests and serializes different ones (never two in flight)', async () => {
+ const a1 = worker.request({ op: 'owner', pid: 10 })
+ const a2 = worker.request({ op: 'owner', pid: 10 })
+ const b = worker.request({ op: 'owner', pid: 20 })
+ const t = worker.request({ op: 'table' })
+ expect(a2).toBe(a1)
+ await flush()
+ expect(children[0].requests()).toHaveLength(1)
+ children[0].reply({ id: children[0].requests()[0].id, ok: true, result: 'a' })
+ await expect(a1).resolves.toEqual({ kind: 'ok', result: 'a' })
+ await flush()
+ expect(children[0].requests().map((r) => r.pid ?? r.op)).toEqual([10, 20])
+ children[0].reply({ id: children[0].requests()[1].id, ok: true, result: 'b' })
+ await expect(b).resolves.toEqual({ kind: 'ok', result: 'b' })
+ await flush()
+ expect(children[0].requests()[2].op).toBe('table')
+ children[0].reply({ id: children[0].requests()[2].id, ok: true, result: [] })
+ await expect(t).resolves.toEqual({ kind: 'ok', result: [] })
+ })
+
+ it('a probe the worker reports as failed is `failed`, and a stale id is ignored', async () => {
+ const p = worker.request({ op: 'owner', pid: 10 })
+ await flush()
+ const id = children[0].requests()[0].id
+ children[0].reply({ id: id + 99, ok: true, result: 'not ours' })
+ children[0].reply({ id, ok: false })
+ await expect(p).resolves.toEqual({ kind: 'failed' })
+ })
+
+ it('refuses an invalid pid before anything is written or spawned', async () => {
+ await expect(worker.request({ op: 'owner', pid: -1 })).resolves.toEqual({ kind: 'failed' })
+ await expect(worker.request({ op: 'owner', pid: 1.5 })).resolves.toEqual({ kind: 'failed' })
+ await expect(worker.request({ op: 'owner', pid: Number.NaN })).resolves.toEqual({ kind: 'failed' })
+ expect(worker.spawnCount).toBe(0)
+ })
+
+ it('a timeout kills the child, answers unavailable, and the next request respawns', async () => {
+ vi.useFakeTimers()
+ worker = make({ firstRequestTimeoutMs: 100, requestTimeoutMs: 50 })
+ const p = worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(101)
+ await expect(p).resolves.toEqual({ kind: 'unavailable' })
+ expect(children[0].killed).toBe(true)
+ const q = worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(worker.spawnCount).toBe(2)
+ children[1].reply({ id: children[1].requests()[0].id, ok: true, result: [] })
+ await expect(q).resolves.toEqual({ kind: 'ok', result: [] })
+ })
+
+ it('the first request after a spawn gets the startup allowance, later ones the short deadline', async () => {
+ vi.useFakeTimers()
+ worker = make({ firstRequestTimeoutMs: 1000, requestTimeoutMs: 50 })
+ const p = worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(500) // past the warm deadline, inside the startup one
+ children[0].reply({ id: children[0].requests()[0].id, ok: true, result: [] })
+ await expect(p).resolves.toEqual({ kind: 'ok', result: [] })
+ const q = worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(51)
+ await expect(q).resolves.toEqual({ kind: 'unavailable' })
+ })
+
+ it('a malformed reply or a dying child is unavailable', async () => {
+ const p = worker.request({ op: 'table' })
+ await flush()
+ ;(children[0].stdout as PassThrough).write('WARNING: not json\n')
+ await expect(p).resolves.toEqual({ kind: 'unavailable' })
+ const q = worker.request({ op: 'table' })
+ await flush()
+ children[1].exit()
+ await expect(q).resolves.toEqual({ kind: 'unavailable' })
+ })
+
+ it('two consecutive failures bench the worker: no respawn loop', async () => {
+ vi.useFakeTimers()
+ let t = 0
+ worker = make({ maxFailures: 2, cooldownMs: 1000, now: () => t })
+ for (let i = 0; i < 2; i++) {
+ const p = worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(0)
+ children[i].exit()
+ await expect(p).resolves.toEqual({ kind: 'unavailable' })
+ }
+ await expect(worker.request({ op: 'table' })).resolves.toEqual({ kind: 'unavailable' })
+ expect(worker.spawnCount).toBe(2)
+ t = 1001
+ void worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(worker.spawnCount).toBe(3)
+ })
+
+ it('a spawn that throws is unavailable, never a crash', async () => {
+ worker = new WindowsProbeWorker({
+ spawn: () => {
+ throw new Error('ENOENT')
+ }
+ })
+ await expect(worker.request({ op: 'table' })).resolves.toEqual({ kind: 'unavailable' })
+ })
+
+ it('ends the child after the idle window', async () => {
+ vi.useFakeTimers()
+ worker = make({ idleMs: 1000 })
+ const p = worker.request({ op: 'table' })
+ await vi.advanceTimersByTimeAsync(0)
+ children[0].reply({ id: children[0].requests()[0].id, ok: true, result: [] })
+ await p
+ await vi.advanceTimersByTimeAsync(999)
+ expect(children[0].killed).toBe(false)
+ await vi.advanceTimersByTimeAsync(2)
+ expect(children[0].killed).toBe(true)
+ })
+
+ it('there is no worker off Windows', () => {
+ expect(getWindowsProbeWorker('linux')).toBeNull()
+ expect(getWindowsProbeWorker('darwin')).toBeNull()
+ })
+})
+
+describe('the worker script', () => {
+ it('compiles the probe type once, outside the request loop', () => {
+ const addType = WINDOWS_PROBE_WORKER_SCRIPT.indexOf('Add-Type')
+ const loop = WINDOWS_PROBE_WORKER_SCRIPT.indexOf('while ($true)')
+ expect(addType).toBeGreaterThan(0)
+ expect(WINDOWS_PROBE_WORKER_SCRIPT.split('Add-Type').length).toBe(2)
+ expect(addType).toBeLessThan(loop)
+ })
+
+ it('holds its own stdio before any probe can Free/AttachConsole', () => {
+ expect(WINDOWS_PROBE_WORKER_SCRIPT.indexOf('OpenStandardOutput')).toBeLessThan(
+ WINDOWS_PROBE_WORKER_SCRIPT.indexOf('FreeConsole()')
+ )
+ })
+
+ it('reads the same console as the one-shot script', () => {
+ const oneShot = windowsConsoleProbeScript(4242)
+ const body = oneShot.slice(oneShot.indexOf('$self = $PID'))
+ expect(WINDOWS_PROBE_WORKER_SCRIPT).toContain(body.replace('AttachConsole(4242)', 'AttachConsole($rootPid)'))
+ })
+})
diff --git a/src/session-host/windows-probe-worker.ts b/src/session-host/windows-probe-worker.ts
new file mode 100644
index 000000000..b62db31df
--- /dev/null
+++ b/src/session-host/windows-probe-worker.ts
@@ -0,0 +1,313 @@
+// One long-lived PowerShell per process for the Windows pane probes.
+//
+// Before this, every probe was a fresh `powershell.exe`: the console-owner read also ran
+// `Add-Type` (csc + a temp assembly in Windows PowerShell 5.1) each time, and the pane-command read
+// (Eco / restart exit poll, agent liveness) re-ran a whole-table CIM query in a new process per
+// call. That is hundreds of ms to over a second and tens of MB transient per probe, and a cold one
+// can outlast the 2 s pane-probe budget agent messaging gives it. The worker pays the startup and
+// the compile ONCE, serves probes FIFO over JSON lines, and goes away when idle.
+//
+// Contract with callers (windows-pane-owner.ts, process-tree.ts):
+// - `ok` the worker answered; `result` is the probe's JSON.
+// - `failed` the worker answered that the PROBE failed (no such console…) — a real answer,
+// the same one a one-shot run would have given. Callers fail closed on it.
+// - `unavailable` the worker could not answer (could not start, timed out, died, spoke garbage).
+// Callers fall back to the one-shot path, so a worker that does not work on some
+// machine costs at most one deadline before the old behaviour takes over.
+// A worker that fails twice in a row is benched for a cooldown, during which every request is
+// `unavailable` immediately — never a respawn loop.
+//
+// Platform-neutral and injectable: the child comes from `deps.spawn`, so tests drive it with a
+// PassThrough fake on any CI host. Only `getWindowsProbeWorker()` touches the real child_process.
+
+import { spawn as spawnChild } from 'child_process'
+import type { Readable, Writable } from 'stream'
+import { powershellArgs, powershellExe } from '../core/win32-powershell'
+import { validProbePid, WINDOWS_PROBE_WORKER_SCRIPT } from './windows-probe-script'
+
+export type ProbeRequest = { op: 'owner'; pid: number } | { op: 'table' }
+
+export type ProbeAnswer =
+ | { kind: 'ok'; result: unknown }
+ | { kind: 'failed' }
+ | { kind: 'unavailable' }
+
+/** The slice of a ChildProcess the worker uses. */
+export interface ProbeChild {
+ stdin: Writable | null
+ stdout: Readable | null
+ kill(): unknown
+ on(event: 'exit' | 'error', listener: (...args: unknown[]) => void): unknown
+ unref?(): void
+}
+
+export interface ProbeWorkerDeps {
+ spawn: () => ProbeChild
+ /** Per-request deadline once the worker is warm. */
+ requestTimeoutMs?: number
+ /** Deadline for the first request after a spawn: PowerShell startup + the one-time Add-Type. */
+ firstRequestTimeoutMs?: number
+ /** Idle time after which the child is ended. */
+ idleMs?: number
+ /** Consecutive transport failures before the worker is benched. */
+ maxFailures?: number
+ cooldownMs?: number
+ now?: () => number
+}
+
+export const PROBE_REQUEST_TIMEOUT_MS = 1500
+export const PROBE_FIRST_REQUEST_TIMEOUT_MS = 6000
+export const PROBE_IDLE_MS = 60_000
+export const PROBE_MAX_FAILURES = 2
+export const PROBE_COOLDOWN_MS = 5 * 60_000
+
+const UNAVAILABLE: ProbeAnswer = { kind: 'unavailable' }
+
+interface Queued {
+ request: ProbeRequest
+ resolve: (answer: ProbeAnswer) => void
+}
+
+interface InFlight extends Queued {
+ id: number
+ timer: ReturnType<typeof setTimeout>
+}
+
+function unrefTimer(t: ReturnType<typeof setTimeout>): void {
+ ;(t as { unref?: () => void }).unref?.()
+}
+
+export class WindowsProbeWorker {
+ private child: ProbeChild | null = null
+ private answeredSinceSpawn = false
+ private buffer = ''
+ private nextId = 1
+ private current: InFlight | null = null
+ private readonly queue: Queued[] = []
+ /** Coalescing: an identical request already queued or in flight shares its answer. */
+ private readonly pending = new Map<string, Promise<ProbeAnswer>>()
+ private idleTimer: ReturnType<typeof setTimeout> | null = null
+ private failures = 0
+ private benchedUntil = 0
+ private spawns = 0
+
+ constructor(private readonly deps: ProbeWorkerDeps) {}
+
+ /** How many children this worker has started — for tests and diagnostics. */
+ get spawnCount(): number {
+ return this.spawns
+ }
+
+ request(request: ProbeRequest): Promise<ProbeAnswer> {
+ // Refused before anything is written: a pid that is not a safe positive integer never reaches
+ // the worker, the same rule `windowsConsoleProbeScript` applies to the one-shot script.
+ if (request.op === 'owner' && !validProbePid(request.pid)) return Promise.resolve({ kind: 'failed' })
+ if (this.now() < this.benchedUntil) return Promise.resolve(UNAVAILABLE)
+ const key = request.op === 'owner' ? `owner:${request.pid}` : 'table'
+ const shared = this.pending.get(key)
+ if (shared) return shared
+ const answer = new Promise<ProbeAnswer>((resolve) => this.queue.push({ request, resolve }))
+ this.pending.set(key, answer)
+ void answer.then(() => {
+ if (this.pending.get(key) === answer) this.pending.delete(key)
+ })
+ this.pump()
+ return answer
+ }
+
+ /** End the child and answer everything outstanding `unavailable`. */
+ dispose(): void {
+ this.clearIdle()
+ const current = this.current
+ this.current = null
+ if (current) {
+ clearTimeout(current.timer)
+ current.resolve(UNAVAILABLE)
+ }
+ for (const q of this.queue.splice(0)) q.resolve(UNAVAILABLE)
+ this.stopChild()
+ }
+
+ private now(): number {
+ return (this.deps.now ?? Date.now)()
+ }
+
+ private pump(): void {
+ if (this.current || this.queue.length === 0) return
+ if (this.now() < this.benchedUntil) {
+ for (const q of this.queue.splice(0)) q.resolve(UNAVAILABLE)
+ return
+ }
+ this.clearIdle()
+ const child = this.ensureChild()
+ if (!child) {
+ for (const q of this.queue.splice(0)) q.resolve(UNAVAILABLE)
+ return
+ }
+ const next = this.queue.shift() as Queued
+ const id = this.nextId++
+ const timeoutMs = this.answeredSinceSpawn
+ ? (this.deps.requestTimeoutMs ?? PROBE_REQUEST_TIMEOUT_MS)
+ : (this.deps.firstRequestTimeoutMs ?? PROBE_FIRST_REQUEST_TIMEOUT_MS)
+ const timer = setTimeout(() => this.transportFailed(), timeoutMs)
+ unrefTimer(timer)
+ this.current = { ...next, id, timer }
+ const line =
+ next.request.op === 'owner'
+ ? JSON.stringify({ id, op: 'owner', pid: next.request.pid })
+ : JSON.stringify({ id, op: 'table' })
+ try {
+ child.stdin?.write(line + '\n')
+ } catch {
+ this.transportFailed()
+ }
+ }
+
+ private ensureChild(): ProbeChild | null {
+ if (this.child) return this.child
+ let child: ProbeChild
+ try {
+ child = this.deps.spawn()
+ } catch {
+ this.recordFailure()
+ return null
+ }
+ this.spawns++
+ this.child = child
+ this.answeredSinceSpawn = false
+ this.buffer = ''
+ // Never what keeps a process alive: the host and main have their own handles, and anything else
+ // (a test runner) must be able to exit with an idle worker still around.
+ child.unref?.()
+ ;(child.stdin as { unref?: () => void } | null)?.unref?.()
+ ;(child.stdout as { unref?: () => void } | null)?.unref?.()
+ // A write into a pipe whose reader died raises EPIPE on the stream; unhandled, that would take
+ // the whole host down with it.
+ child.stdin?.on('error', () => this.childGone(child))
+ child.stdout?.setEncoding('utf8')
+ child.stdout?.on('data', (chunk: string | Buffer) => this.onData(child, String(chunk)))
+ child.on('error', () => this.childGone(child))
+ child.on('exit', () => this.childGone(child))
+ return child
+ }
+
+ private onData(child: ProbeChild, chunk: string): void {
+ if (child !== this.child) return
+ this.buffer += chunk
+ // Guard against a runaway line (a reply is a few hundred kB at most for the owner snapshot).
+ if (this.buffer.length > 16 * 1024 * 1024) {
+ this.transportFailed()
+ return
+ }
+ let nl: number
+ while ((nl = this.buffer.indexOf('\n')) >= 0) {
+ const line = this.buffer.slice(0, nl).trim()
+ this.buffer = this.buffer.slice(nl + 1)
+ if (line) this.onLine(line)
+ if (child !== this.child) return
+ }
+ }
+
+ private onLine(line: string): void {
+ const current = this.current
+ if (!current) return
+ let reply: unknown
+ try {
+ reply = JSON.parse(line)
+ } catch {
+ this.transportFailed()
+ return
+ }
+ if (!reply || typeof reply !== 'object') {
+ this.transportFailed()
+ return
+ }
+ const r = reply as { id?: unknown; ok?: unknown; result?: unknown }
+ // A line for an earlier, already-abandoned request: not ours, keep waiting for ours.
+ if (r.id !== current.id) return
+ this.answeredSinceSpawn = true
+ this.failures = 0
+ this.settle(r.ok === true ? { kind: 'ok', result: r.result } : { kind: 'failed' })
+ }
+
+ private settle(answer: ProbeAnswer): void {
+ const current = this.current
+ if (!current) return
+ clearTimeout(current.timer)
+ this.current = null
+ current.resolve(answer)
+ if (this.queue.length > 0) this.pump()
+ else this.armIdle()
+ }
+
+ /** The worker could not answer the request in flight: end it, answer `unavailable`, move on. */
+ private transportFailed(): void {
+ this.stopChild()
+ this.recordFailure()
+ this.settle(UNAVAILABLE) // a benched worker's queue is drained by the pump this triggers
+ }
+
+ private childGone(child: ProbeChild): void {
+ if (child !== this.child) return
+ this.child = null
+ if (this.current) this.transportFailed()
+ }
+
+ private recordFailure(): void {
+ this.failures++
+ if (this.failures >= (this.deps.maxFailures ?? PROBE_MAX_FAILURES)) {
+ this.benchedUntil = this.now() + (this.deps.cooldownMs ?? PROBE_COOLDOWN_MS)
+ this.failures = 0
+ }
+ }
+
+ private stopChild(): void {
+ const child = this.child
+ this.child = null
+ this.clearIdle()
+ if (!child) return
+ try {
+ child.stdin?.end()
+ } catch {
+ /* already closed */
+ }
+ try {
+ child.kill()
+ } catch {
+ /* already gone */
+ }
+ }
+
+ private armIdle(): void {
+ this.clearIdle()
+ if (!this.child) return
+ this.idleTimer = setTimeout(() => {
+ this.idleTimer = null
+ if (!this.current && this.queue.length === 0) this.stopChild()
+ }, this.deps.idleMs ?? PROBE_IDLE_MS)
+ unrefTimer(this.idleTimer)
+ }
+
+ private clearIdle(): void {
+ if (this.idleTimer) clearTimeout(this.idleTimer)
+ this.idleTimer = null
+ }
+}
+
+let singleton: WindowsProbeWorker | null = null
+
+/**
+ * This process's worker (the session host's, or main's for a direct Windows PTY). Null off
+ * Windows: there is nothing to probe there, and no caller may spawn PowerShell on another OS.
+ */
+export function getWindowsProbeWorker(platformName: NodeJS.Platform = process.platform): WindowsProbeWorker | null {
+ if (platformName !== 'win32') return null
+ singleton ??= new WindowsProbeWorker({
+ spawn: () =>
+ spawnChild(powershellExe(), powershellArgs(WINDOWS_PROBE_WORKER_SCRIPT), {
+ stdio: ['pipe', 'pipe', 'ignore'],
+ windowsHide: true
+ })
+ })
+ return singleton
+}