Skip to content

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

15.3 KB
Raw Blame
import { afterEach, describe, expect, test } from "bun:test";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
  FATAL_MAGMUX_STDERR,
  HOST_IDENTITY_VARS,
  LINUX_ENV_STRING_LIMIT,
  MIN_MAGMUX_VERSION,
  OWNER_START36,
  PaneEnvTooLargeError,
  SHELL_SHIM,
  assertMagmuxAvailable,
  buildClaudishPaneArgv,
  buildPaneEnv,
  createLaunchDirs,
  ensureSockRoot,
  isValidPaneId,
  launcherScript,
  mintPaneId,
  paneCommand,
  sockRootFor,
  versionAtLeast,
} from "./pane-launch.js";
import {
  WATCHER_ARGV0,
  WATCHER_SCRIPT,
  isLaunchDirPath,
  sockPathOf,
  watcherArgv,
} from "./process-identity.js";

const dirs: string[] = [];
afterEach(() => {
  for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
});

function tmp(): string {
  const d = mkdtempSync(join(tmpdir(), "pl-"));
  dirs.push(d);
  return d;
}

/** The release just below `v`: one patch down, or the last patch of the previous minor. */
function versionBelow(v: string): string {
  const [major = 0, minor = 0, patch = 0] = v.split(".").map((x) => Number.parseInt(x, 10));
  return patch > 0 ? `${major}.${minor}.${patch - 1}` : `${major}.${minor - 1}.9`;
}

describe("launcher and shim", () => {
  test("the launcher cds to the realpath cwd, then execs claudish; no watcher, no PATH line", () => {
    const s = launcherScript(
      "/tmp/a b/it's",
      { command: "/opt/bun", prefixArgs: ["run", "/x/index.ts"] },
      ["-i", "--model", "fake-answer"]
    );
    expect(s).toBe(
      `cd -- '/tmp/a b/it'\\''s' || exit 97\nexec '/opt/bun' 'run' '/x/index.ts' '-i' '--model' 'fake-answer'\n`
    );
    expect(s).not.toContain("PATH");
    expect(s).not.toContain("watcher");
  });

  test("the shim drops -l and execs /bin/sh, so no login profile runs", () => {
    expect(SHELL_SHIM).toBe('#!/bin/sh\n[ "$1" = -l ] && shift\nexec /bin/sh "$@"\n');
  });

  test("the -e value never names claude (magmux's controller would attach)", () => {
    expect(paneCommand("/tmp/claudish-mux-501/launch-AbC123")).toBe(
      ". '/tmp/claudish-mux-501/launch-AbC123/pane-launch.sh'"
    );
    expect(() => paneCommand("/tmp/claude ")).toThrow();
  });

  test("argv is -i --model X -y --quiet --session-id U --add-dir D, then the caller flags", () => {
    expect(buildClaudishPaneArgv("m", "u", "/d", ["--agent", "x"])).toEqual([
      "-i",
      "--model",
      "m",
      "-y",
      "--quiet",
      "--session-id",
      "u",
      "--add-dir",
      "/d",
      "--agent",
      "x",
    ]);
  });
});

