Skip to content

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

fix(hooks): run session hooks on v12.1.0's gated send and settle after rebase onto v12.1.0

Jack Rudenkoc2476b3e26c3
diff --git a/packages/cli/src/hooks/session/interactive-driver.ts b/packages/cli/src/hooks/session/interactive-driver.ts
index 65c5a7b7..b20ddcc3 100644
--- a/packages/cli/src/hooks/session/interactive-driver.ts
+++ b/packages/cli/src/hooks/session/interactive-driver.ts
@@ -42,6 +42,11 @@
import { existsSync, statSync } from "node:fs";
import { join } from "node:path";
import { log, logStderr } from "../../logger.js";
+import {
+ SEND_READY_WAIT_DEFAULT_MS,
+ classifySendReply,
+ sendBudgetMs,
+} from "../../pane/input-gate.js";
import { MagmuxClient } from "../../pane/magmux-client.js";
import { findOwnPane } from "../../pane/own-pane.js";
import {
@@ -65,8 +70,8 @@ import {
} from "../../pane/screen-model.js";
import {
CORROBORATION_MS,
+ type CorroborationFacts,
SECONDARY_QUIET_MS,
- type ScreenFacts,
decideSettle,
} from "../../pane/settle-rule.js";
import {
@@ -109,6 +114,8 @@ const WATCH_FPS = 4;
const REPL_STABLE_MS = 500;
/** How long a session id learned from a request may wait for its transcript to appear. */
const RETARGET_WAIT_MS = 10_000;
+/** Added to a send's budget for the client timeout, as a pane does. */
+const SEND_CLIENT_SLACK_MS = 2_000;
/** How long a lost send reply waits for `reconnect()` before the admission fails. */
const RECONNECT_WAIT_MS = 10_000;
const DEFAULT_MAX_CONSECUTIVE = 3;
@@ -700,12 +707,19 @@ export class InteractiveDriver {
this.transition("admit_failed");
}
- private screenFacts(): ScreenFacts | null {
+ /**
+ * Settle corroboration in the settle rule's shape. The driver reads the SCREEN, not
+ * magmux's input gate: the pane it follows may be ungated (an ambient pane, a test's
+ * headless one), and the gate's published view names pane 0 only. So `gate.ready` is
+ * the screen's box drawn and empty with no choice dialog, as the driver settled on
+ * before; corroboration can delay a transcript-proven ending, never veto it (the
+ * settle rule's grace).
+ */
+ private corroborationFacts(): CorroborationFacts | null {
if (!this.client) return null;
- const box = inputBox(this.screen);
+ const reason = screenNotIdleReason(this.screen);
return {
- boxEmpty: !!box && box.text === "",
- choiceDialog: hasChoiceDialog(this.screen),
+ gate: { ready: reason === null, dialog: null, reason },
working: isWorking(this.screen),
aboveBoxQuietMs: Date.now() - this.screen.aboveBoxChangedAt,
};
@@ -721,10 +735,12 @@ export class InteractiveDriver {
session: view.session,
transcriptQuietMs: now - (view.lastAppendAt ?? this.startedAt),
chatQuietMs: now - this.lastChatSeenAt,
- screen: this.screenFacts(),
+ facts: this.corroborationFacts(),
paneExited: false,
secondaryQuietMs: this.ms("secondaryQuietMs", SECONDARY_QUIET_MS),
corroborationMs: this.ms("corroborationMs", CORROBORATION_MS),
+ // the grace is the secondary window, as a pane's (`GATE_GRACE_MS`)
+ corroborationGraceMs: this.ms("secondaryQuietMs", SECONDARY_QUIET_MS),
});
if (decision.settled) this.record(t, decision.by === "local_command", decision.stopReason);
}
@@ -996,15 +1012,34 @@ export class InteractiveDriver {
}
this.transition("deliver");
const adm = this.admission;
+ // On a pane magmux gates (its command names Claude Code, as the `-w` wrap's does) the send waits for
+ // the box and answers only with evidence, so the client timeout is the gated budget:
+ // a shorter one reads a slow gated answer as a lost reply.
+ const rt = SEND_READY_WAIT_DEFAULT_MS;
+ const timeout =
+ sendBudgetMs({ readyTimeoutMs: rt, text: plan.line, keys: 1, submit: true }) +
+ SEND_CLIENT_SLACK_MS;
void client
- .request({ type: "send", pane, text: plan.line, typed: true, enter: true }, 10_000)
+ .request(
+ { type: "send", pane, text: plan.line, typed: true, enter: true, readyTimeoutMs: rt },
+ timeout
+ )
.then(async (r) => {
if (r.ok || this.admission !== adm) return;
+ const out = classifySendReply(r);
// a lost REPLY is not a refusal. The line may already be typed, or typed
- // and entered; the screen and the transcript decide, as in a pane (`typeLine`).
+ // and entered; the screen and the transcript decide, as in a pane.
// Once it landed, the text witness accepts it within `acceptMs` as usual.
- const lost = r.code === "client_timeout" || r.code === "client_lost";
- if (lost && (await this.landedAfterLostReply(adm, pane, plan.line))) return;
+ if (out.kind === "reply_lost" && out.code !== "timeout") {
+ if (await this.landedAfterLostReply(adm, pane, plan.line)) return;
+ } else if (out.kind === "not_accepted" && enterMayHaveBeenPressed(out)) {
+ // the gate pressed Enter (or another writer may have): never pressed again;
+ // the text witness accepts it, or `acceptMs` drops it
+ log(
+ `[hooks] interactive driver: send not confirmed (${out.reason}); awaiting the witness`
+ );
+ return;
+ }
if (this.admission === adm)
this.step(() => this.admitFailed(`send refused: ${r.code} ${r.error}`));
});
@@ -1087,6 +1122,19 @@ export class InteractiveDriver {
}
}
+/** Why the screen does not show an idle REPL (a choice dialog, no box, text in it); null when it does. */
+function screenNotIdleReason(screen: ScreenState): string | null {
+ if (hasChoiceDialog(screen)) return "choice_dialog";
+ const box = inputBox(screen);
+ if (!box) return "no_input_box";
+ return box.text === "" ? null : "box_not_empty";
+}
+
+/** A gated `not_accepted` after which Enter was, or may have been, pressed. */
+function enterMayHaveBeenPressed(o: { reason: string; maybeSubmitted: boolean }): boolean {
+ return o.reason === "still_in_box" || o.reason === "unconfirmed" || o.maybeSubmitted;
+}
+
function assertNeverPhase(p: never): never {
throw new Error(`unhandled driver phase ${String(p)}`);
}
diff --git a/packages/cli/src/pane/pane-hooks.integration.test.ts b/packages/cli/src/pane/pane-hooks.integration.test.ts
index 4aa015d8..63d7b582 100644
--- a/packages/cli/src/pane/pane-hooks.integration.test.ts
+++ b/packages/cli/src/pane/pane-hooks.integration.test.ts
@@ -110,6 +110,13 @@ function engineOf(...defs: Array<Omit<HookDefinition, "apiVersion">>) {
const after = <T>(ms: number, v: T) => new Promise<T>((r) => setTimeout(() => r(v), ms));
+/**
+ * An injected turn's admission bound in the never-accepted rows: enough for ONE gated send
+ * of a short line (its budget, ~13 s with a 1 s readiness wait), so the line is typed and
+ * magmux answers before the bound drops it.
+ */
+const HOOK_ADMIT_BOUND_MS = 16_000;
+
/* ───────────────────────────── helpers ───────────────────────────── */
interface TurnScript {
@@ -643,7 +650,8 @@ wait $child
const x = await team({
script: [{ say: "ANS-ONE" }, { noWitness: true }],
binding: ctl.binding,
- timings: { admitTimeoutMs: 1_500 },
+ // room for one gated send; magmux answers `unconfirmed`, the bound drops the item
+ timings: { admitTimeoutMs: HOOK_ADMIT_BOUND_MS },
});
try {
await until(() => ctl.calls.length === 1, "settle() 1");
@@ -654,6 +662,7 @@ wait $child
expect(ctl.dropped).toEqual([{ text: "HOOK-PING", reason: "send_not_accepted" }]);
for (const m of Object.values(getStatus(x.handle.sessionPath).models))
expect(["RUNNING", "AWAITING_INPUT"]).not.toContain(m.state);
+ expect(keylog(x.t)).toContain("HOOK-PING");
} finally {
await teamDone(x);
}
@@ -691,7 +700,8 @@ wait $child
const c = await channel({
script: [{ say: "ANS-ONE" }, { noWitness: true }],
binding: ctl.binding,
- timings: { admitTimeoutMs: 1_500 },
+ // room for one gated send; magmux answers `unconfirmed`, the bound drops the item
+ timings: { admitTimeoutMs: HOOK_ADMIT_BOUND_MS },
});
try {
await until(() => ctl.calls.length === 1, "settle()");
@@ -702,6 +712,8 @@ wait $child
expect(c.rowEvents()).not.toContain("waiting_for_input");
expect(lineCount(c.output(), "ANS-ONE")).toBe(1);
expect(ctl.dropped).toEqual([{ text: "HOOK-PING", reason: "send_not_accepted" }]);
+ // typed and submitted, never accepted: not dropped before a send was made
+ expect(keylog(c.t)).toContain("HOOK-PING");
} finally {
await done(c);
}
@@ -717,7 +729,8 @@ wait $child
script: [{ say: "ANS-ONE" }, { noWitness: true }],
binding: ctl.binding,
prompt: null,
- timings: { admitTimeoutMs: 1_500 },
+ // room for one gated send; magmux answers `unconfirmed`, the bound drops the item
+ timings: { admitTimeoutMs: HOOK_ADMIT_BOUND_MS },
});
try {
await until(() => c.info().state === "AWAITING_INPUT", "boot");
@@ -730,6 +743,7 @@ wait $child
);
await until(() => c.info().state === "AWAITING_INPUT", "AWAITING_INPUT");
expect(lineCount(c.output(), "ANS-ONE")).toBe(1);
+ expect(keylog(c.t)).toContain("HOOK-PING");
} finally {
await done(c);
}
diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.ts
index 3e7c3653..e4c53f33 100644
--- a/packages/cli/src/pane/pane-session.ts
+++ b/packages/cli/src/pane/pane-session.ts
@@ -329,7 +329,7 @@ export interface PaneSessionOptions {
replStableMs?: number;
/** H-31: hold the exit-path screen capture this long, as a slow magmux reply does */
exitCaptureDelayMs?: number;
- /** the admission bound, through owners that do not pass `admitTimeoutMs` (H-13, H-14) */
+ /** a LATER admission's bound, through owners that do not pass `admitTimeoutMs` (H-13 … H-15) */
admitTimeoutMs?: number;
/** a frame polls the transcript only this long after the last poll (default 250) */
pollDebounceMs?: number;
@@ -1308,11 +1308,12 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
/**
* An admission's bound. `admitTimeoutMs` bounds only the CREATED prompt's admission, as its
- * option says; the test-only `timings.admitTimeoutMs` bounds every admission, for owners
- * that do not pass `admitTimeoutMs` (H-13, H-14).
+ * option says; the test-only `timings.admitTimeoutMs` bounds only a LATER one (an injected
+ * turn, H-13 … H-15), for owners that do not pass `admitTimeoutMs`. A bound must leave room
+ * for one gated send (`readyTimeoutFor`), else no attempt is made at all.
*/
private admitBoundMs(initial: boolean): number {
- if (initial) return this.admitTimeoutMs();
+ if (initial) return this.o.admitTimeoutMs ?? ADMIT_TIMEOUT_MS;
return this.o.timings?.admitTimeoutMs ?? ADMIT_TIMEOUT_MS;
}
@@ -1529,7 +1530,14 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
? { file: plan.file, text: plan.fileContent }
: null;
this.follower.openTurn({ index, offset, witness: plan.witness, delivery });
- const adm = newAdmission({ index, item, text, plan, initial, bound: this.admitBoundMs(initial) });
+ const adm = newAdmission({
+ index,
+ item,
+ text,
+ plan,
+ initial,
+ bound: this.admitBoundMs(initial),
+ });
this.admission = adm;
void this.runAdmission(adm);
}
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 04e8bcb1..1f6fbbd5 100755
--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -560,7 +560,11 @@ interface TurnScript {
partial?: string;
/** write this text (if non-empty), then open an AskUserQuestion and wait for Esc */
ask?: string;
- /** never write the user record: the turn is never accepted */
+ /**
+ * the turn is never accepted: no user record and no echo in the conversation, so neither
+ * claudish's witness nor magmux's input gate (whose `history` evidence is that echo) has
+ * evidence it was submitted
+ */
noWitness?: boolean;
/** exit with this code as soon as the line is submitted (before any witness) */
exitOnSubmit?: number;
@@ -1206,10 +1210,7 @@ async function submit(line: string, opts: { argv?: boolean } = {}): Promise<void
await sleep(30);
return await quit(sc.exitOnSubmit);
}
- if (sc.noWitness) {
- S.history.push(`❯ ${line.split("\n")[0]}`);
- return;
- }
+ if (sc.noWitness) return;
// A command-line prompt is written at once, before the REPL is drawn.
if (!opts.argv) await sleep(gap("WITNESS", 50));
rec.user(line);