Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(mcp): signal a pane's background shells that left its process group

Jack Rudenkob7c6901b783f
diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.ts
index 0e61fed0..cecf6ad5 100644
--- a/packages/cli/src/pane/pane-registry.ts
+++ b/packages/cli/src/pane/pane-registry.ts
@@ -41,6 +41,7 @@ import {
isPaneSockPath,
isPaneWatcherCommand,
isValidPaneId,
+ liveEscaped,
mergeSnapshots,
parseGroupFile,
readProcessTable,
@@ -445,6 +446,7 @@ async function killVerified(rec: PaneRecord, root: string): Promise<SweepTargets
for (const sig of ["SIGTERM", "SIGKILL"] as const) {
const table = readProcessTable();
if (t.group && groupCheck(table, t.group)) signal(-t.group.pgid, sig);
+ for (const pid of liveEscaped(table, t.group)) signal(pid, sig);
if (t.mag && isPaneMagmux(t.mag, rec.paneId, table)) signal(t.mag, sig);
await Bun.sleep(sig === "SIGTERM" ? 2000 : 300);
}
@@ -465,6 +467,7 @@ async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Pro
const after = readProcessTable();
const stillAlive =
(t0.group && groupCheck(after, t0.group)) ||
+ liveEscaped(after, t0.group).length > 0 ||
(t0.mag !== null && isPaneMagmux(t0.mag, rec.paneId, after));
if (stillAlive) {
out.kept.push(rec.paneId);
diff --git a/packages/cli/src/pane/pane-session.integration.test.ts b/packages/cli/src/pane/pane-session.integration.test.ts
index 802aa392..4b418143 100644
--- a/packages/cli/src/pane/pane-session.integration.test.ts
+++ b/packages/cli/src/pane/pane-session.integration.test.ts
@@ -6,8 +6,9 @@
*/
import { afterAll, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import type { SlotState } from "./contract.js";
import {
@@ -337,6 +338,41 @@ describe.skipIf(!MAGMUX)(
T
);
+ test(
+ "bg_detached: a background shell in its own process group is ended by the reap",
+ async () => {
+ const pidFile = join("/tmp", `pane-bg-${process.pid}-${Date.now()}`);
+ const r = await start("bg_detached", { env: { FAKE_BG_PID_FILE: pidFile } });
+ await until(r, () => existsSync(pidFile));
+ const pid = Number(readFileSync(pidFile, "utf8"));
+ rmSync(pidFile, { force: true });
+ try {
+ const pgid = Number(
+ execFileSync("ps", ["-o", "pgid=", "-p", String(pid)], { encoding: "utf8" })
+ );
+ expect(pgid).toBe(pid); // its own group: a group signal to the pane never reaches it
+ expect((await finish(r)).state).toBe("COMPLETED");
+ let alive = true;
+ for (let i = 0; i < 20 && alive; i++) {
+ try {
+ process.kill(pid, 0);
+ await Bun.sleep(100);
+ } catch {
+ alive = false;
+ }
+ }
+ expect(alive).toBe(false);
+ } finally {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // already ended by the reap
+ }
+ }
+ },
+ T
+ );
+
test(
"bg_rewake: waits for the background agent (activity background), then settles",
async () => {
diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.ts
index 4cd21fe1..a77ee4ab 100644
--- a/packages/cli/src/pane/pane-session.ts
+++ b/packages/cli/src/pane/pane-session.ts
@@ -63,6 +63,7 @@ import {
type PaneIdentity,
groupCheck,
isLaunchDirPath,
+ liveEscaped,
readProcessTableAsync,
recordPathOf,
verifiedGroupSnapshot,
@@ -1577,18 +1578,28 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
refreshGroupOf(this, table);
}
+ /** The verified group, or a recorded escaped descendant (own process group), is alive. */
private async groupAlive(): Promise<boolean> {
- return !!this.group && groupCheck(await readProcessTableAsync(), this.group);
+ if (!this.group) return false;
+ const table = await readProcessTableAsync();
+ return groupCheck(table, this.group) || liveEscaped(table, this.group).length > 0;
+ }
+
+ /** The verified group (`-pgid`) and each live escaped descendant (its pid), re-read now. */
+ private async backstopTargets(): Promise<number[]> {
+ if (!this.group) return [];
+ const table = await readProcessTableAsync();
+ return [
+ ...(groupCheck(table, this.group) ? [-this.group.pgid] : []),
+ ...liveEscaped(table, this.group),
+ ];
}
private async groupBackstop(): Promise<void> {
for (const sig of ["SIGTERM", "SIGKILL"] as const) {
- if (!this.group || !(await this.groupAlive())) return;
- try {
- process.kill(-this.group.pgid, sig);
- } catch {
- return;
- }
+ const targets = await this.backstopTargets();
+ if (targets.length === 0) return;
+ for (const target of targets) signalQuietly(target, sig);
const end = Date.now() + (sig === "SIGTERM" ? this.ms(2000, 500) : 1000);
while (Date.now() < end && (await this.groupAlive())) await Bun.sleep(150);
}
@@ -1643,6 +1654,14 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
}
}
+function signalQuietly(target: number, sig: NodeJS.Signals): void {
+ try {
+ process.kill(target, sig);
+ } catch {
+ // gone between the read and the signal
+ }
+}
+
function isControl(text: string): boolean {
const t = text.trim();
return t === "/exit" || t === "/quit";
diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.ts
index a040fc9b..029ad0bd 100644
--- a/packages/cli/src/pane/process-identity.test.ts
+++ b/packages/cli/src/pane/process-identity.test.ts
@@ -3,6 +3,7 @@ import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
+ type GroupSnapshot,
type PaneIdentity,
type PsRow,
WATCHER_FUNCTIONS,
@@ -12,6 +13,7 @@ import {
isLaunchDirPath,
isPaneMagmuxCommand,
isPaneWatcherCommand,
+ liveEscaped,
mergeSnapshots,
paneIdentityMatches,
parseGroupFile,
@@ -140,11 +142,13 @@ describe("TS predicates", () => {
});
/** Run the watcher's shell functions against the same real table through a fake `ps`. */
-function shell(script: string, opts: { ctl?: string; root?: string } = {}): string {
+function shell(script: string, opts: { ctl?: string; root?: string; rows?: PsRow[] } = {}): string {
const bin = join(scratch, "bin");
mkdirSync(bin, { recursive: true });
// the watcher's own ps format: pid=,pgid=,lstart=,command= (the TS table minus ppid)
- const shellTable = table.map((r) => `${r.pid} ${r.pgid} ${r.lstart} ${r.command}`).join("\n");
+ const shellTable = (opts.rows ?? table)
+ .map((r) => `${r.pid} ${r.pgid} ${r.lstart} ${r.command}`)
+ .join("\n");
writeFileSync(join(scratch, "table.txt"), `${shellTable}\n`);
// honours `-p <pid>` with `-o command=` (mag_ok) and prints the whole table otherwise
writeFileSync(
@@ -178,6 +182,36 @@ describe("the generated watcher shell agrees with the TS predicates on the same
if (!dash.error) expect(dash.status).toBe(0);
});
+ test("escaped_live ≡ liveEscaped: an own-group descendant, listed only while its (pid, start) matches", () => {
+ // Claude Code 2.1.291 runs a run_in_background Bash as its own group leader (measured)
+ const bg: PsRow = {
+ pid: leader.pid + 7001,
+ ppid: leader.pid,
+ pgid: leader.pid + 7001,
+ lstart: leader.lstart,
+ command: "/bin/zsh -c eval 'sleep 317'",
+ };
+ const withBg = [...table, bg];
+ const snap = verifiedGroupSnapshot(withBg, fx.panePid, pane) as GroupSnapshot;
+ expect(snap.escaped).toEqual([{ pid: bg.pid, lstart: bg.lstart }]);
+ expect(parseGroupFile(formatGroupFile(snap))).toEqual(snap);
+ expect(groupCheck(withBg, snap)).toBe(true);
+ expect(liveEscaped(withBg, snap)).toEqual([bg.pid]);
+ const reused = withBg.map((r) =>
+ r.pid === bg.pid ? { ...r, lstart: "Thu Jan 1 00:00:00 2099" } : r
+ );
+ expect(liveEscaped(reused, snap)).toEqual([]);
+ const ctl = join(scratch, "launch-EsC123");
+ mkdirSync(ctl, { recursive: true });
+ writeFileSync(join(ctl, "group"), formatGroupFile(snap));
+ expect(shell("escaped_live", { ctl, rows: withBg })).toBe(String(bg.pid));
+ expect(shell("escaped_live", { ctl, rows: reused })).toBe("");
+ // a member line never matches an escaped row: group_ok still needs the recorded pgid
+ expect(shell(`pg=${bg.pgid}; member_in_pg && echo Y || echo N`, { ctl, rows: withBg })).toBe(
+ "N"
+ );
+ });
+
test("mag_ok / find_mag", () => {
expect(shell(`mag=${magRow.pid}; mag_ok && echo Y || echo N`)).toBe("Y");
expect(shell(`mag=${leader.pid}; mag_ok && echo Y || echo N`)).toBe("N");
diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.ts
index cc671b01..7d2f4846 100644
--- a/packages/cli/src/pane/process-identity.ts
+++ b/packages/cli/src/pane/process-identity.ts
@@ -45,6 +45,13 @@ export interface GroupMember {
export interface GroupSnapshot {
pgid: number;
members: GroupMember[];
+ /**
+ * Descendants of group members that run in a process group of their OWN. Measured
+ * (code-review iteration 1, Claude Code 2.1.291): a `run_in_background` Bash shell is
+ * its own group leader (pgid = its pid), so a group signal never reaches it. Each is
+ * signalled by pid, only while its (pid, start time) pair still matches.
+ */
+ escaped?: GroupMember[];
}
/** What identifies one pane's processes. */
@@ -167,7 +174,40 @@ export function verifiedGroupSnapshot(
if (!Number.isInteger(pgid) || pgid <= 1) return null;
const members = table.filter((r) => r.pgid === pgid);
if (!members.some((r) => paneIdentityMatches(r.command, pane))) return null;
- return { pgid, members: members.map((r) => ({ pid: r.pid, lstart: r.lstart })) };
+ return withEscaped(
+ pgid,
+ members.map((r) => ({ pid: r.pid, lstart: r.lstart })),
+ escapedDescendants(table, pgid, new Set(members.map((r) => r.pid)))
+ );
+}
+
+function withEscaped(pgid: number, members: GroupMember[], escaped: GroupMember[]): GroupSnapshot {
+ return escaped.length ? { pgid, members, escaped } : { pgid, members };
+}
+
+/** Processes outside group `pgid` whose parent chain reaches one of its members. */
+function escapedDescendants(table: PsRow[], pgid: number, inGroup: Set<number>): GroupMember[] {
+ const parentOf = new Map(table.map((r) => [r.pid, r.ppid]));
+ const out: GroupMember[] = [];
+ for (const r of table) {
+ if (r.pgid === pgid) continue;
+ let p = r.ppid;
+ for (let hops = 0; hops < 64 && p > 1; hops++) {
+ if (inGroup.has(p)) {
+ out.push({ pid: r.pid, lstart: r.lstart });
+ break;
+ }
+ p = parentOf.get(p) ?? 0;
+ }
+ }
+ return out;
+}
+
+/** The recorded escaped descendants still alive: same pid AND same start time. */
+export function liveEscaped(table: PsRow[], snap: GroupSnapshot | null): number[] {
+ if (!snap?.escaped?.length) return [];
+ const keys = new Set(snap.escaped.map((m) => `${m.pid} ${collapse(m.lstart)}`));
+ return table.filter((r) => keys.has(`${r.pid} ${r.lstart}`)).map((r) => r.pid);
}
/**
@@ -184,15 +224,19 @@ export function mergeSnapshots(
): GroupSnapshot | null {
if (!a) return b;
if (!b || b.pgid !== a.pgid || b.members.length === 0) return a;
- return { pgid: a.pgid, members: [...b.members] };
+ return withEscaped(a.pgid, [...b.members], [...(b.escaped ?? [])]);
}
/** Same pgid and the same (pid, start) members, in any order. */
export function sameSnapshot(a: GroupSnapshot | null, b: GroupSnapshot | null): boolean {
if (!a || !b) return a === b;
- if (a.pgid !== b.pgid || a.members.length !== b.members.length) return false;
- const keys = new Set(a.members.map((m) => `${m.pid} ${collapse(m.lstart)}`));
- return b.members.every((m) => keys.has(`${m.pid} ${collapse(m.lstart)}`));
+ if (a.pgid !== b.pgid) return false;
+ const same = (x: GroupMember[], y: GroupMember[]) => {
+ if (x.length !== y.length) return false;
+ const keys = new Set(x.map((m) => `${m.pid} ${collapse(m.lstart)}`));
+ return y.every((m) => keys.has(`${m.pid} ${collapse(m.lstart)}`));
+ };
+ return same(a.members, b.members) && same(a.escaped ?? [], b.escaped ?? []);
}
/**
@@ -205,9 +249,15 @@ export function groupCheck(table: PsRow[], snap: GroupSnapshot | null): boolean
return table.some((r) => r.pgid === snap.pgid && keys.has(`${r.pid} ${r.lstart}`));
}
-/** Serialise a snapshot as the `group` file: the pgid, then one `pid lstart` line per member. */
+/**
+ * Serialise a snapshot as the `group` file: the pgid, one `pid lstart` line per member,
+ * then `--` and one line per escaped descendant. \`member_in_pg\` reads only the lines
+ * before `--`, so an escaped line never widens the group check.
+ */
export function formatGroupFile(snap: GroupSnapshot): string {
- return `${snap.pgid}\n${snap.members.map((m) => `${m.pid} ${collapse(m.lstart)}`).join("\n")}\n`;
+ const line = (m: GroupMember) => `${m.pid} ${collapse(m.lstart)}`;
+ const esc = snap.escaped?.length ? `--\n${snap.escaped.map(line).join("\n")}\n` : "";
+ return `${snap.pgid}\n${snap.members.map(line).join("\n")}\n${esc}`;
}
export function parseGroupFile(text: string): GroupSnapshot | null {
@@ -215,11 +265,17 @@ export function parseGroupFile(text: string): GroupSnapshot | null {
const pgid = Number(lines[0]);
if (!Number.isInteger(pgid) || pgid <= 1) return null;
const members: GroupMember[] = [];
+ const escaped: GroupMember[] = [];
+ let into = members;
for (const l of lines.slice(1)) {
+ if (l.trim() === "--") {
+ into = escaped;
+ continue;
+ }
const m = l.match(/^(\d+) (.+)$/);
- if (m) members.push({ pid: Number(m[1]), lstart: collapse(m[2] ?? "") });
+ if (m) into.push({ pid: Number(m[1]), lstart: collapse(m[2] ?? "") });
}
- return { pgid, members };
+ return withEscaped(pgid, members, escaped);
}
/* ───────────────────────────── paths (R3-M2) ───────────────────────────── */
@@ -297,7 +353,7 @@ ident_in_pg() {
}
member_in_pg() {
[ -f "$CTL/group" ] || return 1
- pstable | P="$pg" awk '$2 == ENVIRON["P"] { print $1 " " $3 " " $4 " " $5 " " $6 " " $7 }' | grep -Fxq -f "$CTL/group"
+ pstable | P="$pg" G="$CTL/group" awk 'BEGIN { g = ENVIRON["G"]; while ((getline l < g) > 0) { if (++n == 1) continue; if (l == "--") break; k[l] = 1 } } $2 == ENVIRON["P"] && (($1 " " $3 " " $4 " " $5 " " $6 " " $7) in k) { f = 1 } END { exit !f }'
}
group_ok() {
case "$pg" in (''|*[!0-9]*|0|1) return 1;; esac
@@ -313,7 +369,11 @@ find_pg() {
fi
group_ok
}
-alive() { group_ok || mag_ok; }
+escaped_live() {
+ [ -f "$CTL/group" ] || return 0
+ pstable | G="$CTL/group" awk 'BEGIN { g = ENVIRON["G"]; while ((getline l < g) > 0) { if (l == "--") f = 1; else if (f) k[l] = 1 } } { if (($1 " " $3 " " $4 " " $5 " " $6 " " $7) in k) print $1 }'
+}
+alive() { group_ok || mag_ok || [ -n "$(escaped_live)" ]; }
settle_wait() { i=0; while [ "$i" -lt "$1" ] && alive; do sleep 0.2; i=$((i + 1)); done; }
launch_dir_ok() {
case "$1" in ("$ROOT"/launch-??????) ;; (*) return 1;; esac
@@ -332,6 +392,7 @@ find_pg
for s in TERM KILL; do
alive || break
group_ok && kill -"$s" -"$pg" 2>/dev/null
+ for e in $(escaped_live); do kill -"$s" "$e" 2>/dev/null; done
mag_ok && kill -"$s" "$mag" 2>/dev/null
if [ "$s" = TERM ]; then settle_wait 10; else settle_wait 5; fi
done
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
index 5cbb3c41..789e975b 100755
--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -551,6 +551,8 @@ async function runScenario(name: string, d: Delivered): Promise<void> {
return bgRewake(c);
case "bg_server":
return bgServer(c);
+ case "bg_detached":
+ return bgDetached(c);
case "ask_user":
case "ask_user_send":
case "interrupt_td":
@@ -667,6 +669,18 @@ async function bgServer(c: string): Promise<void> {
return answerTurn(c);
}
+/**
+ * A background shell in a process group of its OWN, as Claude Code 2.1.291 runs a
+ * `run_in_background` Bash (measured: pgid = the shell's pid). Unlike real Claude Code
+ * the fake never ends it on exit, so only claudish's reap can.
+ */
+async function bgDetached(c: string): Promise<void> {
+ const child = spawn("sleep", ["300"], { stdio: "ignore", detached: true });
+ child.unref();
+ if (env.FAKE_BG_PID_FILE && child.pid) writeFileSync(env.FAKE_BG_PID_FILE, String(child.pid));
+ return answerTurn(c);
+}
+
async function askUser(name: string, _c: string): Promise<void> {
const id = rec.toolUse("AskUserQuestion", T.askUse.message.content[0].input, {
template: T.askUse,