describe("pane environment", () => {
  const parentEnv = {
    PATH: "/usr/bin",
    HOME: "/h",
    SHELL: "/bin/zsh",
    OPENAI_API_KEY: "k",
    CLAUDECODE: "1",
    CLAUDE_CODE_CHILD_SESSION: "1",
    MAGMUX_SOCK: "/tmp/outer.sock",
    MAGMUX_SOCK_DIR: "/tmp/outer",
    TMUX: "/tmp/tmux-501/default,1,0",
    TERM_PROGRAM: "iTerm.app",
    ITERM_SESSION_ID: "w0",
    VSCODE_PID: "1",
    COLUMNS: "80",
    LINES: "24",
    TERM: "xterm",
    SHLVL: "2",
    PWD: "/elsewhere",
    CLAUDISH_LAUNCHER_PID: "10",
    CLAUDISH_LAUNCHER_PPID: "9",
    CLAUDE_CODE_SESSION_ID: "host-session",
  };

  test("strips child, magmux, terminal-identity and host-identity keys; sets geometry and markers", () => {
    const { magmuxEnv } = buildPaneEnv({
      parentEnv,
      slotEnv: { CLAUDISH_TOKEN_FILE: "/t.json" },
      cwd: "/real/cwd",
      ctlDir: "/root/launch-AAAAAA",
      configFile: null,
    });
    for (const k of [
      "CLAUDECODE",
      "CLAUDE_CODE_CHILD_SESSION",
      "MAGMUX_SOCK",
      "MAGMUX_SOCK_DIR",
      "TMUX",
      "TERM_PROGRAM",
      "ITERM_SESSION_ID",
      "VSCODE_PID",
      ...HOST_IDENTITY_VARS,
    ])
      expect(magmuxEnv[k]).toBeUndefined();
    expect(magmuxEnv.COLUMNS).toBe("160");
    expect(magmuxEnv.LINES).toBe("50");
    expect(magmuxEnv.CLAUDISH_PANE_CHILD).toBe("1");
    expect(magmuxEnv.CLAUDISH_PANE_CWD).toBe("/real/cwd");
    expect(magmuxEnv.CLAUDISH_TOKEN_FILE).toBe("/t.json");
    expect(magmuxEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("1");
    expect(magmuxEnv.SHELL).toBe("/root/launch-AAAAAA/sh-shim");
  });

  test("the snapshot keeps the REAL SHELL and excludes shell-managed keys and itself", () => {
    const { magmuxEnv } = buildPaneEnv({
      parentEnv,
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    });
    const snap = JSON.parse(magmuxEnv.CLAUDISH_PANE_ENV as string);
    expect(snap.SHELL).toBe("/bin/zsh");
    expect(snap.OPENAI_API_KEY).toBe("k");
    for (const k of [
      "COLUMNS",
      "LINES",
      "TERM",
      "SHLVL",
      "PWD",
      "MAGMUX_SOCK",
      "CLAUDISH_PANE_ENV",
      "TMUX",
    ])
      expect(snap[k]).toBeUndefined();
    expect(snap.CLAUDISH_PANE_CHILD).toBe("1");
  });

  test("the parent's config file reaches the child in the env and the snapshot", () => {
    // A parent started with `--config <file>`: the override is passed explicitly, so
    // a parentEnv without CLAUDISH_CONFIG, or with another value, cannot drop it.
    const { magmuxEnv } = buildPaneEnv({
      parentEnv: { ...parentEnv, CLAUDISH_CONFIG: "/elsewhere.json" },
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: "/trusted/config.json",
    });
    expect(magmuxEnv.CLAUDISH_CONFIG).toBe("/trusted/config.json");
    expect(JSON.parse(magmuxEnv.CLAUDISH_PANE_ENV as string).CLAUDISH_CONFIG).toBe(
      "/trusted/config.json"
    );

    const none = buildPaneEnv({
      parentEnv,
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    });
    expect(none.magmuxEnv.CLAUDISH_CONFIG).toBeUndefined();
  });

  test("a caller's own CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is kept", () => {
    const { magmuxEnv } = buildPaneEnv({
      parentEnv: { ...parentEnv, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "0" },
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    });
    expect(magmuxEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("0");
  });

  // REGRESSION: pane child boot_timeout — self-drawn cursor on the placeholder read as typed text — /dev:fix session dev-fix-20261017-g10-socket
  test("CLAUDE_CODE_NATIVE_CURSOR defaults to 1 alongside the traffic default", () => {
    const { magmuxEnv } = buildPaneEnv({
      parentEnv,
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    });
    expect(magmuxEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("1");
    expect(magmuxEnv.CLAUDE_CODE_NATIVE_CURSOR).toBe("1");
    expect(JSON.parse(magmuxEnv.CLAUDISH_PANE_ENV as string).CLAUDE_CODE_NATIVE_CURSOR).toBe("1");
  });

  // REGRESSION: pane child boot_timeout — self-drawn cursor on the placeholder read as typed text — /dev:fix session dev-fix-20261017-g10-socket
  test("a caller's own CLAUDE_CODE_NATIVE_CURSOR is kept as given", () => {
    const { magmuxEnv } = buildPaneEnv({
      parentEnv: { ...parentEnv, CLAUDE_CODE_NATIVE_CURSOR: "yes" },
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    });
    expect(magmuxEnv.CLAUDE_CODE_NATIVE_CURSOR).toBe("yes");
  });

  test("the native cursor defaults to 1 when the caller turned traffic off itself", () => {
    const { magmuxEnv } = buildPaneEnv({
      parentEnv: { ...parentEnv, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" },
      slotEnv: {},
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    });
    expect(magmuxEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("1");
    expect(magmuxEnv.CLAUDE_CODE_NATIVE_CURSOR).toBe("1");
  });

  // REGRESSION: pane child boot_timeout — self-drawn cursor on the placeholder read as typed text — /dev:fix session dev-fix-20261017-g10-socket
  test("the slot env overrides both pane defaults and the parent's values", () => {
    const slotEnv = {
      CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "slot-traffic",
      CLAUDE_CODE_NATIVE_CURSOR: "slot-cursor",
    };
    const fromDefault = buildPaneEnv({
      parentEnv,
      slotEnv,
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    }).magmuxEnv;
    expect(fromDefault.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("slot-traffic");
    expect(fromDefault.CLAUDE_CODE_NATIVE_CURSOR).toBe("slot-cursor");
    const fromParent = buildPaneEnv({
      parentEnv: {
        ...parentEnv,
        CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "parent-traffic",
        CLAUDE_CODE_NATIVE_CURSOR: "parent-cursor",
      },
      slotEnv,
      cwd: "/c",
      ctlDir: "/r/launch-AAAAAA",
      configFile: null,
    }).magmuxEnv;
    expect(fromParent.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC).toBe("slot-traffic");
    expect(fromParent.CLAUDE_CODE_NATIVE_CURSOR).toBe("slot-cursor");
  });

  test("Linux refuses a snapshot over 131,000 bytes; macOS has no per-string limit", () => {
    const big = { ...parentEnv, BIG: "x".repeat(LINUX_ENV_STRING_LIMIT) };
    expect(() =>
      buildPaneEnv({
        parentEnv: big,
        slotEnv: {},
        cwd: "/c",
        ctlDir: "/r/launch-AAAAAA",
        configFile: null,
        platform: "linux",
      })
    ).toThrow(PaneEnvTooLargeError);
    expect(() =>
      buildPaneEnv({
        parentEnv: big,
        slotEnv: {},
        cwd: "/c",
        ctlDir: "/r/launch-AAAAAA",
        configFile: null,
        platform: "linux",
      })
    ).toThrow(/over Linux's 131072-byte limit per variable/);
    expect(() =>
      buildPaneEnv({
        parentEnv: big,
        slotEnv: {},
        cwd: "/c",
        ctlDir: "/r/launch-AAAAAA",
        configFile: null,
        platform: "darwin",
      })
    ).not.toThrow();
  });
});

describe("ids, socket paths and the socket root", () => {
  test("minted ids are valid, ≤ 40 chars, embed the owner pid and start", () => {
    const id = mintPaneId("t", "01-slot/with spaces");
    expect(isValidPaneId(id)).toBe(true);
    expect(id.length).toBeLessThanOrEqual(40);
    expect(id.startsWith(`c${process.pid}-${OWNER_START36}-t`)).toBe(true);
    expect(mintPaneId("s", "x")).not.toBe(mintPaneId("s", "x"));
  });

  test("ids: all digits and bad characters are refused (magmux would ignore them)", () => {
    expect(isValidPaneId("12345")).toBe(false);
    expect(isValidPaneId("a/b")).toBe(false);
    expect(isValidPaneId("x".repeat(65))).toBe(false);
    expect(isValidPaneId("c1-a-t01-abcdef")).toBe(true);
  });

  // REGRESSION: G-10 deep socket paths (>= 100 bytes) refused — Fixed in /dev:fix session dev-fix-20261017-g10-socket
  test("a 121-byte pane socket path is accepted", () => {
    expect(sockPathOf("/tmp/r", "c1-x")).toBe("/tmp/r/magmux-c1-x.sock");
    const id = "c1-abcdefghij";
    const fixed = Buffer.byteLength(join("/tmp/", `magmux-${id}.sock`)) + 1; // + the "/" after the root
    const root = `/tmp/${"d".repeat(121 - fixed)}`;
    const want = join(root, `magmux-${id}.sock`);
    expect(Buffer.byteLength(want)).toBe(121);
    expect(sockPathOf(root, id)).toBe(want);
  });

  test("CLAUDISH_PANE_ROOT overrides the default root", () => {
    expect(sockRootFor({ CLAUDISH_PANE_ROOT: "/tmp/cpt-1" })).toBe("/tmp/cpt-1");
    expect(sockRootFor({})).toMatch(/^\/tmp\/claudish-mux-\d+$/);
  });

  test("a trailing-slash or relative root is resolved once, so the launch-dir check still matches", () => {
    expect(sockRootFor({ CLAUDISH_PANE_ROOT: "/tmp/cpt-1/" })).toBe("/tmp/cpt-1");
    expect(sockRootFor({ CLAUDISH_PANE_ROOT: "rel/root" })).toBe(join(process.cwd(), "rel/root"));
    const base = tmp();
    const root = ensureSockRoot(`${join(base, "r")}/`);
    expect(root).toBe(join(base, "r"));
    const dirs = createLaunchDirs(root);
    expect(isLaunchDirPath(root, dirs.ctlDir)).toBe(true);
  });

  test("ensureSockRoot creates 0700 dirs and refuses a symlink or a group/world-readable dir", () => {
    const base = tmp();
    const root = join(base, "root");
    expect(ensureSockRoot(root)).toBe(root);
    const link = join(base, "link");
    symlinkSync(root, link);
    expect(() => ensureSockRoot(link)).toThrow(/not a real directory/);
    const open = join(base, "open");
    mkdirSync(open);
    chmodSync(open, 0o755);
    expect(() => ensureSockRoot(open)).toThrow(/must be 0700/);
  });
});

describe("watcher argv and version gate", () => {
  test("values reach the watcher only as positional parameters, under argv0 claudish-pane-watcher", () => {
    const a = watcherArgv({
      paneId: "c1-x-t01-abcdef",
      sessionUuid: "u'; rm -rf /",
      ctlDir: "/r/launch-AAAAAA",
      sockPath: "/r/magmux-c1-x-t01-abcdef.sock",
      recordPath: "/r/panes/c1-x-t01-abcdef.json",
      turnDir: "/r/launch-BBBBBB",
      sockRoot: "/r",
    });
    expect(a[0]).toBe("-c");
    expect(a[1]).toBe(WATCHER_SCRIPT);
    expect(a[2]).toBe(WATCHER_ARGV0);
    expect(a.slice(3)).toEqual([
      "c1-x-t01-abcdef",
      "u'; rm -rf /",
      "/r/launch-AAAAAA",
      "/r/magmux-c1-x-t01-abcdef.sock",
      "/r/panes/c1-x-t01-abcdef.json",
      "/r/launch-BBBBBB",
      "/r",
    ]);
    expect(WATCHER_SCRIPT).not.toContain("u'; rm -rf /");
  });

  test("the magmux version probe never blocks the event loop; an old version is refused", async () => {
    const dir = tmp();
    const slow = join(dir, "magmux-slow");
    writeFileSync(slow, `#!/bin/sh\nsleep 0.6\necho 'magmux ${MIN_MAGMUX_VERSION} (fake)'\n`);
    chmodSync(slow, 0o755);
    let ticks = 0;
    const timer = setInterval(() => ticks++, 50);
    try {
      expect(await assertMagmuxAvailable(slow)).toEqual({
        binary: slow,
        version: MIN_MAGMUX_VERSION,
      });
    } finally {
      clearInterval(timer);
    }
    expect(ticks).toBeGreaterThanOrEqual(5); // a synchronous probe would let none run
    const old = join(dir, "magmux-old");
    writeFileSync(old, `#!/bin/sh\necho 'magmux ${versionBelow(MIN_MAGMUX_VERSION)}'\n`);
    chmodSync(old, 0o755);
    await expect(assertMagmuxAvailable(old)).rejects.toThrow(`panes need >= ${MIN_MAGMUX_VERSION}`);
  });

  test("versionAtLeast", () => {
    expect(versionAtLeast("0.17.0", "0.17.0")).toBe(true);
    expect(versionAtLeast("0.17.2", "0.17.0")).toBe(true);
    expect(versionAtLeast("0.16.0", "0.17.0")).toBe(false);
    expect(versionAtLeast("1.0.0", "0.17.0")).toBe(true);
  });

  // REGRESSION: G-10 deep socket paths (>= 100 bytes) refused — Fixed in /dev:fix session dev-fix-20261017-g10-socket
  test("panes need magmux 0.18.0, the first release that binds and dials a deep socket", async () => {
    expect(MIN_MAGMUX_VERSION).toBe("0.18.0");
    const dir = tmp();
    const old = join(dir, "magmux-0.17.0");
    writeFileSync(old, "#!/bin/sh\necho 'magmux 0.17.0'\n");
    chmodSync(old, 0o755);
    await expect(assertMagmuxAvailable(old)).rejects.toThrow(
      "is version 0.17.0; panes need >= 0.18.0"
    );
  });

  // REGRESSION: G-10 deep socket paths (>= 100 bytes) refused — Fixed in /dev:fix session dev-fix-20261017-g10-socket
  test("magmux's loud --sock-dir / MAGMUX_SOCK_DIR refusal and a bind failure are fatal stderr", () => {
    expect(FATAL_MAGMUX_STDERR.test('magmux: --sock-dir "/x": not a directory')).toBe(true);
    expect(
      FATAL_MAGMUX_STDERR.test(
        'magmux: MAGMUX_SOCK_DIR "/x": cannot stat it: stat /x: no such file or directory'
      )
    ).toBe(true);
    expect(
      FATAL_MAGMUX_STDERR.test("magmux: socket /x/magmux-a.sock: bind: permission denied")
    ).toBe(true);
  });
});