Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(mcp): keep a pane's escaped background shell after its parent dies
Jack Rudenko70c0f11a552b
diff --git a/ai-docs/architecture/pane-session.md b/ai-docs/architecture/pane-session.mdindex 51ae3908..226edf1f 100644--- a/ai-docs/architecture/pane-session.md+++ b/ai-docs/architecture/pane-session.md@@ -187,7 +187,13 @@ after it, which was never observed.The normal reap ends it anyway — `close_pane` lets Claude Code end its own shells (measured) —but the group backstop, the owner-EOF watcher and the startup sweep record such descendants as`escaped` (pid, start) pairs after `--` in the group file and signal each by pid while its pair- still matches.+ still matches. A fresh snapshot finds an escaped process only while its parent chain reaches a+ member, and when `claude` dies without its own cleanup the shell is reparented to pid 1 while the+ claudish wrapper (a verified member) lives on. So a refresh keeps every recorded escaped pair+ that still matches the live table, plus that survivor's own descendants outside the group;+ replacing the list with the fresh one dropped the shell in exactly the crash this exists for+ (code-review iteration 2, M2). Dead or reused pairs drop out, so the list stays bounded. A shell+ started and orphaned between two 2 s ticks is never recorded; that window remains.**A turn that never gets its record.** When the activity is `finishing` (the model's message ended,Claude Code's end-of-turn record has not arrived) and the screen has been static with no Stop-hookdiff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.tsindex 5df504e4..aee014d3 100644--- a/packages/cli/src/pane/pane-registry.test.ts+++ b/packages/cli/src/pane/pane-registry.test.ts@@ -23,11 +23,13 @@ import {MAX_LIVE_PANES,PaneLimitError,type PaneRecord,+ type RegisteredPane,livePaneCount,ownerStartOfSelf,readRecord,readRecords,reapAllPanes,+ refreshGroupOf,releasePaneReservations,removePaneFiles,reservePanes,@@ -506,6 +508,100 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_}, 20_000);});+/** `ps -o <field>= -p <pid>`, or null when the pid is gone. */+function psField(pid: number, field: string): number | null {+ try {+ const v = execFileSync("ps", ["-o", `${field}=`, "-p", String(pid)], { encoding: "utf8" });+ return Number(v.trim());+ } catch {+ return null;+ }+}++describe("escaped background shells (code-review iteration 2, M2)", () => {+ test("a shell whose parent died before the wrapper stays in the group file; the watcher ends it, no orphan", async () => {+ const t = env();+ ensureSockRoot(t.sockRoot);+ const ctl = join(t.sockRoot, "launch-EsCaP1");+ const turn = join(t.sockRoot, "launch-EsCaP2");+ mkdirSync(ctl, { mode: 0o700 });+ mkdirSync(turn, { mode: 0o700 });+ const uuid = crypto.randomUUID();+ const paneId = `c${deadPid()}-zz-tescape-abcdef`;+ // The pane group, as a real pane runs it: a session leader standing in for the claudish+ // wrapper (its argv carries --session-id), and under it "claude", which starts a+ // background shell in a process group of its own (as 2.1.291 runs run_in_background)+ // and then dies on a line from the test while the wrapper lives on.+ const claude = `const c = require("node:child_process").spawn("sleep", ["300"], { detached: true, stdio: "ignore" }); c.unref(); console.log(c.pid); process.stdin.once("data", () => process.exit(0));`;+ const wrapper = spawn(+ "/bin/sh",+ ["-c", `"${process.execPath}" -e "$CLAUDE"; sleep 60; :`, "wrapper", "--session-id", uuid],+ {+ detached: true,+ stdio: ["pipe", "pipe", "ignore"],+ env: { PATH: "/usr/bin:/bin", CLAUDE: claude },+ }+ );+ extraProcs.push(wrapper);+ const bgPid = await new Promise<number>((resolve, reject) => {+ let buf = "";+ wrapper.stdout?.on("data", (d: Buffer) => {+ buf += d.toString();+ if (buf.includes("\n")) resolve(Number(buf.trim()));+ });+ wrapper.on("exit", (c) => reject(new Error(`wrapper exited ${c}`)));+ });+ const wrapperPid = wrapper.pid as number;+ try {+ expect(psField(bgPid, "pgid")).toBe(bgPid);+ const pane = {+ paneId,+ root: t.sockRoot,+ identity: { paneId, sessionUuid: uuid, ctlDir: ctl },+ panePid: () => wrapperPid,+ group: null,+ } as unknown as RegisteredPane;+ refreshGroupOf(pane, readProcessTable());+ expect(pane.group?.escaped?.map((m) => m.pid)).toEqual([bgPid]);++ wrapper.stdin?.write("die\n"); // claude dies without its own cleanup+ for (let i = 0; i < 100 && psField(bgPid, "ppid") !== 1; i++) await Bun.sleep(50);+ expect(psField(bgPid, "ppid")).toBe(1);+ // a refresh in the window between claude's death and the wrapper's exit, while the+ // wrapper still carries the identity (so the fresh snapshot is a verified one)+ const table = readProcessTable();+ expect(table.find((r) => r.pid === wrapperPid)?.command).toContain(`--session-id ${uuid}`);+ refreshGroupOf(pane, table);+ expect(pane.group?.members.some((m) => m.pid === wrapperPid)).toBe(true);+ expect(pane.group?.escaped?.map((m) => m.pid)).toEqual([bgPid]);++ // the owner is gone: the watcher reads the same group file and ends both+ const w = spawnPaneWatcher({+ paneId,+ sessionUuid: uuid,+ ctlDir: ctl,+ sockPath: join(t.sockRoot, `magmux-${paneId}.sock`),+ recordPath: join(t.sockRoot, "panes", `${paneId}.json`),+ turnDir: turn,+ sockRoot: t.sockRoot,+ });+ w.stdin?.end();+ expect(await waitForExit(w, 10_000)).toBe(true);+ expect(alive(wrapperPid)).toBe(false);+ expect(alive(bgPid)).toBe(false);+ expect(existsSync(ctl)).toBe(false);+ } finally {+ for (const target of [bgPid, -wrapperPid]) {+ try {+ process.kill(target, "SIGKILL");+ } catch {+ // already ended by the watcher+ }+ }+ }+ }, 30_000);+});+describe("records", () => {test("a record round-trips and is written 0600", () => {const t = env();diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.tsindex cecf6ad5..acd7b603 100644--- a/packages/cli/src/pane/pane-registry.ts+++ b/packages/cli/src/pane/pane-registry.ts@@ -258,7 +258,7 @@ export function refreshGroupOf(p: RegisteredPane, table: PsRow[]): void {const pid = p.panePid();if (!pid) return;const fresh = verifiedGroupSnapshot(table, pid, p.identity);- const merged = mergeSnapshots(p.group, fresh);+ const merged = mergeSnapshots(p.group, fresh, table);if (!merged || sameSnapshot(merged, p.group)) return;p.group = merged;writeGroupFile(p.identity.ctlDir, merged);@@ -426,7 +426,8 @@ function sweepGroup(const pgid = recorded?.pgid ?? rec.panePid ?? null;const group = mergeSnapshots(recorded,- pgid ? verifiedGroupSnapshot(table, pgid, identity) : null+ pgid ? verifiedGroupSnapshot(table, pgid, identity) : null,+ table);if (group || !mag) return group;const lead = table.find((r) => r.ppid === mag && r.pgid === r.pid);diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.tsindex 029ad0bd..428bedd1 100644--- a/packages/cli/src/pane/process-identity.test.ts+++ b/packages/cli/src/pane/process-identity.test.ts@@ -122,8 +122,8 @@ describe("TS predicates", () => {test("group file round trip and snapshot merge", () => {const snap = verifiedGroupSnapshot(table, fx.panePid, pane);expect(parseGroupFile(formatGroupFile(snap!))).toEqual(snap);- expect(mergeSnapshots(snap, { pgid: 7, members: [] })).toBe(snap);- expect(mergeSnapshots(snap, null)).toBe(snap);+ expect(mergeSnapshots(snap, { pgid: 7, members: [] }, table)).toBe(snap);+ expect(mergeSnapshots(snap, null, table)).toBe(snap);});test("merge prunes members that died: a long session's group record stays bounded", () => {@@ -131,14 +131,47 @@ describe("TS predicates", () => {// 500 ticks, each sampling a different short-lived process in the pane groupfor (let i = 0; i < 500; i++) {const brief: PsRow = { ...leader, pid: 90_000 + i, ppid: leader.pid, command: "ls -la" };- rec = mergeSnapshots(rec, verifiedGroupSnapshot([...table, brief], fx.panePid, pane));+ const withBrief = [...table, brief];+ rec = mergeSnapshots(rec, verifiedGroupSnapshot(withBrief, fx.panePid, pane), withBrief);}const live = verifiedGroupSnapshot(table, fx.panePid, pane);- rec = mergeSnapshots(rec, live);+ rec = mergeSnapshots(rec, live, table);expect(rec?.members.length).toBe(live?.members.length);expect(sameSnapshot(rec, live)).toBe(true);expect(groupCheck(table, rec)).toBe(true);});++ test("merge keeps a recorded escaped shell whose parent died while a verified member lives", () => {+ // claude (in the pane group) starts a run_in_background shell in its own group (measured on+ // 2.1.291), then dies without its own cleanup: the shell is reparented to pid 1 while the+ // claudish wrapper, which carries --session-id, is still a verified member.+ const claude: PsRow = { ...leader, pid: leader.pid + 11, ppid: leader.pid, command: "claude" };+ const bg: PsRow = {+ pid: leader.pid + 7002,+ ppid: claude.pid,+ pgid: leader.pid + 7002,+ lstart: leader.lstart,+ command: "/bin/zsh -c eval 'npm run dev'",+ };+ const before = [...table, claude, bg];+ const rec = verifiedGroupSnapshot(before, fx.panePid, pane) as GroupSnapshot;+ expect(rec.escaped).toEqual([{ pid: bg.pid, lstart: bg.lstart }]);++ const devServer: PsRow = { ...bg, pid: bg.pid + 1, ppid: bg.pid, command: "node server.js" };+ const after = [...table, { ...bg, ppid: 1 }, devServer];+ const fresh = verifiedGroupSnapshot(after, fx.panePid, pane) as GroupSnapshot;+ expect(fresh.escaped).toBeUndefined(); // the chain now ends at pid 1+ const merged = mergeSnapshots(rec, fresh, after) as GroupSnapshot;+ expect(merged.members).toEqual(fresh.members);+ expect(liveEscaped(after, merged).sort()).toEqual([bg.pid, devServer.pid].sort());++ // a recorded pair that died, or whose pid now has another start time, drops out+ const reused = after.map((r) =>+ r.pid === bg.pid ? { ...r, lstart: "Thu Jan 1 00:00:00 2099" } : r+ );+ expect(mergeSnapshots(rec, fresh, reused)?.escaped).toBeUndefined();+ expect(mergeSnapshots(rec, fresh, table)?.escaped).toBeUndefined();+ });});/** Run the watcher's shell functions against the same real table through a fake `ps`. */diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.tsindex 7d2f4846..6bad3404 100644--- a/packages/cli/src/pane/process-identity.ts+++ b/packages/cli/src/pane/process-identity.ts@@ -217,14 +217,40 @@ export function liveEscaped(table: PsRow[], snap: GroupSnapshot | null): number[* the recorded pgid): the fresh one replaces the record, which therefore stays bounded* over a session of days. With no fresh snapshot (no member carries the identity any* more) the record is kept as it is: it is what still recognises an orphaned grandchild.+ *+ * Escaped descendants are the exception to "the fresh one replaces": the fresh snapshot+ * finds one only while its parent chain still reaches a member, and when `claude` dies+ * without its own cleanup its `run_in_background` shells are reparented to pid 1 while+ * the claudish wrapper (a verified member) lives on. So the merged list is the fresh one+ * PLUS every recorded escaped (pid, start) pair still in `table` — the same process, by+ * the identity rule — plus that survivor's own descendants outside the group. Dead or+ * reused entries drop out, so this list stays bounded too.*/export function mergeSnapshots(a: GroupSnapshot | null,- b: GroupSnapshot | null+ b: GroupSnapshot | null,+ table: PsRow[]): GroupSnapshot | null {if (!a) return b;if (!b || b.pgid !== a.pgid || b.members.length === 0) return a;- return withEscaped(a.pgid, [...b.members], [...(b.escaped ?? [])]);+ const kept = new Set(liveEscaped(table, a));+ const survivors = table+ .filter((r) => kept.has(r.pid) && r.pgid !== a.pgid)+ .map((r) => ({ pid: r.pid, lstart: r.lstart }));+ const theirs = escapedDescendants(table, a.pgid, new Set(survivors.map((m) => m.pid)));+ return withEscaped(a.pgid, [...b.members], unionMembers(b.escaped ?? [], survivors, theirs));+}++function unionMembers(...lists: GroupMember[][]): GroupMember[] {+ const seen = new Set<string>();+ const out: GroupMember[] = [];+ for (const m of lists.flat()) {+ const k = `${m.pid} ${collapse(m.lstart)}`;+ if (seen.has(k)) continue;+ seen.add(k);+ out.push(m);+ }+ return out;}/** Same pgid and the same (pid, start) members, in any order. */