Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
test(pane): cover the input-gate adapter and the cursor box locator
Jack Rudenkoa46ce1d836b1
diff --git a/packages/cli/src/pane/box-locate.test.ts b/packages/cli/src/pane/box-locate.test.tsnew file mode 100644index 00000000..23e287d6--- /dev/null+++ b/packages/cli/src/pane/box-locate.test.ts@@ -0,0 +1,246 @@+import { describe, expect, test } from "bun:test";+import { isRuleRow, locateBox } from "./box-locate.js";+import { boxTopRow, type ScreenState } from "./screen-model.js";+import { loadScreen } from "./test-helpers/fixtures.js";++// Literal row indexes read from the real captures, independent of either locator.+const BOX_SCREENS = [+ ["api-error", 45, 47, 46],+ ["ask-user-question-declined", 45, 47, 46],+ ["background-agent-wait", 45, 47, 46],+ ["bash-running-tip", 45, 47, 46],+ ["interrupted-streaming", 45, 47, 46],+ ["interrupted-tool", 45, 47, 46],+ ["long-bash-running", 45, 47, 46],+ ["menu-at-open", 45, 47, 46],+ ["menu-slash-command", 45, 47, 46],+ ["menu-slash-open", 45, 47, 46],+ ["numbered-prose-bash-running", 45, 47, 46],+ ["permission-write-declined", 45, 47, 46],+ ["prompt-hook-running", 45, 47, 46],+ ["repl-boot-agent", 45, 47, 46],+ ["repl-boot-empty", 45, 47, 46],+ ["repl-boot-placeholder", 45, 47, 46],+ ["repl-just-submitted", 45, 47, 46],+ ["repl-settled", 45, 47, 46],+ ["repl-typed", 45, 47, 46],+ ["repl-typed-multiline", 44, 47, 46],+ ["size-120x40-answer-short", 36, 38, 37],+ ["size-120x40-echo-submitted", 36, 38, 37],+ ["size-120x40-repl-boot-empty", 36, 38, 37],+ ["size-120x40-repl-typed-long", 35, 38, 37],+ ["size-120x40-working", 36, 38, 37],+ ["size-250x60-answer-short", 56, 58, 57],+ ["size-250x60-echo-submitted", 56, 58, 57],+ ["size-250x60-repl-boot-empty", 56, 58, 57],+ ["size-250x60-repl-typed-long", 56, 58, 57],+ ["size-250x60-working", 56, 58, 57],+ ["size-350x80-answer-short", 76, 78, 77],+ ["size-350x80-repl-boot-empty", 76, 78, 77],+ ["size-350x80-repl-typed-long", 75, 78, 77],+ ["size-350x80-working", 76, 78, 77],+ ["size-500x100-answer-short", 96, 98, 97],+ ["size-500x100-repl-boot-empty", 96, 98, 97],+ ["size-500x100-repl-typed-long", 95, 98, 97],+ ["size-500x100-working", 96, 98, 97],+ ["size-80x24-answer-short", 20, 22, 21],+ ["size-80x24-echo-submitted", 20, 22, 21],+ ["size-80x24-echo-wrapped", 20, 22, 21],+ ["size-80x24-repl-boot-empty", 20, 22, 21],+ ["size-80x24-repl-typed-long", 19, 22, 21],+ ["size-80x24-working", 20, 22, 21],+ ["size-80x24-working-tail", 20, 22, 21],+ ["stop-hook-running", 45, 47, 46],+ ["stop-hook-settled", 45, 47, 46],+ ["streaming-answer", 45, 47, 46],+] as const;++const NO_BOX_SCREENS = [+ "agent-rejected",+ "ask-user-question",+ "dialog-bypass",+ "dialog-onboarding",+ "dialog-trust",+ "dialog-unnamed-mcp-server",+ "permission-bash",+ "permission-write",+ "plan-approval",+ "size-120x40-dialog-trust",+ "size-120x40-permission-write-long-path",+ "size-250x60-dialog-trust",+ "size-250x60-permission-write-long-path",+ "size-350x80-ask-user-question",+ "size-350x80-permission-write",+ "size-500x100-ask-user-question",+ "size-500x100-permission-write",+ "size-80x24-dialog-trust",+ "size-80x24-permission-header-wrapped",+ "size-80x24-permission-write-long-path",+ "usage-panel",+] as const;++// Boundary mutations of a capture, not additional screen captures. Retain its+// 160x50 geometry and move the two captured rules around its captured prompt.+function withRuleDistances(above: number, below: number): ScreenState {+ const screen = loadScreen("repl-typed");+ const rule = screen.lines[45]!;+ const prompt = screen.lines[46]!;+ screen.lines[45] = "";+ screen.lines[46] = "";+ screen.lines[47] = "";+ screen.lines[0] = rule;+ screen.lines[1] = prompt;+ if (above > 1) screen.lines[above] = "";+ screen.lines[above + below] = rule;+ screen.cursor = { ...screen.cursor, y: above };+ return screen;+}++describe("U5 locateBox at captured widths", () => {+ test("accounts for all 69 supplied screens without duplicate names", () => {+ const names = [...BOX_SCREENS.map(([name]) => name), ...NO_BOX_SCREENS];+ expect(names).toHaveLength(69);+ expect(new Set(names).size).toBe(69);+ });++ test.each(BOX_SCREENS)("%s: locates the captured REPL box", (name, top, bottom, caretRow) => {+ const screen = loadScreen(name);+ expect(locateBox(screen)).toEqual({ top, bottom, caretRow });+ // Pin the old public behaviour too; agreement alone could hide a shared regression.+ expect(boxTopRow(screen.lines, screen.cols)).toBe(top);+ });++ test.each([...NO_BOX_SCREENS])("%s: does not locate an input box", (name) => {+ expect(locateBox(loadScreen(name))).toBeNull();+ });++ test("returns null when the cursor leaves the box or the screen", () => {+ for (const name of ["repl-typed", "repl-typed-multiline"]) {+ const screen = loadScreen(name);+ const top = name === "repl-typed" ? 45 : 44;+ for (const y of [-1, 0, top, 47, screen.rows - 1, screen.rows, screen.rows + 1]) {+ expect(locateBox({ ...screen, cursor: { ...screen.cursor, y } })).toBeNull();+ }+ }+ });++ test("keeps the caret on a multiline continuation rather than the prompt row", () => {+ const screen = loadScreen("repl-typed-multiline");+ expect(screen.lines[45]).toBe("❯ alpha");+ expect(screen.lines[46]).toBe(" beta");+ expect(locateBox(screen)).toEqual({ top: 44, bottom: 47, caretRow: 46 });+ });++ test("rejects ASCII-space submitted echoes as prompt rows", () => {+ const screen = loadScreen("repl-typed");+ screen.lines[46] = "❯ alpha";+ expect(locateBox(screen)).toBeNull();+ });++ test("accepts bare caret nonbreaking-space and bash-mode prompt prefixes", () => {+ for (const prompt of ["❯", "❯ alpha", "!", "! ls"]) {+ const screen = loadScreen("repl-typed");+ screen.lines[46] = prompt;+ expect(locateBox(screen)).toEqual({ top: 45, bottom: 47, caretRow: 46 });+ }+ });++ test("rejects missing indented or tab-separated prompt prefixes", () => {+ for (const prompt of ["", "alpha", " ❯ alpha", "❯\talpha"]) {+ const screen = loadScreen("repl-typed");+ screen.lines[46] = prompt;+ expect(locateBox(screen)).toBeNull();+ }+ });++ test("rejects numbered options on either the prompt row or the continuation caret", () => {+ for (const row of [45, 46]) {+ const screen = loadScreen("repl-typed-multiline");+ screen.lines[row] = "❯ 1. Red";+ expect(locateBox(screen)).toBeNull();+ }+ });++ test("accepts numbered prompt text after a no-break space", () => {+ const screen = loadScreen("repl-typed-multiline");+ screen.lines[45] = "❯\u00a01. Red";+ expect(locateBox(screen)).toEqual({ top: 44, bottom: 47, caretRow: 46 });+ });++ test("returns null when either bounding rule is absent", () => {+ for (const row of [45, 47]) {+ const screen = loadScreen("repl-typed");+ screen.lines[row] = "";+ expect(locateBox(screen)).toBeNull();+ }+ });++ test("does not skip a nearer rule to reuse an older prompt box", () => {+ const screen = loadScreen("repl-typed-multiline");+ screen.lines[45] = screen.lines[44]!;+ expect(locateBox(screen)).toBeNull();+ });++ test("includes a bounding rule exactly 40 rows from the cursor", () => {+ for (const [above, below] of [[40, 1], [1, 40]] as const) {+ expect(locateBox(withRuleDistances(above, below))).toEqual({+ top: 0, bottom: 41, caretRow: above,+ });+ }+ });++ test("does not search beyond 40 rows for either bounding rule", () => {+ for (const [above, below] of [[41, 1], [1, 41]] as const) {+ expect(locateBox(withRuleDistances(above, below))).toBeNull();+ }+ });+});++describe("U6 isRuleRow without a width test", () => {+ test("accepts a 20-cell rule and the captured agent-labelled rule", () => {+ const plain = loadScreen("repl-typed").lines[45]!;+ const labelled = loadScreen("repl-boot-agent").lines[45]!;+ expect(labelled).toContain("Explore");+ expect(isRuleRow(plain.slice(0, 20))).toBe(true);+ expect(isRuleRow(labelled)).toBe(true);+ });++ test("rejects 19-cell indented dashed empty and missing rows", () => {+ const rule = loadScreen("repl-typed").lines[45]!.slice(0, 20);+ for (const line of [rule.slice(0, 19), ` ${rule}`, `${rule} `, "╌".repeat(20), "-".repeat(20), "", undefined]) {+ expect(isRuleRow(line)).toBe(false);+ }+ });++ test("requires a single complete label tail", () => {+ const rule = loadScreen("repl-typed").lines[45]!.slice(0, 20);+ expect(isRuleRow(`${rule} Explore ─`)).toBe(true);+ for (const line of [`${rule} Explore`, `${rule} Explore ─ More ─`, `${rule} Explore ─ `]) {+ expect(isRuleRow(line)).toBe(false);+ }+ });++ test("locates 20-cell boundaries at every captured width without proportional sizing", () => {+ for (const [name, top, bottom, caretRow] of [+ ["size-80x24-repl-boot-empty", 20, 22, 21],+ ["size-120x40-repl-boot-empty", 36, 38, 37],+ ["repl-boot-empty", 45, 47, 46],+ ["size-250x60-repl-boot-empty", 56, 58, 57],+ ["size-350x80-repl-boot-empty", 76, 78, 77],+ ["size-500x100-repl-boot-empty", 96, 98, 97],+ ] as const) {+ const screen = loadScreen(name);+ screen.lines[top] = screen.lines[top]!.slice(0, 20);+ screen.lines[bottom] = screen.lines[bottom]!.slice(0, 20);+ expect(locateBox(screen)).toEqual({ top, bottom, caretRow });+ }+ });++ test("locating a box never reads cols", () => {+ const screen = loadScreen("repl-typed");+ Object.defineProperty(screen, "cols", {+ get() { throw new Error("locateBox read cols"); },+ });+ expect(locateBox(screen)).toEqual({ top: 45, bottom: 47, caretRow: 46 });+ });+});diff --git a/packages/cli/src/pane/input-gate.test.ts b/packages/cli/src/pane/input-gate.test.tsnew file mode 100644index 00000000..9970acb7--- /dev/null+++ b/packages/cli/src/pane/input-gate.test.ts@@ -0,0 +1,698 @@+import { afterEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, relative } from "node:path";+import { checkGateBinding, normaliseTranscriptPath } from "./gate-binding.js";+import {+ type GateDialogKind,+ type SendOutcome,+ classifySendReply,+ parseGateBinding,+ parseGateInput,+ readyWaitMs,+ sendBudgetMs,+ typedWriteCount,+} from "./input-gate.js";+import type { MagmuxReply } from "./magmux-client.js";++const DIALOG_KINDS = [+ "permission",+ "question",+ "plan",+ "select",+ "trust",+ "bypass",+ "api_key",+ "onboarding",+] as const;++// Verbatim format strings from magmux v0.16.0 inputgate_send.go:884 and :893.+// Substitute only the two fmt arguments, as magmux does on the socket.+const LEFT_BOX_MESSAGE =+ "pane %d: the input box showed the text and then emptied without magmux's Enter (%s); it is unknown whether another Enter submitted it, so check the conversation before sending it again; magmux pressed no Enter and did not retype it";+const CONVERSATION_MOVED_MESSAGE =+ "pane %d: the input box stayed empty after typing (%s); it is unknown whether another writer's Enter submitted it, so check the conversation before sending it again; magmux pressed no Enter";+const MISMATCH_MESSAGE =+ "pane %d: the input box does not hold what was typed (%s); Enter was not pressed, nothing was submitted, and the box may hold partial text";++function formatDetail(message: string, detail: string): string {+ return message.replace("%d", "0").replace("%s", detail);+}++function failure(+ code: string,+ error: string,+ fields: { reason?: string; typed?: boolean } = {}+): MagmuxReply {+ return { ok: false, code, error, ...fields };+}++function paneList(pane: Record<string, unknown>): unknown {+ return { panes: [{ pane: 0, ...pane }] };+}++const ACCEPTED: Extract<SendOutcome, { kind: "accepted" }> = {+ kind: "accepted",+ accept: "confirmed",+ evidence: "history",+ enterByMagmux: true,+ retyped: false,+ retypeCause: null,+ dismissed: [],+ waitedMs: 0,+ verified: null,+};++const IN_BOX: Extract<SendOutcome, { kind: "in_box" }> = {+ kind: "in_box",+ retyped: false,+ retypeCause: null,+ waitedMs: 0,+ verified: null,+};++describe("U1 classifySendReply", () => {+ test("maps confirmed and resent_enter with either evidence source", () => {+ for (const accept of ["confirmed", "resent_enter"] as const) {+ for (const evidence of ["history", "transcript"] as const) {+ expect(+ classifySendReply({+ ok: true,+ result: { accept, evidence, enter: true, waitedMs: 2400, verified: "exact" },+ })+ ).toEqual({ ...ACCEPTED, accept, evidence, waitedMs: 2400, verified: "exact" });+ }+ }+ });++ test("maps submitted_by_other without a magmux Enter for SUBMIT or TYPE", () => {+ // Both request classes have the same reply: accept, not enter, proves submission.+ for (const evidence of ["history", "transcript"] as const) {+ expect(+ classifySendReply({+ ok: true,+ result: {+ pane: 0,+ bytes: 13,+ keys: 0,+ enter: false,+ accept: "submitted_by_other",+ evidence,+ },+ })+ ).toEqual({ ...ACCEPTED, accept: "submitted_by_other", evidence, enterByMagmux: false });+ }+ });++ test("preserves accepted metadata and dismissed dialog order", () => {+ for (const verified of ["exact", "non_empty", "paste_token"]) {+ expect(+ classifySendReply({+ ok: true,+ result: {+ accept: "confirmed",+ evidence: "history",+ enter: true,+ waitedMs: 137,+ verified,+ dismissed: ["permission", "question", "plan"],+ },+ })+ ).toEqual({+ ...ACCEPTED,+ waitedMs: 137,+ verified,+ dismissed: ["permission", "question", "plan"],+ });+ }+ });++ test("maps in_box to TYPE completion without acceptance evidence", () => {+ expect(+ classifySendReply({+ ok: true,+ result: { accept: "in_box", enter: false, waitedMs: 1200, verified: "exact" },+ })+ ).toEqual({ ...IN_BOX, waitedMs: 1200, verified: "exact" });+ });++ test("defaults omitted optional success metadata", () => {+ expect(+ classifySendReply({+ ok: true,+ result: { accept: "confirmed", evidence: "history", enter: true },+ })+ ).toEqual(ACCEPTED);+ expect(classifySendReply({ ok: true, result: { accept: "in_box", enter: false } })).toEqual(+ IN_BOX+ );+ });++ test("preserves both retype causes on accepted and in_box replies", () => {+ for (const retypeCause of ["terminal_reset", "never_drawn"] as const) {+ expect(+ classifySendReply({+ ok: true,+ result: {+ accept: "confirmed",+ evidence: "history",+ enter: true,+ retyped: true,+ retypeCause,+ },+ })+ ).toEqual({ ...ACCEPTED, retyped: true, retypeCause });+ expect(+ classifySendReply({+ ok: true,+ result: { accept: "in_box", enter: false, retyped: true, retypeCause },+ })+ ).toEqual({ ...IN_BOX, retyped: true, retypeCause });+ }+ });++ test("uses unknown for an absent or future retype cause only when retyped", () => {+ for (const shape of [+ { accept: "confirmed", evidence: "history", enter: true },+ { accept: "in_box", enter: false },+ ]) {+ for (const cause of [{}, { retypeCause: "future_loss_signal" }]) {+ expect(+ classifySendReply({ ok: true, result: { ...shape, retyped: true, ...cause } })+ ).toMatchObject({ retyped: true, retypeCause: "unknown" });+ }+ for (const flag of [{}, { retyped: false }]) {+ expect(+ classifySendReply({+ ok: true,+ result: { ...shape, ...flag, retypeCause: "terminal_reset" },+ })+ ).toMatchObject({ retyped: false, retypeCause: null });+ }+ }+ });++ test("does not accept ungated, unknown-accept or evidence-free success replies", () => {+ for (const result of [+ { pane: 0, bytes: 13, keys: 0, enter: true },+ { accept: "future_accept", evidence: "history", enter: true },+ { accept: "confirmed", enter: true },+ { accept: "resent_enter", enter: true },+ { accept: "submitted_by_other", enter: false },+ { accept: "confirmed", evidence: "future_evidence", enter: true },+ ]) {+ expect(classifySendReply({ ok: true, result })).toMatchObject({+ kind: "unexpected",+ code: expect.any(String),+ error: expect.any(String),+ });+ }+ });++ test("maps every busy reason with omitted, false or true typed", () => {+ const reasons: Array<{ reason: string; dialog: GateDialogKind | null }> = [+ ...[+ "starting",+ "terminal_not_ready",+ "no_input_box",+ "typing_in_progress",+ "queue_full",+ "in_flight",+ "box_not_empty",+ "vim_mode",+ ].map((reason) => ({ reason, dialog: null })),+ ...DIALOG_KINDS.map((dialog) => ({ reason: `dialog:${dialog}`, dialog })),+ ];+ for (const { reason, dialog } of reasons) {+ for (const fields of [{}, { typed: false }, { typed: true }]) {+ expect(classifySendReply(failure("busy", "not ready", { reason, ...fields }))).toEqual({+ kind: "busy",+ reason,+ dialog,+ typed: fields.typed === true,+ });+ }+ }+ });++ test("keeps unknown busy reasons raw without inventing a dialog", () => {+ for (const reason of ["future_reason", "dialog:future_kind"]) {+ for (const typed of [false, true]) {+ expect(classifySendReply(failure("busy", "not ready", { reason, typed }))).toEqual({+ kind: "busy",+ reason,+ dialog: null,+ typed,+ });+ }+ }+ });++ test("maps every not_accepted reason and preserves typed and detail", () => {+ for (const reason of ["text_mismatch", "empty_box", "still_in_box", "unconfirmed"] as const) {+ for (const fields of [{}, { typed: false }, { typed: true }]) {+ expect(+ classifySendReply(failure("not_accepted", "pane 0: refusal detail", { reason, ...fields }))+ ).toEqual({+ kind: "not_accepted",+ reason,+ maybeSubmitted: false,+ typed: fields.typed === true,+ detail: "pane 0: refusal detail",+ });+ }+ }+ });++ test.each([+ ["leftBox", LEFT_BOX_MESSAGE],+ ["convMoved", CONVERSATION_MOVED_MESSAGE],+ ])("marks the verbatim %s text_mismatch message maybeSubmitted", (_name, message) => {+ const error = formatDetail(message, "it differs from what was sent");+ expect(+ classifySendReply(failure("not_accepted", error, { reason: "text_mismatch", typed: true }))+ ).toEqual({ kind: "not_accepted", reason: "text_mismatch", maybeSubmitted: true, typed: true, detail: error });+ });++ test("does not mark noLoss, windowCut or lostAgain mismatches maybeSubmitted", () => {+ // Exact detail tails from inputgate_send.go:864, :866 and :868, with fmt values filled in.+ for (const detail of [+ "it differs from what was sent; it stayed empty but the terminal showed no stdin reset, and the deadline left less than the 3s verify window that tells a silent drop from a slow draw, so the text was not retyped",+ "it differs from what was sent; it stayed empty but the terminal showed no stdin reset, and the box was not seen empty on every read for the whole 3s verify window, so the text was not retyped",+ "it differs from what was sent; the text was already retyped once (terminal reset) and the box stayed empty again, so it was not retyped a second time",+ "it differs from what was sent; the text was already retyped once (never drawn) and the box stayed empty again, so it was not retyped a second time",+ ]) {+ const error = formatDetail(MISMATCH_MESSAGE, detail);+ expect(+ classifySendReply(failure("not_accepted", error, { reason: "text_mismatch", typed: true }))+ ).toEqual({ kind: "not_accepted", reason: "text_mismatch", maybeSubmitted: false, typed: true, detail: error });+ }+ });++ test("requires the documented marker and text_mismatch reason for maybeSubmitted", () => {+ const ambiguous = formatDetail(LEFT_BOX_MESSAGE, "it differs from what was sent");+ for (const reason of ["empty_box", "still_in_box", "unconfirmed"]) {+ expect(classifySendReply(failure("not_accepted", ambiguous, { reason }))).toMatchObject({+ kind: "not_accepted",+ reason,+ maybeSubmitted: false,+ });+ }+ expect(+ classifySendReply(+ failure("not_accepted", "it is unknown whether another Enter submitted it", {+ reason: "text_mismatch",+ })+ )+ ).toMatchObject({ kind: "not_accepted", maybeSubmitted: false });+ });++ test("preserves bad_request error text", () => {+ expect(classifySendReply(failure("bad_request", "Enter must be the final key"))).toEqual({+ kind: "bad_request",+ error: "Enter must be the final key",+ });+ });++ test("maps caller timeout and client reply losses to reply_lost", () => {+ for (const code of ["timeout", "client_timeout", "client_lost"] as const) {+ expect(classifySendReply(failure(code, "reply unavailable"))).toEqual({+ kind: "reply_lost",+ code,+ });+ }+ });++ test("maps client_closed and no_client to unsent", () => {+ for (const code of ["client_closed", "no_client"] as const) {+ expect(classifySendReply(failure(code, "not written"))).toEqual({ kind: "unsent", code });+ }+ });++ test("maps dead or missing panes and preserves partial typing", () => {+ for (const code of ["pane_dead", "no_such_pane"] as const) {+ for (const fields of [{}, { typed: false }, { typed: true }]) {+ expect(classifySendReply(failure(code, "pane unavailable", fields))).toEqual({+ kind: "pane_gone",+ code,+ typed: fields.typed === true,+ });+ }+ }+ });++ test("keeps other README codes and unknown codes unexpected", () => {+ for (const code of ["unknown_verb", "unsupported", "internal", "pane_is_control", "too_small", "future_code"]) {+ expect(classifySendReply(failure(code, "upstream detail"))).toEqual({+ kind: "unexpected",+ code,+ error: "upstream detail",+ });+ }+ });+});++describe("U3 sendBudgetMs", () => {+ // Literal expected values from magmux's TestSendBudgetWorkedValues; no copied formula oracle.+ test.each([+ ["Go short submit", { readyTimeoutMs: 0, text: "", keys: 0, submit: true, typed: false }, 20780],+ ["Go 500 keys and a submit", { readyTimeoutMs: 0, text: "", keys: 500, submit: true, typed: false }, 42780],+ ["Go readyTimeoutMs 60000", { readyTimeoutMs: 60000, text: "", keys: 0, submit: true, typed: false }, 70780],+ ["Go TYPE with three writes", { readyTimeoutMs: 0, text: "a\nb", keys: 0, submit: false, typed: true }, 14840],+ ["13-character SUBMIT", { readyTimeoutMs: 10000, text: "run the tests", keys: 1, submit: true }, 20844],+ ["300-character file-template SUBMIT", { readyTimeoutMs: 10000, text: "x".repeat(300), keys: 1, submit: true }, 21024],+ ["512-character typed SUBMIT", { readyTimeoutMs: 10000, text: "x".repeat(512), keys: 1, submit: true }, 21144],+ ["command TYPE", { readyTimeoutMs: 10000, text: "/model haiku", keys: 0, submit: false }, 14800],+ ["command Enter SUBMIT", { readyTimeoutMs: 10000, text: "", keys: 1, submit: true }, 20824],+ ] as const)("matches %s exactly", (_name, shape, expected) => {+ expect(sendBudgetMs(shape)).toBe(expected);+ });++ test("defaults nonpositive readiness waits and clamps only above 60000", () => {+ for (const [ready, expected] of [[0, 10000], [-5, 10000], [1, 1], [2500, 2500], [60000, 60000], [600000, 60000]] as const) {+ expect(readyWaitMs(ready)).toBe(expected);+ }+ });++ test("uses the default or clamped readiness wait in the full budget", () => {+ for (const [readyTimeoutMs, expected] of [[0, 20844], [-5, 20844], [60000, 70844], [600000, 70844]] as const) {+ expect(sendBudgetMs({ readyTimeoutMs, text: "run the tests", keys: 1, submit: true })).toBe(expected);+ }+ });++ test("counts typed writes at rune and newline boundaries", () => {+ for (const [text, expected] of [+ ["", 0], ["hi", 1], ["a".repeat(32), 1], ["a".repeat(33), 2],+ ["a".repeat(512), 16], ["a\nb", 3], ["a\r\nb", 3], ["a\rb", 3],+ ["\n", 1], ["\r\n", 1], ["\r", 1], ["\n\n", 2],+ ["😀".repeat(32), 1], ["😀".repeat(33), 2],+ ] as const) {+ expect(typedWriteCount(text)).toBe(expected);+ }+ });++ test("uses rune and newline write counts in full TYPE budgets", () => {+ for (const [text, expected] of [["😀".repeat(33), 14820], ["a\nb", 14840], ["a\r\nb", 14840], ["a\rb", 14840]] as const) {+ expect(sendBudgetMs({ readyTimeoutMs: 10000, text, keys: 0, submit: false })).toBe(expected);+ }+ });+});++describe("U4 parseGateInput", () => {+ test("selects pane 0 by id rather than array position", () => {+ expect(+ parseGateInput({ panes: [+ { pane: 7, input: { ready: false, reason: "dialog:trust" } },+ { pane: 0, input: { ready: true } },+ ] }, 1234)+ ).toEqual({ ready: true, reason: null, dialog: null, detail: null, receivedAt: 1234 });+ });++ test("returns null when pane 0 or its input is absent", () => {+ for (const list of [undefined, null, {}, { panes: [] },+ { panes: [{ pane: 1, input: { ready: true } }] },+ paneList({}), paneList({ input: null }),+ ]) {+ expect(parseGateInput(list, 1234)).toBeNull();+ }+ });++ test("preserves the documented reason detail and caller timestamp", () => {+ expect(parseGateInput(paneList({ input: {+ ready: false, reason: "box_not_empty", detail: "the input box holds text",+ } }), 42)).toEqual({+ ready: false, reason: "box_not_empty", dialog: null,+ detail: "the input box holds text", receivedAt: 42,+ });+ });++ test("parses all eight dialog kinds", () => {+ for (const dialog of DIALOG_KINDS) {+ expect(parseGateInput(paneList({ input: { ready: false, reason: `dialog:${dialog}` } }), 10)).toEqual({+ ready: false, reason: `dialog:${dialog}`, dialog, detail: null, receivedAt: 10,+ });+ }+ });++ test("keeps future dialog and readiness reasons raw", () => {+ for (const reason of ["dialog:future_kind", "future_readiness_reason"]) {+ expect(parseGateInput(paneList({ input: { ready: false, reason, detail: "new detail" } }), 10)).toEqual({+ ready: false, reason, dialog: null, detail: "new detail", receivedAt: 10,+ });+ }+ });++ test("ignores undocumented boxHasText and dismissable fields", () => {+ expect(parseGateInput(paneList({ input: {+ ready: true, boxHasText: true, dismissable: ["permission"],+ } }), 10)).toEqual({ ready: true, reason: null, dialog: null, detail: null, receivedAt: 10 });+ });++ test("normalises omitted reason and detail and refreshes receivedAt", () => {+ const list = paneList({ input: { ready: false } });+ for (const now of [0, 100, 200]) {+ expect(parseGateInput(list, now)).toEqual({+ ready: false, reason: null, dialog: null, detail: null, receivedAt: now,+ });+ }+ });+});++describe("U4 R1.8 parseGateBinding", () => {+ const sessionId = "session-a";+ const transcriptPath = "/isolated/config/projects/project-a/session-a.jsonl";++ test("selects pane 0 binding by id rather than array position", () => {+ expect(parseGateBinding({ panes: [+ { pane: 2, bound: "mtime", sessionId: "other-session", transcriptPath: "/other/session.jsonl" },+ { pane: 0, bound: "named", sessionId, transcriptPath },+ ] })).toEqual({ bound: "named", boundRaw: "named", sessionId, transcriptPath });+ });++ test("preserves named prompt and mtime binding kinds without promoting them", () => {+ for (const bound of ["named", "prompt", "mtime"] as const) {+ expect(parseGateBinding(paneList({ bound, sessionId, transcriptPath }))).toEqual({+ bound, boundRaw: bound, sessionId, transcriptPath,+ });+ }+ });++ test("returns null when pane 0 is absent", () => {+ for (const list of [undefined, null, {}, { panes: [] }, { panes: [{ pane: 1, bound: "named", sessionId, transcriptPath }] }]) {+ expect(parseGateBinding(list)).toBeNull();+ }+ });++ test("reports missing binding metadata as unbound rather than named", () => {+ expect(parseGateBinding(paneList({}))).toEqual({+ bound: "unbound", boundRaw: null, sessionId: null, transcriptPath: null,+ });+ expect(parseGateBinding(paneList({ sessionId, transcriptPath }))).toEqual({+ bound: "unbound", boundRaw: null, sessionId, transcriptPath,+ });+ });++ test("keeps an unknown raw binding while classifying it unbound", () => {+ expect(parseGateBinding(paneList({ bound: "future_binding", sessionId, transcriptPath }))).toEqual({+ bound: "unbound", boundRaw: "future_binding", sessionId, transcriptPath,+ });+ });++ test("treats missing identity or path as unbound without borrowing another pane", () => {+ // R1.8: a missing binding field is unbound, even if bound itself says named.+ for (const [own, missing] of [+ [{ bound: "named", transcriptPath }, { sessionId: null, transcriptPath }],+ [{ bound: "named", sessionId }, { sessionId, transcriptPath: null }],+ ] as const) {+ expect(parseGateBinding({ panes: [+ { pane: 1, bound: "named", sessionId, transcriptPath }, { pane: 0, ...own },+ ] })).toEqual({ bound: "unbound", boundRaw: "named", ...missing });+ }+ });+});++describe("U11 checkGateBinding and normaliseTranscriptPath", () => {+ type ExpectedBinding = Parameters<typeof checkGateBinding>[1];+ const roots: string[] = [];+ const declaredPane = {+ controller: "claude-code",+ gateBasis: "declared",+ input: { ready: true },+ };++ afterEach(() => {+ for (const root of roots.splice(0)) {+ rmSync(root, { recursive: true, force: true });+ expect(existsSync(root)).toBe(false);+ }+ });++ function bindingSetup(createTranscript = true) {+ const root = mkdtempSync(join(tmpdir(), "cgb-"));+ roots.push(root);+ const configDir = join(root, "config");+ const projectDir = join(configDir, "projects", "project-a");+ mkdirSync(projectDir, { recursive: true });+ const expected: ExpectedBinding = {+ sessionUuid: "11111111-1111-4111-8111-111111111111",+ transcriptPath: join(projectDir, "11111111-1111-4111-8111-111111111111.jsonl"),+ magmuxVersion: "0.17.0",+ };+ if (createTranscript) writeFileSync(expected.transcriptPath, "");+ return { root, configDir, projectDir, expected };+ }++ function namedList(expected: ExpectedBinding, fields: Record<string, unknown> = {}): unknown {+ return paneList({+ ...declaredPane,+ bound: "named",+ sessionId: expected.sessionUuid,+ transcriptPath: expected.transcriptPath,+ ...fields,+ });+ }++ function expectUnbound(list: unknown, expected: ExpectedBinding): void {+ expect(checkGateBinding(list, expected)).toEqual({+ ok: false,+ detail: expect.stringContaining("input_gate_unbound"),+ });+ }++ test("accepts named binding with equal session id and existing normalised path", () => {+ const { projectDir, expected } = bindingSetup();+ const canonical = realpathSync(expected.transcriptPath);+ const paths = [+ expected.transcriptPath,+ `${projectDir}/../project-a/./${expected.sessionUuid}.jsonl`,+ relative(process.cwd(), expected.transcriptPath),+ ];+ for (const transcriptPath of paths) {+ expect(normaliseTranscriptPath(transcriptPath)).toBe(canonical);+ expect(checkGateBinding(namedList(expected, { transcriptPath }), expected)).toEqual({ ok: true });+ }+ });++ test("accepts named binding through a symlink-normalised existing transcript path", () => {+ const { root, projectDir, expected } = bindingSetup();+ const parentLink = join(root, "project-link");+ const fileLink = join(root, "transcript-link.jsonl");+ symlinkSync(projectDir, parentLink, "dir");+ symlinkSync(expected.transcriptPath, fileLink, "file");+ const canonical = realpathSync(expected.transcriptPath);+ for (const transcriptPath of [join(parentLink, `${expected.sessionUuid}.jsonl`), fileLink]) {+ expect(normaliseTranscriptPath(transcriptPath)).toBe(canonical);+ expect(checkGateBinding(namedList(expected, { transcriptPath }), expected)).toEqual({ ok: true });+ expect(checkGateBinding(namedList(expected), { ...expected, transcriptPath })).toEqual({ ok: true });+ }+ });++ test("normalises parent directory plus basename when the transcript does not exist yet", () => {+ const { root, projectDir, expected } = bindingSetup(false);+ const parentLink = join(root, "project-link");+ symlinkSync(projectDir, parentLink, "dir");+ // Also cover a missing project subdirectory: the deepest existing ancestor is the link target.+ for (const suffix of [+ `${expected.sessionUuid}.jsonl`,+ join("not-yet-created", "deeper", `${expected.sessionUuid}.jsonl`),+ ]) {+ const actualPath = join(parentLink, suffix);+ const expectedPath = join(projectDir, suffix);+ const canonical = join(realpathSync(projectDir), suffix);+ expect(existsSync(actualPath)).toBe(false);+ expect(existsSync(expectedPath)).toBe(false);+ expect(normaliseTranscriptPath(actualPath)).toBe(canonical);+ expect(normaliseTranscriptPath(expectedPath)).toBe(canonical);+ expect(checkGateBinding(+ namedList(expected, { transcriptPath: actualPath, transcriptSeen: false }),+ { ...expected, transcriptPath: expectedPath }+ )).toEqual({ ok: true });+ expect(checkGateBinding(+ namedList(expected, { transcriptPath: expectedPath, transcriptSeen: false }),+ { ...expected, transcriptPath: actualPath }+ )).toEqual({ ok: true });+ expect(existsSync(expectedPath)).toBe(false);+ }+ });++ test("rejects prompt binding even when session id and transcript path match", () => {+ const { expected } = bindingSetup();+ expectUnbound(namedList(expected, { bound: "prompt" }), expected);+ });++ test("rejects mtime binding even when session id and transcript path match", () => {+ const { expected } = bindingSetup();+ expectUnbound(namedList(expected, { bound: "mtime" }), expected);+ });++ test("rejects missing or unknown binding metadata instead of treating it as named", () => {+ const { expected } = bindingSetup();+ const sessionId = expected.sessionUuid;+ const transcriptPath = expected.transcriptPath;+ const bindings: Record<string, unknown>[] = [+ {},+ { sessionId, transcriptPath },+ { bound: "future_binding", sessionId, transcriptPath },+ { bound: "unbound", sessionId, transcriptPath },+ { bound: null, sessionId, transcriptPath },+ { bound: "named", transcriptPath },+ { bound: "named", sessionId },+ { bound: "named" },+ ];+ for (const binding of bindings) {+ expectUnbound({ panes: [+ { pane: 1, ...declaredPane, bound: "named", sessionId, transcriptPath },+ { pane: 0, ...declaredPane, ...binding },+ ] }, expected);+ }+ });++ test("rejects a different session id even when the transcript path matches", () => {+ const { expected } = bindingSetup();+ expectUnbound(namedList(expected, {+ sessionId: "22222222-2222-4222-8222-222222222222",+ }), expected);+ });++ test("rejects a different transcript path even when the session id or basename matches", () => {+ const { root, projectDir, expected } = bindingSetup();+ const otherProject = join(root, "other-project");+ mkdirSync(otherProject);+ const otherParentLink = join(root, "other-project-link");+ symlinkSync(otherProject, otherParentLink, "dir");+ const sameBasename = join(otherProject, `${expected.sessionUuid}.jsonl`);+ const differentBasename = join(projectDir, "other-session.jsonl");+ for (const transcriptPath of [sameBasename, differentBasename]) writeFileSync(transcriptPath, "");+ for (const transcriptPath of [+ sameBasename,+ differentBasename,+ join(otherParentLink, `${expected.sessionUuid}.jsonl`),+ ]) {+ expect(normaliseTranscriptPath(transcriptPath)).not.toBe(realpathSync(expected.transcriptPath));+ expectUnbound(namedList(expected, { transcriptPath }), expected);+ }+ });++ test("rejects a path under ~/.claude when CLAUDE_CONFIG_DIR points elsewhere", () => {+ const { root, configDir, expected } = bindingSetup();+ const home = join(root, "home");+ const defaultProject = join(home, ".claude", "projects", "project-a");+ mkdirSync(defaultProject, { recursive: true });+ const defaultPath = join(defaultProject, `${expected.sessionUuid}.jsonl`);+ writeFileSync(defaultPath, "");+ const priorHome = process.env.HOME;+ const priorConfig = process.env.CLAUDE_CONFIG_DIR;+ try {+ process.env.HOME = home;+ process.env.CLAUDE_CONFIG_DIR = configDir;+ expect(normaliseTranscriptPath(defaultPath)).not.toBe(realpathSync(expected.transcriptPath));+ expectUnbound(namedList(expected, { transcriptPath: defaultPath }), expected);+ expect(checkGateBinding(namedList(expected), expected)).toEqual({ ok: true });+ } finally {+ if (priorHome === undefined) delete process.env.HOME;+ else process.env.HOME = priorHome;+ if (priorConfig === undefined) delete process.env.CLAUDE_CONFIG_DIR;+ else process.env.CLAUDE_CONFIG_DIR = priorConfig;+ }+ });+});diff --git a/packages/cli/src/pane/magmux-client-reason.test.ts b/packages/cli/src/pane/magmux-client-reason.test.tsnew file mode 100644index 00000000..fe37340c--- /dev/null+++ b/packages/cli/src/pane/magmux-client-reason.test.ts@@ -0,0 +1,149 @@+import { describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { createServer, type Socket } from "node:net";+import { join } from "node:path";+import { MagmuxClient, type MagmuxReply } from "./magmux-client.js";++type FailureLine = {+ ok: false;+ code: string;+ error: string;+ reason?: string;+ typed?: boolean;+};++// A protocol-decoding unit test, not a simulated pane integration test. Replay+// only NDJSON replies through the public socket API; no child, credentials or+// real magmux socket is opened. Each exchange owns and removes its short path.+async function exchange(replies: FailureLine[], fragmented = false): Promise<MagmuxReply[]> {+ const root = mkdtempSync("/tmp/cmr-");+ const sockPath = join(root, "m.sock");+ const peers = new Set<Socket>();+ let nextReply = 0;+ const server = createServer((socket) => {+ peers.add(socket);+ socket.write(`${JSON.stringify({ type: "snapshot", panes: [] })}\n`);+ let buffer = "";+ socket.on("data", (chunk) => {+ buffer += chunk.toString("utf8");+ let newline: number;+ while ((newline = buffer.indexOf("\n")) >= 0) {+ const line = buffer.slice(0, newline);+ buffer = buffer.slice(newline + 1);+ if (!line) continue;+ const request = JSON.parse(line) as { id: string };+ const reply = replies[nextReply++];+ if (!reply) {+ socket.destroy();+ continue;+ }+ const encoded = `${JSON.stringify({ type: "reply", id: request.id, ...reply })}\n`;+ if (fragmented) {+ // Split inside reason; the remainder carries typed and the line terminator.+ const cut = encoded.indexOf("dialog:") + "dialog:".length;+ socket.write(encoded.slice(0, cut));+ setImmediate(() => {+ if (!socket.destroyed) socket.write(encoded.slice(cut));+ });+ } else {+ socket.write(encoded);+ }+ }+ });+ });++ let client: MagmuxClient | undefined;+ try {+ await new Promise<void>((resolve, reject) => {+ const onError = (error: Error) => reject(error);+ server.once("error", onError);+ server.listen(sockPath, () => {+ server.off("error", onError);+ resolve();+ });+ });+ client = await MagmuxClient.dial(sockPath);+ const results: MagmuxReply[] = [];+ for (let index = 0; index < replies.length; index++) {+ results.push(await client.request({ type: "send", pane: 0, text: "run the tests", typed: true }, 2000));+ }+ return results;+ } finally {+ client?.close();+ for (const socket of peers) socket.destroy();+ try {+ if (server.listening) {+ await new Promise<void>((resolve, reject) => {+ server.close((error) => error ? reject(error) : resolve());+ });+ }+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ expect(server.listening).toBe(false);+ expect([...peers].every((socket) => socket.destroyed)).toBe(true);+ expect(existsSync(root)).toBe(false);+ }+}++describe("U2 MagmuxClient failure reply fields", () => {+ test("keeps busy reason and typed true", async () => {+ const reply: FailureLine = { ok: false, code: "busy", error: "typing stopped", reason: "dialog:permission", typed: true };+ expect(await exchange([reply])).toEqual([reply]);+ });++ test("keeps not_accepted reason and typed true", async () => {+ const reply: FailureLine = { ok: false, code: "not_accepted", error: "the text is still in the box", reason: "still_in_box", typed: true };+ expect(await exchange([reply])).toEqual([reply]);+ });++ test("keeps reason while omitting absent typed", async () => {+ const reply: FailureLine = { ok: false, code: "busy", error: "booting", reason: "starting" };+ const results = await exchange([reply]);+ expect(results).toEqual([reply]);+ expect(Object.hasOwn(results[0]!, "typed")).toBe(false);+ });++ test("keeps typed while omitting absent reason", async () => {+ const reply: FailureLine = { ok: false, code: "pane_dead", error: "pane died while typing", typed: true };+ const results = await exchange([reply]);+ expect(results).toEqual([reply]);+ expect(Object.hasOwn(results[0]!, "reason")).toBe(false);+ });++ test("preserves an explicitly false typed field", async () => {+ const reply: FailureLine = { ok: false, code: "busy", error: "not ready", reason: "terminal_not_ready", typed: false };+ const results = await exchange([reply]);+ expect(results).toEqual([reply]);+ expect(Object.hasOwn(results[0]!, "typed")).toBe(true);+ });++ test("omits both fields on an ordinary failure", async () => {+ const reply: FailureLine = { ok: false, code: "no_such_pane", error: "no pane 0 (it may have been closed)" };+ const results = await exchange([reply]);+ expect(results).toEqual([reply]);+ expect(Object.hasOwn(results[0]!, "reason")).toBe(false);+ expect(Object.hasOwn(results[0]!, "typed")).toBe(false);+ });++ test("keeps an unknown reason verbatim", async () => {+ const reply: FailureLine = { ok: false, code: "busy", error: "new gate state", reason: "dialog:future_kind", typed: true };+ expect(await exchange([reply])).toEqual([reply]);+ });++ test("does not carry optional fields into the next reply on the connection", async () => {+ const replies: FailureLine[] = [+ { ok: false, code: "busy", error: "dialog", reason: "dialog:question", typed: true },+ { ok: false, code: "bad_request", error: "unknown key name" },+ ];+ const results = await exchange(replies);+ expect(results).toEqual(replies);+ expect(Object.hasOwn(results[1]!, "reason")).toBe(false);+ expect(Object.hasOwn(results[1]!, "typed")).toBe(false);+ });++ test("keeps optional fields when a failure line arrives in fragments", async () => {+ const reply: FailureLine = { ok: false, code: "busy", error: "question appeared", reason: "dialog:question", typed: true };+ expect(await exchange([reply], true)).toEqual([reply]);+ });+});