Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
refactor(recovery): move findOwnPane to pane/own-pane.ts
Jack Rudenkob8bf95843d23
diff --git a/packages/cli/src/pane/own-pane.test.ts b/packages/cli/src/pane/own-pane.test.tsnew file mode 100644index 00000000..f0edc84e--- /dev/null+++ b/packages/cli/src/pane/own-pane.test.ts@@ -0,0 +1,61 @@+/**+ * `findOwnPane`: the pane whose process is this process or one of its ancestors+ * (hook-system §7.5; one rule shared by the recovery banner and the interactive driver).+ * The live two-pane case is in `hooks/session/interactive-driver.integration.test.ts`.+ */++import { describe, expect, test } from "bun:test";+import { ancestorPids, findOwnPane, panesOfList } from "./own-pane.js";++const mine =+ (...pids: number[]) =>+ async () =>+ new Set(pids);++describe("panesOfList", () => {+ test("reads {panes: [...]} and a bare array; skips entries without a pane number", () => {+ expect(+ panesOfList({ panes: [{ pane: 0, pid: 10 }, { pane: 2, control: true }, { pid: 3 }] })+ ).toEqual([+ { pane: 0, pid: 10 },+ { pane: 2, pid: null },+ ]);+ expect(panesOfList([{ pane: 1, pid: 11 }])).toEqual([{ pane: 1, pid: 11 }]);+ expect(panesOfList(null)).toEqual([]);+ expect(panesOfList({ nope: true })).toEqual([]);+ });+});++describe("findOwnPane", () => {+ const list = async () => ({+ panes: [+ { pane: 0, pid: 100 },+ { pane: 1, pid: 200 },+ { pane: 2, control: true, hidden: true },+ ],+ });++ test("the pane whose pid is an ancestor — never pane 0 by default", async () => {+ expect(await findOwnPane(list, mine(999, 200, 50))).toBe(1);+ expect(await findOwnPane(list, mine(100))).toBe(0);+ });++ test("null when no pane's pid is this process or an ancestor", async () => {+ expect(await findOwnPane(list, mine(1, 2, 3))).toBeNull();+ });++ test("null when list fails or returns nothing", async () => {+ expect(await findOwnPane(async () => null, mine(100))).toBeNull();+ expect(+ await findOwnPane(async () => {+ throw new Error("socket closed");+ }, mine(100))+ ).toBeNull();+ });++ test("ancestorPids starts at this process and walks up through its parent", async () => {+ const pids = await ancestorPids();+ expect(pids.has(process.pid)).toBe(true);+ expect(pids.has(process.ppid)).toBe(true);+ });+});diff --git a/packages/cli/src/pane/own-pane.ts b/packages/cli/src/pane/own-pane.tsnew file mode 100644index 00000000..4cf91914--- /dev/null+++ b/packages/cli/src/pane/own-pane.ts@@ -0,0 +1,86 @@+/**+ * Which magmux pane this claudish process runs in, in a magmux claudish did not+ * launch (an ambient `MAGMUX_SOCK`: `team --grid --mode interactive`, or a pane the+ * user opened by hand).+ *+ * magmux exports `MAGMUX_SOCK` and `MAGMUX_THEME` to its panes and nothing that names+ * the pane, so the pane is found by process ancestry against `list`: the pane whose+ * pid is this process or one of its ancestors. Measured (hooks spike S2-2) in both+ * layouts that matter: claudish AS the pane process (matched at depth 0) and claudish+ * as the child of a shell that stays the pane process (matched at depth 1). In both+ * the pane was 1, not 0, so nothing may assume pane 0 outside a wrap.+ *+ * One rule, two callers: the recovery banner (`recovery/magmux-ui.ts`) and the+ * interactive driver (`hooks/session/interactive-driver.ts`). Each asks `list` over+ * its own connection and hands the reply's `result` here.+ */++import { execFile } from "node:child_process";+import { promisify } from "node:util";++const execFileAsync = promisify(execFile);++/** How many parents the ancestry walk visits above this process. */+export const ANCESTRY_DEPTH = 6;++/**+ * This process and its ancestors, up to `maxDepth` parents. The pane process is a+ * login shell or the claudish launcher, and this process runs somewhere beneath it.+ * Asynchronous on purpose: callers run inside the proxy while requests are served.+ */+export async function ancestorPids(maxDepth = ANCESTRY_DEPTH): Promise<Set<number>> {+ const out = new Set<number>([process.pid]);+ let pid = process.ppid;+ for (let i = 0; i < maxDepth && pid > 1; i++) {+ out.add(pid);+ try {+ const { stdout } = await execFileAsync("ps", ["-o", "ppid=", "-p", String(pid)], {+ timeout: 1_000,+ });+ const next = Number(stdout.trim());+ if (!Number.isFinite(next) || next <= 1) break;+ pid = next;+ } catch {+ break;+ }+ }+ return out;+}++/** The panes of a `list` reply's `result`: `{panes: [...]}` or a bare array. */+export function panesOfList(result: unknown): Array<{ pane: number; pid: number | null }> {+ const raw = Array.isArray(result)+ ? result+ : Array.isArray((result as { panes?: unknown } | null | undefined)?.panes)+ ? ((result as { panes: unknown[] }).panes as unknown[])+ : [];+ const out: Array<{ pane: number; pid: number | null }> = [];+ for (const p of raw) {+ const pane = (p as { pane?: unknown } | null)?.pane;+ const pid = (p as { pid?: unknown } | null)?.pid;+ if (typeof pane === "number") out.push({ pane, pid: typeof pid === "number" ? pid : null });+ }+ return out;+}++/**+ * The pane whose process is this process or one of its ancestors, or null when+ * none is. `list` returns the reply's `result` (null when the request failed);+ * `ancestors` is a test seam.+ */+export async function findOwnPane(+ list: () => Promise<unknown>,+ ancestors: () => Promise<Set<number>> = () => ancestorPids()+): Promise<number | null> {+ let result: unknown;+ try {+ result = await list();+ } catch {+ return null;+ }+ const panes = panesOfList(result);+ if (panes.length === 0) return null;+ const mine = await ancestors();+ for (const p of panes) if (p.pid !== null && mine.has(p.pid)) return p.pane;+ return null;+}diff --git a/packages/cli/src/recovery/magmux-ui.ts b/packages/cli/src/recovery/magmux-ui.tsindex 82a88929..562705d6 100644--- a/packages/cli/src/recovery/magmux-ui.ts+++ b/packages/cli/src/recovery/magmux-ui.ts@@ -41,11 +41,10 @@* its `ai-docs/feature-request-status-line.md`.*/-import { execFile } from "node:child_process";import { existsSync } from "node:fs";import { type Socket, connect as netConnect } from "node:net";-import { promisify } from "node:util";import { log } from "../logger.js";+import { findOwnPane } from "../pane/own-pane.js";import { recoveryClock } from "./clock.js";import {type RecoveryOutcome,@@ -57,8 +56,6 @@ import {} from "./coordinator.js";import { FRAME_TICK_MS, type RecoveryEpisodeFrame, UI_LEASE_MS } from "./types.js";-const execFileAsync = promisify(execFile);-/** How long the "recovered" banner stays up before the overlay is cleared. */export const OUTCOME_LINGER_MS = 4_000;@@ -183,6 +180,17 @@ export function describeLease(episodeId: string): {};}+/**+ * The recovery banner owns the pane right now: an outage is being painted (its+ * tick runs), a lease is held, or the recovered outcome is lingering. The+ * interactive driver never types an injection while this is true: the overlay+ * sits on top of the screen it reads, and the turn it would start is the turn+ * the outage is holding (architecture §7.5, the delivery gate).+ */+export function recoveryOverlayHeld(): boolean {+ return state.tickTimer !== null || state.lingerTimer !== null || state.leases.size > 0;+}+// ─── The magmux control connection ───────────────────────────────────────────async function connectControl(sock: string): Promise<Socket | null> {@@ -249,55 +257,13 @@ function dropConnection(): void {}/**- * This process and its ancestors, nearest first.- *- * In an ambient magmux the pane's process is whatever magmux started — usually- * a login shell or the `claudish` launcher — and this proxy runs somewhere- * beneath it. Asynchronous on purpose: it runs inside the proxy while requests- * are being served.- */-async function ancestorPids(maxDepth = 6): Promise<Set<number>> {- const out = new Set<number>([process.pid]);- let pid = process.ppid;- for (let i = 0; i < maxDepth && pid > 1; i++) {- out.add(pid);- try {- const { stdout } = await execFileAsync("ps", ["-o", "ppid=", "-p", String(pid)], {- timeout: 1_000,- });- const next = Number(stdout.trim());- if (!Number.isFinite(next) || next <= 1) break;- pid = next;- } catch {- break;- }- }- return out;-}--/**- * Which pane is ours, in a magmux claudish did not launch.- *- * magmux exports `MAGMUX_SOCK` and `MAGMUX_THEME` to its panes and nothing that- * names the pane, so it is found by process ancestry against `list`. Null when- * nothing matches: the banner is then unavailable, and recovery still retries- * and still answers the inline error at exhaustion.+ * Which pane is ours, in a magmux claudish did not launch: process ancestry+ * against `list` (`pane/own-pane.ts`, shared with the interactive driver). Null+ * when nothing matches: the banner is then unavailable, and recovery still+ * retries and still answers the inline error at exhaustion.*/-async function findOwnPane(socket: Socket): Promise<number | null> {- const reply = await request(socket, { type: "list" });- const result = reply?.result as { panes?: unknown } | unknown[] | undefined;- const panes = Array.isArray(result)- ? result- : Array.isArray((result as { panes?: unknown })?.panes)- ? ((result as { panes: unknown[] }).panes as unknown[])- : [];- const ancestors = await ancestorPids();- for (const p of panes) {- const pane = (p as { pane?: unknown }).pane;- const pid = (p as { pid?: unknown }).pid;- if (typeof pane === "number" && typeof pid === "number" && ancestors.has(pid)) return pane;- }- return null;+function findPaneOf(socket: Socket): Promise<number | null> {+ return findOwnPane(async () => (await request(socket, { type: "list" }))?.result ?? null);}/** Connect once and find our pane. Concurrent callers share one attempt. */@@ -328,7 +294,7 @@ function ensureConnected(): Promise<boolean> {state.control = socket;// A magmux claudish launched has exactly one `-e` pane, and magmux numbers// `-e` panes 0..N-1 in argument order, so Claude Code is pane 0.- const pane = endpoint.wrapped ? 0 : await findOwnPane(socket);+ const pane = endpoint.wrapped ? 0 : await findPaneOf(socket);if (pane === null) {state.paneNotFound = true;log("[Recovery] this claudish's pane was not found in magmux — no banner");