mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-25 23:29:34 +01:00
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:
1 parent
5548c17c4a
commit
babb55e4d9
6 files changed
+212
-17
No files matched your search
@@ -158,7 +158,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
|||||||
|
|
||||||
**Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept)
|
**Workspace-trust dialog auto-accept** (`session-trust-dialog.ts`, pure): Claude Code's per-directory trust dialog is always answered yes, or the session is stuck. ⚠️ Match the compacted SCREEN (`compactScreenText()`, all whitespace removed), never the stream (tmux sends words joined by cursor-forwards, not spaces). ⚠️ Never answer with a blind `\r` (newer versions highlight "No, exit" first): `trustDialogNextKey()` returns ONE key per re-read frame (arrow, then Enter only once `❯` is on the trust option), and the LAST marked option wins. ⚠️ All three guards must hold: startup window `TRUST_DIALOG_WINDOW_MS` (90s), two-marker match (`isTrustDialogScreen`), attempt cap `TRUST_DIALOG_MAX_ATTEMPTS` (6). ⚠️ Read `capturePaneText()`; only a direct-PTY session falls back to a SHORT buffer tail. ⚠️ The scan must schedule its own next read (`_trustDialogTimer`, cleared in `_clearAllTimers()`), not rely on PTY output, and a throttled read is DEFERRED onto that timer, never dropped (the dialog's paint is often the pane's last output); a stopped session never scans. → [architecture-invariants#workspace-trust-dialog-auto-accept](docs/architecture-invariants.md#workspace-trust-dialog-auto-accept)
|
||||||
|
|
||||||
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
|
**Process-tree walks are bounded** (`proc-tree.ts`, pure): `collectDescendants(pid, byParent)` is the ONE descendant traversal, fed by one cached `ps -eo pid=,ppid=` snapshot (`refreshProcSnapshot()` in tmux-manager.ts: async, in-flight-shared, and ANY error discards the result rather than caching a truncated `ps`). ⚠️ Never walk a process tree with per-node `pgrep` or unbounded recursion (the unbounded version took a machine down): the walk must terminate on cycles, cap depth (`PROC_WALK_MAX_DEPTH`) and node count (`PROC_WALK_MAX_NODES`), and never spawn anything. ⚠️ Keep it in its own module so the test exercises the shipped code, and report truncation through `onTruncated` naming both caps, never silently. ⚠️ **A kill never takes pid 0 or 1** (`isSignalablePid()`): the children of pid 0 are the whole machine, and tmux really answers 0 for an empty pane (`split-window ''`), which the pane list at server start records as `session.pid`; a close then signalled every process of the account. `killSession` signals only through `signalProcess()`, walks nothing for such a pid and leaves the close to `tmux kill-session`. Never call `process.kill` in tmux-manager.ts with a signal anywhere else, and never drive a real `killSession` from a script: stub `process.kill` in vitest (`test/kill-pid-guard.test.ts`). → [architecture-invariants#process-tree-walks-are-bounded](docs/architecture-invariants.md#process-tree-walks-are-bounded)
|
||||||
|
|
||||||
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
|
**A `persistent: false` chokidar watcher stops on its first error**: ⚠️ its `'error'` handler goes through `closeWatcherOnError()` (`utils/close-watcher-on-error.ts`), never a bare log or `close()`. chokidar 3 retries a failed `fs.watch` (EMFILE once the inotify instances are used up, ENOSPC once the watches are) on the parent directory up to `/` forever, logging every pass (one server wrote 174 GiB of log that way); a bare `close()` turns the follow-up TypeError into an unhandled rejection, and a callback already in flight can reopen it through `add()`. The watcher's own poll must cover what it watched and create it again on a later tick (`TeamWatcher`, `WorkflowRunWatcher`): chokidar 3 reports a one-off ENOENT race (a new file gone between its `stat` and `watch`) through the same TypeError, so a watcher that stayed closed would end live updates until a restart. Tests: `test/watcher-fs-watch-failure.test.ts`.
|
||||||
|
|
||||||
|
|||||||
@@ -1385,6 +1385,8 @@ Target: 20 sessions, 50 agent windows at 60fps. Limits in `src/config/`: termina
|
|||||||
|
|
||||||
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
|
⚠️ Truncation is reported through `onTruncated` rather than silently, with BOTH caps named: a silent depth cap hides a deep tree exactly as effectively as a silent node cap hides a wide one.
|
||||||
|
|
||||||
|
⚠️ **A kill never takes pid 0 or 1** (2026-11-25). A bound limits how MUCH a walk collects, not what it is a walk of: the children of pid 0 are init and everything below it, so `killSession()` with pid 0 signalled every process of the account, which took down every session, tmux itself and the systemd user manager (the machine did not reboot, and with the manager gone the server did not come back until the next login). It was reached by a script that drove the real `killSession()` on an empty pane lookup (`Number('')` is 0), but it needs no script. tmux answers `0` for `#{pane_pid}` of a pane without a process (`split-window ''`; measured on 3.4), `parsePaneRows()` keeps that row, and `reconcileSessions()` at server start writes it to `session.pid`, where the last pane of a session wins. The next close read 0 from tmux, fell back to the record, found 0 there too, and walked it. Reproduced on master with the signals logged instead of sent, inside a PID namespace: "Killing session codeman-feed1234 (PID 0)", "Found 15 child processes to kill". So 0 is an ordinary answer and means "nothing to signal". Three layers, all pinned in `test/kill-pid-guard.test.ts`: `killSession()` decides once (`isSignalablePid()`, an integer above 1) and otherwise leaves the close to `tmux kill-session`; `getChildPidsFresh()` walks nothing for such a root; and `signalProcess()`, the only place in `tmux-manager.ts` that sends a signal, refuses it for the group form as well (`kill(-1)` is every process, `kill(0)` is our own group). `collectDescendants()` itself stays a plain walk. A recorded 0 is deliberately left on the record rather than replaced by the older pid: that pid belongs to a process that may have exited since and been reused.
|
||||||
|
|
||||||
## Local packages and build artifacts
|
## Local packages and build artifacts
|
||||||
|
|
||||||
### xterm-zerolag-input is single-source
|
### xterm-zerolag-input is single-source
|
||||||
|
|||||||
@@ -32,6 +32,23 @@ export const PROC_WALK_MAX_DEPTH = 10;
|
|||||||
/** Hard ceiling on collected descendants. A backstop, not an expected limit. */
|
/** Hard ceiling on collected descendants. A backstop, not an expected limit. */
|
||||||
export const PROC_WALK_MAX_NODES = 500;
|
export const PROC_WALK_MAX_NODES = 500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a session kill may signal `pid`, or walk the tree below it: a real process of
|
||||||
|
* the user's, so an integer above 1.
|
||||||
|
*
|
||||||
|
* On 2026-11-25 a kill that got pid 0 took down every process of the account: all of the
|
||||||
|
* user's sessions, tmux itself and the systemd user manager. The children of pid 0 are
|
||||||
|
* the whole machine, so the bounds above do not help (500 processes are most of one), and
|
||||||
|
* `kill(-1)` means every process one may signal while `kill(0)` means one's own group.
|
||||||
|
*
|
||||||
|
* tmux answers 0 for a pane with no process (`split-window ''`), and that 0 reaches the
|
||||||
|
* session record through the pane list read at server start. So 0 is an ordinary answer
|
||||||
|
* here, not a corrupt one, and it means "nothing to signal".
|
||||||
|
*/
|
||||||
|
export function isSignalablePid(pid: number | null | undefined): pid is number {
|
||||||
|
return typeof pid === 'number' && Number.isInteger(pid) && pid > 1;
|
||||||
|
}
|
||||||
|
|
||||||
export interface WalkOptions {
|
export interface WalkOptions {
|
||||||
maxDepth?: number;
|
maxDepth?: number;
|
||||||
maxNodes?: number;
|
maxNodes?: number;
|
||||||
|
|||||||
+30
-10
@@ -22,7 +22,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { collectDescendants, descendantsInPaneGroup } from './proc-tree.js';
|
import { collectDescendants, descendantsInPaneGroup, isSignalablePid } from './proc-tree.js';
|
||||||
import {
|
import {
|
||||||
foreignViewSessionName,
|
foreignViewSessionName,
|
||||||
buildForeignDockerViewKillCommand,
|
buildForeignDockerViewKillCommand,
|
||||||
@@ -3148,6 +3148,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
* its process-group and tmux fallbacks.
|
* its process-group and tmux fallbacks.
|
||||||
*/
|
*/
|
||||||
private async getChildPidsFresh(pid: number): Promise<number[]> {
|
private async getChildPidsFresh(pid: number): Promise<number[]> {
|
||||||
|
// The children of pid 0 or 1 are the whole machine (see isSignalablePid).
|
||||||
|
if (!isSignalablePid(pid)) return [];
|
||||||
let byParent: ReadonlyMap<number, readonly number[]>;
|
let byParent: ReadonlyMap<number, readonly number[]>;
|
||||||
try {
|
try {
|
||||||
byParent = await Promise.race([
|
byParent = await Promise.race([
|
||||||
@@ -3205,6 +3207,19 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The one way this class signals a process. Refuses what is not a session's process
|
||||||
|
* (see {@link isSignalablePid}); a negative `pid` is the process group, so it is judged
|
||||||
|
* by its absolute value and `-1` (everything) and `-0` (our own group) are refused too.
|
||||||
|
*/
|
||||||
|
private signalProcess(pid: number, signal: 'SIGTERM' | 'SIGKILL'): void {
|
||||||
|
if (!isSignalablePid(Math.abs(pid))) {
|
||||||
|
console.error(`[TmuxManager] Refusing to send ${signal} to pid ${pid}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
process.kill(pid, signal);
|
||||||
|
}
|
||||||
|
|
||||||
// Check if a process is still alive. Signal decisions only: an unreaped zombie
|
// Check if a process is still alive. Signal decisions only: an unreaped zombie
|
||||||
// counts here, so its process group still gets the SIGKILL below. The WAITS use
|
// counts here, so its process group still gets the SIGKILL below. The WAITS use
|
||||||
// waitForProcessesExit(), which counts a zombie as exited.
|
// waitForProcessesExit(), which counts a zombie as exited.
|
||||||
@@ -3348,10 +3363,15 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
|
|
||||||
// Get current PID (may have changed)
|
// Get current PID (may have changed)
|
||||||
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
|
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
|
||||||
|
// An empty pane has no process: tmux says 0, and so does the record once a server
|
||||||
|
// start has read it. Nothing is signalled then, and only tmux is asked to close it.
|
||||||
|
const hasProcess = isSignalablePid(currentPid);
|
||||||
|
|
||||||
console.log(`[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`);
|
console.log(
|
||||||
|
`[TmuxManager] Killing session ${session.muxName} (${hasProcess ? `PID ${currentPid}` : `no process, pane pid ${currentPid}`})`
|
||||||
|
);
|
||||||
|
|
||||||
const allPids: number[] = [currentPid];
|
const allPids: number[] = hasProcess ? [currentPid] : [];
|
||||||
|
|
||||||
// Strategy 1: Kill all child processes recursively (but never a shared daemon the
|
// Strategy 1: Kill all child processes recursively (but never a shared daemon the
|
||||||
// pane's CLI started for every session of that CLI: see killableDescendants)
|
// pane's CLI started for every session of that CLI: see killableDescendants)
|
||||||
@@ -3363,7 +3383,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
for (const childPid of [...childPids].reverse()) {
|
for (const childPid of [...childPids].reverse()) {
|
||||||
if (this.isProcessAlive(childPid)) {
|
if (this.isProcessAlive(childPid)) {
|
||||||
try {
|
try {
|
||||||
process.kill(childPid, 'SIGTERM');
|
this.signalProcess(childPid, 'SIGTERM');
|
||||||
} catch {
|
} catch {
|
||||||
// Process may already be dead
|
// Process may already be dead
|
||||||
}
|
}
|
||||||
@@ -3378,7 +3398,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
for (const childPid of childPids) {
|
for (const childPid of childPids) {
|
||||||
if (this.isProcessAlive(childPid)) {
|
if (this.isProcessAlive(childPid)) {
|
||||||
try {
|
try {
|
||||||
process.kill(childPid, 'SIGKILL');
|
this.signalProcess(childPid, 'SIGKILL');
|
||||||
} catch {
|
} catch {
|
||||||
// Process already terminated
|
// Process already terminated
|
||||||
}
|
}
|
||||||
@@ -3387,12 +3407,12 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Strategy 2: Kill the entire process group
|
// Strategy 2: Kill the entire process group
|
||||||
if (this.isProcessAlive(currentPid)) {
|
if (hasProcess && this.isProcessAlive(currentPid)) {
|
||||||
try {
|
try {
|
||||||
process.kill(-currentPid, 'SIGTERM');
|
this.signalProcess(-currentPid, 'SIGTERM');
|
||||||
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
|
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
|
||||||
if (this.isProcessAlive(currentPid)) {
|
if (this.isProcessAlive(currentPid)) {
|
||||||
process.kill(-currentPid, 'SIGKILL');
|
this.signalProcess(-currentPid, 'SIGKILL');
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Process group may not exist or already terminated
|
// Process group may not exist or already terminated
|
||||||
@@ -3439,9 +3459,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Strategy 4: Direct kill by PID as final fallback
|
// Strategy 4: Direct kill by PID as final fallback
|
||||||
if (this.isProcessAlive(currentPid)) {
|
if (hasProcess && this.isProcessAlive(currentPid)) {
|
||||||
try {
|
try {
|
||||||
process.kill(currentPid, 'SIGKILL');
|
this.signalProcess(currentPid, 'SIGKILL');
|
||||||
} catch {
|
} catch {
|
||||||
// Already dead
|
// Already dead
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -146,11 +146,14 @@ describe('collectDescendants', () => {
|
|||||||
* even with both caps bypassed.
|
* even with both caps bypassed.
|
||||||
*/
|
*/
|
||||||
describe('TmuxManager uses the bounded walk', () => {
|
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[]> {
|
function bigTree(width: number, depth: number): Map<number, number[]> {
|
||||||
const t = new Map<number, number[]>();
|
const t = new Map<number, number[]>();
|
||||||
let next = 2;
|
let next = ROOT + 1;
|
||||||
let frontier = [1];
|
let frontier = [ROOT];
|
||||||
for (let d = 0; d < depth; d += 1) {
|
for (let d = 0; d < depth; d += 1) {
|
||||||
const nf: number[] = [];
|
const nf: number[] = [];
|
||||||
for (const p of frontier) {
|
for (const p of frontier) {
|
||||||
@@ -163,7 +166,7 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
return t;
|
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 { TmuxManager } = await import('../src/tmux-manager.js');
|
||||||
const Klass = TmuxManager as unknown as {
|
const Klass = TmuxManager as unknown as {
|
||||||
refreshProcSnapshot(): Promise<Map<number, number[]>>;
|
refreshProcSnapshot(): Promise<Map<number, number[]>>;
|
||||||
@@ -174,7 +177,7 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
Klass.procSnapshot = { at: Date.now(), byParent: fixture };
|
Klass.procSnapshot = { at: Date.now(), byParent: fixture };
|
||||||
try {
|
try {
|
||||||
const mgr = new TmuxManager();
|
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 {
|
} finally {
|
||||||
Klass.refreshProcSnapshot = original;
|
Klass.refreshProcSnapshot = original;
|
||||||
Klass.procSnapshot = null;
|
Klass.procSnapshot = null;
|
||||||
@@ -190,7 +193,7 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
|
|
||||||
it('honours the depth cap on a deep chain', async () => {
|
it('honours the depth cap on a deep chain', async () => {
|
||||||
const chainTree = new Map<number, number[]>();
|
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);
|
const out = await walkVia(chainTree);
|
||||||
|
|
||||||
@@ -203,6 +206,16 @@ describe('TmuxManager uses the bounded walk', () => {
|
|||||||
const out = await walkVia(bigTree(4, 6));
|
const out = await walkVia(bigTree(4, 6));
|
||||||
expect(out.length).toBeLessThanOrEqual(PROC_WALK_MAX_NODES);
|
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)', () => {
|
describe('descendantsInPaneGroup (a shared daemon outlives the pane that started it)', () => {
|
||||||
|
|||||||
Reference in new issue
Block a user