Skip to content

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

test(pane): prove a gated prompt is never lost or submitted twice

Jack Rudenko944d37ff7269
diff --git a/packages/cli/src/pane/pane-gated-delivery.integration.test.ts b/packages/cli/src/pane/pane-gated-delivery.integration.test.ts
new file mode 100644
index 00000000..3da3c1f5
--- /dev/null
+++ b/packages/cli/src/pane/pane-gated-delivery.integration.test.ts
@@ -0,0 +1,785 @@
+/** §10.2/R1.9 and D-A/D-B: real pinned magmux, fake child, PRODUCTION timings. */
+import { afterEach, describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { cpus } from "node:os";
+import { dirname, join } from "node:path";
+import { Worker } from "node:worker_threads";
+import { locateBox } from "./box-locate.js";
+import { gateBasisOf, parseGateBinding } from "./input-gate.js";
+import type { MagmuxReply } from "./magmux-client.js";
+import { inputBox } from "./screen-classifier.js";
+import type { ScreenState } from "./screen-model.js";
+import {
+ clientOf,
+ disposeGatePanes,
+ gateUntil,
+ gatedSends,
+ type GateRun,
+ startGatePane,
+ submissions,
+ type SendTrace,
+} from "./test-helpers/gated-pane.js";
+import { MAGMUX, NO_MAGMUX_MESSAGE } from "./test-helpers/hermetic-env.js";
+
+const T = 90_000;
+const PROMPT = "Reply with exactly PEAR.";
+const sha8 = (text: string) => createHash("sha1").update(text).digest("hex").slice(0, 8);
+const cases = [
+ { name: "plain", prompt: PROMPT, mode: "typed" },
+ { name: "command", prompt: "/model haiku", mode: "command" },
+ { name: "file", prompt: "First line.\nSecond line with `markdown` and **words**.", mode: "file" },
+] as const;
+
+function screen(r: GateRun): ScreenState {
+ const capture = r.s.capture(undefined, { spans: true });
+ if (!("lines" in capture)) throw new Error("full capture required");
+ return { ...capture, spans: capture.spans ?? [], alt: true, changedAt: 0, aboveBoxChangedAt: 0 };
+}
+
+function listResult(reply: MagmuxReply): Record<string, unknown> {
+ if (!reply.ok) throw new Error(`list failed: ${reply.code}: ${reply.error}`);
+ return reply.result;
+}
+
+async function settled(r: GateRun, count = 1): Promise<void> {
+ await gateUntil(r, (snapshot) => snapshot.turnsCompleted >= count, 45_000);
+}
+
+function assertOneCopy(r: GateRun, prompt: string): void {
+ const typed = gatedSends(r).filter(({ message }) => typeof message.text === "string");
+ expect(typed).toHaveLength(1);
+ expect(typeof typed[0]?.message.text).toBe("string");
+ expect(submissions(r).map(({ text }) => text)).toEqual([typed[0]?.message.text as string]);
+ expect(typed[0]?.message).toMatchObject({ typed: true });
+ if (prompt === "/model haiku") {
+ expect(submissions(r)[0]?.text).toBe(prompt);
+ expect(r.turns[0]?.answer).toBe("Set model to `haiku`");
+ } else {
+ expect(r.turns[0]?.answer).toBe(`ANSWER fake-${r.scenario} ${sha8(prompt)}`);
+ if (prompt.includes("\n")) {
+ expect(submissions(r)[0]?.text).toMatch(/^Your task is in the file `.+`\. Read all of it/);
+ expect(r.turns[0]?.delivery).toMatchObject({ mode: "file", complete: true });
+ } else expect(submissions(r)[0]?.text).toBe(prompt);
+ }
+}
+
+/** Real CPU load in separate threads; every thread is joined, including on assertion failure. */
+async function underLoad(work: () => Promise<void>): Promise<void> {
+ const workers: Worker[] = [];
+ try {
+ const ready: Promise<unknown>[] = [];
+ for (let i = 0; i < cpus().length; i++) {
+ const worker = new Worker(
+ `const { parentPort } = require('node:worker_threads'); parentPort.postMessage('ready'); let n = 0; while (true) { n = (n + Math.sqrt(n + 1)) % 1000000; }`,
+ { eval: true }
+ );
+ workers.push(worker);
+ ready.push(
+ new Promise((resolve, reject) => {
+ worker.once("message", resolve);
+ worker.once("error", reject);
+ })
+ );
+ }
+ await Promise.all(ready);
+ await work();
+ } finally {
+ await Promise.all(workers.map((worker) => worker.terminate()));
+ }
+}
+
+async function allRuns(runs: Promise<void>[]): Promise<void> {
+ // Do not leave sibling assertions polling after an early Promise.all rejection.
+ const results = await Promise.allSettled(runs);
+ const failed = results.find((result) => result.status === "rejected");
+ if (failed?.status === "rejected") throw failed.reason;
+}
+
+async function assertLoudLoss(r: GateRun, reason: string): Promise<void> {
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED", 40_000);
+ expect(snapshot.reason).toBe("prompt_not_accepted");
+ expect(snapshot.detail).toContain(`magmux not_accepted ${reason}`);
+ expect(snapshot.anomalies).not.toContain("degraded_mode");
+ expect(r.turns).toHaveLength(0);
+ expect(r.transitions.some(({ to }) => to === "EMPTY" || to === "COMPLETED")).toBe(false);
+ expect(submissions(r)).toEqual([]);
+ const failedAt = r.transitions.find(({ to }) => to === "FAILED")?.at ?? 0;
+ expect(failedAt - (gatedSends(r)[0]?.at ?? Infinity)).toBeGreaterThanOrEqual(29_000);
+ expect(failedAt - (gatedSends(r)[0]?.at ?? 0)).toBeLessThanOrEqual(31_000);
+}
+
+describe.skipIf(!MAGMUX)(
+ `gated delivery at production timings (${MAGMUX ? "real magmux" : NO_MAGMUX_MESSAGE})`,
+ () => {
+ afterEach(disposeGatePanes);
+
+ test(
+ "I1: promptless boot uses the declared gate, without a transcript or a send",
+ async () => {
+ const r = await startGatePane("answer");
+ await r.s.ready;
+ expect(r.s.snapshot().state).toBe("AWAITING_INPUT");
+ expect(r.s.diagnostics().gate?.ready).toBe(true);
+ expect(existsSync(r.transcript)).toBe(false);
+ expect(r.sends).toEqual([]);
+ const list = await clientOf(r).request({ type: "list" });
+ expect(gateBasisOf(listResult(list))).toBe("declared");
+ expect(parseGateBinding(listResult(list))).toMatchObject({
+ bound: "named",
+ sessionId: r.uuid,
+ });
+ },
+ T
+ );
+
+ for (const c of cases) {
+ test(
+ `DB-1 / I2-I4: 800 ms render lag submits the ${c.name} prompt exactly once`,
+ async () => {
+ const r = await startGatePane("answer", {
+ shape: "one-shot",
+ initialPrompt: c.prompt,
+ env: { FAKE_RENDER_LAG_MS: "800", FAKE_GAP_MS_WITNESS: "3000" },
+ });
+ await settled(r);
+ assertOneCopy(r, c.prompt);
+ expect(r.s.snapshot().state).toBe("COMPLETED");
+ if (c.name === "plain")
+ expect(r.s.diagnostics().lastSend).toMatchObject({
+ kind: "accepted",
+ accept: "confirmed",
+ evidence: "history",
+ });
+ if (c.name === "command") {
+ expect(gatedSends(r).map(({ message }) => message)).toMatchObject([
+ { text: c.prompt, enter: false, typed: true },
+ { keys: ["enter"], enter: false },
+ ]);
+ expect(gatedSends(r)[0]?.reply).toMatchObject({
+ ok: true,
+ result: { accept: "in_box" },
+ });
+ }
+ },
+ T
+ );
+ }
+
+ test(
+ "DB-1/DB-3 loaded: six panes, 800 ms render lag and late resets never duplicate a prompt",
+ async () => {
+ await underLoad(async () => {
+ await allRuns(
+ ["answer", "late_reset_swallow"].flatMap((scenario) =>
+ cases.map(async (c) => {
+ const r = await startGatePane(scenario, {
+ shape: "one-shot",
+ initialPrompt: c.prompt,
+ env: { FAKE_RENDER_LAG_MS: "800", FAKE_GAP_MS_WITNESS: "5000" },
+ });
+ await settled(r);
+ assertOneCopy(r, c.prompt);
+ if (scenario === "late_reset_swallow")
+ expect(r.s.snapshot().anomalies).toContain("gate_retyped:terminal_reset");
+ })
+ )
+ );
+ });
+ },
+ T * 2
+ );
+
+ test(
+ "DA-1: transcript off and Enter ignored fails loudly at 30 s, never as an empty answer",
+ async () => {
+ const r = await startGatePane("never_submit_transcript_off", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ });
+ await assertLoudLoss(r, "still_in_box");
+ expect(
+ gatedSends(r).filter(({ message }) => message.text === PROMPT).length
+ ).toBeLessThanOrEqual(2);
+ },
+ T
+ );
+
+ test(
+ "DA-2: a 12 s transcript gap and ignored first Enter still submit exactly one non-empty answer",
+ async () => {
+ const r = await startGatePane("enter_ignored_1", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ env: { FAKE_GAP_MS_WITNESS: "12000" },
+ });
+ await r.s.ready;
+ expect(r.s.snapshot().state).toBe("RUNNING");
+ // Initial delivery remains STARTING until confirmation or its OWN witness.
+ const runningAt = r.transitions.find(({ to }) => to === "RUNNING")?.at ?? 0;
+ const confirmation = gatedSends(r).find(
+ ({ reply }) => reply?.ok && reply.result.evidence === "history"
+ );
+ expect(confirmation?.repliedAt).toBeDefined();
+ expect(runningAt).toBeGreaterThanOrEqual(confirmation?.repliedAt ?? Infinity);
+ expect(existsSync(r.transcript)).toBe(false);
+ await settled(r);
+ assertOneCopy(r, PROMPT);
+ expect(r.s.snapshot().anomalies).toContain("gate_resent_enter");
+ },
+ T
+ );
+
+ test(
+ "DA loaded: six panes under CPU load either land once or fail prompt_not_accepted, never quietly lose a prompt",
+ async () => {
+ await underLoad(async () => {
+ await allRuns(
+ Array.from({ length: 6 }, async (_, i) => {
+ const loses = i % 2 === 0;
+ const scenario = loses ? "never_submit_transcript_off" : "enter_ignored_1";
+ const r = await startGatePane(scenario, {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ env: { FAKE_GAP_MS_WITNESS: "12000" },
+ });
+ if (loses) await assertLoudLoss(r, "still_in_box");
+ else {
+ await settled(r);
+ assertOneCopy(r, PROMPT);
+ }
+ })
+ );
+ });
+ },
+ T * 2
+ );
+
+ for (const command of [false, true]) {
+ test(
+ `DB-2 / I17: lost ${command ? "TYPE" : "SUBMIT"} reply never submits a second copy`,
+ async () => {
+ const prompt = command ? "/model haiku" : PROMPT;
+ const r = await startGatePane("answer", {
+ shape: "one-shot",
+ initialPrompt: prompt,
+ env: { FAKE_GAP_MS_WITNESS: "6000", FAKE_RENDER_LAG_MS: "800" },
+ });
+ const client = clientOf(r);
+ const real = client.request.bind(client);
+ let lost = false;
+ client.request = async (message, timeout) => {
+ const reply = await real(message, timeout);
+ if (message.type === "send" && typeof message.text === "string" && !lost) {
+ lost = true;
+ return {
+ ok: false,
+ code: "client_lost",
+ error: "connection closed after delivery, before reply",
+ };
+ }
+ return reply;
+ };
+ await settled(r);
+ expect(lost).toBe(true);
+ expect(submissions(r).map(({ text }) => text)).toEqual([prompt]);
+ expect(r.turns[0]?.answer).toBe(
+ command ? "Set model to `haiku`" : `ANSWER fake-answer ${sha8(prompt)}`
+ );
+ expect(r.s.snapshot().anomalies).toContain("send_reply_lost");
+ const typed = gatedSends(r).filter(({ message }) => typeof message.text === "string");
+ expect(typed).toHaveLength(command ? 2 : 1);
+ const clears = r.sends.filter(({ message }) =>
+ (message.keys as string[] | undefined)?.includes("ctrl-u")
+ );
+ expect(clears).toHaveLength(command ? 1 : 0);
+ if (command)
+ expect(clears[0]?.at).toBeGreaterThanOrEqual(typed[0]?.repliedAt ?? Infinity);
+ },
+ T
+ );
+ }
+
+ test(
+ "I17: a real socket drop during SUBMIT leaves magmux delivering, and the own witness accepts once",
+ async () => {
+ const r = await startGatePane("answer", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ env: { FAKE_GAP_MS_WITNESS: "6000", FAKE_RENDER_LAG_MS: "800" },
+ });
+ const client = clientOf(r);
+ const real = client.request.bind(client);
+ let dropped = false;
+ client.request = async (message, timeout) => {
+ const delivery = real(message, timeout);
+ if (message.type === "send" && typeof message.text === "string" && !dropped) {
+ dropped = true;
+ // Verification alone takes >= 1.2 s; close while that real request is out.
+ await Bun.sleep(100);
+ client.close();
+ }
+ return delivery;
+ };
+ await settled(r);
+ expect(dropped).toBe(true);
+ assertOneCopy(r, PROMPT);
+ expect(gatedSends(r)[0]?.reply).toMatchObject({ ok: false, code: "client_lost" });
+ expect(r.s.snapshot().anomalies).toContain("send_reply_lost");
+ expect(r.s.snapshot().anomalies).toContain("socket_reconnected");
+ },
+ T
+ );
+
+ test(
+ "I6: a created /cost prompt dismisses its panel once, then fails prompt_not_accepted with the panel detail",
+ async () => {
+ const r = await startGatePane("answer", { shape: "one-shot", initialPrompt: "/cost" });
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED");
+ expect(snapshot.reason).toBe("prompt_not_accepted");
+ expect(snapshot.detail).toContain("/cost opened a panel");
+ expect(snapshot.anomalies).toContain("panel_dismissed");
+ expect(snapshot.anomalies).toContain("panel_command");
+ expect(
+ r.sends.filter(({ message }) =>
+ (message.keys as string[] | undefined)?.includes("escape")
+ )
+ ).toHaveLength(1);
+ expect(submissions(r).map(({ text }) => text)).toEqual(["/cost"]);
+ expect(r.turns).toHaveLength(0);
+ },
+ T
+ );
+
+ for (const [scenario, cause] of [
+ ["late_reset_swallow", "terminal_reset"],
+ ["drop_first_prompt", "never_drawn"],
+ ] as const) {
+ test(
+ `DB-3 / F13: ${scenario} permits only magmux's one ${cause} retype`,
+ async () => {
+ const r = await startGatePane(scenario, {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ env: { FAKE_RENDER_LAG_MS: "800", FAKE_GAP_MS_WITNESS: "5000" },
+ });
+ await settled(r);
+ assertOneCopy(r, PROMPT);
+ const retyped = gatedSends(r).filter(
+ ({ reply }) => reply?.ok && reply.result.retyped === true
+ );
+ expect(retyped).toHaveLength(1);
+ expect(retyped[0]?.reply).toMatchObject({ ok: true, result: { retypeCause: cause } });
+ expect(
+ r.s.snapshot().anomalies.filter((anomaly) => anomaly === `gate_retyped:${cause}`)
+ ).toHaveLength(1);
+ },
+ T
+ );
+ }
+
+ test(
+ "I8: ignored Enters yield still_in_box twice, one ctrl-u, no third typed copy",
+ async () => {
+ const r = await startGatePane("enter_ignored_forever", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ });
+ await assertLoudLoss(r, "still_in_box");
+ expect(gatedSends(r)).toHaveLength(2);
+ expect(
+ gatedSends(r).every(({ reply }) => !reply?.ok && reply?.reason === "still_in_box")
+ ).toBe(true);
+ expect(
+ r.sends.filter(({ message }) =>
+ (message.keys as string[] | undefined)?.includes("ctrl-u")
+ )
+ ).toHaveLength(1);
+ const count = r.sends.length;
+ await Bun.sleep(1000);
+ expect(r.sends).toHaveLength(count);
+ },
+ T
+ );
+
+ test(
+ "I9: history withheld gives unconfirmed; only the delayed own transcript witness accepts",
+ async () => {
+ const r = await startGatePane("history_withheld", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ env: { FAKE_GAP_MS_WITNESS: "9000" },
+ });
+ await settled(r);
+ assertOneCopy(r, PROMPT);
+ expect(gatedSends(r)[0]?.reply).toMatchObject({
+ ok: false,
+ code: "not_accepted",
+ reason: "unconfirmed",
+ });
+ expect(r.s.snapshot().anomalies).toContain("gate_unconfirmed");
+ expect(readFileSync(r.transcript, "utf8")).toContain(PROMPT);
+ },
+ T
+ );
+
+ test(
+ "I10: vim insert after boot fails the created admission with vim_mode, not a 30 s timeout",
+ async () => {
+ const r = await startGatePane("vim_insert", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ prepare(t) {
+ t.env.FAKE_VIM_FILE = join(t.tmp, "enable-vim");
+ return {};
+ },
+ });
+ const client = clientOf(r);
+ const real = client.request.bind(client);
+ client.request = async (message, timeout) => {
+ if (message.type === "send" && typeof message.text === "string") {
+ writeFileSync(r.t.env.FAKE_VIM_FILE as string, "on");
+ await gateUntil(r, () => r.s.diagnostics().gate?.reason === "vim_mode");
+ }
+ return real(message, timeout);
+ };
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED");
+ expect(snapshot.reason).toBe("prompt_not_accepted");
+ expect(snapshot.detail).toContain("vim");
+ expect(snapshot.detail).toContain("-- INSERT --");
+ expect(snapshot.anomalies).toContain("gate_vim_mode");
+ expect(submissions(r)).toEqual([]);
+ expect(
+ (r.transitions.find(({ to }) => to === "FAILED")?.at ?? Infinity) -
+ (gatedSends(r)[0]?.at ?? 0)
+ ).toBeLessThan(12_000);
+ },
+ T
+ );
+
+ test(
+ "I10b: vim insert before the send fails prompt_not_accepted within 5 s without a gated send",
+ async () => {
+ const r = await startGatePane("vim_insert", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ prepare(t) {
+ t.env.FAKE_VIM_FILE = join(t.tmp, "enable-vim");
+ return {};
+ },
+ });
+ // Pause before the admission pre-check, not inside an already-started send (I10).
+ const driver = r.s as unknown as { runAdmission(admission: unknown): Promise<void> };
+ const real = driver.runAdmission.bind(driver);
+ let paused = false;
+ let resume = () => {};
+ const beforePrecheck = new Promise<void>((resolve) => {
+ resume = resolve;
+ });
+ driver.runAdmission = async (admission) => {
+ paused = true;
+ await beforePrecheck;
+ return real(admission);
+ };
+ try {
+ await gateUntil(r, () => paused);
+ writeFileSync(r.t.env.FAKE_VIM_FILE as string, "on");
+ await gateUntil(
+ r,
+ () =>
+ r.s.diagnostics().gate?.reason === "vim_mode" &&
+ screen(r).lines.some((line) => line.includes("-- INSERT --"))
+ );
+ const startedAt = Date.now();
+ resume();
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED", 5000);
+ expect(snapshot.reason).toBe("prompt_not_accepted");
+ expect(snapshot.detail).toContain("vim");
+ expect(snapshot.detail).toContain("-- INSERT --");
+ expect(snapshot.anomalies).toContain("gate_vim_mode");
+ expect(
+ (r.transitions.find(({ to }) => to === "FAILED")?.at ?? Infinity) - startedAt
+ ).toBeLessThan(5000);
+ expect(gatedSends(r)).toEqual([]);
+ expect(submissions(r)).toEqual([]);
+ expect(r.turns).toHaveLength(0);
+ } finally {
+ resume();
+ }
+ },
+ T
+ );
+
+ test(
+ "I11: a trust dialog fails with its words and no key is ever sent during boot",
+ async () => {
+ const r = await startGatePane("dialog_trust", { shape: "one-shot", initialPrompt: PROMPT });
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED");
+ expect(snapshot.reason).toBe("first_run_dialog");
+ expect(snapshot.detail).toContain("Is this a project you created or one you trust");
+ expect(r.sends).toEqual([]);
+ expect(submissions(r)).toEqual([]);
+ },
+ T
+ );
+
+ test(
+ "I14: a transcript-closed turn with box text settles after the 32 s gate grace, naming box_not_empty",
+ async () => {
+ const r = await startGatePane("settle_box_text", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ });
+ await gateUntil(
+ r,
+ () =>
+ existsSync(r.transcript) &&
+ readFileSync(r.transcript, "utf8").includes('"subtype":"turn_duration"')
+ );
+ const endedAt = Date.now();
+ await Bun.sleep(1000);
+ expect(r.s.snapshot().turnsCompleted).toBe(0);
+ await settled(r);
+ expect(Date.now() - endedAt).toBeGreaterThanOrEqual(30_000);
+ expect(r.s.snapshot().anomalies).toContain("settle_gate_unconfirmed:box_not_empty");
+ expect(r.turns[0]?.answer).toBe(`ANSWER fake-settle_box_text ${sha8(PROMPT)}`);
+ },
+ T
+ );
+
+ test(
+ "I15: resize to 400 columns and mid-turn to 600 and back retains the box and settles",
+ async () => {
+ const r = await startGatePane("tool_slow", { env: { FAKE_GAP_MS_TOOL: "5000" } });
+ await r.s.ready;
+ expect(await r.s.resize(400, 100)).toMatchObject({ cols: 400, rows: 100 });
+ await gateUntil(r, () => screen(r).cols === 400 && locateBox(screen(r)) !== null);
+ r.s.send(PROMPT);
+ await gateUntil(r, (s) => s.activity === "Bash");
+ expect(await r.s.resize(600, 120)).toMatchObject({ cols: 600, rows: 120 });
+ await gateUntil(r, () => screen(r).cols === 600 && locateBox(screen(r)) !== null);
+ await r.s.resize(400, 100);
+ await settled(r);
+ expect(screen(r).cols).toBe(400);
+ expect(locateBox(screen(r))).not.toBeNull();
+ expect(r.turns[0]?.answer).toBe(`ANSWER fake-tool_slow ${sha8(PROMPT)}`);
+ expect(submissions(r).map(({ text }) => text)).toEqual([PROMPT]);
+ },
+ T
+ );
+
+ test(
+ "I16: a starting refusal cannot leave a client request beyond the 30 s admission deadline",
+ async () => {
+ const r = await startGatePane("answer", { shape: "one-shot", initialPrompt: PROMPT });
+ // Client-response seam: hold each request for its real readyTimeoutMs. Never scale time.
+ const client = clientOf(r);
+ const real = client.request.bind(client);
+ let inFlight = 0;
+ client.request = async (message, timeout) => {
+ if (message.type !== "send" || message.noGate === true) return real(message, timeout);
+ const trace: SendTrace = { message: { ...message }, at: Date.now(), timeout };
+ r.sends.push(trace);
+ inFlight++;
+ try {
+ await Bun.sleep(message.readyTimeoutMs as number);
+ trace.reply = {
+ ok: false,
+ code: "busy",
+ reason: "starting",
+ error: "fake child is still starting",
+ };
+ trace.repliedAt = Date.now();
+ return trace.reply;
+ } finally {
+ inFlight--;
+ }
+ };
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED", 40_000);
+ expect(snapshot.reason).toBe("prompt_not_accepted");
+ expect(snapshot.detail).toContain("busy starting");
+ expect(inFlight).toBe(0);
+ const began = gatedSends(r)[0]?.at ?? 0;
+ const failedAt = r.transitions.find(({ to }) => to === "FAILED")?.at ?? 0;
+ expect(failedAt - began).toBeGreaterThanOrEqual(29_000);
+ expect(failedAt - began).toBeLessThanOrEqual(31_000);
+ expect(gatedSends(r).length).toBeGreaterThan(0);
+ for (const send of gatedSends(r)) {
+ expect(send.message.readyTimeoutMs as number).toBeGreaterThanOrEqual(1000);
+ expect(send.message.readyTimeoutMs as number).toBeLessThanOrEqual(10_000);
+ expect(send.at + (send.timeout ?? Infinity)).toBeLessThanOrEqual(began + 30_000);
+ expect(send.repliedAt).toBeDefined();
+ }
+ expect(submissions(r)).toEqual([]);
+ },
+ T
+ );
+
+ test(
+ "I19: a sibling in the same cwd cannot change the named binding, even before any transcript exists",
+ async () => {
+ const first = await startGatePane("answer", {
+ prepare(t, uuid) {
+ const config = join(t.tmp, "custom-config");
+ mkdirSync(config, { recursive: true });
+ t.env.CLAUDE_CONFIG_DIR = config;
+ return { transcriptPath: t.transcriptPathFor(uuid).replace(t.configDir, config) };
+ },
+ });
+ await first.s.ready;
+ const before = await clientOf(first).request({ type: "list" });
+ expect(parseGateBinding(listResult(before))).toMatchObject({
+ bound: "named",
+ sessionId: first.uuid,
+ transcriptPath: first.transcript,
+ });
+ expect(existsSync(first.transcript)).toBe(false);
+ const second = await startGatePane("answer", {
+ prepare(t, uuid) {
+ // Distinct socket roots and submit logs, one config directory and cwd.
+ t.env.HOME = first.t.home;
+ t.env.CLAUDE_CONFIG_DIR = first.t.env.CLAUDE_CONFIG_DIR as string;
+ return {
+ cwd: first.t.cwd,
+ transcriptPath: join(dirname(first.transcript), `${uuid}.jsonl`),
+ };
+ },
+ });
+ await second.s.ready;
+ const sibling = await clientOf(second).request({ type: "list" });
+ expect(parseGateBinding(listResult(sibling))).toMatchObject({
+ bound: "named",
+ sessionId: second.uuid,
+ transcriptPath: second.transcript,
+ });
+ expect(second.transcript.startsWith(`${first.t.env.CLAUDE_CONFIG_DIR}/projects/`)).toBe(
+ true
+ );
+ expect(second.transcript.startsWith(`${first.t.home}/.claude/`)).toBe(false);
+ second.s.send("sibling writes first");
+ await settled(second);
+ expect(existsSync(first.transcript)).toBe(false);
+ expect(
+ parseGateBinding(listResult(await clientOf(first).request({ type: "list" })))
+ ).toEqual(parseGateBinding(listResult(before)));
+ first.s.send(PROMPT);
+ await settled(first);
+ expect(first.turns[0]?.answer).toBe(`ANSWER fake-answer ${sha8(PROMPT)}`);
+ expect(
+ first.s.snapshot().anomalies.some((a) => a.startsWith("gate_dialog_at_admission:"))
+ ).toBe(false);
+ },
+ T
+ );
+
+ test(
+ "I20: a magmux with no named-binding flags fails input_gate_unbound before any send",
+ async () => {
+ const r = await startGatePane("answer", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ prepare(t) {
+ // Exercise the old unbound contract with the pinned binary; 0.16 itself is below the version floor.
+ const wrapper = join(t.tmp, "unbound-magmux");
+ writeFileSync(
+ wrapper,
+ `#!/bin/bash\nargs=()\nwhile (( $# )); do\ncase "$1" in\n--session-id|--transcript) shift 2;;\n*) args+=("$1"); shift;;\nesac\ndone\nexec ${JSON.stringify(MAGMUX)} "\${args[@]}"\n`,
+ { mode: 0o755 }
+ );
+ return { magmuxBinary: wrapper };
+ },
+ });
+ const snapshot = await gateUntil(r, (s) => s.state === "FAILED");
+ expect(snapshot.reason).toBe("pane_lost");
+ expect(snapshot.detail).toContain("input_gate_unbound");
+ expect(r.sends).toEqual([]);
+ expect(submissions(r)).toEqual([]);
+ },
+ T
+ );
+
+ for (const command of [false, true]) {
+ test(
+ `F14a: another writer's Enter on ${command ? "TYPE" : "SUBMIT"} is accepted without claudish's Enter`,
+ async () => {
+ const prompt = command ? "/model haiku" : PROMPT;
+ const r = await startGatePane("self_submit", {
+ shape: "one-shot",
+ initialPrompt: prompt,
+ env: { FAKE_GAP_MS_WITNESS: "5000" },
+ });
+ await settled(r);
+ expect(submissions(r).map(({ text }) => text)).toEqual([prompt]);
+ expect(gatedSends(r)).toHaveLength(1);
+ expect(gatedSends(r)[0]?.reply).toMatchObject({
+ ok: true,
+ result: { accept: "submitted_by_other", evidence: "history", enter: false },
+ });
+ expect(r.s.snapshot().anomalies).toContain("gate_submitted_by_other");
+ },
+ T
+ );
+ }
+
+ test(
+ "F14b: a leftBox text_mismatch is maybeSubmitted, no retry, and the delayed witness accepts",
+ async () => {
+ const r = await startGatePane("self_submit_history_withheld", {
+ shape: "one-shot",
+ initialPrompt: PROMPT,
+ });
+ await settled(r);
+ expect(submissions(r).map(({ text }) => text)).toEqual([PROMPT]);
+ expect(gatedSends(r)).toHaveLength(1);
+ expect(gatedSends(r)[0]?.reply).toMatchObject({
+ ok: false,
+ code: "not_accepted",
+ reason: "text_mismatch",
+ maybeSubmitted: true,
+ });
+ expect(r.s.snapshot().anomalies).toContain("gate_maybe_submitted_by_other");
+ expect(r.sends.filter(({ message }) => message.keys !== undefined)).toEqual([]);
+ expect(r.turns[0]?.answer).toBe(`ANSWER fake-self_submit_history_withheld ${sha8(PROMPT)}`);
+ },
+ T
+ );
+
+ test(
+ "F15: a command leaving the box after in_box yields empty_box, never a retyped command",
+ async () => {
+ const r = await startGatePane("command_left_box", {
+ shape: "one-shot",
+ initialPrompt: "/model haiku",
+ prepare(t) {
+ t.env.FAKE_COMMAND_LEFT_BOX_FILE = join(t.tmp, "command-may-leave");
+ return {};
+ },
+ });
+ const client = clientOf(r);
+ const real = client.request.bind(client);
+ client.request = async (message, timeout) => {
+ if (
+ message.type === "send" &&
+ (message.keys as string[] | undefined)?.includes("enter")
+ ) {
+ writeFileSync(r.t.env.FAKE_COMMAND_LEFT_BOX_FILE as string, "go");
+ await gateUntil(r, () => inputBox(screen(r))?.text === "");
+ }
+ return real(message, timeout);
+ };
+ await settled(r);
+ expect(submissions(r).map(({ text }) => text)).toEqual(["/model haiku"]);
+ expect(gatedSends(r)).toHaveLength(2);
+ expect(gatedSends(r)[0]?.reply).toMatchObject({ ok: true, result: { accept: "in_box" } });
+ expect(gatedSends(r)[1]?.reply).toMatchObject({
+ ok: false,
+ code: "not_accepted",
+ reason: "empty_box",
+ });
+ expect(r.s.snapshot().anomalies).toContain("gate_command_left_box");
+ expect(r.turns[0]?.answer).toBe("Set model to `haiku`");
+ },
+ T
+ );
+ }
+);
diff --git a/packages/cli/src/pane/pane-session.integration.test.ts b/packages/cli/src/pane/pane-session.integration.test.ts
index f672c600..3e58fc37 100644
--- a/packages/cli/src/pane/pane-session.integration.test.ts
+++ b/packages/cli/src/pane/pane-session.integration.test.ts
@@ -51,6 +51,7 @@ interface Run {
transitions: Array<[SlotState, SlotState]>;
turns: SettledTurn[];
blocks: PaneBlock[];
+ submits: Array<{ text: string; at: number }>;
}
/** team-like policy: verdict at the first settle; api error → FAILED; question → FAILED blocked */
@@ -65,7 +66,8 @@ async function start(
scenario: string,
over: Partial<PaneSessionOptions> & { env?: Record<string, string> } = {}
): Promise<Run> {
- const t = makePaneTestEnv(over.env ?? {});
+ const t = makePaneTestEnv({ CONTRACT_FAKE_MAX_MS: "60000", ...over.env });
+ t.env.FAKE_SUBMIT_LOG = join(t.tmp, "submits.jsonl");
const uuid = newSessionUuid();
const transitions: Array<[SlotState, SlotState]> = [];
const turns: SettledTurn[] = [];
@@ -102,7 +104,7 @@ async function start(
},
...rest,
});
- const run = { s, t, uuid, transitions, turns, blocks };
+ const run: Run = { s, t, uuid, transitions, turns, blocks, submits: [] };
open.add(run);
return run;
}
@@ -121,6 +123,13 @@ async function finish(r: Run, ms = 20_000): Promise<PaneSnapshot> {
open.delete(r);
r.s.cancel();
await r.s.reaped();
+ const log = r.t.env.FAKE_SUBMIT_LOG as string;
+ if (existsSync(log))
+ r.submits = readFileSync(log, "utf8")
+ .trim()
+ .split("\n")
+ .filter(Boolean)
+ .map((line) => JSON.parse(line));
const left = await waitNoOrphans({
sockRoot: r.t.sockRoot,
ids: [r.uuid],
@@ -175,8 +184,8 @@ interface InputSend {
at: number;
}
-/** Observe actual sends; optionally make ctrl-u leave the old line or a different draft. */
-function traceInput(r: Run, clear: "normal" | "ignored" | "different" = "normal"): InputSend[] {
+/** Observe actual sends without replacing the gate's decisions. */
+function traceInput(r: Run): InputSend[] {
const sends: InputSend[] = [];
const client = (r.s as unknown as { client: { request: Request } }).client;
const real = client.request.bind(client);
@@ -187,18 +196,6 @@ function traceInput(r: Run, clear: "normal" | "ignored" | "different" = "normal"
box: inputBox(screenOf(r))?.text ?? null,
at: Date.now(),
});
- if (Array.isArray(message.keys) && message.keys.includes("ctrl-u")) {
- if (clear === "ignored") return { ok: true };
- const reply = await real(message, ms);
- if (clear === "different") {
- await real(
- { type: "send", pane: 0, text: "Different unsent draft", typed: true, enter: false },
- ms
- );
- await until(r, () => inputBox(screenOf(r))?.text === "Different unsent draft");
- }
- return reply;
- }
}
return real(message, ms);
};
@@ -216,10 +213,10 @@ describe.skipIf(!MAGMUX)(
});
test(
- "production boot does not type until the empty REPL has been stable for three seconds",
+ "no_boot_reset: the gate waits its 3.5 second raw-terminal floor before typing",
async () => {
// Explicit undefined removes the helper's short test seam: exercise the production default.
- const r = await start("answer", { timings: { replStableMs: undefined } });
+ const r = await start("no_boot_reset", { timings: { replStableMs: undefined } });
const sends = traceInput(r);
try {
await until(r, () => readBoot(screenOf(r)).kind === "repl");
@@ -230,7 +227,7 @@ describe.skipIf(!MAGMUX)(
expect(snap.state).toBe("COMPLETED");
// Measure actual typing, not a sleep that can overshoot under concurrent process tests.
// The screen polling above can observe the first frame up to 50 ms late.
- expect((sends[0]?.at ?? 0) - firstEmptyBox).toBeGreaterThanOrEqual(2850);
+ expect((sends[0]?.at ?? 0) - firstEmptyBox).toBeGreaterThanOrEqual(3350);
expect(sends[0]?.message.text).toBe("Reply with exactly PEAR.");
expect(sends[0]?.message).toMatchObject({ typed: true, enter: true });
expect(sends).toHaveLength(1);
@@ -331,26 +328,19 @@ describe.skipIf(!MAGMUX)(
);
test(
- "menu_eats_enter: clear the stuck prompt, retype once, submit (retyped_prompt), never duplicate",
+ "menu_eats_enter: magmux resends Enter inside one gated SUBMIT, never retypes",
async () => {
const prompt = "Reply with exactly PEAR.";
- const r = await start("menu_eats_enter", { timings: { resendAfterMs: 800 } });
+ const r = await start("menu_eats_enter", { env: { FAKE_GAP_MS_WITNESS: "5000" } });
const sends = traceInput(r);
const snap = await finish(r);
expect(snap.state).toBe("COMPLETED");
- expect(snap.anomalies).toContain("resent_enter");
- expect(snap.anomalies.filter((a) => a === "retyped_prompt")).toHaveLength(1);
- expect(snap.anomalies).not.toContain("clear_failed");
- expect(sends).toHaveLength(3);
+ expect(snap.anomalies).toContain("gate_resent_enter");
expect(sends.map(({ message }) => message)).toMatchObject([
{ text: prompt, typed: true, enter: true },
- { keys: ["ctrl-u"], enter: false },
- { text: prompt, typed: true, enter: true },
]);
- const typed = sends.filter(({ message }) => typeof message.text === "string");
- expect(typed.every(({ message }) => message.typed === true)).toBe(true);
- expect(typed.map(({ box }) => box)).toEqual(["", ""]);
- expect(sends[1]?.box).toBe(prompt);
+ expect(sends).toHaveLength(1);
+ expect(r.submits.map(({ text }) => text)).toEqual([prompt]);
expect(r.turns).toHaveLength(1);
expect(r.turns[0]?.answer).toBe(`ANSWER fake-menu_eats_enter ${sha8(prompt)}`);
expect(snap.turnsCompleted).toBe(1);
@@ -359,48 +349,57 @@ describe.skipIf(!MAGMUX)(
);
test(
- "nudge: ctrl-u leaving different text records clear_failed and never types or submits a second copy",
+ "I21: a published leftover draft is cleared before the next gated send",
async () => {
- const r = await start("menu_eats_enter", {
- admitTimeoutMs: 5000,
- timings: { resendAfterMs: 800 },
+ const r = await start("answer", {
+ shape: "interactive",
+ initialPrompt: undefined,
+ decide: () => "continue",
});
- const sends = traceInput(r, "different");
- await until(r, (s) => s.anomalies.includes("clear_failed"));
- expect(inputBox(screenOf(r))?.text).toBe("Different unsent draft");
- const snap = await finish(r);
- expect(snap.reason).toBe("prompt_not_accepted");
- expect(snap.anomalies).toContain("resent_enter");
- expect(snap.anomalies).not.toContain("retyped_prompt");
- expect(sends).toHaveLength(2);
+ await r.s.ready;
+ const client = (r.s as unknown as { client: { request: Request } }).client;
+ await client.request({
+ type: "send",
+ pane: 0,
+ text: "Different unsent draft",
+ typed: true,
+ enter: false,
+ });
+ await until(r, () => r.s.diagnostics().gate?.reason === "box_not_empty");
+ const sends = traceInput(r);
+ const at = Date.now();
+ r.s.send("Reply with exactly PEAR.");
+ await until(r, (s) => s.turnsCompleted === 1 && s.state === "AWAITING_INPUT");
+ expect(Date.now() - at).toBeLessThan(15_000);
+ const snap = await close(r);
+ expect(snap.anomalies).not.toContain("gate_busy:box_not_empty");
expect(sends.map(({ message }) => message)).toMatchObject([
+ { keys: ["ctrl-u"], enter: false, noGate: true },
{ text: "Reply with exactly PEAR.", typed: true, enter: true },
- { keys: ["ctrl-u"], enter: false },
]);
- expect(r.turns).toHaveLength(0);
+ expect(sends).toHaveLength(2);
+ expect(r.submits.map(({ text }) => text)).toEqual(["Reply with exactly PEAR."]);
},
T
);
test(
- "nudge: ctrl-u leaving the original line uses one more Enter without retyping",
+ "I7: enter_ignored_1 is accepted by magmux's resent_enter, with one submitted copy",
async () => {
- const r = await start("menu_eats_enter", { timings: { resendAfterMs: 800 } });
- const sends = traceInput(r, "ignored");
+ const r = await start("enter_ignored_1", { env: { FAKE_GAP_MS_WITNESS: "5000" } });
+ const sends = traceInput(r);
const snap = await finish(r);
expect(snap.state).toBe("COMPLETED");
- expect(snap.anomalies).toContain("resent_enter");
- expect(snap.anomalies).not.toContain("retyped_prompt");
- expect(snap.anomalies).not.toContain("clear_failed");
- expect(sends).toHaveLength(3);
- expect(sends.map(({ message }) => message)).toMatchObject([
- { text: "Reply with exactly PEAR.", typed: true, enter: true },
- { keys: ["ctrl-u"], enter: false },
- { keys: ["enter"] },
- ]);
- expect(r.turns).toHaveLength(1);
+ expect(snap.anomalies).toContain("gate_resent_enter");
+ expect(sends).toHaveLength(1);
+ expect(sends[0]?.message).toMatchObject({
+ text: "Reply with exactly PEAR.",
+ typed: true,
+ enter: true,
+ });
+ expect(r.submits.map(({ text }) => text)).toEqual(["Reply with exactly PEAR."]);
expect(r.turns[0]?.answer).toBe(
- `ANSWER fake-menu_eats_enter ${sha8("Reply with exactly PEAR.")}`
+ `ANSWER fake-enter_ignored_1 ${sha8("Reply with exactly PEAR.")}`
);
},
T
@@ -916,21 +915,27 @@ describe.skipIf(!MAGMUX)(
);
test(
- "promptless_first_send_ignored: AWAITING_INPUT → RUNNING → AWAITING_INPUT, never STARTING or FAILED",
+ "promptless_first_send_ignored: unconfirmed fails the later admission loudly at 30 s, then accepts the next prompt",
async () => {
const r = await start("promptless_first_send_ignored", {
shape: "interactive",
initialPrompt: undefined,
decide: () => "continue",
- admitTimeoutMs: 2000,
- timings: { resendAfterMs: 800, degradedEntryMs: 800 },
});
await r.s.ready;
+ const sends = traceInput(r);
+ const at = Date.now();
r.s.send("first, ignored");
await until(
r,
- (s) => s.anomalies.includes("send_not_accepted") && s.state === "AWAITING_INPUT"
+ (s) => s.anomalies.includes("send_not_accepted") && s.state === "AWAITING_INPUT",
+ 35_000
);
+ expect(Date.now() - at).toBeGreaterThanOrEqual(29_000);
+ expect(r.s.diagnostics().lastSend?.reason).toBe("unconfirmed");
+ expect(r.s.snapshot().anomalies).not.toContain("degraded_mode");
+ expect(sends.filter(({ message }) => typeof message.text === "string")).toHaveLength(1);
+ expect(r.turns).toHaveLength(0);
r.s.send("second, answered");
await until(r, (s) => s.turnsCompleted === 1);
await close(r);
@@ -940,8 +945,9 @@ describe.skipIf(!MAGMUX)(
["RUNNING", "AWAITING_INPUT"],
]);
expect(r.transitions.some(([, to]) => to === "STARTING" || to === "FAILED")).toBe(false);
+ expect(r.submits.map(({ text }) => text)).toEqual(["second, answered"]);
},
- T
+ T * 2
);
test(
@@ -1094,6 +1100,7 @@ describe.skipIf(!MAGMUX)(
decide: () => "continue",
});
await r.s.ready;
+ const sends = traceInput(r);
type Req = (m: Record<string, unknown>, ms?: number) => Promise<unknown>;
const client = (r.s as unknown as { client: { request: Req } }).client;
const real = client.request.bind(client);
@@ -1114,6 +1121,13 @@ describe.skipIf(!MAGMUX)(
expect(r.s.snapshot().anomalies).toContain("send_reply_lost");
r.s.cancel();
await finish(r);
+ expect(sends.filter(({ message }) => message.text === "/model haiku")).toHaveLength(2);
+ expect(
+ sends.filter(
+ ({ message }) => Array.isArray(message.keys) && message.keys.includes("ctrl-u")
+ )
+ ).toHaveLength(1);
+ expect(r.submits.map(({ text }) => text)).toEqual(["/model haiku"]);
},
T
);
diff --git a/packages/cli/src/pane/repl-wrap.test.ts b/packages/cli/src/pane/repl-wrap.test.ts
new file mode 100644
index 00000000..d960ba6f
--- /dev/null
+++ b/packages/cli/src/pane/repl-wrap.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { wrapPrompt } from "./test-helpers/repl-wrap.js";
+
+function capturedBox(name: string): { cols: number; rows: string[] } {
+ const screen = JSON.parse(
+ readFileSync(join(import.meta.dir, "test-fixtures", "screens", `${name}.json`), "utf8")
+ ) as { cols: number; lines: string[] };
+ const first = screen.lines.findIndex((line) => line.startsWith("❯ "));
+ const end = screen.lines.findIndex((line, i) => i > first && /^─+$/.test(line));
+ return { cols: screen.cols, rows: screen.lines.slice(first, end) };
+}
+const nonSpace = (rows: string[]) => rows.join("").replace(/[❯\s]/g, "");
+
+describe("fake child prompt reflow (pure)", () => {
+ const narrow = capturedBox("size-80x24-repl-typed-long");
+ const wide = capturedBox("size-120x40-repl-typed-long");
+ const prompt = narrow.rows.map((line) => line.slice(2)).join(" ");
+
+ test("box word wrap matches both real Claude Code captures", () => {
+ expect(wrapPrompt(prompt, narrow.cols)).toEqual(narrow.rows);
+ expect(wrapPrompt(prompt, wide.cols)).toEqual(wide.rows);
+ });
+
+ test("resize reflows the original text, not already wrapped rows", () => {
+ for (const cols of [80, 120, 160, 400, 80]) {
+ const rows = wrapPrompt(prompt, cols);
+ expect(nonSpace(rows)).toBe(prompt.replace(/\s/g, ""));
+ expect(rows.every((line) => Bun.stringWidth(line) <= cols)).toBe(true);
+ }
+ expect(wrapPrompt(prompt, 80)).toEqual(narrow.rows);
+ });
+
+ test("a long file pointer and an unbroken token lose no non-space runes", () => {
+ for (const text of [
+ `Your task is in the file \`/a/long/path/${"segment/".repeat(30)}turn-1.md\`. Read all of it with the Read tool, then do exactly what it says.`,
+ "x".repeat(512),
+ ]) {
+ for (const cols of [80, 120, 160]) {
+ const rows = wrapPrompt(text, cols);
+ expect(nonSpace(rows)).toBe(text.replace(/\s/g, ""));
+ expect(rows.every((line) => Bun.stringWidth(line) <= cols)).toBe(true);
+ expect(rows.slice(1).every((line) => line.startsWith(" "))).toBe(true);
+ }
+ }
+ });
+
+ test("history has an ASCII-space prompt and strips the observed markdown markers", () => {
+ const text = "Read `task.md` and **keep** *all* ~~words~~ _and_ [links](here)";
+ expect(wrapPrompt(text, 80)[0]).toBe(`❯ ${text}`);
+ expect(wrapPrompt(text, 80, true)).toEqual([
+ "❯ Read task.md and keep all words _and_ [links](here)",
+ ]);
+ expect(nonSpace(wrapPrompt(prompt, 80, true))).toBe(nonSpace(narrow.rows));
+ });
+
+ test("newlines, repeated spaces and wide characters retain their content", () => {
+ expect(wrapPrompt("one\n\n two", 80)).toEqual(["❯ one", " ", " two"]);
+ const text = "答え 🍐 東京 ✓ ".repeat(30);
+ const rows = wrapPrompt(text, 80);
+ expect(nonSpace(rows)).toBe(text.replace(/\s/g, ""));
+ expect(rows.every((line) => Bun.stringWidth(line) <= 80)).toBe(true);
+ expect(wrapPrompt("", 80)).toEqual(["❯ "]);
+ });
+});
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
index 0e588962..439e624d 100755
--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -32,9 +32,17 @@
import { spawn, spawnSync } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import { appendFileSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
+import {
+ appendFileSync,
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ writeFileSync,
+} from "node:fs";
import { dirname, join } from "node:path";
import { projectDirNameFor } from "../../mcp-session/home-dir.js";
+import { wrapPrompt } from "./repl-wrap.js";
/* ───────────────────────────── argv and env ───────────────────────────── */
@@ -263,6 +271,7 @@ const writeTranscript = ![
"missing_no_warning",
"screen_fast",
"screen_api_error",
+ "never_submit_transcript_off",
].includes(scenario);
function newMsgId(): string {
@@ -407,12 +416,14 @@ const PLACEHOLDER = 'Try "how does <filepath> work?"'; // repl-boot-placeholder,
const S = {
booted: false,
box: "",
+ drawnBox: "", // F4: bytes reach the editor before its next render
history: [] as string[],
working: null as string | null,
full: null as string[] | null, // a whole fixture screen (dialogs, panels)
menu: null as string | null,
statusTick: 0,
ghost: false,
+ vim: false,
};
function fit(l: string): string {
@@ -431,28 +442,37 @@ function render(): void {
if (l.startsWith("\u0000ghost")) out += `❯ \x1b[2m${PLACEHOLDER}\x1b[22m`;
else out += fit(l);
});
- const boxRow = S.full ? ROWS - 1 : ROWS - 4;
- out += `\x1b[${boxRow + 1};${3 + Array.from(S.box.split("\n").pop() ?? "").length}H`;
+ const lastBoxLine = wrapPrompt(S.drawnBox, COLS).at(-1) ?? "❯ ";
+ const selected = S.full?.findIndex((line) => /^❯ /.test(line));
+ const boxRow = S.full
+ ? selected !== undefined && selected >= 0
+ ? selected
+ : ROWS - 1
+ : ROWS - 4;
+ const cursorCol = S.full ? 2 : Math.min(COLS - 1, Bun.stringWidth(lastBoxLine));
+ out += `\x1b[${boxRow + 1};${cursorCol + 1}H`;
process.stdout.write(out);
}
function replRows(): string[] {
const RULE = "─".repeat(COLS);
const out: string[] = Array.from({ length: ROWS }, () => "");
- const boxLines = S.box.split("\n");
+ const boxLines = wrapPrompt(S.drawnBox, COLS).slice(-(ROWS - 9));
const top = ROWS - 4 - boxLines.length;
BANNER.forEach((l, i) => {
out[i] = i === 3 ? `${l.slice(0, 11)}${cwd}` : l;
});
out[top] = RULE;
boxLines.forEach((l, i) => {
- out[top + 1 + i] = i === 0 ? `❯ ${l}` : ` ${l}`;
+ out[top + 1 + i] = l;
});
- if (!S.box && S.ghost) out[top + 1] = "\u0000ghost";
+ if (!S.drawnBox && S.ghost) out[top + 1] = "\u0000ghost";
out[ROWS - 3] = RULE;
out[ROWS - 2] = S.statusTick ? `${STATUS[0]} · ${S.statusTick}` : (STATUS[0] as string);
- out[ROWS - 1] = STATUS[1] as string;
- const above: string[] = [...S.history];
+ out[ROWS - 1] = S.vim ? "-- INSERT --" : (STATUS[1] as string);
+ const above = S.history.flatMap((line) =>
+ line.startsWith("❯ ") ? wrapPrompt(line.slice(2), COLS, true) : [line]
+ );
if (S.working) above.push(S.working);
if (S.menu) above.push("", S.menu);
const room = top - 4;
@@ -463,6 +483,46 @@ function replRows(): string[] {
return out;
}
+const renderLagMs = Math.max(0, Number(env.FAKE_RENDER_LAG_MS) || 0);
+let inputRender: ReturnType<typeof setTimeout> | null = null;
+let selfSubmit: ReturnType<typeof setTimeout> | null = null;
+let externalSubmitDone = false;
+
+function drawInput(): void {
+ if (inputRender) clearTimeout(inputRender);
+ inputRender = null;
+ const selfSubmitting = scenario.startsWith("self_submit") && S.box && !externalSubmitDone;
+ const historyWithheld = scenario === "self_submit_history_withheld";
+ // F14a must submit before the first verify read at 150 ms; never draw the exact text.
+ // F14b needs a non-exact prefix visible to verify before the box empties, with no history.
+ S.drawnBox = selfSubmitting ? (historyWithheld ? S.box.slice(0, -1) : "") : S.box;
+ render();
+ if (selfSubmitting) {
+ if (selfSubmit) clearTimeout(selfSubmit);
+ selfSubmit = setTimeout(() => {
+ externalSubmitDone = true;
+ acceptText(S.box);
+ }, historyWithheld ? 300 : 75);
+ }
+ if (
+ scenario === "command_left_box" &&
+ !env.FAKE_COMMAND_LEFT_BOX_FILE &&
+ S.box.startsWith("/model ") &&
+ !externalSubmitDone
+ ) {
+ if (selfSubmit) clearTimeout(selfSubmit);
+ selfSubmit = setTimeout(() => {
+ externalSubmitDone = true;
+ acceptText(S.box);
+ }, 1800);
+ }
+}
+
+function renderInput(): void {
+ if (!renderLagMs) drawInput();
+ else if (!inputRender) inputRender = setTimeout(drawInput, renderLagMs);
+}
+
function showHistory(...rows: string[]): void {
S.history.push(...rows);
render();
@@ -632,6 +692,11 @@ async function runScenario(name: string, d: Delivered): Promise<void> {
rec.stopSummary();
showHistory(`⏺ ${answerFor(c)}`, finishedRow());
return;
+ case "settle_box_text":
+ await answerTurn(c);
+ S.box = "Unsent text after the end record";
+ drawInput();
+ return;
case "td_withheld":
// the answer, but no turn_duration: the test appends it itself, at the moment it chooses
rec.text(answerFor(c));
@@ -887,7 +952,6 @@ async function permission(_c: string): Promise<void> {
async function screenOnlyTurn(line: string): Promise<void> {
// degraded scenarios: no transcript evidence at all; the screen is the only witness
- S.history.push(`❯ ${line}`);
if (scenario === "no_transcript") S.history.push(" ⎿ Transcript saving is off");
if (scenario !== "screen_fast") {
S.working = "✶ Simmering… (1s)";
@@ -907,7 +971,6 @@ async function screenOnlyTurn(line: string): Promise<void> {
const LOCAL_COMMANDS = new Set(["compact", "model", "color"]);
async function localCommandTurn(name: string, args: string): Promise<void> {
- S.history.push(`❯ /${name}${args ? ` ${args}` : ""}`);
let stdout = `Set model to \`${args}\``;
if (name === "compact") {
// file order as captured: the typed line, the boundary and summary, then the
@@ -941,20 +1004,24 @@ async function submit(line: string): Promise<void> {
)
return await screenOnlyTurn(line);
if (scenario === "slow_prompt_hook") {
- S.history.push(`❯ ${line}`);
S.working = "✶ Blanching… (running UserPromptSubmit hook · 2s)";
render();
await sleep(gap("PROMPT_HOOK", 12_000));
S.working = null;
rec.user(line);
} else {
- if (scenario !== "immediate_write") await sleep(gap("WITNESS", 50));
+ if (scenario !== "immediate_write")
+ await sleep(
+ gap(
+ "WITNESS",
+ ["self_submit_history_withheld", "command_left_box"].includes(scenario) ? 5000 : 50
+ )
+ );
const slash = line.match(/^\/([A-Za-z0-9][A-Za-z0-9:_-]*)\s*(.*)$/);
if (slash && LOCAL_COMMANDS.has(slash[1] as string))
return await localCommandTurn(slash[1] as string, slash[2] ?? "");
if (slash) rec.command(slash[1] as string, slash[2] ?? "");
else rec.user(line);
- S.history.push(`❯ ${line.split("\n")[0]}`);
}
S.working = "✶ Simmering… (thinking)";
render();
@@ -971,9 +1038,16 @@ async function submit(line: string): Promise<void> {
/* ───────────────────────────── keys ───────────────────────────── */
+let ignoredEnters = 0;
+const ignoredEnterLimit =
+ scenario === "enter_ignored_forever"
+ ? Infinity
+ : Number(scenario.match(/^enter_ignored_(\d+)$/)?.[1]) || 0;
+
function onEnter(): void {
const text = S.box;
- if (!text.trim()) return;
+ if (!text.trim() || S.vim) return;
+ if (ignoredEnters++ < ignoredEnterLimit || scenario === "never_submit_transcript_off") return;
if (scenario === "menu_eats_enter" && !menuEaten) {
menuEaten = true; // the first Enter only closes a menu (phase-2 keylog: Esc/Enter on menus)
S.menu = null;
@@ -984,12 +1058,22 @@ function onEnter(): void {
if (scenario === "promptless_first_send_ignored" && !firstSubmitIgnored) {
firstSubmitIgnored = true;
S.box = "";
- render();
+ drawInput();
return;
}
+ acceptText(text);
+}
+
+/** F9 counts accepted submissions, not Enter attempts or transient box contents. */
+function acceptText(text: string): void {
+ if (!text.trim() || (busy && !/^\/(exit|quit)$/.test(text.trim()))) return;
+ if (env.FAKE_SUBMIT_LOG)
+ appendFileSync(env.FAKE_SUBMIT_LOG, `${JSON.stringify({ text, at: Date.now() })}\n`);
S.box = "";
S.menu = null;
- render();
+ if (!["history_withheld", "self_submit_history_withheld", "command_left_box"].includes(scenario))
+ S.history.push(`❯ ${text}`);
+ drawInput(); // history and empty box are one render, as in the real REPL
const t = text.trim();
if (t === "/exit" || t === "/quit") return void exitCommand(t.slice(1));
if (t === "/cost") {
@@ -1029,8 +1113,36 @@ function updateMenu(): void {
else S.menu = null;
}
+let firstBurstDropped = false;
+let dropUntil = 0;
+
+/** F6/F13 lose a whole typing burst, not just its first character. */
+function dropTyping(ch: string): boolean {
+ if (Date.now() < dropUntil) {
+ dropUntil = Date.now() + 700;
+ return true;
+ }
+ if (
+ !firstBurstDropped &&
+ ch >= " " &&
+ ["late_reset_swallow", "drop_first_prompt"].includes(scenario)
+ ) {
+ firstBurstDropped = true;
+ dropUntil = Date.now() + 700;
+ if (scenario === "late_reset_swallow" && process.stdin.isTTY) {
+ process.stdin.setRawMode(false);
+ // A swallowed burst must not become kernel-echoed box text while cooked.
+ spawnSync("stty", ["-echo"], { stdio: ["inherit", "ignore", "ignore"] });
+ setTimeout(() => process.stdin.setRawMode(true), 120);
+ }
+ return true;
+ }
+ return false;
+}
+
/** One plain key (not an escape sequence). */
function onKey(ch: string): void {
+ if (dropTyping(ch)) return;
if (ch === "\x1b") {
onEsc();
return;
@@ -1072,7 +1184,7 @@ function onData(buf: Buffer): void {
onKey(s[0] as string);
s = s.slice(1);
}
- render();
+ renderInput();
}
/* ───────────────────────────── lifecycle ───────────────────────────── */
@@ -1094,7 +1206,7 @@ function restore(): void {
async function exitCommand(name: string): Promise<void> {
if (env.FAKE_EXIT_RECORDS !== "none") {
rec.localCommand(name, "", "(no content)");
- showHistory(`❯ /${name}`, " ⎿ (no content)");
+ showHistory(" ⎿ (no content)");
await sleep(gap("EXIT", 600));
}
return quit(0);
@@ -1123,7 +1235,12 @@ function installSignals(): void {
// Bun's stdout dimensions can still be stale inside SIGWINCH; query the pty.
const size = spawnSync("stty", ["size"], { stdio: ["inherit", "pipe", "ignore"] });
const match =
- size.status === 0 ? size.stdout?.toString().trim().match(/^(\d+)\s+(\d+)$/) : null;
+ size.status === 0
+ ? size.stdout
+ ?.toString()
+ .trim()
+ .match(/^(\d+)\s+(\d+)$/)
+ : null;
if (match) {
const rows = Number(match[1]);
const cols = Number(match[2]);
@@ -1208,7 +1325,30 @@ async function boot(): Promise<void> {
process.stdout.write("\x1b[?1049h\x1b[?2004h");
S.booted = true;
S.ghost = scenario === "idle_suggestion";
+ S.vim = scenario === "vim_insert" && !env.FAKE_VIM_FILE;
+ if (scenario === "never_submit_transcript_off") S.history.push(" ⎿ Transcript saving is off");
render();
+ // F1: the first box precedes Claude Code's cooked → raw startup reset.
+ if (scenario !== "no_boot_reset" && process.stdin.isTTY) {
+ await sleep(100);
+ process.stdin.setRawMode(false);
+ await sleep(120);
+ process.stdin.setRawMode(true);
+ }
+ if (env.FAKE_VIM_FILE)
+ setInterval(() => {
+ if (!S.vim && existsSync(env.FAKE_VIM_FILE as string)) {
+ S.vim = true;
+ render();
+ }
+ }, 20);
+ if (scenario === "command_left_box" && env.FAKE_COMMAND_LEFT_BOX_FILE)
+ setInterval(() => {
+ if (externalSubmitDone || !S.box.startsWith("/model ")) return;
+ if (env.FAKE_COMMAND_LEFT_BOX_FILE && !existsSync(env.FAKE_COMMAND_LEFT_BOX_FILE)) return;
+ externalSubmitDone = true;
+ acceptText(S.box);
+ }, 20);
if (scenario === "status_tick")
setInterval(() => {
S.statusTick++;
diff --git a/packages/cli/src/pane/test-helpers/gated-pane.ts b/packages/cli/src/pane/test-helpers/gated-pane.ts
new file mode 100644
index 00000000..d52e70dd
--- /dev/null
+++ b/packages/cli/src/pane/test-helpers/gated-pane.ts
@@ -0,0 +1,181 @@
+/** Real-magmux test driver. Deliberately has NO timings seam: D-A/D-B use production defaults. */
+import { expect } from "bun:test";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { MagmuxReply } from "../magmux-client.js";
+import { type PaneSession, type PaneSessionOptions, startPaneSession } from "../pane-session.js";
+import type { PaneSnapshot, SettledTurn } from "../types.js";
+import {
+ killLeftovers,
+ makePaneTestEnv,
+ newSessionUuid,
+ type PaneTestEnv,
+ waitNoOrphans,
+} from "./hermetic-env.js";
+
+export type Message = Record<string, unknown>;
+export type Request = (message: Message, timeout?: number) => Promise<MagmuxReply>;
+export interface SendTrace {
+ message: Message;
+ at: number;
+ timeout: number | undefined;
+ reply?: MagmuxReply;
+ repliedAt?: number;
+}
+export interface GateRun {
+ scenario: string;
+ s: PaneSession;
+ t: PaneTestEnv;
+ uuid: string;
+ transcript: string;
+ log: string;
+ sends: SendTrace[];
+ turns: SettledTurn[];
+ transitions: Array<{ to: string; at: number }>;
+}
+type Options = Omit<Partial<PaneSessionOptions>, "timings"> & {
+ env?: Record<string, string>;
+ prepare?: (t: PaneTestEnv, uuid: string) => Partial<Omit<PaneSessionOptions, "timings">>;
+};
+const open = new Set<GateRun>();
+
+interface TestClient {
+ request: Request;
+ close(): void;
+}
+
+export function clientOf(r: GateRun): TestClient {
+ return (r.s as unknown as { client: TestClient }).client;
+}
+
+export async function startGatePane(scenario: string, opts: Options = {}): Promise<GateRun> {
+ const t = makePaneTestEnv({ CONTRACT_FAKE_MAX_MS: "120000", ...opts.env });
+ const uuid = newSessionUuid();
+ const log = join(t.tmp, "submits.jsonl");
+ t.env.FAKE_SUBMIT_LOG = log;
+ const { env: _env, prepare, ...over } = opts;
+ const prepared = prepare?.(t, uuid) ?? {};
+ const transcript = prepared.transcriptPath ?? over.transcriptPath ?? t.transcriptPathFor(uuid);
+ const turns: SettledTurn[] = [];
+ const transitions: GateRun["transitions"] = [];
+ let s: PaneSession;
+ try {
+ s = await startPaneSession({
+ kind: "s",
+ label: "gate",
+ callerFlags: [],
+ spawnModel: `fake-${scenario}`,
+ cwd: t.cwd,
+ sessionUuid: uuid,
+ transcriptPath: transcript,
+ slotEnv: {},
+ shape: "interactive",
+ readAvailable: true,
+ parentEnv: t.env,
+ sockRoot: t.sockRoot,
+ ...over,
+ ...prepared,
+ decide: (turn) => {
+ turns.push(turn);
+ if (opts.decide) return opts.decide(turn);
+ if (opts.shape !== "one-shot") return "continue";
+ if (!turn.answer.trim()) return { state: "EMPTY", reason: "empty_output" };
+ return { state: "COMPLETED" };
+ },
+ onBlocked: opts.onBlocked ?? (() => "wait"),
+ onTransition: (transition) => {
+ transitions.push({ to: transition.to, at: Date.parse(transition.at) });
+ opts.onTransition?.(transition);
+ },
+ });
+ } catch (error) {
+ killLeftovers({ sockRoot: t.sockRoot, ids: [uuid] });
+ t.cleanup();
+ throw error;
+ }
+ const r: GateRun = { scenario, s, t, uuid, transcript, log, sends: [], turns, transitions };
+ open.add(r);
+ // Observe replacement connections too: I17 must count sends across a real redial.
+ const seen = new WeakSet<TestClient>();
+ const observe = (client: TestClient | null) => {
+ if (!client || seen.has(client)) return;
+ seen.add(client);
+ const real = client.request.bind(client);
+ client.request = async (message, timeout) => {
+ if (message.type !== "send") return real(message, timeout);
+ const trace: SendTrace = { message: { ...message }, at: Date.now(), timeout };
+ r.sends.push(trace);
+ const reply = await real(message, timeout);
+ trace.reply = reply;
+ trace.repliedAt = Date.now();
+ return reply;
+ };
+ };
+ let current: TestClient | null = clientOf(r);
+ observe(current);
+ Object.defineProperty(s, "client", {
+ configurable: true,
+ get: () => current,
+ set: (client: TestClient | null) => {
+ current = client;
+ observe(client);
+ },
+ });
+ return r;
+}
+
+export async function gateUntil(
+ r: GateRun,
+ predicate: (snapshot: PaneSnapshot) => boolean,
+ ms = 20_000
+): Promise<PaneSnapshot> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const snapshot = r.s.snapshot();
+ if (predicate(snapshot)) return snapshot;
+ if (Date.now() >= end)
+ throw new Error(
+ `condition not met: ${JSON.stringify({ snapshot, diagnostics: r.s.diagnostics(), sends: r.sends })}`
+ );
+ await Bun.sleep(25);
+ }
+}
+
+export function submissions(r: GateRun): Array<{ text: string; at: number }> {
+ if (!existsSync(r.log)) return [];
+ return readFileSync(r.log, "utf8")
+ .split("\n")
+ .filter(Boolean)
+ .map((line) => JSON.parse(line));
+}
+
+export function gatedSends(r: GateRun): SendTrace[] {
+ return r.sends.filter(({ message }) => message.noGate !== true);
+}
+
+/** Assertions happen before deleting the root; even an assertion failure reaps every pane. */
+export async function disposeGatePane(r: GateRun): Promise<void> {
+ if (!open.has(r)) return;
+ r.s.cancel();
+ await r.s.reaped();
+ const report = await waitNoOrphans({
+ sockRoot: r.t.sockRoot,
+ ids: [r.uuid],
+ pgids: [r.s.snapshot().panePid ?? 0],
+ });
+ try {
+ expect(report).toEqual({ processes: [], files: [] });
+ } finally {
+ open.delete(r);
+ killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });
+ r.t.cleanup();
+ }
+}
+
+export async function disposeGatePanes(): Promise<void> {
+ // Shared-cwd tests need both children stopped before either environment is removed.
+ for (const r of open) r.s.cancel();
+ const results = await Promise.allSettled([...open].map(disposeGatePane));
+ const failed = results.find((result) => result.status === "rejected");
+ if (failed?.status === "rejected") throw failed.reason;
+}
diff --git a/packages/cli/src/pane/test-helpers/repl-wrap.ts b/packages/cli/src/pane/test-helpers/repl-wrap.ts
new file mode 100644
index 00000000..7a5e8994
--- /dev/null
+++ b/packages/cli/src/pane/test-helpers/repl-wrap.ts
@@ -0,0 +1,32 @@
+/** Test-only reflow matching the captured 80- and 120-column Claude Code boxes. */
+export function wrapPrompt(text: string, cols: number, history = false): string[] {
+ // The history copy is markdown-rendered; the input box contains the raw characters.
+ const content = history ? text.replace(/[`*~]/g, "") : text;
+ const width = Math.max(1, cols - 2);
+ const rows: string[] = [];
+ for (const line of content.split("\n")) {
+ let remaining = Array.from(line);
+ do {
+ let cells = 0;
+ let end = 0;
+ while (end < remaining.length) {
+ const next = Bun.stringWidth(remaining[end] as string);
+ if (cells + next > width) break;
+ cells += next;
+ end++;
+ }
+ if (end === 0 && remaining.length) end = 1;
+ if (end < remaining.length) {
+ // A space consumed at a word boundary is not drawn on either row.
+ let space = end;
+ while (space > 0 && !/\s/.test(remaining[space] ?? "")) space--;
+ if (space > 0) end = space;
+ }
+ rows.push(remaining.slice(0, end).join(""));
+ const wrapped = end < remaining.length;
+ remaining = remaining.slice(end);
+ if (wrapped && remaining[0] === " ") remaining.shift();
+ } while (remaining.length);
+ }
+ return rows.map((row, i) => `${i === 0 ? (history ? "❯ " : "❯ ") : " "}${row}`);
+}