Skip to content

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

fix(pane): check a pane owner's start time from etime, not lstart

Jack Rudenko2b35fb372eee
diff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.ts
index 59295db6..32402364 100644
--- a/packages/cli/src/pane/pane-registry.test.ts
+++ b/packages/cli/src/pane/pane-registry.test.ts
@@ -792,14 +792,70 @@ describe("with the process table unavailable (a sandbox refuses ps): every pane
expect(livePaneCount(t.sockRoot)).toBe(1);
expect(await withProcessTableUnavailable(() => livePaneCount(t.sockRoot))).toBe(1);
});
+});
+
+describe("owner identity: one check for the pane limit, the record sweep and the socket sweep", () => {
+ const selfId = (start36: string) => `c${process.pid}-${start36}-towner-abcdef`;
- test("a record written with no ownerStart (its owner could not read ps) counts its live owner", () => {
+ test("no ownerStart: the start time the pane id embeds must match the live pid's", () => {
const table = requireProcessTable();
- expect(ownerAlive({ ownerPid: process.pid, ownerStart: "" }, table)).toBe(true);
- expect(ownerAlive({ ownerPid: deadPid(), ownerStart: "" }, table)).toBe(false);
- // a recorded start time still tells a reused pid apart
+ const owner = { ownerPid: process.pid, ownerStart: "" };
+ expect(ownerAlive({ ...owner, paneId: selfId(OWNER_START36) }, table)).toBe(true);
+ // the same pid now running a process that started an hour later: a reused pid
+ const anHourEarlier = (Number.parseInt(OWNER_START36, 36) - 3_600_000).toString(36);
+ expect(ownerAlive({ ...owner, paneId: selfId(anHourEarlier) }, table)).toBe(false);
+ const gone = deadPid();
expect(
- ownerAlive({ ownerPid: process.pid, ownerStart: "Thu Jan 1 00:00:00 1970" }, table)
+ ownerAlive(
+ { ownerPid: gone, ownerStart: "", paneId: `c${gone}-${OWNER_START36}-towner-abcdef` },
+ table
+ )
).toBe(false);
});
+
+ test("a recorded ownerStart still decides by lstart", () => {
+ const table = requireProcessTable();
+ const paneId = selfId(OWNER_START36);
+ expect(
+ ownerAlive({ paneId, ownerPid: process.pid, ownerStart: ownerStartOfSelf() }, table)
+ ).toBe(true);
+ expect(
+ ownerAlive({ paneId, ownerPid: process.pid, ownerStart: "Thu Jan 1 00:00:00 1970" }, table)
+ ).toBe(false);
+ });
+
+ test("the id start check does not depend on the process timezone", () => {
+ const dir = import.meta.dir;
+ const script = [
+ `import { ownerAlive } from ${JSON.stringify(join(dir, "pane-registry.ts"))};`,
+ `import { OWNER_START36 } from ${JSON.stringify(join(dir, "pane-launch.ts"))};`,
+ `import { readProcessTable } from ${JSON.stringify(join(dir, "process-identity.ts"))};`,
+ "const paneId = `c${process.pid}-${OWNER_START36}-ttz-abcdef`;",
+ 'console.log(ownerAlive({ paneId, ownerPid: process.pid, ownerStart: "" }, readProcessTable() ?? []));',
+ ].join("\n");
+ // at least two of these differ from any system zone
+ for (const tz of ["UTC", "Pacific/Kiritimati", "America/Adak"]) {
+ const r = Bun.spawnSync([process.execPath, "-e", script], {
+ env: { ...process.env, TZ: tz },
+ });
+ expect(`${tz}: ${r.stdout.toString().trim()}`).toBe(`${tz}: true`);
+ }
+ }, 30_000);
+
+ test("the recordless-socket sweep keeps a live owner's socket under a non-system TZ", async () => {
+ // bun test runs with TZ=UTC; the socket's id embeds this process's own start
+ const t = env();
+ const root = ensureSockRoot(t.sockRoot);
+ const sock = join(root, `magmux-${selfId(OWNER_START36)}.sock`);
+ const server = createServer((c) => c.end());
+ await new Promise<void>((resolve) => server.listen(sock, resolve));
+ try {
+ const r = await sweepOrphanPanes(root);
+ expect(r.cleaned).toEqual([]);
+ expect(r.kept).toEqual([]);
+ expect(existsSync(sock)).toBe(true);
+ } finally {
+ server.close();
+ }
+ }, 20_000);
});
diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.ts
index 385af09a..2add5095 100644
--- a/packages/cli/src/pane/pane-registry.ts
+++ b/packages/cli/src/pane/pane-registry.ts
@@ -49,6 +49,7 @@ import {
readProcessTableAsync,
recordPathOf,
sameSnapshot,
+ startedAt,
verifiedGroupSnapshot,
} from "./process-identity.js";
@@ -89,16 +90,22 @@ export function ownerStartOfSelf(): string {
return row?.lstart ?? "";
}
+/** Who owns a pane: the record's fields, or the pid a recordless socket's pane id embeds. */
+export type PaneOwner = Pick<PaneRecord, "paneId" | "ownerPid" | "ownerStart">;
+
/**
- * The record's owner is alive: same pid, same start time. A record written while its owner
- * could not read the table has no `ownerStart`, so its live pid alone counts as the owner.
+ * THE owner-liveness check, for the pane limit, the record sweep and the recordless-socket
+ * sweep: the owner's pid is alive and is the same process. A recorded `ownerStart` must
+ * equal the row's `lstart`. Without one (written while the owner could not read the
+ * table, or a recordless socket) the start time the pane id embeds must match the row's
+ * timezone-free `startMs`; an id that embeds none is not ours to judge and counts alive.
*/
-export function ownerAlive(
- rec: Pick<PaneRecord, "ownerPid" | "ownerStart">,
- table: PsRow[]
-): boolean {
- const row = table.find((r) => r.pid === rec.ownerPid);
- return !!row && (!rec.ownerStart || row.lstart === rec.ownerStart);
+export function ownerAlive(owner: PaneOwner, table: PsRow[]): boolean {
+ const row = table.find((r) => r.pid === owner.ownerPid);
+ if (!row) return false;
+ if (owner.ownerStart) return row.lstart === owner.ownerStart;
+ const minted = ownerOfPaneId(owner.paneId);
+ return !minted || startedAt(row, minted.startMs);
}
/* ───────────────────────────── records ───────────────────────────── */
@@ -513,13 +520,10 @@ export function ownerOfPaneId(id: string): { pid: number; startMs: number } | nu
return { pid: Number(m[1]), startMs: Number.parseInt(m[2] ?? "", 36) };
}
-function ownerOfIdAlive(id: string, table: PsRow[]): boolean {
+/** The owner a recordless socket's pane id names; null when the id embeds none. */
+function ownerOfSocketId(id: string): PaneOwner | null {
const o = ownerOfPaneId(id);
- if (!o) return true; // not ours to judge
- const row = table.find((r) => r.pid === o.pid);
- if (!row) return false;
- const started = Date.parse(row.lstart);
- return !Number.isFinite(started) || Math.abs(started - o.startMs) < 2000;
+ return o ? { paneId: id, ownerPid: o.pid, ownerStart: "" } : null;
}
async function sweepRecordlessSocket(root: string, name: string, out: SweepResult): Promise<void> {
@@ -529,7 +533,8 @@ async function sweepRecordlessSocket(root: string, name: string, out: SweepResul
out.kept.push(id); // the owner may be alive and the socket a live magmux's
return;
}
- if (ownerOfIdAlive(id, table)) return;
+ const owner = ownerOfSocketId(id);
+ if (!owner || ownerAlive(owner, table)) return; // no owner in the id: not ours to judge
const sockPath = join(root, name);
let client: MagmuxClient | null = null;
try {
diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.ts
index 3d291515..d0a98932 100644
--- a/packages/cli/src/pane/process-identity.test.ts
+++ b/packages/cli/src/pane/process-identity.test.ts
@@ -16,6 +16,7 @@ import {
type PsRow,
WATCHER_FUNCTIONS,
WATCHER_SCRIPT,
+ etimeSeconds,
formatGroupFile,
groupCheck,
isLaunchDirPath,
@@ -30,6 +31,7 @@ import {
readProcessTableAsync,
sameSnapshot,
setPsSpawnForTest,
+ startedAt,
verifiedGroupSnapshot,
} from "./process-identity.js";
import { FIXTURES } from "./test-helpers/fixtures.js";
@@ -337,6 +339,34 @@ describe("the generated watcher shell agrees with the TS predicates on the same
});
});
+describe("start times from etime (timezone-free)", () => {
+ test("etime forms: mm:ss, hh:mm:ss, dd-hh:mm:ss", () => {
+ expect(etimeSeconds("05:07")).toBe(307);
+ expect(etimeSeconds("1:02:03")).toBe(3723);
+ expect(etimeSeconds("01-02:32:10")).toBe(95_530);
+ });
+
+ test("a row with etime gets startMs = spawn time - etime; a row without it parses as before", () => {
+ const at = Date.UTC(2026, 9, 20, 12, 0, 0);
+ const [row] = parsePsTable(
+ " 796 1 796 01-02:30:47 Mon Oct 19 20:34:11 2026 /System/Finder\n",
+ at
+ );
+ expect(row).toMatchObject({ pid: 796, pgid: 796, lstart: "Mon Oct 19 20:34:11 2026" });
+ expect(row?.command).toBe("/System/Finder");
+ expect(row?.startMs).toBe(at - 95_447_000);
+ expect(startedAt(row as PsRow, at - 95_447_000 + 1500)).toBe(true);
+ expect(startedAt(row as PsRow, at - 95_447_000 + 2500)).toBe(false);
+ expect(parsePsTable(fx.ps).every((r) => r.startMs === undefined)).toBe(true);
+ });
+
+ test("a real read carries this process's start within the tolerance", () => {
+ const self = readProcessTable()?.find((r) => r.pid === process.pid) as PsRow;
+ const started = Date.now() - process.uptime() * 1000;
+ expect(Math.abs((self.startMs as number) - started)).toBeLessThan(2000);
+ });
+});
+
describe("the process table when ps cannot run (macOS refuses the setuid ps in any sandbox)", () => {
test("a real read lists the reader itself, synchronously and asynchronously", async () => {
expect(readProcessTable()?.some((r) => r.pid === process.pid)).toBe(true);
diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.ts
index 8551138a..cb9071b5 100644
--- a/packages/cli/src/pane/process-identity.ts
+++ b/packages/cli/src/pane/process-identity.ts
@@ -15,8 +15,9 @@
* not reused while any member lives, so a passing check proves the group is the
* pane's — even when only an unidentifiable grandchild is left.
*
- * Every process-table read is ONE `LC_ALL=C ps -ax -ww -o pid=,ppid=,pgid=,lstart=,command=`
- * (portable across macOS and Linux; `ps -g` means different things on the two).
+ * Every process-table read is ONE
+ * `LC_ALL=C ps -ax -ww -o pid=,ppid=,pgid=,etime=,lstart=,command=` (portable across macOS
+ * and Linux; `ps -g` means different things on the two).
*
* Paths are validated before any `rm` (R3-M2): a control or turn directory is a DIRECT
* child of the socket root named `launch-` + six `[A-Za-z0-9]`; a socket is exactly
@@ -31,8 +32,17 @@ export interface PsRow {
pid: number;
ppid: number;
pgid: number;
- /** `lstart`, whitespace collapsed: `Mon Oct 6 12:34:56 2026` */
+ /**
+ * `lstart`, whitespace collapsed: `Mon Oct 6 12:34:56 2026`. Wall-clock time in the
+ * SYSTEM zone with no offset: an identity string, compared only with another `lstart`.
+ */
lstart: string;
+ /**
+ * Start time in epoch ms: when `ps` was spawned minus its `etime` (whole seconds), so
+ * within about 1 s and independent of every timezone. Absent when the read carried no
+ * `etime` column.
+ */
+ startMs?: number;
command: string;
}
@@ -62,30 +72,57 @@ export interface PaneIdentity {
ctlDir: string;
}
-const PS_ARGS = ["-ax", "-ww", "-o", "pid=,ppid=,pgid=,lstart=,command="];
-const PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d\d:\d\d:\d\d\s+\d{4})\s?(.*)$/;
+const PS_ARGS = ["-ax", "-ww", "-o", "pid=,ppid=,pgid=,etime=,lstart=,command="];
+// `etime` is `[[dd-]hh:]mm:ss`; it is optional so a recorded table without it still parses
+const PS_ROW =
+ /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(?:((?:\d+-)?(?:\d+:)?\d+:\d+)\s+)?(\S+\s+\S+\s+\d+\s+\d\d:\d\d:\d\d\s+\d{4})\s?(.*)$/;
export function collapse(s: string): string {
return s.trim().replace(/\s+/g, " ");
}
-/** Parse `ps -o pid=,ppid=,pgid=,lstart=,command=` output. Unparseable rows are dropped. */
-export function parsePsTable(text: string): PsRow[] {
+/** `etime` (`[[dd-]hh:]mm:ss`) in seconds. */
+export function etimeSeconds(etime: string): number {
+ const [days, clock] = etime.includes("-") ? etime.split("-") : ["0", etime];
+ const parts = (clock ?? "").split(":").map(Number);
+ while (parts.length < 3) parts.unshift(0);
+ const [h = 0, m = 0, s = 0] = parts;
+ return Number(days) * 86_400 + h * 3600 + m * 60 + s;
+}
+
+/**
+ * Parse `ps -o pid=,ppid=,pgid=[,etime=],lstart=,command=` output. Unparseable rows are
+ * dropped. `spawnedAtMs` (when that `ps` was spawned) turns each `etime` into `startMs`.
+ */
+export function parsePsTable(text: string, spawnedAtMs?: number): PsRow[] {
const rows: PsRow[] = [];
for (const line of text.split("\n")) {
const m = line.match(PS_ROW);
if (!m) continue;
- rows.push({
+ const row: PsRow = {
pid: Number(m[1]),
ppid: Number(m[2]),
pgid: Number(m[3]),
- lstart: collapse(m[4] ?? ""),
- command: (m[5] ?? "").trim(),
- });
+ lstart: collapse(m[5] ?? ""),
+ command: (m[6] ?? "").trim(),
+ };
+ if (m[4] && spawnedAtMs !== undefined) row.startMs = spawnedAtMs - etimeSeconds(m[4]) * 1000;
+ rows.push(row);
}
return rows;
}
+/** How far a `startMs` may sit from a start time measured in-process (`etime` is whole seconds). */
+const START_TOLERANCE_MS = 2000;
+
+/**
+ * `row` started at `startMs` (epoch ms, measured by the process itself), within
+ * `START_TOLERANCE_MS`. True when the row has no `startMs`: nothing to contradict it.
+ */
+export function startedAt(row: PsRow, startMs: number): boolean {
+ return row.startMs === undefined || Math.abs(row.startMs - startMs) < START_TOLERANCE_MS;
+}
+
/**
* The process table, or null when it is UNAVAILABLE: `ps` could not run, failed, or
* printed no row. A readable table is never empty (it lists the reader), so null never
@@ -139,14 +176,15 @@ export function processTableTrusted(rows: PsRow[]): boolean {
* or no trusted table (`processTableTrusted`). Both readers end here, so they agree on
* what "unavailable" is.
*/
-function tableOf(stdout: string | null): ProcessTable {
+function tableOf(stdout: string | null, spawnedAtMs: number): ProcessTable {
if (stdout === null) return null;
- const rows = parsePsTable(stdout);
+ const rows = parsePsTable(stdout, spawnedAtMs);
return processTableTrusted(rows) ? rows : null;
}
/** The whole process table, synchronously (exit hooks, the sweep); null when unavailable. */
export function readProcessTable(): ProcessTable {
+ const spawnedAt = Date.now();
let stdout: string | null;
try {
stdout = psSpawn.execFileSync("ps", PS_ARGS, {
@@ -156,7 +194,7 @@ export function readProcessTable(): ProcessTable {
} catch {
stdout = null;
}
- return tableOf(stdout);
+ return tableOf(stdout, spawnedAt);
}
/**
@@ -166,12 +204,13 @@ export function readProcessTable(): ProcessTable {
*/
export function readProcessTableAsync(): Promise<ProcessTable> {
return new Promise((resolve) => {
+ const spawnedAt = Date.now();
try {
psSpawn.execFile("ps", PS_ARGS, PS_OPTIONS, (err, stdout) =>
- resolve(tableOf(err ? null : String(stdout)))
+ resolve(tableOf(err ? null : String(stdout), spawnedAt))
);
} catch {
- resolve(tableOf(null));
+ resolve(tableOf(null, spawnedAt));
}
});
}