Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): add the magmux socket client for pane sessions
Jack Rudenko75259760ed25
diff --git a/packages/cli/src/pane/magmux-client.test.ts b/packages/cli/src/pane/magmux-client.test.tsnew file mode 100644index 00000000..a220bc71--- /dev/null+++ b/packages/cli/src/pane/magmux-client.test.ts@@ -0,0 +1,109 @@+import { afterEach, describe, expect, test } from "bun:test";+import { type ChildProcess, spawn } from "node:child_process";+import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync, rmSync } from "node:fs";+import { join } from "node:path";+import { waitForExit } from "../process-tree.js";+import { MagmuxClient } from "./magmux-client.js";+import { MAGMUX, NO_MAGMUX_MESSAGE, orphanReport } from "./test-helpers/hermetic-env.js";++const procs: ChildProcess[] = [];+const roots: string[] = [];++afterEach(async () => {+ for (const p of procs.splice(0)) {+ if (p.exitCode === null && p.signalCode === null) p.kill("SIGKILL");+ await waitForExit(p, 2000);+ }+ for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true });+});++function startMagmux(cmd: string): { sock: string; proc: ChildProcess; root: string } {+ const root = `/tmp/cmc-${randomBytes(4).toString("hex")}`;+ mkdirSync(root, { mode: 0o700 });+ roots.push(root);+ const id = `cmc-${randomBytes(3).toString("hex")}`;+ const proc = spawn(+ MAGMUX as string,+ ["--headless", "--no-status", "--id", id, "--sock-dir", root, "-e", cmd],+ {+ env: {+ PATH: process.env.PATH ?? "/usr/bin:/bin",+ HOME: root,+ SHELL: "/bin/sh",+ COLUMNS: "80",+ LINES: "24",+ },+ stdio: ["ignore", "ignore", "ignore"],+ detached: true,+ }+ );+ procs.push(proc);+ return { sock: join(root, `magmux-${id}.sock`), proc, root };+}++describe.skipIf(!MAGMUX)(+ `MagmuxClient against real magmux (${MAGMUX ? "" : NO_MAGMUX_MESSAGE})`,+ () => {+ test("connect retries until the socket binds; the first line is the aggregate snapshot", async () => {+ const m = startMagmux("sleep 30");+ const snaps: unknown[] = [];+ const c = await MagmuxClient.connect(m.sock);+ c.on("snapshot", (e) => snaps.push(e));+ const caps = await c.request<{ version: string; protocol: number }>({ type: "capabilities" });+ expect(caps.ok).toBe(true);+ if (caps.ok) expect(caps.result.protocol).toBe(1);+ c.close();+ });++ test("replies are correlated by id across concurrent requests; error replies carry the code", async () => {+ const m = startMagmux("sleep 30");+ const c = await MagmuxClient.connect(m.sock);+ const [a, b, bad] = await Promise.all([+ c.request({ type: "capabilities" }),+ c.request({ type: "list" }),+ c.request({ type: "capture", pane: 7 }),+ ]);+ expect(a.ok && "verbs" in a.result).toBe(true);+ expect(b.ok && Array.isArray((b.result as { panes?: unknown[] }).panes)).toBe(true);+ expect(bad).toMatchObject({ ok: false, code: "no_such_pane" });+ c.close();+ });++ test("a pane's own exit is pushed as an `exit` event with its code", async () => {+ const m = startMagmux("sleep 0.3; echo bye; exit 3");+ const c = await MagmuxClient.connect(m.sock);+ const exit = await new Promise<{ exitCode: number; lastLine: string }>((resolve) =>+ c.on("exit", resolve)+ );+ expect(exit.exitCode).toBe(3);+ expect(exit.lastLine).toBe("bye");+ await c.request({ type: "close_pane", pane: 0, force: true });+ c.close();+ });++ test("EOF resolves every pending request client_closed and emits disconnected; it is not a death", async () => {+ const m = startMagmux("sleep 30");+ const c = await MagmuxClient.connect(m.sock);+ const disc = new Promise<{ sawShutdown: boolean }>((r) => c.on("disconnected", r));+ // a watch reply arrives, then frames; a request still in flight when the peer dies resolves closed+ const pending = c.request({ type: "capabilities" }, 5000);+ m.proc.kill("SIGKILL");+ const [r, d] = await Promise.all([pending, disc]);+ expect(r.ok === true || (r.ok === false && r.code === "client_closed")).toBe(true);+ expect(d.sawShutdown).toBe(false);+ expect(await c.request({ type: "list" })).toMatchObject({ ok: false, code: "client_closed" });+ });++ test("close_pane on the last pane: results, shutdown, EOF with sawShutdown, socket removed", async () => {+ const m = startMagmux("sleep 30");+ const c = await MagmuxClient.connect(m.sock);+ const disc = new Promise<{ sawShutdown: boolean }>((r) => c.on("disconnected", r));+ expect((await c.request({ type: "close_pane", pane: 0, force: true })).ok).toBe(true);+ expect((await disc).sawShutdown).toBe(true);+ expect(await waitForExit(m.proc, 5000)).toBe(true);+ expect(existsSync(m.sock)).toBe(false);+ expect(orphanReport({ sockRoot: m.root }).processes).toEqual([]);+ });+ }+);diff --git a/packages/cli/src/pane/magmux-client.ts b/packages/cli/src/pane/magmux-client.tsnew file mode 100644index 00000000..5c1d260b--- /dev/null+++ b/packages/cli/src/pane/magmux-client.ts@@ -0,0 +1,207 @@+/**+ * One NDJSON connection to one headless magmux (architecture §2.4).+ *+ * One connection is one subscriber: the first line is always the aggregate `snapshot`,+ * every request carries a string id (`r<n>`) and gets exactly one `reply`, and+ * everything else is a pushed event (research-magmux §1–2). One reader buffers partial+ * lines across chunks and never awaits inside the data handler, so magmux's per-+ * subscriber limits (1024 messages / 8 MB / 2 s write deadline) are never hit by a+ * stall of ours.+ *+ * EOF is NOT a death signal: magmux keeps its panes when a client leaves, and closes slow+ * subscribers on its own. `disconnected` reports `sawShutdown` and the owner decides+ * (`PaneSession`'s reconnect, §2.9).+ */++import { type Socket, connect } from "node:net";++export type MagmuxReply<T = Record<string, unknown>> =+ | { ok: true; result: T }+ | { ok: false; code: string; error: string };++export type MagmuxEventName =+ | "snapshot"+ | "exit"+ | "pane_closed"+ | "results"+ | "shutdown"+ | "frame"+ | "disconnected";++// Events are untyped JSON from magmux; listeners narrow the fields they read.+// biome-ignore lint/suspicious/noExplicitAny: raw protocol events+type Listener = (e: any) => void;++export class MagmuxConnectError extends Error {+ constructor(+ message: string,+ readonly errno: string | null+ ) {+ super(message);+ }+}++function dialOnce(sockPath: string): Promise<Socket> {+ return new Promise((resolve, reject) => {+ const s = connect(sockPath);+ const onError = (e: NodeJS.ErrnoException) => {+ s.destroy();+ reject(new MagmuxConnectError(e.message, e.code ?? null));+ };+ s.once("error", onError);+ s.once("connect", () => {+ s.off("error", onError);+ resolve(s);+ });+ });+}++export class MagmuxClient {+ private buf = "";+ private nextId = 1;+ private pending = new Map<+ string,+ { resolve: (r: MagmuxReply) => void; timer: ReturnType<typeof setTimeout> }+ >();+ private listeners = new Map<string, Set<Listener>>();+ private closed = false;+ private sawShutdown = false;++ private constructor(private readonly sock: Socket) {+ sock.setEncoding("utf8");+ sock.on("data", (chunk: string) => this.onData(chunk));+ sock.on("error", () => {});+ sock.on("close", () => this.onClose());+ }++ /** Dial `sockPath`, retrying every `retryMs` (50) for up to `timeoutMs` (5000). */+ static async connect(+ sockPath: string,+ opts: { retryMs?: number; timeoutMs?: number; alive?: () => boolean } = {}+ ): Promise<MagmuxClient> {+ const retry = opts.retryMs ?? 50;+ const end = Date.now() + (opts.timeoutMs ?? 5000);+ let last: MagmuxConnectError | null = null;+ for (;;) {+ try {+ return new MagmuxClient(await dialOnce(sockPath));+ } catch (e) {+ last = e as MagmuxConnectError;+ }+ if (Date.now() >= end || (opts.alive && !opts.alive())) break;+ await Bun.sleep(retry);+ }+ throw last ?? new MagmuxConnectError(`cannot connect to ${sockPath}`, null);+ }++ /** One dial, no retry. */+ static async dial(sockPath: string): Promise<MagmuxClient> {+ return new MagmuxClient(await dialOnce(sockPath));+ }++ get isClosed(): boolean {+ return this.closed;+ }++ request<T = Record<string, unknown>>(+ msg: Record<string, unknown>,+ timeoutMs = 10_000+ ): Promise<MagmuxReply<T>> {+ if (this.closed)+ return Promise.resolve({ ok: false, code: "client_closed", error: "connection closed" });+ const id = `r${this.nextId++}`;+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ resolve({ ok: false, code: "client_timeout", error: `no reply in ${timeoutMs} ms` });+ }, timeoutMs);+ this.pending.set(id, { resolve: resolve as (r: MagmuxReply) => void, timer });+ try {+ this.sock.write(`${JSON.stringify({ ...msg, id })}\n`);+ } catch {+ clearTimeout(timer);+ this.pending.delete(id);+ resolve({ ok: false, code: "client_closed", error: "write failed" });+ }+ });+ }++ on(ev: MagmuxEventName | string, fn: Listener): void {+ let set = this.listeners.get(ev);+ if (!set) {+ set = new Set();+ this.listeners.set(ev, set);+ }+ set.add(fn);+ }++ off(ev: string, fn: Listener): void {+ this.listeners.get(ev)?.delete(fn);+ }++ close(): void {+ if (this.closed) return;+ try {+ this.sock.destroy();+ } catch {+ // already gone+ }+ }++ private emit(ev: string, e: unknown): void {+ for (const fn of this.listeners.get(ev) ?? []) {+ try {+ fn(e);+ } catch {+ // a listener's bug must not kill the reader+ }+ }+ }++ private onData(chunk: string): void {+ this.buf += chunk;+ let nl = this.buf.indexOf("\n");+ while (nl >= 0) {+ const line = this.buf.slice(0, nl);+ this.buf = this.buf.slice(nl + 1);+ nl = this.buf.indexOf("\n");+ if (line.trim()) this.dispatch(line);+ }+ }++ private dispatch(line: string): void {+ let m: Record<string, unknown>;+ try {+ m = JSON.parse(line);+ } catch {+ return;+ }+ if (!m || typeof m !== "object") return;+ if (m.type === "reply" && typeof m.id === "string") {+ const p = this.pending.get(m.id);+ if (!p) return;+ clearTimeout(p.timer);+ this.pending.delete(m.id);+ p.resolve(+ m.ok === true+ ? { ok: true, result: (m.result ?? {}) as Record<string, unknown> }+ : { ok: false, code: String(m.code ?? "error"), error: String(m.error ?? "") }+ );+ return;+ }+ if (m.type === "shutdown") this.sawShutdown = true;+ // Unknown event types (control, overlay, changed, …) reach no listener.+ if (typeof m.type === "string") this.emit(m.type, m);+ }++ private onClose(): void {+ if (this.closed) return;+ this.closed = true;+ for (const [id, p] of this.pending) {+ clearTimeout(p.timer);+ p.resolve({ ok: false, code: "client_closed", error: "connection closed" });+ this.pending.delete(id);+ }+ this.emit("disconnected", { sawShutdown: this.sawShutdown });+ }+}diff --git a/packages/cli/src/pane/test-helpers/hermetic-env.ts b/packages/cli/src/pane/test-helpers/hermetic-env.tsnew file mode 100644index 00000000..ae7c70de--- /dev/null+++ b/packages/cli/src/pane/test-helpers/hermetic-env.ts@@ -0,0 +1,173 @@+/**+ * Hermetic environments for process-spawning pane tests (architecture §12.1). Test-only.+ *+ * The environment is built by ALLOWLIST, never by deleting from `process.env`: no+ * `ANTHROPIC_*` or provider key survives because none is listed, and `HOME`,+ * `CLAUDE_CONFIG_DIR`, `ZDOTDIR` and `XDG_CONFIG_HOME` all point into a temp dir, so+ * nothing reads or writes the real `~/.claude`, `~/.claudish` or the keychain.+ *+ * `sockRoot` is a short `/tmp/cpt-<8 hex>` so socket paths stay under 100 bytes.+ *+ * `assertNoOrphans` is the per-test no-orphan check: no process whose argv contains the+ * test's sockRoot or a session id, no process in any of the pane pgids, and no socket,+ * record or launcher dir left in sockRoot.+ */++import { randomBytes, randomUUID } from "node:crypto";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join } from "node:path";+import { findMagmuxBinaryOrNull } from "../../launcher/magmux-binary.js";+import { readProcessTable } from "../process-identity.js";++export const FAKE_CHILD = join(import.meta.dir, "fake-interactive-child.ts");+export const MAGMUX = findMagmuxBinaryOrNull();+export const NO_MAGMUX_MESSAGE = "magmux not installed — not checked";++export interface PaneTestEnv {+ tmp: string;+ home: string;+ configDir: string;+ cwd: string;+ sockRoot: string;+ env: Record<string, string>;+ /** a transcript path for `uuid` in this env's config dir (F1 slug of the realpath cwd) */+ transcriptPathFor(uuid: string): string;+ cleanup(): void;+}++export function makePaneTestEnv(extra: Record<string, string> = {}): PaneTestEnv {+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), "pane-test-")));+ const home = join(tmp, "home");+ const configDir = join(home, ".claude");+ const cwd = join(tmp, "cwd");+ mkdirSync(configDir, { recursive: true });+ mkdirSync(cwd, { recursive: true });+ mkdirSync(join(tmp, "xdg"), { recursive: true });+ const sockRoot = `/tmp/cpt-${randomBytes(4).toString("hex")}`;+ const env: Record<string, string> = {+ PATH: process.env.PATH ?? "/usr/bin:/bin",+ TMPDIR: process.env.TMPDIR ?? "/tmp",+ USER: process.env.USER ?? "test",+ LOGNAME: process.env.USER ?? "test",+ LANG: "en_US.UTF-8",+ HOME: home,+ CLAUDE_CONFIG_DIR: configDir,+ ZDOTDIR: home,+ XDG_CONFIG_HOME: join(tmp, "xdg"),+ SHELL: "/bin/zsh",+ CLAUDISH_DISABLE_KEYCHAIN: "1",+ CLAUDISH_DISABLE_OP: "1",+ CLAUDISH_DISABLE_CATALOG_WARM: "1",+ CLAUDISH_NO_PREDEFINED_ENDPOINTS: "1",+ CLAUDISH_BIN: FAKE_CHILD,+ CLAUDISH_PANE_ROOT: sockRoot,+ ...extra,+ };+ assertHermetic(env);+ const realCwd = realpathSync(cwd);+ return {+ tmp,+ home,+ configDir,+ cwd,+ sockRoot,+ env,+ transcriptPathFor: (uuid) =>+ join(configDir, "projects", realCwd.replace(/[^a-zA-Z0-9]/g, "-"), `${uuid}.jsonl`),+ cleanup() {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(sockRoot, { recursive: true, force: true });+ },+ };+}++/** Fail when HOME, CLAUDE_CONFIG_DIR or ZDOTDIR resolve under the real home. */+export function assertHermetic(env: Record<string, string>): void {+ const realHome = homedir();+ for (const k of ["HOME", "CLAUDE_CONFIG_DIR", "ZDOTDIR"]) {+ const v = env[k];+ if (!v) throw new Error(`hermetic env lacks ${k}`);+ if (v === realHome || v.startsWith(`${realHome}/`))+ throw new Error(`hermetic env ${k}=${v} is under the real home ${realHome}`);+ }+}++export function newSessionUuid(): string {+ return randomUUID();+}++/** A CLAUDE_PATH wrapper that runs the fake child in "claude" mode. */+export function writeFakeClaudeWrapper(dir: string): string {+ const p = join(dir, "fake-claude");+ writeFileSync(+ p,+ `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(FAKE_CHILD)} --fake-as-claude "$@"\n`,+ {+ mode: 0o755,+ }+ );+ return p;+}++export interface OrphanReport {+ processes: string[];+ files: string[];+}++export function orphanReport(o: {+ sockRoot: string;+ ids?: string[];+ pgids?: number[];+}): OrphanReport {+ const needles = [o.sockRoot, ...(o.ids ?? [])];+ const pgids = new Set((o.pgids ?? []).filter((p) => p > 1));+ const processes = readProcessTable()+ .filter((r) => r.pid !== process.pid)+ .filter((r) => needles.some((n) => r.command.includes(n)) || pgids.has(r.pgid))+ .map((r) => `${r.pid} ${r.pgid} ${r.command.slice(0, 200)}`);+ const files: string[] = [];+ if (existsSync(o.sockRoot)) {+ for (const n of readdirSync(o.sockRoot)) if (n !== "panes") files.push(n);+ if (existsSync(join(o.sockRoot, "panes")))+ for (const n of readdirSync(join(o.sockRoot, "panes"))) files.push(`panes/${n}`);+ }+ return { processes, files };+}++/** Wait up to `ms` for nothing of the test to remain; returns the last report. */+export async function waitNoOrphans(+ o: { sockRoot: string; ids?: string[]; pgids?: number[] },+ ms = 8000+): Promise<OrphanReport> {+ const end = Date.now() + ms;+ let r = orphanReport(o);+ while ((r.processes.length || r.files.length) && Date.now() < end) {+ await Bun.sleep(200);+ r = orphanReport(o);+ }+ return r;+}++/** SIGKILL anything a failed test left behind (by sockRoot / session id needles only). */+export function killLeftovers(o: { sockRoot: string; ids?: string[] }): void {+ const needles = [o.sockRoot, ...(o.ids ?? [])];+ for (const r of readProcessTable()) {+ if (r.pid === process.pid) continue;+ if (needles.some((n) => r.command.includes(n))) {+ try {+ process.kill(r.pid, "SIGKILL");+ } catch {+ // gone+ }+ }+ }+}