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(pty): subtract a shadow from tmux's client COUNT, never force detached
enes1bee080f4b20
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 6b7845e78..e53ebf835 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -577,9 +577,11 @@ export class PtyManager {* under the same name. Never shadow it locally.** It deliberately outlives the `Session` (the tmux session outlives it too) and is dropped when- * the node is destroyed. Growth is one small record per tmux-backed node this process has ever- * released — the same order as the session map itself, and rewritten rather than appended on- * every subsequent release.+ * the node is destroyed. The write is unconditional for every PERSISTED session released — local+ * tmux-backed and remote alike, with or without a recorded size — so the map also holds records+ * whose only content is "remote, do not shadow". Growth is therefore one small record per+ * persisted node this process has ever released: the same order as the session map itself, and+ * rewritten rather than appended on every subsequent release of the same node.*/private released = new Map<string, { size?: PtySize; remote: boolean }>()/** The child-process seam for shadow clients. Undefined in production, where `ControlModeClient`diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.tsindex 1e7998036..4cf769192 100644--- a/src/core/pty-shadow.test.ts+++ b/src/core/pty-shadow.test.ts@@ -414,6 +414,49 @@ describe('control-mode shadow clients for released sessions', () => {expect(killed).toEqual([{ socket: 'node-terminal', target: '=nt-node-1' }])})+ it('leaves a session somebody is really watching alone — the attached flag is a client COUNT', async () => {+ // `#{session_attached}` counts clients. Subtracting our shadow by forcing the flag to false+ // would report a session that has our shadow PLUS a real client — the user's own+ // `tmux -L node-terminal attach`, or a second nodeterm process on the same socket — as+ // detached, and the budget would then kill a session out from under a live user, inverting its+ // one hard rule in the state-destroying direction. The shadow comes off the COUNT.+ const { createSessionReaper } = await import('./session-budget')+ const m = await tmuxManager()+ const a = await create(ALICE, 'node-1')+ const b = await create(BOB, 'node-2')+ kill(ALICE, a.sessionId)+ kill(BOB, b.sessionId)+ await m.shadowAttach('node-1')+ await m.shadowAttach('node-2')++ const NOW = 1_000_000+ const OLD = NOW - 100_000+ const killed: string[] = []+ let listings = 0+ const reaper = createSessionReaper({+ tmuxBin: () => m.getTmuxBin(),+ sockets: ['node-terminal'],+ shadowed: (socket) => m.shadowedTmuxSessions(socket),+ exec: async (_bin: string, args: string[]) => {+ if (args.includes('kill-session')) {+ killed.push(args[args.indexOf('-t') + 1])+ return ''+ }+ // nt-node-1 carries the user's own client the whole time (2 = theirs + ours), so the PLAN+ // must never name it. nt-node-2 is shadow-only when the plan is made and gains a real+ // client before the kill — precisely what the kill-time re-verify exists for.+ const nodeTwo = listings++ === 0 ? 1 : 2+ return `nt-node-1|2|${OLD}\nnt-node-2|${nodeTwo}|${OLD}`+ },+ readMem: () => ({ availableMb: 100, totalMb: 8000 }), // under the watermark: real pressure+ env: {},+ nowSec: () => NOW+ })++ expect(await reaper.sweep()).toBe(0)+ expect(killed).toEqual([])+ })+it('refuses a released REMOTE node — its tmux lives on the far host, not on our socket', async () => {const m = await tmuxManager()const res = (await fake.handlers[IPC.ptyCreate](ALICE, {diff --git a/src/core/session-budget.test.ts b/src/core/session-budget.test.tsindex 8fcf25024..a869c1fc5 100644--- a/src/core/session-budget.test.ts+++ b/src/core/session-budget.test.ts@@ -19,10 +19,10 @@ const cfg = (over: Partial<SessionBudgetConfig> = {}): SessionBudgetConfig => ({...over})-/** A detached nt- session idle for `idleH` hours. */-const idle = (name: string, idleH: number, attached = false): SessionInfo => ({+/** An nt- session idle for `idleH` hours, with `clients` attached (0 = detached). */+const idle = (name: string, idleH: number, clients = 0): SessionInfo => ({name,- attached,+ clients,activitySec: NOW - idleH * 3600})@@ -36,7 +36,7 @@ describe('planReap (pure policy)', () => {})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())+ const plan = planReap([idle('nt-watched', 500, 1), idle('nt-idle', 500)], lowMem, NOW, cfg())expect(plan).toEqual(['nt-idle'])})@@ -68,7 +68,7 @@ describe('planReap (pure policy)', () => {})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 sessions = [idle('nt-live', 500, 2), ...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'])})@@ -92,11 +92,11 @@ describe('planReap (pure policy)', () => {})describe('parseSessionList', () => {- it('parses names, attached counts and activity, skipping malformed lines', () => {+ it('parses names, CLIENT 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 }+ { name: 'nt-a', clients: 0, activitySec: 1_753_000_000 },+ { name: 'nt-b', clients: 2, activitySec: 1_753_000_100 }])})})diff --git a/src/core/session-budget.ts b/src/core/session-budget.tsindex 7fc8c4710..0ffd2d915 100644--- a/src/core/session-budget.ts+++ b/src/core/session-budget.ts@@ -35,7 +35,18 @@ const runAsync = promisify(execFile)/** One tmux session as reported by `list-sessions`. `activitySec` is epoch seconds. */export interface SessionInfo {name: string- attached: boolean+ /**+ * How many clients tmux reports attached. A COUNT, not a flag: `#{session_attached}` is the+ * number of clients, and one session can have several — the app's painter, the user's own `tmux+ * -L node-terminal attach`, a second nodeterm process on the same socket, one of our+ * control-mode shadows.+ *+ * Carried numerically rather than collapsed to a boolean at parse time because the `shadowed`+ * seam SUBTRACTS: a session holding our shadow AND a real client must still read as attached,+ * and a boolean can only be forced to false — which would reap the session out from under+ * whoever the other client belongs to.+ */+ clients: numberactivitySec: number}@@ -98,7 +109,7 @@ export function planReap(): string[] {if (cfg.disabled) return []const nt = sessions.filter((s) => s.name.startsWith('nt-'))- const detached = nt.filter((s) => !s.attached)+ const detached = nt.filter((s) => s.clients === 0)const eligible = detached.filter((s) => nowSec - s.activitySec >= cfg.graceSec).sort((a, b) => a.activitySec - b.activitySec)@@ -119,7 +130,7 @@ export function parseSessionList(stdout: string): SessionInfo[] {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 })+ out.push({ name: parts[0], clients: Math.max(0, attached), activitySec: activity })}return out}@@ -209,13 +220,20 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {const listSocket = async (bin: string, socket: string): Promise<SessionInfo[] | null> => {try {const listed = parseSessionList(await exec(bin, ['-L', socket, 'list-sessions', '-F', LIST_FMT]))- // Our own shadows are subtracted from tmux's `attached` HERE, at the one place every listing- // comes through, so the plan and the kill-time re-verify can never disagree about it (a- // shadow attached between the two would otherwise resurrect the exemption). Re-read each+ // Our own shadows are subtracted from tmux's client COUNT here, at the one place every+ // listing comes through, so the plan and the kill-time re-verify can never disagree about it+ // (a shadow attached between the two would otherwise resurrect the exemption). Re-read each// time: the set changes as sessions are shadowed and swapped back to painters.+ //+ // Minus ONE client, never "detached": this app holds at most one shadow per session, and+ // anything left over is somebody else's client — the user's own `tmux attach`, another+ // nodeterm process on this socket — whose session must keep the exemption. Forcing the flag+ // false here would reap a session out from under a live user.const shadowed = new Set(opts.shadowed?.(socket) ?? [])if (shadowed.size === 0) return listed- return listed.map((s) => (s.attached && shadowed.has(s.name) ? { ...s, attached: false } : s))+ return listed.map((s) =>+ s.clients > 0 && shadowed.has(s.name) ? { ...s, clients: s.clients - 1 } : s+ )} catch {// "no server running" and a real failure both land here; neither yields candidates.return null@@ -245,7 +263,7 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {// 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))+ const stillDetached = new Set(fresh.filter((s) => s.clients === 0).map((s) => s.name))for (const name of names) {if (!stillDetached.has(name)) continuetry {