Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
test(pane): record pane-session sends from the moment the magmux client exists
Jack Rudenkoc788541718b7
diff --git a/packages/cli/src/pane/pane-session.integration.test.ts b/packages/cli/src/pane/pane-session.integration.test.tsindex 3e58fc37..55185d84 100644--- a/packages/cli/src/pane/pane-session.integration.test.ts+++ b/packages/cli/src/pane/pane-session.integration.test.ts@@ -20,6 +20,7 @@ import {} from "./pane-session.js";import { inputBox, readBoot } from "./screen-classifier.js";import type { ScreenState } from "./screen-model.js";+import { type ObservedClient, observeClients } from "./test-helpers/client-observer.js";import {MAGMUX,NO_MAGMUX_MESSAGE,@@ -37,6 +38,7 @@ const sha8 = (s: string) => createHash("sha1").update(s).digest("hex").slice(0,const open = new Set<Run>();afterAll(async () => {for (const r of open) {+ r.unobserve();r.s.cancel();await r.s.reaped();killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });@@ -52,6 +54,19 @@ interface Run {turns: SettledTurn[];blocks: PaneBlock[];submits: Array<{ text: string; at: number }>;+ sendLog: SendLog;+ /** Stop handing this run's new magmux clients to its send observer. */+ unobserve: () => void;+}++/** Every `send` the run's magmux clients carried, recorded from the moment each client exists. */+interface SendLog {+ /** Set once `startPaneSession` returns; until then a send's box reads null. */+ session: PaneSession | null;+ /** Sends issued before `start` returned: no test could have attached a trace that early. */+ early: InputSend[];+ /** The live lists `traceInput` handed out. */+ traces: InputSend[][];}/** team-like policy: verdict at the first settle; api error → FAILED; question → FAILED blocked */@@ -73,6 +88,10 @@ async function start(const turns: SettledTurn[] = [];const blocks: PaneBlock[] = [];const { env: _e, decide, onBlocked, timings, ...rest } = over;+ // A one-shot pane's first gated send can leave from inside `attach()`, before+ // `startPaneSession` returns: observe each client as it is created, not `s.client` later.+ const sendLog: SendLog = { session: null, early: [], traces: [] };+ const unobserve = observeClients(t.sockRoot, recordSends(sendLog));const s = await startPaneSession({kind: "t",label: "01",@@ -103,8 +122,22 @@ async function start(...timings,},...rest,+ }).catch((error: unknown) => {+ unobserve();+ throw error;});- const run: Run = { s, t, uuid, transitions, turns, blocks, submits: [] };+ sendLog.session = s;+ const run: Run = {+ s,+ t,+ uuid,+ transitions,+ turns,+ blocks,+ submits: [],+ sendLog,+ unobserve,+ };open.add(run);return run;}@@ -121,6 +154,7 @@ async function finish(r: Run, ms = 20_000): Promise<PaneSnapshot> {return snap;} finally {open.delete(r);+ r.unobserve();r.s.cancel();await r.s.reaped();const log = r.t.env.FAKE_SUBMIT_LOG as string;@@ -166,7 +200,11 @@ async function until(}function screenOf(r: Run): ScreenState {- const capture = r.s.capture(undefined, { spans: true });+ return screenOfSession(r.s);+}++function screenOfSession(s: PaneSession): ScreenState {+ const capture = s.capture(undefined, { spans: true });if (!("lines" in capture)) throw new Error("expected a full capture");return {...capture,@@ -184,21 +222,35 @@ interface InputSend {at: number;}-/** 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);- client.request = async (message, ms) => {- if (message.type === "send") {- sends.push({- message: { ...message },- box: inputBox(screenOf(r))?.text ?? null,- at: Date.now(),- });- }- return real(message, ms);+/** The client observer for one run: wrap each new client's `request` once, recording sends. */+function recordSends(log: SendLog): (client: ObservedClient) => void {+ const seen = new WeakSet<ObservedClient>();+ return (client) => {+ if (seen.has(client)) return;+ seen.add(client);+ const real = client.request.bind(client);+ client.request = async (message, ms) => {+ if (message.type === "send") {+ const send: InputSend = {+ message: { ...message },+ box: log.session ? (inputBox(screenOfSession(log.session))?.text ?? null) : null,+ at: Date.now(),+ };+ if (!log.session) log.early.push(send);+ for (const trace of log.traces) trace.push(send);+ }+ return real(message, ms);+ };};+}++/**+ * Observe actual sends without replacing the gate's decisions: every send from this call+ * on, plus any issued while `start` was still running (a one-shot pane's first gated send).+ */+function traceInput(r: Run): InputSend[] {+ const sends = [...r.sendLog.early];+ r.sendLog.traces.push(sends);return sends;}diff --git a/packages/cli/src/pane/test-helpers/client-observer.ts b/packages/cli/src/pane/test-helpers/client-observer.tsnew file mode 100644index 00000000..c93f80a0--- /dev/null+++ b/packages/cli/src/pane/test-helpers/client-observer.ts@@ -0,0 +1,69 @@+/**+ * Observe every MagmuxClient a pane creates, from the moment it exists.+ *+ * A pane's first gated send can leave from inside `attach()`, before `startPaneSession`+ * returns: wrapping `s.client` afterwards misses it. So `MagmuxClient.connect` and+ * `MagmuxClient.dial` are wrapped once, and each client they return is handed to the+ * observer registered for the socket root its `sockPath` sits under.+ */+import { realpathSync } from "node:fs";+import { basename, dirname, join } from "node:path";+import { MagmuxClient, type MagmuxReply } from "../magmux-client.js";++export type ObservedRequest = (+ message: Record<string, unknown>,+ timeout?: number+) => Promise<MagmuxReply>;+export interface ObservedClient {+ request: ObservedRequest;+ close(): void;+}++/** Socket root (with a trailing slash) -> the observer of the pane started under it. */+const routes = new Map<string, (client: ObservedClient) => 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<ObservedClient>+ >;+ 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];+}++/**+ * Hand every client created under `sockRoot` to `observe`. Register BEFORE starting the+ * pane. Returns the unregister function; calling it twice is harmless.+ */+export function observeClients(+ sockRoot: string,+ observe: (client: ObservedClient) => void+): () => void {+ hookClientCreation();+ const keys = routeKeys(sockRoot);+ for (const key of keys) routes.set(key, observe);+ return () => {+ for (const key of keys) if (routes.get(key) === observe) routes.delete(key);+ };+}diff --git a/packages/cli/src/pane/test-helpers/gated-pane.ts b/packages/cli/src/pane/test-helpers/gated-pane.tsindex 1a07ebc3..210779c0 100644--- a/packages/cli/src/pane/test-helpers/gated-pane.ts+++ b/packages/cli/src/pane/test-helpers/gated-pane.ts@@ -1,10 +1,11 @@/** Real-magmux test driver. Deliberately has NO timings seam: D-A/D-B use production defaults. */import { expect } from "bun:test";-import { existsSync, readFileSync, realpathSync } from "node:fs";-import { basename, dirname, join } from "node:path";-import { MagmuxClient, type MagmuxReply } from "../magmux-client.js";+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 { type ObservedClient, observeClients } from "./client-observer.js";import {type PaneTestEnv,killLeftovers,@@ -38,62 +39,15 @@ 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[]>();+const unrouteOf = new WeakMap<GateRun, () => void>();-interface TestClient {- request: Request;- close(): void;-}+type TestClient = ObservedClient;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");@@ -120,8 +74,9 @@ export async function startGatePane(scenario: string, opts: Options = {}): Promireturn reply;};};- const keys = routeKeys(t.sockRoot);- for (const key of keys) routes.set(key, observe);+ // A pane's first gated send can leave from inside `attach()`, before `startPaneSession`+ // returns: observe every client as it is created, not `s.client` afterwards.+ const unroute = observeClients(t.sockRoot, observe);let s: PaneSession;try {s = await startPaneSession({@@ -153,14 +108,14 @@ export async function startGatePane(scenario: string, opts: Options = {}): Promi},});} catch (error) {- unroute(keys);+ unroute();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);- routeKeysOf.set(r, keys);+ unrouteOf.set(r, unroute);// Backstop: a client assigned without passing connect/dial is still observed.let current: TestClient | null = clientOf(r);observe(current);@@ -218,7 +173,7 @@ export async function disposeGatePane(r: GateRun): Promise<void> {expect(report).toEqual({ processes: [], files: [] });} finally {open.delete(r);- unroute(routeKeysOf.get(r) ?? []);+ unrouteOf.get(r)?.();killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });r.t.cleanup();}