Skip to content

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

test(pane): record gated sends from the moment the magmux client exists

Jack Rudenko16f222cb9aab
diff --git a/packages/cli/src/pane/pane-gated-delivery.integration.test.ts b/packages/cli/src/pane/pane-gated-delivery.integration.test.ts
index 36d463e7..56f6500b 100644
--- a/packages/cli/src/pane/pane-gated-delivery.integration.test.ts
+++ b/packages/cli/src/pane/pane-gated-delivery.integration.test.ts
@@ -104,6 +104,9 @@ async function assertLoudLoss(r: GateRun, reason: string): Promise<void> {
expect(r.turns).toHaveLength(0);
expect(r.transitions.some(({ to }) => to === "EMPTY" || to === "COMPLETED")).toBe(false);
expect(submissions(r)).toEqual([]);
+ // A recording gap must fail here as a missed send, not below as a timing bound.
+ const typed = gatedSends(r).filter(({ message }) => typeof message.text === "string");
+ expect(typed.length).toBe(r.s.diagnostics().lastSend?.attempts ?? -1);
const failedAt = r.transitions.find(({ to }) => to === "FAILED")?.at ?? 0;
expect(failedAt - (gatedSends(r)[0]?.at ?? Number.POSITIVE_INFINITY)).toBeGreaterThanOrEqual(
29_000
@@ -114,7 +117,8 @@ async function assertLoudLoss(r: GateRun, reason: string): Promise<void> {
describe.skipIf(!MAGMUX)(
`gated delivery at production timings (${MAGMUX ? "real magmux" : NO_MAGMUX_MESSAGE})`,
() => {
- afterEach(disposeGatePanes);
+ // One disposal awaits reaped() and then polls up to 8 s for orphans; 5 s is bun's default.
+ afterEach(disposeGatePanes, 30_000);
test(
"I1: promptless boot uses the declared gate, without a transcript or a send",
diff --git a/packages/cli/src/pane/test-helpers/gated-pane.ts b/packages/cli/src/pane/test-helpers/gated-pane.ts
index 0e1a8a17..1a07ebc3 100644
--- a/packages/cli/src/pane/test-helpers/gated-pane.ts
+++ b/packages/cli/src/pane/test-helpers/gated-pane.ts
@@ -1,8 +1,8 @@
/** 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 { existsSync, readFileSync, realpathSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+import { MagmuxClient, type MagmuxReply } from "../magmux-client.js";
import { type PaneSession, type PaneSessionOptions, startPaneSession } from "../pane-session.js";
import type { PaneSnapshot, SettledTurn } from "../types.js";
import {
@@ -38,6 +38,7 @@ type Options = Omit<Partial<PaneSessionOptions>, "timings"> & {
prepare?: (t: PaneTestEnv, uuid: string) => Partial<Omit<PaneSessionOptions, "timings">>;
};
const open = new Set<GateRun>();
+const routeKeysOf = new WeakMap<GateRun, string[]>();
interface TestClient {
request: Request;
@@ -48,7 +49,51 @@ export function clientOf(r: GateRun): TestClient {
return (r.s as unknown as { client: TestClient }).client;
}
+/**
+ * Socket root (with a trailing slash) -> the observer of the pane started under it.
+ *
+ * A pane's first gated send can leave from inside `attach()`, before `startPaneSession`
+ * returns: wrapping `s.client` afterwards misses it. So every client is handed to its
+ * pane's observer as `MagmuxClient.connect` / `MagmuxClient.dial` return it.
+ */
+const routes = new Map<string, (client: TestClient) => void>();
+let creationHooked = false;
+
+/** Wrap the two client-creation statics once. With no matching route they pass through. */
+function hookClientCreation(): void {
+ if (creationHooked) return;
+ creationHooked = true;
+ const statics = MagmuxClient as unknown as Record<
+ "connect" | "dial",
+ (sockPath: string, ...rest: unknown[]) => Promise<TestClient>
+ >;
+ for (const name of ["connect", "dial"] as const) {
+ const real = statics[name].bind(MagmuxClient);
+ statics[name] = async (sockPath, ...rest) => {
+ const client = await real(sockPath, ...rest);
+ for (const [root, observe] of routes) if (sockPath.startsWith(root)) observe(client);
+ return client;
+ };
+ }
+}
+
+/** The raw root and its realpath form (`/tmp` is `/private/tmp` on macOS); the root may not exist yet. */
+function routeKeys(sockRoot: string): string[] {
+ const keys = new Set([`${sockRoot}/`]);
+ try {
+ keys.add(`${join(realpathSync(dirname(sockRoot)), basename(sockRoot))}/`);
+ } catch {
+ // parent missing: only the raw key can match
+ }
+ return [...keys];
+}
+
+function unroute(keys: string[]): void {
+ for (const key of keys) routes.delete(key);
+}
+
export async function startGatePane(scenario: string, opts: Options = {}): Promise<GateRun> {
+ hookClientCreation();
const t = makePaneTestEnv({ CONTRACT_FAKE_MAX_MS: "120000", ...opts.env });
const uuid = newSessionUuid();
const log = join(t.tmp, "submits.jsonl");
@@ -58,6 +103,25 @@ export async function startGatePane(scenario: string, opts: Options = {}): Promi
const transcript = prepared.transcriptPath ?? over.transcriptPath ?? t.transcriptPathFor(uuid);
const turns: SettledTurn[] = [];
const transitions: GateRun["transitions"] = [];
+ const sends: SendTrace[] = [];
+ // 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 };
+ sends.push(trace);
+ const reply = await real(message, timeout);
+ trace.reply = reply;
+ trace.repliedAt = Date.now();
+ return reply;
+ };
+ };
+ const keys = routeKeys(t.sockRoot);
+ for (const key of keys) routes.set(key, observe);
let s: PaneSession;
try {
s = await startPaneSession({
@@ -89,28 +153,15 @@ export async function startGatePane(scenario: string, opts: Options = {}): Promi
},
});
} catch (error) {
+ unroute(keys);
killLeftovers({ sockRoot: t.sockRoot, ids: [uuid] });
t.cleanup();
throw error;
}
- const r: GateRun = { scenario, s, t, uuid, transcript, log, sends: [], turns, transitions };
+ 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;
- };
- };
+ routeKeysOf.set(r, keys);
+ // Backstop: a client assigned without passing connect/dial is still observed.
let current: TestClient | null = clientOf(r);
observe(current);
Object.defineProperty(s, "client", {
@@ -167,6 +218,7 @@ export async function disposeGatePane(r: GateRun): Promise<void> {
expect(report).toEqual({ processes: [], files: [] });
} finally {
open.delete(r);
+ unroute(routeKeysOf.get(r) ?? []);
killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });
r.t.cleanup();
}