fix(tmux): closing a session never signals pid 0 or 1

tmux answers 0 for the pid of a pane without a process (`split-window ''`).
The pane list read at server start recorded that 0 on the session, and the
next close of the tab walked the children of pid 0, which is the whole
machine: every process of the account was signalled, all sessions, tmux
itself and the systemd user manager included.

killSession() now decides once whether there is a process to signal
(isSignalablePid(), an integer above 1) and otherwise leaves the close to
`tmux kill-session`. The descendant walk of the kill path returns nothing
for such a root, and signalProcess(), the only place in tmux-manager.ts
that sends a signal, refuses it for the process group form as well.

proc-walk-bounds used pid 1 as the root of its fixture tree, which the kill
path now refuses on purpose, so the fixture is rooted at a real pid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-11-25 16:03:54 +01:00
1 parent 5548c17c4a
commit babb55e4d9
6 files changed
+212 -17

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
/**
* @fileoverview killSession() must never signal the machine.
*
* On 2026-11-25 a kill that got pid 0 took down every process of the account: every
* session, tmux and the systemd user manager. The children of pid 0 are the whole process
* table, so the descendant walk handed all of it to SIGTERM. tmux answers 0 for a pane
* with no process (`split-window ''`), the pane list read at server start records it on
* the session, and the next close of that tab killed everything.
*
* These drive the SHIPPED killSession() with the tmux and ps answers mocked and
* process.kill stubbed: nothing here may reach a real process.
*
* Port: N/A (no server needed)
*/
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { exec, execFile, execSync } from 'node:child_process';
import { isSignalablePid } from '../src/proc-tree.js';
import type { MuxSession } from '../src/mux-interface.js';
vi.mock('node:child_process', async () => {
const actual = await vi.importActual('node:child_process');
return { ...actual, exec: vi.fn(), execFile: vi.fn(), execSync: vi.fn(), spawn: vi.fn() };
});
/** A machine: init, kthreadd, the user's own programs, and one agent (4242) with a child. */
const PS = ['1 0', '2 0', '900 1', '901 900', '902 900', '4242 901', '4243 4242'].join('\n') + '\n';
describe('isSignalablePid', () => {
it('admits only a process of the user', () => {
for (const pid of [2, 4242, 2 ** 22]) expect(isSignalablePid(pid)).toBe(true);
for (const pid of [1, 0, -0, -1, -4242, NaN, Infinity, 1.5, null, undefined]) {
expect(isSignalablePid(pid as number)).toBe(false);
}
});
});
describe('killSession and a pane without a process', () => {
let panePid: string;
let commands: string[];
let kill: MockInstance<typeof process.kill>;
let signals: [number, string | number | undefined][];
beforeEach(() => {
panePid = '4242\n';
commands = [];
signals = [];
vi.mocked(execSync).mockImplementation(((cmd: string) => {
if (cmd.includes('list-panes -a')) return `codeman-feed1234|${panePid.trim()}|0||\n`;
return '';
}) as unknown as typeof execSync);
vi.mocked(exec).mockImplementation(((cmd: string, options: unknown, maybeCallback?: unknown) => {
commands.push(cmd);
const callback = (typeof options === 'function' ? options : maybeCallback) as (e: null, out: object) => void;
const stdout = cmd.includes('display-message') ? panePid : '';
setImmediate(() => callback(null, { stdout, stderr: '' }));
return { on: vi.fn(), kill: vi.fn(), pid: 12345 };
}) as unknown as typeof exec);
// The process snapshot the descendant walk reads.
vi.mocked(execFile).mockImplementation(((file: string, _args: string[], _options: unknown, callback: unknown) => {
setImmediate(() => (callback as (e: null, out: string) => void)(null, file === 'ps' ? PS : ''));
return { on: vi.fn(), kill: vi.fn(), pid: 12345 };
}) as unknown as typeof execFile);
// Every process dies at its first real signal, so no wait runs its full length.
const gone = new Set<number>();
kill = vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: string | number) => {
if (signal !== 0) {
signals.push([pid, signal]);
gone.add(Math.abs(pid));
} else if (gone.has(Math.abs(pid))) {
throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' });
}
return true;
}) as typeof process.kill);
});
afterEach(() => {
kill.mockRestore();
vi.restoreAllMocks();
});
async function manager(recordedPid: number) {
const vitest = process.env.VITEST;
vi.resetModules();
delete process.env.VITEST;
const { TmuxManager } = await import('../src/tmux-manager.js');
process.env.VITEST = vitest;
const m = new TmuxManager();
m.registerSession({
sessionId: 'feed1234',
muxName: 'codeman-feed1234',
pid: recordedPid,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'claude',
attached: false,
} as MuxSession);
return m;
}
const closedByTmux = () => commands.some((c) => c.includes('kill-session -t "codeman-feed1234"'));
// The control: without it, a guard that refused every kill would pass the rest.
it('still signals the process tree of a real pane', async () => {
const m = await manager(4242);
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toContainEqual([4243, 'SIGTERM']);
expect(signals).toContainEqual([-4242, 'SIGTERM']);
expect(signals.every(([pid]) => [4242, 4243].includes(Math.abs(pid)))).toBe(true);
expect(closedByTmux()).toBe(true);
m.destroy();
});
for (const pid of [0, 1]) {
it(`signals nothing for pid ${pid}, and tmux still closes the session`, async () => {
panePid = `${pid}\n`;
const m = await manager(pid);
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toEqual([]);
expect(closedByTmux()).toBe(true);
expect(m.getSession('feed1234')).toBeUndefined();
m.destroy();
});
}
it('signals nothing when tmux gives no answer and the record holds 0', async () => {
panePid = '\n';
const m = await manager(0);
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toEqual([]);
expect(closedByTmux()).toBe(true);
m.destroy();
});
it('survives the real route: the pane list at server start records 0, then the tab is closed', async () => {
panePid = '0\n';
const m = await manager(4242);
await m.reconcileSessions();
expect(m.getSession('feed1234')?.pid).toBe(0); // what master did next was walk it
expect(await m.killSession('feed1234')).toBe(true);
expect(signals).toEqual([]);
expect(closedByTmux()).toBe(true);
m.destroy();
});
});
+19 -6
View File
@@ -146,11 +146,14 @@ describe('collectDescendants', () => {
* even with both caps bypassed.
*/
describe('TmuxManager uses the bounded walk', () => {
/** Build a tree `width` wide and `depth` deep, rooted at 1. */
/** A pane's pid. Never 0 or 1: the kill path walks nothing for those (kill-pid-guard.test.ts). */
const ROOT = 1000;
/** Build a tree `width` wide and `depth` deep, rooted at ROOT. */
function bigTree(width: number, depth: number): Map<number, number[]> {
const t = new Map<number, number[]>();
let next = 2;
let frontier = [1];
let next = ROOT + 1;
let frontier = [ROOT];
for (let d = 0; d < depth; d += 1) {
const nf: number[] = [];
for (const p of frontier) {
@@ -163,7 +166,7 @@ describe('TmuxManager uses the bounded walk', () => {
return t;
}
async function walkVia(fixture: Map<number, number[]>): Promise<number[]> {
async function walkVia(fixture: Map<number, number[]>, root = ROOT): Promise<number[]> {
const { TmuxManager } = await import('../src/tmux-manager.js');
const Klass = TmuxManager as unknown as {
refreshProcSnapshot(): Promise<Map<number, number[]>>;
@@ -174,7 +177,7 @@ describe('TmuxManager uses the bounded walk', () => {
Klass.procSnapshot = { at: Date.now(), byParent: fixture };
try {
const mgr = new TmuxManager();
return await (mgr as unknown as { getChildPidsFresh(pid: number): Promise<number[]> }).getChildPidsFresh(1);
return await (mgr as unknown as { getChildPidsFresh(pid: number): Promise<number[]> }).getChildPidsFresh(root);
} finally {
Klass.refreshProcSnapshot = original;
Klass.procSnapshot = null;
@@ -190,7 +193,7 @@ describe('TmuxManager uses the bounded walk', () => {
it('honours the depth cap on a deep chain', async () => {
const chainTree = new Map<number, number[]>();
for (let i = 1; i < 40; i += 1) chainTree.set(i, [i + 1]);
for (let i = ROOT; i < ROOT + 39; i += 1) chainTree.set(i, [i + 1]);
const out = await walkVia(chainTree);
@@ -203,6 +206,16 @@ describe('TmuxManager uses the bounded walk', () => {
const out = await walkVia(bigTree(4, 6));
expect(out.length).toBeLessThanOrEqual(PROC_WALK_MAX_NODES);
});
it.each([0, 1])('walks nothing below pid %i, whose children are the whole machine', async (root) => {
const machine = new Map([
[0, [1, 2]],
[1, [900]],
[900, [901]],
]);
expect(await walkVia(machine, root)).toEqual([]);
expect(await walkVia(machine, 900)).toEqual([901]);
});
});
describe('descendantsInPaneGroup (a shared daemon outlives the pane that started it)', () => {