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(core): session budget — reap long-idle detached tmux sessions under memory pressure

enes0e2532f60eb7
diff --git a/docs/SERVER.md b/docs/SERVER.md
index bbbfb81f0..11236978f 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -169,6 +169,27 @@ The whole point of this mode is that it adds **no network attack surface**:
The phone's own SSH session into the host is the trust boundary; nodeterm adds nothing listening
beside it.
+### Session budget (idle-session reaper)
+
+tmux sessions deliberately outlive their clients (that is the continuity contract), so a host that
+serves many SSH projects slowly accumulates **detached** agent sessions nobody will ever come back
+to — a field report counted 95 sessions holding 34 GB of idle `claude` processes. Every
+nodeterm-server (headless or serving) runs a **session budget** (`src/core/session-budget.ts`, the
+tmux counterpart of the renderer's WebGL budget): every 10 minutes it sweeps the local
+`node-terminal` **and** SSH-remote `nodeterm-rmt` sockets and reaps the **least-recently-active
+detached** `nt-*` sessions when
+
+- host **available memory** drops below a watermark (default 10% of RAM, floor 1 GB) — the
+ primary, pressure-driven trigger; or
+- the **detached session count** exceeds a cap (default 48) — the accumulation backstop.
+
+**Attached sessions are never touched**, a grace window (default 6 h since last activity) protects
+recent work, kills are re-verified against a fresh listing, and each sweep reaps at most a small
+batch (default 8) so convergence is gradual. A reaped session is indistinguishable from a reboot
+to its node: on next open it **cold-restores** (scrollback snapshot + `claude --resume`). Tuning /
+kill switch via env: `NODETERM_SESSION_MIN_AVAILABLE_MB`, `NODETERM_SESSION_MAX_DETACHED`,
+`NODETERM_SESSION_GRACE_HOURS`, `NODETERM_SESSION_REAP_BATCH`, `NODETERM_SESSION_REAP_DISABLED=1`.
+
## Security model
Single-user auth. There is one password; sessions are per-browser.
diff --git a/src/core/session-budget.test.ts b/src/core/session-budget.test.ts
new file mode 100644
index 000000000..8fcf25024
--- /dev/null
+++ b/src/core/session-budget.test.ts
@@ -0,0 +1,242 @@
+import { describe, expect, it } from 'vitest'
+import {
+ planReap,
+ parseSessionList,
+ sessionBudgetConfig,
+ createSessionReaper,
+ type SessionInfo,
+ type SessionBudgetConfig
+} from './session-budget'
+
+const NOW = 1_753_000_000 // fixed epoch seconds for every test
+
+const cfg = (over: Partial<SessionBudgetConfig> = {}): SessionBudgetConfig => ({
+ disabled: false,
+ minAvailableMb: 2048,
+ maxDetached: 48,
+ graceSec: 6 * 3600,
+ batchMax: 8,
+ ...over
+})
+
+/** A detached nt- session idle for `idleH` hours. */
+const idle = (name: string, idleH: number, attached = false): SessionInfo => ({
+ name,
+ attached,
+ activitySec: NOW - idleH * 3600
+})
+
+const lowMem = { availableMb: 500, totalMb: 64_000 }
+const okMem = { availableMb: 30_000, totalMb: 64_000 }
+
+describe('planReap (pure policy)', () => {
+ it('under memory pressure, reaps the least-recently-active detached sessions first', () => {
+ const plan = planReap([idle('nt-old', 240), idle('nt-mid', 48), idle('nt-new', 7)], lowMem, NOW, cfg({ batchMax: 2 }))
+ expect(plan).toEqual(['nt-old', 'nt-mid'])
+ })
+
+ it('never reaps an attached session, no matter how idle', () => {
+ const plan = planReap([idle('nt-watched', 500, true), idle('nt-idle', 500)], lowMem, NOW, cfg())
+ expect(plan).toEqual(['nt-idle'])
+ })
+
+ it('never reaps within the grace window, even under pressure', () => {
+ const plan = planReap([idle('nt-recent', 1), idle('nt-old', 100)], lowMem, NOW, cfg())
+ expect(plan).toEqual(['nt-old'])
+ })
+
+ it('ignores sessions not named nt-* (a user session on the same socket is untouchable)', () => {
+ const plan = planReap([idle('main', 500), idle('nt-x', 500)], lowMem, NOW, cfg())
+ expect(plan).toEqual(['nt-x'])
+ })
+
+ it('healthy memory + under cap → reaps nothing', () => {
+ const plan = planReap([idle('nt-a', 500), idle('nt-b', 500)], okMem, NOW, cfg())
+ expect(plan).toEqual([])
+ })
+
+ it('a FAILED memory read is not pressure (mem=null never triggers the watermark)', () => {
+ const plan = planReap([idle('nt-a', 500)], null, NOW, cfg())
+ expect(plan).toEqual([])
+ })
+
+ it('count cap is a backstop: excess detached sessions are reaped even with healthy memory', () => {
+ const sessions = Array.from({ length: 10 }, (_, i) => idle(`nt-s${i}`, 100 + i))
+ const plan = planReap(sessions, okMem, NOW, cfg({ maxDetached: 7 }))
+ // 10 detached, cap 7 → 3 oldest go (highest idle hours = oldest activity)
+ expect(plan).toEqual(['nt-s9', 'nt-s8', 'nt-s7'])
+ })
+
+ it('attached sessions do not count toward freeing the cap, but are never the ones killed', () => {
+ const sessions = [idle('nt-live', 500, true), ...Array.from({ length: 5 }, (_, i) => idle(`nt-d${i}`, 100 + i))]
+ const plan = planReap(sessions, okMem, NOW, cfg({ maxDetached: 4 }))
+ expect(plan).toEqual(['nt-d4'])
+ })
+
+ it('combined triggers stay bounded by batchMax per sweep (gradual convergence)', () => {
+ const sessions = Array.from({ length: 30 }, (_, i) => idle(`nt-s${i}`, 100 + i))
+ const plan = planReap(sessions, lowMem, NOW, cfg({ maxDetached: 5, batchMax: 4 }))
+ expect(plan).toHaveLength(4)
+ })
+
+ it('disabled kill switch plans nothing', () => {
+ const plan = planReap([idle('nt-a', 500)], lowMem, NOW, cfg({ disabled: true }))
+ expect(plan).toEqual([])
+ })
+
+ it('pressure alone reaps at most batchMax even with many eligible', () => {
+ const sessions = Array.from({ length: 20 }, (_, i) => idle(`nt-s${i}`, 100 + i))
+ const plan = planReap(sessions, lowMem, NOW, cfg({ batchMax: 3 }))
+ expect(plan).toHaveLength(3)
+ })
+})
+
+describe('parseSessionList', () => {
+ it('parses names, attached counts and activity, skipping malformed lines', () => {
+ const out = parseSessionList('nt-a|0|1753000000\nnt-b|2|1753000100\n\njunk\nx|y|z\n')
+ expect(out).toEqual([
+ { name: 'nt-a', attached: false, activitySec: 1_753_000_000 },
+ { name: 'nt-b', attached: true, activitySec: 1_753_000_100 }
+ ])
+ })
+})
+
+describe('sessionBudgetConfig', () => {
+ it('defaults: 10% of RAM watermark (floor 1GB), cap 48, grace 6h, batch 8', () => {
+ const c = sessionBudgetConfig({}, 64_000)
+ expect(c).toEqual({ disabled: false, minAvailableMb: 6400, maxDetached: 48, graceSec: 21_600, batchMax: 8 })
+ expect(sessionBudgetConfig({}, 4000).minAvailableMb).toBe(1024)
+ })
+
+ it('env overrides win; junk values fall back', () => {
+ const c = sessionBudgetConfig(
+ {
+ NODETERM_SESSION_MIN_AVAILABLE_MB: '3000',
+ NODETERM_SESSION_MAX_DETACHED: 'garbage',
+ NODETERM_SESSION_GRACE_HOURS: '12',
+ NODETERM_SESSION_REAP_DISABLED: '1'
+ },
+ 64_000
+ )
+ expect(c.minAvailableMb).toBe(3000)
+ expect(c.maxDetached).toBe(48)
+ expect(c.graceSec).toBe(43_200)
+ expect(c.disabled).toBe(true)
+ })
+})
+
+// ---- service over fake exec ------------------------------------------------------------------
+
+type Call = { args: string[] }
+
+function fakeWorld(listings: Record<string, string[]>): {
+ calls: Call[]
+ exec: (bin: string, args: string[]) => Promise<string>
+} {
+ const calls: Call[] = []
+ return {
+ calls,
+ exec: async (_bin, args) => {
+ calls.push({ args })
+ const socket = args[1]
+ if (args[2] === 'list-sessions') {
+ const lines = listings[socket]
+ if (!lines) throw new Error('no server running')
+ return lines.join('\n')
+ }
+ return '' // kill-session
+ }
+ }
+}
+
+const OLD = String(NOW - 100 * 3600)
+
+describe('createSessionReaper (service)', () => {
+ const base = {
+ readMem: () => ({ availableMb: 100, totalMb: 64_000 }),
+ env: {} as NodeJS.ProcessEnv,
+ nowSec: () => NOW,
+ log: () => {}
+ }
+
+ it('sweeps every socket, kills planned sessions on the right socket with exact-match targets', async () => {
+ const w = fakeWorld({
+ 'node-terminal': [`nt-local|0|${OLD}`],
+ 'nodeterm-rmt': [`nt-remote|0|${OLD}`]
+ })
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', exec: w.exec })
+ expect(await reaper.sweep()).toBe(2)
+ const kills = w.calls.filter((c) => c.args[2] === 'kill-session')
+ expect(kills).toEqual([
+ { args: ['-L', 'node-terminal', 'kill-session', '-t', '=nt-local'] },
+ { args: ['-L', 'nodeterm-rmt', 'kill-session', '-t', '=nt-remote'] }
+ ])
+ })
+
+ it('re-verifies at kill time: a session attached between plan and kill is spared', async () => {
+ let first = true
+ const w = fakeWorld({})
+ const exec = async (bin: string, args: string[]): Promise<string> => {
+ if (args[2] === 'list-sessions' && args[1] === 'node-terminal') {
+ if (first) {
+ first = false
+ return `nt-x|0|${OLD}`
+ }
+ return `nt-x|1|${OLD}` // now attached
+ }
+ return w.exec(bin, args)
+ }
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', sockets: ['node-terminal'], exec })
+ expect(await reaper.sweep()).toBe(0)
+ expect(w.calls.filter((c) => c.args[2] === 'kill-session')).toHaveLength(0)
+ })
+
+ it('a socket whose listing fails contributes no candidates; the other socket still sweeps', async () => {
+ const w = fakeWorld({ 'nodeterm-rmt': [`nt-r|0|${OLD}`] }) // node-terminal listing throws
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', exec: w.exec })
+ expect(await reaper.sweep()).toBe(1)
+ const kills = w.calls.filter((c) => c.args[2] === 'kill-session')
+ expect(kills).toEqual([{ args: ['-L', 'nodeterm-rmt', 'kill-session', '-t', '=nt-r'] }])
+ })
+
+ it('kill switch: disabled env runs no tmux commands at all', async () => {
+ const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })
+ const reaper = createSessionReaper({
+ ...base,
+ env: { NODETERM_SESSION_REAP_DISABLED: '1' },
+ tmuxBin: () => 'tmux',
+ exec: w.exec
+ })
+ expect(await reaper.sweep()).toBe(0)
+ expect(w.calls).toHaveLength(0)
+ })
+
+ it('tmux unavailable (bin=null) → quiet no-op', async () => {
+ const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => null, exec: w.exec })
+ expect(await reaper.sweep()).toBe(0)
+ expect(w.calls).toHaveLength(0)
+ })
+
+ it('a failing kill is tolerated and does not abort the rest of the batch', async () => {
+ const w = fakeWorld({ 'node-terminal': [`nt-a|0|${OLD}`, `nt-b|0|${String(NOW - 99 * 3600)}`] })
+ const exec = async (bin: string, args: string[]): Promise<string> => {
+ if (args[2] === 'kill-session' && args[4] === '=nt-a') throw new Error('gone already')
+ return w.exec(bin, args)
+ }
+ const reaper = createSessionReaper({ ...base, tmuxBin: () => 'tmux', sockets: ['node-terminal'], exec })
+ expect(await reaper.sweep()).toBe(1) // nt-b still dies
+ })
+
+ it('healthy memory + under cap → lists but never kills', async () => {
+ const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })
+ const reaper = createSessionReaper({
+ ...base,
+ readMem: () => ({ availableMb: 30_000, totalMb: 64_000 }),
+ tmuxBin: () => 'tmux',
+ exec: w.exec
+ })
+ expect(await reaper.sweep()).toBe(0)
+ expect(w.calls.filter((c) => c.args[2] === 'kill-session')).toHaveLength(0)
+ })
+})
diff --git a/src/core/session-budget.ts b/src/core/session-budget.ts
new file mode 100644
index 000000000..80d5b838d
--- /dev/null
+++ b/src/core/session-budget.ts
@@ -0,0 +1,254 @@
+// Session budget: reap long-idle DETACHED nt- tmux sessions under memory pressure (or past a
+// count cap), so abandoned agent sessions can't accumulate until the host swaps itself to death
+// (field report: 95 sessions / 34 GB of idle claude processes on one host).
+//
+// This is the tmux counterpart of the renderer's WebGL budget (`terminal/webgl-budget.ts`), and it
+// deliberately reuses that design's rules rather than inventing an expiry policy:
+// - a bounded budget, enforced only when exceeded — never a calendar-based expiry;
+// - eviction picks the LEAST-RECENTLY-ACTIVE holder;
+// - an ATTACHED session (someone is looking at it) is never evicted, exactly like a visible
+// WebGL holder; a recently-active one is protected by a grace window (the release delay);
+// - reaping is gradual (per-sweep batch), so one sweep can never mass-kill its way past the
+// target — the next sweep re-evaluates.
+//
+// Killing a detached session is safe BECAUSE of the cold-restore contract: to the node, a reap is
+// indistinguishable from a machine reboot. On next open `tmux has-session` fails → fresh=true →
+// the renderer replays the scrollback snapshot and re-launches a resumable agent
+// (`claude --resume …`). For that to hold, the reaper must kill ONLY the tmux session: it must
+// never delete scrollback snapshots and never write a pty-manager tombstone (both belong to the
+// user-deletes-the-node path, `destroySession`).
+//
+// 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.
+
+import fs from 'fs'
+import os from 'os'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import { TMUX_SOCKET } from './tmux-naming'
+import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'
+
+const runAsync = promisify(execFile)
+
+/** One tmux session as reported by `list-sessions`. `activitySec` is epoch seconds. */
+export interface SessionInfo {
+ name: string
+ attached: boolean
+ activitySec: number
+}
+
+/** Host memory snapshot in MB. `null` from a reader means "could not read" — see planReap. */
+export interface MemInfo {
+ availableMb: number
+ totalMb: number
+}
+
+export interface SessionBudgetConfig {
+ /** Kill switch (`NODETERM_SESSION_REAP_DISABLED=1`): sweeps become no-ops. */
+ disabled: boolean
+ /** Watermark: reap only while host available memory is BELOW this (primary trigger). */
+ minAvailableMb: number
+ /** Backstop: max detached nt- sessions across sockets; excess is reaped even without pressure. */
+ maxDetached: number
+ /** A session with activity newer than this is never reaped (protects same-day project switches). */
+ graceSec: number
+ /** Max kills per sweep — convergence is gradual and re-evaluated each sweep. */
+ batchMax: number
+}
+
+function envInt(env: NodeJS.ProcessEnv, key: string, fallback: number): number {
+ const n = Number(env[key])
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
+}
+
+/**
+ * Defaults, overridable per host via env (systemd `Environment=` lines):
+ * NODETERM_SESSION_MIN_AVAILABLE_MB (default: 10% of total RAM, floor 1 GB)
+ * NODETERM_SESSION_MAX_DETACHED (default: 48)
+ * NODETERM_SESSION_GRACE_HOURS (default: 6)
+ * NODETERM_SESSION_REAP_BATCH (default: 8)
+ * NODETERM_SESSION_REAP_DISABLED=1 (kill switch)
+ */
+export function sessionBudgetConfig(env: NodeJS.ProcessEnv, totalMb: number): SessionBudgetConfig {
+ return {
+ disabled: env.NODETERM_SESSION_REAP_DISABLED === '1' || env.NODETERM_SESSION_REAP_DISABLED === 'true',
+ minAvailableMb: envInt(env, 'NODETERM_SESSION_MIN_AVAILABLE_MB', Math.max(1024, Math.round(totalMb * 0.1))),
+ maxDetached: envInt(env, 'NODETERM_SESSION_MAX_DETACHED', 48),
+ graceSec: envInt(env, 'NODETERM_SESSION_GRACE_HOURS', 6) * 3600,
+ batchMax: envInt(env, 'NODETERM_SESSION_REAP_BATCH', 8)
+ }
+}
+
+/**
+ * Pure policy: which sessions to kill this sweep, least-recently-active first.
+ *
+ * Eligible = named `nt-*` AND detached AND idle past the grace window. Then:
+ * - memory below the watermark → up to `batchMax` (a failed memory read — `mem === null` — is
+ * NOT pressure: absence of evidence never triggers the primary path);
+ * - detached count over `maxDetached` → the excess, even with healthy memory;
+ * combined take is bounded by `batchMax`.
+ */
+export function planReap(
+ sessions: SessionInfo[],
+ mem: MemInfo | null,
+ nowSec: number,
+ cfg: SessionBudgetConfig
+): string[] {
+ if (cfg.disabled) return []
+ const nt = sessions.filter((s) => s.name.startsWith('nt-'))
+ const detached = nt.filter((s) => !s.attached)
+ const eligible = detached
+ .filter((s) => nowSec - s.activitySec >= cfg.graceSec)
+ .sort((a, b) => a.activitySec - b.activitySec)
+
+ const pressure = mem !== null && mem.availableMb < cfg.minAvailableMb ? cfg.batchMax : 0
+ const overCap = Math.max(0, detached.length - cfg.maxDetached)
+ const take = Math.min(cfg.batchMax, Math.max(pressure, overCap))
+ return eligible.slice(0, take).map((s) => s.name)
+}
+
+/** Parse `list-sessions -F '#{session_name}|#{session_attached}|#{session_activity}'` output.
+ * Tolerant: malformed lines are skipped, never thrown on. */
+export function parseSessionList(stdout: string): SessionInfo[] {
+ const out: SessionInfo[] = []
+ for (const line of stdout.split('\n')) {
+ const parts = line.trim().split('|')
+ if (parts.length !== 3) continue
+ const attached = Number(parts[1])
+ const activity = Number(parts[2])
+ if (!parts[0] || !Number.isFinite(attached) || !Number.isFinite(activity)) continue
+ out.push({ name: parts[0], attached: attached > 0, activitySec: activity })
+ }
+ return out
+}
+
+/** Linux `/proc/meminfo` (MemAvailable is the honest number); `os.freemem()` fallback elsewhere.
+ * Returns null when nothing readable — the policy treats that as "no pressure signal". */
+export function readMemInfo(): MemInfo | null {
+ try {
+ const text = fs.readFileSync('/proc/meminfo', 'utf8')
+ const avail = /MemAvailable:\s+(\d+)\s*kB/.exec(text)
+ const total = /MemTotal:\s+(\d+)\s*kB/.exec(text)
+ if (avail && total) {
+ return { availableMb: Math.round(Number(avail[1]) / 1024), totalMb: Math.round(Number(total[1]) / 1024) }
+ }
+ } catch {
+ // fall through to the os fallback
+ }
+ try {
+ return { availableMb: Math.round(os.freemem() / 1048576), totalMb: Math.round(os.totalmem() / 1048576) }
+ } catch {
+ return null
+ }
+}
+
+export interface SessionReaperOpts {
+ /** Lazy tmux binary resolver (PtyManager resolves after init; null = tmux unavailable → no-op). */
+ tmuxBin: () => string | null
+ /** tmux sockets to sweep. Default: the local socket + the SSH-remote socket — a host that serves
+ * SSH projects accumulates sessions on `nodeterm-rmt`, and its own nodeterm-server (this
+ * process) is the natural owner of reaping them; the desktops that spawned them may be gone. */
+ sockets?: string[]
+ exec?: (bin: string, args: string[]) => Promise<string>
+ readMem?: () => MemInfo | null
+ env?: NodeJS.ProcessEnv
+ nowSec?: () => number
+ intervalMs?: number
+ log?: (msg: string) => void
+}
+
+export interface SessionReaper {
+ /** One sweep; resolves to the number of sessions killed. Never throws. */
+ sweep(): Promise<number>
+ start(): void
+ stop(): void
+}
+
+export const SESSION_SWEEP_INTERVAL_MS = 10 * 60_000
+
+/**
+ * Periodic reaper over the injectable seams. Failure rules (CLAUDE.md: a failed read is never
+ * evidence of absence): a socket whose `list-sessions` fails contributes NO candidates — only a
+ * successful listing can put a session on the kill list, and the kill is re-verified against a
+ * FRESH listing at kill time (a session that got attached between plan and kill is spared).
+ */
+export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {
+ const sockets = opts.sockets ?? [TMUX_SOCKET, RMT_TMUX_SOCKET]
+ const exec =
+ opts.exec ??
+ (async (bin: string, args: string[]): Promise<string> => {
+ const { stdout } = await runAsync(bin, args, { timeout: 15_000 })
+ return stdout
+ })
+ const readMem = opts.readMem ?? readMemInfo
+ const env = opts.env ?? process.env
+ const nowSec = opts.nowSec ?? ((): number => Math.floor(Date.now() / 1000))
+ const log = opts.log ?? ((m: string): void => console.log(m))
+ const cfg = sessionBudgetConfig(env, readMem()?.totalMb ?? Math.round(os.totalmem() / 1048576))
+
+ const LIST_FMT = '#{session_name}|#{session_attached}|#{session_activity}'
+
+ const listSocket = async (bin: string, socket: string): Promise<SessionInfo[] | null> => {
+ try {
+ return parseSessionList(await exec(bin, ['-L', socket, 'list-sessions', '-F', LIST_FMT]))
+ } catch {
+ // "no server running" and a real failure both land here; neither yields candidates.
+ return null
+ }
+ }
+
+ const sweep = async (): Promise<number> => {
+ if (cfg.disabled) return 0
+ const bin = opts.tmuxBin()
+ if (!bin) return 0
+
+ const bySocket = new Map<string, SessionInfo[]>()
+ for (const s of sockets) {
+ const listed = await listSocket(bin, s)
+ if (listed) bySocket.set(s, listed)
+ }
+ if (bySocket.size === 0) return 0
+
+ const all = [...bySocket.entries()].flatMap(([, list]) => list)
+ const plan = new Set(planReap(all, readMem(), nowSec(), cfg))
+ if (plan.size === 0) return 0
+
+ let killed = 0
+ for (const [socket, listed] of bySocket) {
+ const names = listed.filter((s) => plan.has(s.name)).map((s) => s.name)
+ if (names.length === 0) continue
+ // Kill-time re-verify on a FRESH list: only sessions still present and still detached die.
+ const fresh = await listSocket(bin, socket)
+ if (!fresh) continue
+ const stillDetached = new Set(fresh.filter((s) => !s.attached).map((s) => s.name))
+ for (const name of names) {
+ if (!stillDetached.has(name)) continue
+ try {
+ // `=` forces an exact target match — never tmux's prefix matching.
+ await exec(bin, ['-L', socket, 'kill-session', '-t', `=${name}`])
+ killed++
+ log(`[session-budget] reaped idle detached session ${name} (socket ${socket})`)
+ } catch {
+ // A vanished-in-between session or a kill failure changes nothing; next sweep re-plans.
+ }
+ }
+ }
+ return killed
+ }
+
+ let timer: ReturnType<typeof setInterval> | null = null
+ return {
+ sweep,
+ start(): void {
+ if (timer) return
+ timer = setInterval(() => void sweep(), opts.intervalMs ?? SESSION_SWEEP_INTERVAL_MS)
+ timer.unref?.()
+ },
+ stop(): void {
+ if (timer) {
+ clearInterval(timer)
+ timer = null
+ }
+ }
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index dadf71106..ed6a5393d 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -53,6 +53,7 @@ import {
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
import { createAckSweeper } from '../core/ack-sweep'
+import { createSessionReaper } from '../core/session-budget'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -1177,6 +1178,12 @@ app.whenReady().then(async () => {
// local-project nodes, and a REMOTE sweep of each connected SSH project's host over its
// ControlMaster (a Mac→SSH node's acks land on the REMOTE fs, invisible to the local sweep).
// sshProjectManager is created below; the tick resolves it lazily.
+ // Session budget: reap long-idle DETACHED nt- tmux sessions on THIS machine under memory
+ // pressure or past a count cap (core/session-budget.ts — the tmux counterpart of the WebGL
+ // budget). Attached sessions are never touched; a reaped node cold-restores on next open.
+ // Local sockets only — a remote SSH host's sessions are reaped by that host's own
+ // nodeterm-server, never across the wire. Timer is unref'd; no explicit stop needed.
+ createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() }).start()
const ackSweeper = createAckSweeper({
handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
})
diff --git a/src/server/index.ts b/src/server/index.ts
index db501a23f..a55bccaf7 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -40,6 +40,7 @@ import {
import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
import { createAckSweeper } from '../core/ack-sweep'
+import { createSessionReaper } from '../core/session-budget'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
@@ -349,6 +350,15 @@ export async function startServer(
}
await hookServer.start()
+ // Session budget (docs/SERVER.md): reap long-idle DETACHED nt- tmux sessions under memory
+ // pressure (10%-of-RAM watermark) or past a count cap, on BOTH the local socket and the
+ // SSH-remote socket (`nodeterm-rmt`) — a host serving SSH projects accumulates sessions there,
+ // and this standing process is the natural owner of reaping them (field report: 95 sessions /
+ // 34 GB idle claude). Attached sessions are never touched; a reaped node cold-restores on next
+ // open. Kill switch + tuning via NODETERM_SESSION_* env (core/session-budget.ts).
+ const sessionReaper = createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() })
+ sessionReaper.start()
+
// Headless notification host: every core service above (incl. the loopback hook server, which
// is its own listener and MUST run) is booted, but we bind NO public HTTP/WS listener — no
// renderer serving, no auth surface, no open port. The granted push senders reach the phone over
@@ -359,6 +369,7 @@ export async function startServer(
port: 0, // nothing bound
async close() {
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
+ sessionReaper.stop()
await ptyManager.killAll()
hookServer.stop()
}
@@ -392,6 +403,7 @@ export async function startServer(
port,
async close() {
// Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
+ sessionReaper.stop()
await ptyManager.killAll()
// Close the loopback hook-server listener (it would otherwise die with the process anyway).
hookServer.stop()