Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(pane): send a resize_session size stored during a redial
Jack Rudenko6978d2a5f5ae
diff --git a/packages/cli/src/pane/pane-session-resize.test.ts b/packages/cli/src/pane/pane-session-resize.test.tsnew file mode 100644index 00000000..421b422a--- /dev/null+++ b/packages/cli/src/pane/pane-session-resize.test.ts@@ -0,0 +1,206 @@+import { afterEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { join } from "node:path";+import type { MagmuxReply } from "./magmux-client.js";+import { PaneSessionImpl, type PaneSessionOptions } from "./pane-session.js";++type Request = Record<string, unknown>;+type RecordedRequest = {+ msg: Request;+ timeoutMs?: number;+ reply: (reply: MagmuxReply) => void;+};++/** Only the attach/resize client surface; no transport, process or module mocks. */+class FakeClient {+ isClosed = false;+ readonly requests: RecordedRequest[] = [];+ private readonly listeners = new Map<string, Array<(event: unknown) => void>>();+ private readonly pending = new Set<(reply: MagmuxReply) => void>();++ on(event: string, cb: (event: unknown) => void): void {+ const callbacks = this.listeners.get(event) ?? [];+ callbacks.push(cb);+ this.listeners.set(event, callbacks);+ }++ emit(event: string, value: unknown = {}): void {+ if (event === "disconnected") this.isClosed = true;+ for (const cb of this.listeners.get(event) ?? []) cb(value);+ }++ request(msg: Request, timeoutMs?: number): Promise<MagmuxReply> {+ return new Promise((resolve) => {+ const reply = (r: MagmuxReply) => {+ this.pending.delete(reply);+ resolve(r);+ };+ this.requests.push({ msg, timeoutMs, reply });+ if (this.isClosed) {+ reply({ ok: false, code: "client_closed", error: "fake closed" });+ } else if (msg.type === "capabilities") {+ reply({+ ok: true,+ result: { protocol: 1, version: "0.15.1", verbs: ["watch", "list", "resize"] },+ });+ } else if (msg.type === "watch" || msg.type === "list") {+ reply({ ok: true, result: { panes: [] } });+ } else if (msg.type === "resize") {+ this.pending.add(reply);+ } else {+ throw new Error(`unexpected fake request: ${String(msg.type)}`);+ }+ });+ }++ close(): void {+ this.isClosed = true;+ for (const reply of this.pending)+ reply({ ok: false, code: "client_closed", error: "fake closed" });+ this.emit("disconnected");+ }+}++const fixtures: Array<{ session: PaneSessionImpl; root: string; clients: FakeClient[] }> = [];++function fixture() {+ const root = mkdtempSync("/tmp/prsz-");+ const configDir = join(root, "config");+ const ctlDir = join(root, "launch-ctl000");+ const turnDir = join(root, "launch-turn00");+ for (const dir of [configDir, ctlDir, turnDir]) mkdirSync(dir);+ const opts: PaneSessionOptions = {+ kind: "s",+ label: "resize-test",+ callerFlags: [],+ spawnModel: "resize-test",+ cwd: root,+ sessionUuid: crypto.randomUUID(),+ transcriptPath: join(root, "transcript.jsonl"),+ slotEnv: {},+ shape: "interactive",+ readAvailable: true,+ parentEnv: { HOME: root, CLAUDE_CONFIG_DIR: configDir },+ decide: () => "continue",+ onBlocked: () => "wait",+ };+ // Do not start(): magmux stays null, so onDisconnected cannot dial a socket.+ const session = new PaneSessionImpl(opts, {+ paneId: "resize-test",+ sockPath: join(root, "absent.sock"),+ root,+ ctlDir,+ turnDir,+ });+ const f = { session, root, clients: [] as FakeClient[] };+ fixtures.push(f);+ return {+ session,+ async attach(reconnect = false) {+ const client = new FakeClient();+ f.clients.push(client);+ await (session as any).attach(client, reconnect);+ return client;+ },+ };+}++async function within(predicate: () => boolean, ms: number): Promise<boolean> {+ const deadline = Date.now() + ms;+ while (!predicate() && Date.now() < deadline) await Bun.sleep(10);+ return predicate();+}++function resizeRequest(client: FakeClient): RecordedRequest {+ const request = client.requests.find((r) => r.msg.type === "resize");+ if (!request) throw new Error("resize() did not send a resize request");+ return request;+}++afterEach(async () => {+ for (const { session, root, clients } of fixtures.splice(0)) {+ try {+ for (const client of clients) client.close();+ // start() was never called: there is no process/group/watcher to reap.+ // Keep shutdown's terminal transition, without its unrelated `ps` subprocess.+ (session as any).reapPromise = Promise.resolve();+ await session.shutdownReap("resize test cleanup");+ expect(await within(() => !(session as any).resizeDraining, 500)).toBe(true);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ }+}, 5000);++describe("pane resize review regressions", () => {+ test("M1: reconnect applies a pending size queued during the previous screen wait", async () => {+ const { session, attach } = fixture();+ const first = await attach();+ const resized = session.resize(100, 40);+ resizeRequest(first).reply({+ ok: true,+ result: { cols: 100, rows: 40, changed: true, manual: true },+ });+ // Confirm the reply was consumed, with no frame to end the 1 s screen wait.+ expect(await within(() => (session as any).appliedSize?.cols === 100, 200)).toBe(true);+ expect((session as any).resizeDraining).toBe(true);+ expect(session.capture()).toMatchObject({ cols: 160 });+ first.emit("disconnected");+ expect(await session.resize(120, 45)).toMatchObject({ cols: 120, rows: 45, pending: true });+ const second = await attach(true);+ expect((session as any).resizeDraining).toBe(true);+ const received = await within(+ () =>+ second.requests.some(+ (r) => r.msg.type === "resize" && r.msg.cols === 120 && r.msg.rows === 45+ ),+ 3000+ );+ await resized;+ expect(received, "fresh client must receive the pending 120x45 resize within 3 s").toBe(true);+ }, 5000);++ test("M2a: quiet window includes a redraw frame received before the resize reply", async () => {+ const { session, attach } = fixture();+ const client = await attach();+ const resized = session.resize(100, 40);+ client.emit("frame", {+ type: "frame",+ pane: 0,+ key: true,+ cols: 100,+ rows: 40,+ lines: [{ y: 0, t: "resize redraw" }],+ });+ const frameChangedAt = (session as any).screen.changedAt as number;+ expect(frameChangedAt).toBeGreaterThan(0);+ expect(session.capture()).toMatchObject({ cols: 100, rows: 40 });+ expect((session as any).inResizeQuiet(frameChangedAt)).toBe(true);+ await Bun.sleep(300);+ resizeRequest(client).reply({+ ok: true,+ result: { cols: 100, rows: 40, changed: true, manual: true },+ });+ await resized;+ expect(+ (session as any).inResizeQuiet(frameChangedAt),+ "pre-reply redraw must remain inside the quiet window"+ ).toBe(true);+ }, 5000);++ test("M2b: a timed-out resize retains its quiet window", async () => {+ const { session, attach } = fixture();+ const client = await attach();+ // Observe either outcome without letting the expected rejection escape the test.+ const settled = session.resize(100, 40).then(+ () => undefined,+ () => undefined+ );+ resizeRequest(client).reply({ ok: false, code: "client_timeout", error: "fake reply timeout" });+ await settled;+ expect(+ (session as any).inResizeQuiet(Date.now()),+ "a timeout may follow an applied resize and must retain the quiet window"+ ).toBe(true);+ }, 5000);+});diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.tsindex 01df900a..3449e97f 100644--- a/packages/cli/src/pane/pane-session.ts+++ b/packages/cli/src/pane/pane-session.ts@@ -413,8 +413,14 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {private supportsResize = false;private resizeWaiters: ResizeWaiter[] = [];private resizeDraining = false;- /** when the last resize request was sent (or confirmed changed); 0 = never */- private lastResizeAt = 0;+ /** the size of the worker's last send on this connection; null = none since the attach */+ private lastSentSize: PaneSize | null = null;+ /**+ * The resize quiet window [from, until): opened at a send, only ever extended (a lost+ * reply may follow an applied resize, so nothing retracts it); 0 = never opened.+ */+ private resizeQuietFrom = 0;+ private resizeQuietUntil = 0;/** the last screen change that is activity, i.e. not a resize redraw (M4) */private activityChangedAt = 0;@@ -604,6 +610,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {}}// a size set while disconnected, or one whose reply was lost, is applied now+ this.lastSentSize = null;if (this.supportsResize && !samePaneSize(this.appliedSize, this.desiredSize)) this.kickResize();await client.request({ type: "watch", pane: 0, mode: "frames", fps: WATCH_FPS });// An `exit` pushed before this connection subscribed (a child that dies in its first@@ -1771,10 +1778,30 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {return { cols: this.screen.cols, rows: this.screen.rows, changed: false, seq: this.screen.seq };}- /** A screen change at `at` falls within RESIZE_QUIET_MS after the last resize. */+ /** A screen change at `at` falls within the resize quiet window. */private inResizeQuiet(at: number): boolean {+ return this.resizeQuietFrom > 0 && at >= this.resizeQuietFrom && at < this.resizeQuietUntil;+ }++ /** Open the quiet window (or keep the open one's start) and extend its end, never retract it. */+ private extendResizeQuiet(): void {+ const now = Date.now();+ if (now >= this.resizeQuietUntil) this.resizeQuietFrom = now;+ this.resizeQuietUntil = Math.max(this.resizeQuietUntil, now + RESIZE_QUIET_MS);+ }++ /**+ * A size no waiter carries is still owed: a `pending` one stored while the worker sat in+ * its screen wait, whose redial's `attach` kick found the worker running. Only a size the+ * worker has not sent on this connection is owed, so a refused one is never resent.+ */+ private resizeOwed(): boolean {return (- this.lastResizeAt > 0 && at >= this.lastResizeAt && at - this.lastResizeAt < RESIZE_QUIET_MS+ !!this.client &&+ this.supportsResize &&+ !isTerminalPhase(this.phase) &&+ !samePaneSize(this.appliedSize, this.desiredSize) &&+ !samePaneSize(this.lastSentSize, this.desiredSize));}@@ -1784,8 +1811,8 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {this.resizeDraining = true;void this.drainResize().finally(() => {this.resizeDraining = false;- // a waiter that arrived after the loop's last check- if (this.resizeWaiters.length > 0) this.kickResize();+ // a waiter, or an owed size, that arrived after the loop's last check+ if (this.resizeWaiters.length > 0 || this.resizeOwed()) this.kickResize();});}@@ -1793,12 +1820,13 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {* The single resize worker of this pane (H3, M3): one request at a time, always the* LATEST desired size, so the sizes of a drag coalesce. Each send answers every waiter* queued before it; a waiter that arrives during it gets the next send. With no waiter- * it runs once: `attach` re-applying the size after a redial. The phase is re-checked- * after every await: a terminal pane answers its last size, `changed:false`.+ * it runs once (`attach` re-applying the size after a redial), and again while a size is+ * owed. The phase is re-checked after every await: a terminal pane answers its last+ * size, `changed:false`.*/private async drainResize(): Promise<void> {let first = true;- while (first || this.resizeWaiters.length > 0) {+ while (first || this.resizeWaiters.length > 0 || this.resizeOwed()) {first = false;const batch = this.resizeWaiters.splice(0);const answer = (r: PaneResizeOutcome) => {@@ -1821,9 +1849,9 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {fail(new ContractErrorException("resize_unsupported", "this magmux has no resize op"));continue;}- // stamped before the send: the child's SIGWINCH redraw can arrive before the reply- const before = this.lastResizeAt;- this.lastResizeAt = Date.now();+ // opened before the send: the child's SIGWINCH redraw can arrive before the reply+ this.lastSentSize = want;+ this.extendResizeQuiet();const r = await c.request<{ cols?: number; rows?: number; changed?: boolean }>({ type: "resize", pane: 0, cols: want.cols, rows: want.rows },RESIZE_REPLY_MS@@ -1833,14 +1861,17 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {continue;}if (!r.ok) {- // magmux may have applied a request whose reply was lost: the size is unknown- if (r.code === "client_lost" || r.code === "client_timeout") this.appliedSize = null;+ // magmux may have applied a request whose reply was lost: the size is unknown, and+ // its redraw may still arrive+ if (r.code === "client_lost" || r.code === "client_timeout") {+ this.appliedSize = null;+ this.extendResizeQuiet();+ }// the connection is gone: the redial's attach re-applies desiredSizeif (r.code === "client_lost" || r.code === "client_closed") {answer(this.pendingOutcome(this.desiredSize));continue;}- this.lastResizeAt = before;fail(new ContractErrorException("delivery_unavailable",@@ -1855,12 +1886,10 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {};this.appliedSize = set;if (r.result.changed !== true) {- // no reflow, no keyframe: nothing to keep quiet- this.lastResizeAt = before;answer({ ...set, changed: false, seq: this.screen.seq });continue;}- this.lastResizeAt = Date.now();+ this.extendResizeQuiet();// H4: the answer's seq is the first screen at the new size (magmux's forced keyframe)await this.waitFor(() =>