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.

feat(windows): reap detached session-host sessions under the session budget

review1bf20241bee0
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 0e7282b15..1ca777b36 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -207,6 +207,8 @@ import {
sessionHostHasSession,
sessionHostKillSession,
sessionHostListSessions,
+ sessionHostListSessionsDetailed,
+ type SessionHostListing,
sessionHostPaneCommand,
sessionHostMessageOwner,
sessionHostMessagePasteReady,
@@ -216,6 +218,7 @@ import {
SessionHostProtocolCompatibilityError
} from './session-host-backend'
import type { SessionHostPty } from './session-host-pty'
+import type { SessionHostReaperBackend, SessionInfo } from './session-budget'
import { NativeWindowsPane } from './native-windows-pane'
import type { ProjectSpawnOverrides, ProjectSpawnOverridesReader } from './project-spawn-overrides'
@@ -3051,6 +3054,65 @@ export class PtyManager {
)
}
+ /**
+ * The session host's per-session listing for the observability surfaces (session-memory panel,
+ * dev-server ports), or `undefined` when the session host is not this machine's backend — the
+ * caller then behaves exactly as before it existed. Same eligibility guard as every other host
+ * read; the listing itself never launches a host either (`listSessionsDetailed`).
+ */
+ sessionHostListing(): Promise<SessionHostListing | null> | undefined {
+ if (!this.hostBackendEligible()) return undefined
+ return sessionHostListSessionsDetailed()
+ }
+
+ /** Generation each name had in the reaper backend's most recent listing (see below). */
+ private readonly reaperGenerations = new Map<string, string>()
+
+ /**
+ * The session reaper's session-host leg (`SessionReaperOpts.sessionHost`), or `undefined` when
+ * the session host is not this machine's backend.
+ *
+ * Two rules beyond the plain mapping:
+ * - A name THIS process has a live session for counts as watched (`clients >= 1`) whatever the
+ * host says. A subscription is re-applied after a host reconnect, and in that window the host
+ * reports zero subscribers for a terminal the user is looking at — a tmux painter is a process
+ * and has no such window. Only ever ADDS a viewer, so it can only spare, never doom.
+ * - The kill ends exactly the generation the latest listing observed (`expectedGeneration`), and
+ * nothing else: no scrollback deletion, no tombstone — those belong to the user-deletes-the-
+ * node path (`destroySession`). A reaped node cold-restores on next open (`fresh: true`), the
+ * same contract as a tmux reap (session-budget.ts header).
+ */
+ sessionHostReaperBackend(): SessionHostReaperBackend | undefined {
+ if (!this.hostBackendEligible()) return undefined
+ return {
+ list: async (): Promise<SessionInfo[] | null> => {
+ const listing = await sessionHostListSessionsDetailed()
+ // A failed read, or a host that cannot describe its sessions: no candidates at all.
+ if (!listing || listing.sessions === null) return null
+ this.reaperGenerations.clear()
+ return listing.sessions.map((row) => {
+ this.reaperGenerations.set(row.name, row.generation)
+ const watched = this.sessionByPersistKey(row.name.slice('nt-'.length)) ? 1 : 0
+ const outputSec = Math.floor(row.lastOutputMs / 1000)
+ return {
+ name: row.name,
+ clients: Math.max(row.subscribers, watched),
+ // The host has no attach clock; the output clock is the only honest one it keeps.
+ activitySec: outputSec,
+ outputSec
+ }
+ })
+ },
+ kill: async (name: string): Promise<boolean> => {
+ const expectedGeneration = this.reaperGenerations.get(name)
+ // Never kill by name alone: without the observed generation a same-name successor could die.
+ if (!expectedGeneration) return false
+ await sessionHostKillSession(name, { expectedGeneration })
+ return true
+ }
+ }
+ }
+
/**
* The `zellij` binary, POSIX only (there is no Zellij backend on Windows: the session host owns
* persistence there). Same lookup shape as `findSsh`: the login-shell PATH, then the usual install
diff --git a/src/core/pty-session-host-observability.test.ts b/src/core/pty-session-host-observability.test.ts
new file mode 100644
index 000000000..e3e9d6ab1
--- /dev/null
+++ b/src/core/pty-session-host-observability.test.ts
@@ -0,0 +1,153 @@
+// PtyManager's two session-host observability seams: `sessionHostListing()` (session memory,
+// dev-server ports) and `sessionHostReaperBackend()` (the session reaper). The backend facade is
+// mocked, as in pty-session-host.test.ts; the rules pinned are the manager's own.
+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'
+import type { SessionHostListing } from './session-host-client'
+
+const backend = vi.hoisted(() => ({
+ supported: vi.fn(() => true),
+ create: vi.fn(),
+ listDetailed: vi.fn(async (): Promise<unknown> => null),
+ kill: vi.fn(async (_name: string, _options: { expectedGeneration?: string } = {}): Promise<void> => {})
+}))
+
+vi.mock('./session-host-backend', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./session-host-backend')>()),
+ sessionHostSupported: backend.supported,
+ createSessionHostPty: backend.create,
+ sessionHostListSessionsDetailed: backend.listDetailed,
+ sessionHostKillSession: backend.kill
+}))
+
+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() {
+ return {
+ ready: Promise.resolve({ fresh: true }),
+ onSize: vi.fn(),
+ onData: vi.fn(),
+ onExit: vi.fn(),
+ onAttachError: vi.fn(),
+ write: vi.fn(),
+ resize: vi.fn(),
+ pause: vi.fn(),
+ resume: vi.fn(),
+ kill: vi.fn(),
+ destroy: vi.fn()
+ }
+}
+
+const row = (name: string, subscribers: number, generation: string) => ({
+ name,
+ pid: 100,
+ subscribers,
+ lastOutputMs: 3_600_000,
+ createdMs: 0,
+ generation
+})
+
+describe('PtyManager session-host observability', () => {
+ let manager: import('./pty-manager').PtyManager | undefined
+ let host: FakePlatform
+
+ beforeEach(() => {
+ host = fakePlatform()
+ initPlatform(host)
+ backend.supported.mockReset().mockReturnValue(true)
+ backend.create.mockReset().mockImplementation(() => fakeSessionHostPty())
+ backend.listDetailed.mockReset().mockResolvedValue(null)
+ 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('both seams are undefined where the session host is not the backend', async () => {
+ backend.supported.mockReturnValue(false)
+ const m = await makeManager()
+ expect(m.sessionHostListing()).toBeUndefined()
+ expect(m.sessionHostReaperBackend()).toBeUndefined()
+ expect(backend.listDetailed).not.toHaveBeenCalled()
+ })
+
+ it('the listing is the backend\'s detailed read', async () => {
+ const listing: SessionHostListing = { running: true, names: ['nt-a'], sessions: [row('nt-a', 0, 'gen-aaaaaaaa')] }
+ backend.listDetailed.mockResolvedValue(listing)
+ const m = await makeManager()
+ await expect(m.sessionHostListing()).resolves.toBe(listing)
+ })
+
+ it('reaper rows: subscribers are clients, the output clock is in seconds', async () => {
+ backend.listDetailed.mockResolvedValue({
+ running: true,
+ names: ['nt-a', 'nt-b'],
+ sessions: [row('nt-a', 0, 'gen-aaaaaaaa'), row('nt-b', 2, 'gen-bbbbbbbb')]
+ })
+ const m = await makeManager()
+ expect(await m.sessionHostReaperBackend()?.list()).toEqual([
+ { name: 'nt-a', clients: 0, activitySec: 3600, outputSec: 3600 },
+ { name: 'nt-b', clients: 2, activitySec: 3600, outputSec: 3600 }
+ ])
+ })
+
+ it('a failed read, or a host that cannot describe its sessions, yields no candidates (null)', async () => {
+ const m = await makeManager()
+ const reaper = m.sessionHostReaperBackend()
+ expect(await reaper?.list()).toBeNull()
+ backend.listDetailed.mockResolvedValue({ running: true, names: ['nt-a'], sessions: null })
+ expect(await reaper?.list()).toBeNull()
+ backend.listDetailed.mockResolvedValue({ running: false, names: [], sessions: [] })
+ expect(await reaper?.list()).toEqual([])
+ })
+
+ it('a node this process has a live session for counts as watched, whatever the host says', async () => {
+ backend.listDetailed.mockResolvedValue({
+ running: true,
+ names: ['nt-live'],
+ sessions: [row('nt-live', 0, 'gen-llllllll')]
+ })
+ const m = await makeManager()
+ m.registerIpc()
+ await host.handlers[IPC.ptyCreate](7, { cols: 80, rows: 24, persistKey: 'live' })
+ expect((await m.sessionHostReaperBackend()?.list())?.[0].clients).toBe(1)
+ })
+
+ it('the kill targets the generation the latest listing observed, and only a listed name', async () => {
+ backend.listDetailed.mockResolvedValue({
+ running: true,
+ names: ['nt-a'],
+ sessions: [row('nt-a', 0, 'gen-aaaaaaaa')]
+ })
+ const m = await makeManager()
+ const reaper = m.sessionHostReaperBackend()
+ expect(await reaper?.kill('nt-a')).toBe(false) // never listed yet: no generation, no kill
+ expect(backend.kill).not.toHaveBeenCalled()
+ await reaper?.list()
+ expect(await reaper?.kill('nt-a')).toBe(true)
+ expect(backend.kill).toHaveBeenCalledWith('nt-a', { expectedGeneration: 'gen-aaaaaaaa' })
+ backend.kill.mockRejectedValueOnce(new Error('unconfirmed'))
+ await expect(reaper?.kill('nt-a')).rejects.toThrow('unconfirmed')
+ })
+})
diff --git a/src/core/session-budget.test.ts b/src/core/session-budget.test.ts
index cb3a94669..56e1631d8 100644
--- a/src/core/session-budget.test.ts
+++ b/src/core/session-budget.test.ts
@@ -654,3 +654,130 @@ describe('sessionBudgetConfig with fractional env values', () => {
}
})
})
+
+describe('createSessionReaper — session-host leg (no tmux, Windows)', () => {
+ const base = {
+ readMem: () => ({ availableMb: 100, totalMb: 64_000 }), // under the watermark: pressure
+ env: {} as NodeJS.ProcessEnv,
+ nowSec: () => NOW,
+ log: () => {}
+ }
+ const hostRow = (name: string, clients: number, idleH: number): SessionInfo => ({
+ name,
+ clients,
+ activitySec: NOW - idleH * 3600,
+ outputSec: NOW - idleH * 3600
+ })
+ const fakeHost = (listings: Array<SessionInfo[] | null>) => {
+ const killed: string[] = []
+ let call = 0
+ return {
+ killed,
+ backend: {
+ list: async () => listings[Math.min(call++, listings.length - 1)],
+ kill: async (name: string) => {
+ killed.push(name)
+ return true
+ }
+ }
+ }
+ }
+
+ it('reaps detached, silent sessions past the grace window and spares attached ones', async () => {
+ const rows = [hostRow('nt-idle', 0, 100), hostRow('nt-watched', 1, 100), hostRow('nt-fresh', 0, 1)]
+ const h = fakeHost([rows])
+ const lines: string[] = []
+ const reaper = createSessionReaper({
+ ...base,
+ log: (m) => lines.push(m),
+ tmuxBin: () => null,
+ sessionHost: () => h.backend
+ })
+ expect(await reaper.sweep()).toBe(1)
+ expect(h.killed).toEqual(['nt-idle'])
+ expect(lines).toEqual([
+ '[session-budget] reaped detached session nt-idle — no pane output for 100.0h (session host)'
+ ])
+ })
+
+ it('a failed (null) listing kills nothing', async () => {
+ const h = fakeHost([null])
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => null, sessionHost: () => h.backend })
+ expect(await reaper.sweep()).toBe(0)
+ expect(h.killed).toEqual([])
+ })
+
+ it('a listing that throws kills nothing and the sweep does not throw', async () => {
+ const reaper = createSessionReaper({
+ ...base,
+ tmuxBin: () => null,
+ sessionHost: () => ({
+ list: async () => {
+ throw new Error('host gone')
+ },
+ kill: async () => true
+ })
+ })
+ expect(await reaper.sweep()).toBe(0)
+ })
+
+ it('re-verifies at kill time: attached, freshly active, vanished or unlistable sessions are spared', async () => {
+ const planned = [hostRow('nt-a', 0, 100), hostRow('nt-b', 0, 100), hostRow('nt-c', 0, 100)]
+ const fresh = [hostRow('nt-a', 1, 100), hostRow('nt-b', 0, 0)] // nt-c vanished
+ const h = fakeHost([planned, fresh])
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => null, sessionHost: () => h.backend })
+ expect(await reaper.sweep()).toBe(0)
+ expect(h.killed).toEqual([])
+
+ const unlistable = fakeHost([planned, null])
+ const r2 = createSessionReaper({ ...base, tmuxBin: () => null, sessionHost: () => unlistable.backend })
+ expect(await r2.sweep()).toBe(0)
+ expect(unlistable.killed).toEqual([])
+ })
+
+ it('a kill the backend did not confirm is not counted', async () => {
+ const reaper = createSessionReaper({
+ ...base,
+ tmuxBin: () => null,
+ sessionHost: () => ({ list: async () => [hostRow('nt-a', 0, 100)], kill: async () => false })
+ })
+ expect(await reaper.sweep()).toBe(0)
+ })
+
+ it('without pressure and under the cap, nothing is planned (same budget rules as tmux)', async () => {
+ const h = fakeHost([[hostRow('nt-idle', 0, 100)]])
+ const reaper = createSessionReaper({
+ ...base,
+ readMem: () => ({ availableMb: 60_000, totalMb: 64_000 }),
+ tmuxBin: () => null,
+ sessionHost: () => h.backend
+ })
+ expect(await reaper.sweep()).toBe(0)
+ expect(await reaper.sweep({ pressure: 'pty' })).toBe(1)
+ })
+
+ it('is never consulted while tmux exists, and the kill switch covers it too', async () => {
+ let asked = 0
+ const backend = () => {
+ asked++
+ return fakeHost([[hostRow('nt-idle', 0, 100)]]).backend
+ }
+ const w = fakeWorld({})
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', exec: w.exec, sessionHost: backend })
+ await reaper.sweep()
+ expect(asked).toBe(0)
+ const off = createSessionReaper({
+ ...base,
+ env: { NODETERM_SESSION_REAP_DISABLED: '1' },
+ tmuxBin: () => null,
+ sessionHost: backend
+ })
+ expect(await off.sweep()).toBe(0)
+ expect(asked).toBe(0)
+ })
+
+ it('no backend (session host not in use) is the historical no-op', async () => {
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => null, sessionHost: () => undefined })
+ expect(await reaper.sweep()).toBe(0)
+ })
+})
diff --git a/src/core/session-budget.ts b/src/core/session-budget.ts
index 33724cd5f..6a62a8ca9 100644
--- a/src/core/session-budget.ts
+++ b/src/core/session-budget.ts
@@ -27,6 +27,9 @@
//
// Electron-free (src/core): all exec/mem/clock access is behind injectable seams (template:
// ack-sweep.ts), so both shells boot it and tests drive it without touching tmux.
+//
+// Windows has no tmux: there the same budget runs over the session host's own listing
+// (`SessionReaperOpts.sessionHost`) — same plan, same rules, a generation-checked kill.
import os from 'os'
import { execFile } from 'child_process'
@@ -412,6 +415,22 @@ export function hostMemReader(platform: NodeJS.Platform = process.platform): ()
return platform === 'darwin' ? (): null => null : readMemInfo
}
+/**
+ * The Windows session host (or any machine with no tmux, where PtyManager runs sessions under it)
+ * as a reaper backend — the same two questions the tmux leg asks with `list-windows` and
+ * `kill-session`. `PtyManager.sessionHostReaperBackend()` supplies it.
+ *
+ * `list()` answers with SessionInfo rows whose `clients` is the host's SUBSCRIBER count and whose
+ * `outputSec` is the host's last-output stamp (its `window_activity`); `null` is a failed or
+ * undescribable listing (an older host that names sessions without describing them), and yields NO
+ * candidates — never "everything is detached". `kill(name)` ends exactly the generation the most
+ * recent `list()` observed, and resolves true only when the host acknowledged the kill.
+ */
+export interface SessionHostReaperBackend {
+ list(): Promise<SessionInfo[] | null>
+ kill(name: string): Promise<boolean>
+}
+
export interface SessionReaperOpts {
/** Lazy tmux binary resolver (PtyManager resolves after init; null = tmux unavailable → no-op). */
tmuxBin: () => string | null
@@ -444,6 +463,16 @@ export interface SessionReaperOpts {
* session of the same name on `nodeterm-rmt` must keep its exemption.
*/
shadowed?: (socket: string) => Iterable<string>
+ /**
+ * The session-host leg, consulted ONLY when `tmuxBin()` is null — which is exactly when
+ * PtyManager runs persistent sessions under the session host (Windows). Lazy, like `tmuxBin`:
+ * PtyManager decides after init whether the host is this machine's backend, and answers
+ * `undefined` when it is not. The tmux leg never reads it, so a tmux machine's sweep is unchanged.
+ *
+ * No `shadowed`-style subtraction is owed here: the session host has no control-mode shadows —
+ * background writes (`sendKeys`) need no subscription — so every subscriber is a real viewer.
+ */
+ sessionHost?: () => SessionHostReaperBackend | undefined
exec?: (bin: string, args: string[]) => Promise<string>
readMem?: () => MemInfo | null
env?: NodeJS.ProcessEnv
@@ -523,10 +552,57 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {
}
}
+ const listHost = async (backend: SessionHostReaperBackend): Promise<SessionInfo[] | null> => {
+ try {
+ return await backend.list()
+ } catch {
+ return null
+ }
+ }
+
+ /**
+ * The session-host leg: the SAME `planReap` and the same kill-time re-verify as tmux, over the
+ * host's own listing. The re-verify is one notch stricter than the tmux leg's — a session that
+ * produced output between plan and kill is spared too, not only one that got a viewer — because
+ * the host's clock is cheap to re-read and a reaper that kills a session someone is using is far
+ * worse than one that waits a sweep.
+ */
+ const sweepSessionHost = async (sweepOpts?: SweepOptions): Promise<number> => {
+ const backend = opts.sessionHost?.()
+ if (!backend) return 0
+ const listed = await listHost(backend)
+ if (!listed) return 0
+ const now = nowSec()
+ const plan = planReap(listed, readMem(), now, cfg, sweepOpts?.pressure !== undefined)
+ if (plan.length === 0) return 0
+ const fresh = await listHost(backend)
+ if (!fresh) return 0
+ const reapable = new Map(
+ fresh
+ .filter((s) => s.clients === 0 && now - s.outputSec >= cfg.graceSec)
+ .map((s) => [s.name, s])
+ )
+ let killed = 0
+ for (const name of plan) {
+ const row = reapable.get(name)
+ if (!row) continue
+ try {
+ if (!(await backend.kill(name))) continue
+ killed++
+ log(
+ `[session-budget] reaped detached session ${name} — no pane output for ${((now - row.outputSec) / 3600).toFixed(1)}h (session host)`
+ )
+ } catch {
+ // A vanished-in-between session or a kill failure changes nothing; next sweep re-plans.
+ }
+ }
+ return killed
+ }
+
const sweep = async (sweepOpts?: SweepOptions): Promise<number> => {
if (cfg.disabled) return 0
const bin = opts.tmuxBin()
- if (!bin) return 0
+ if (!bin) return sweepSessionHost(sweepOpts)
const bySocket = new Map<string, SessionInfo[]>()
for (const s of sockets) {
diff --git a/src/main/index.ts b/src/main/index.ts
index 3372a392a..5f5b475bf 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3230,7 +3230,9 @@ app.whenReady().then(async () => {
// session-memory panel gives the user the visibility to cull deliberately.
const sessionReaper = createSessionReaper({
tmuxBin: () => ptyManager.getTmuxBin(),
- shadowed: (socket) => ptyManager.shadowedTmuxSessions(socket)
+ shadowed: (socket) => ptyManager.shadowedTmuxSessions(socket),
+ // No tmux (Windows): the session host's sessions are reaped under the same budget rules.
+ sessionHost: () => ptyManager.sessionHostReaperBackend()
})
sessionReaper.start()
// Memory pressure (core/memory-pressure.ts): the reaper's own 10-minute timer is the steady
diff --git a/src/server/index.ts b/src/server/index.ts
index bb363c0d7..b9d193e95 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -856,7 +856,9 @@ export async function startServer(
// hostMemReader). Kept identical to the desktop shell so the two cannot drift.
const sessionReaper = createSessionReaper({
tmuxBin: () => ptyManager.getTmuxBin(),
- shadowed: (socket) => ptyManager.shadowedTmuxSessions(socket)
+ shadowed: (socket) => ptyManager.shadowedTmuxSessions(socket),
+ // No tmux (Windows): the session host's sessions are reaped under the same budget rules.
+ sessionHost: () => ptyManager.sessionHostReaperBackend()
})
sessionReaper.start()
// Memory pressure (core/memory-pressure.ts): only the reaper leg on this shell. A CRITICAL