The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 12:15 UTC
fix(web, mobile): a failed terminal resize is sent again (#32047)
Julius Marminge committed
Nov 14, 2026 at 21:07 UTC
e0ca4fcecb071fb80d3a82a0bb2cc6ce4b6da4ee
4 files changed
+166
-17
apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
+68
-10
@@ -6,6 +6,7 @@ import {
6
type FilesystemEntryMetadata,
7
type ResolvedKeybindingsConfig,
8
} from "@t3tools/contracts";
9
+import { Cause } from "effect";
10
import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";
11
import { Atom, AsyncResult } from "effect/reactivity";
12
import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
@@ -28,17 +29,29 @@ const fixture = vi.hoisted(() => ({
29
_thread: ScopedThreadRef,
30
_status: "closed" | "starting" | "running",
31
_version: number,
32
+ _generation?: number,
33
) => {},
34
surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
35
+ reportedSize: null as { cols: number; rows: number } | null,
36
+ resizeCommand: {},
37
+ runResize: (_input: unknown): Promise<AsyncResult.AsyncResult<unknown, unknown>> =>
38
+ Promise.resolve(AsyncResult.success(undefined)),
39
metadata: new Map<
40
string,
41
Atom.Writable<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>
42
>(),
43
}));
44
39
-// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
45
+// Every other surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
46
const fakeSurface: object = new Proxy(
41
- { input: document.createElement("textarea") },
47
+ {
48
+ input: document.createElement("textarea"),
49
+ // The real surface re-reports its measured grid.
50
+ resendSize: () => {
51
+ const size = fixture.reportedSize;
52
+ if (size) fixture.surfaceOptions.at(-1)!.onResize(size.cols, size.rows);
53
+ },
54
+ },
55
{
56
get: (target, key) =>
57
key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined,
@@ -76,11 +89,14 @@ vi.mock("../state/terminalSessions", async () => {
89
fixture.resetSessions = () => {
90
sessions = new Map();
91
};
79
- fixture.setSession = (thread, status, version) => {
92
+ fixture.setSession = (thread, status, version, generation) => {
93
appAtomRegistry.set(session(thread.environmentId, thread.threadId), {
94
...EMPTY_TERMINAL_SESSION_STATE,
95
status,
96
version,
97
+ ...(generation === undefined
98
+ ? {}
99
+ : { output: { ...EMPTY_TERMINAL_SESSION_STATE.output, generation } }),
100
});
101
};
102
return {
@@ -93,12 +109,14 @@ vi.mock("../state/session", () => ({
109
readEnvironmentScope: () => true,
110
}));
111
vi.mock("../state/use-atom-command", () => ({
96
- useAtomCommand: () => async (args: { input: { threadId: string; data?: string } }) => {
97
- if (args.input.data !== undefined) {
98
- fixture.writes.push({ threadId: args.input.threadId, data: args.input.data });
99
- }
100
- return { _tag: "Success" };
101
- },
112
+ useAtomCommand:
113
+ (command: object) => async (args: { input: { threadId: string; data?: string } }) => {
114
+ if (command === fixture.resizeCommand) return fixture.runResize(args);
115
+ if (args.input.data !== undefined) {
116
+ fixture.writes.push({ threadId: args.input.threadId, data: args.input.data });
117
+ }
118
+ return { _tag: "Success" };
119
+ },
120
}));
121
// The commands are replaced above; importing their runtime would connect a client.
122
vi.mock("../state/server", async () => {
@@ -106,7 +124,9 @@ vi.mock("../state/server", async () => {
124
const config = Atom.make(null);
125
return { serverEnvironment: { configValueAtom: () => config } };
126
});
109
-vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } }));
127
+vi.mock("../state/terminal", () => ({
128
+ terminalEnvironment: { write: {}, resize: fixture.resizeCommand },
129
+}));
130
vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
131
vi.mock("../state/projects", async () => {
132
const { Atom, AsyncResult } = await import("effect/reactivity");
@@ -190,6 +210,8 @@ function setup(originalStatus: "starting" | "exited" = "exited") {
210
fixture.pressKey = null;
211
fixture.writes = [];
212
fixture.surfaceOptions = [];
213
+ fixture.reportedSize = null;
214
+ fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined));
215
fixture.metadata.clear();
216
useRightPanelStore.setState(useRightPanelStore.getInitialState());
217
useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState());
@@ -354,3 +376,39 @@ it("only activates terminal paths confirmed to exist on their environment", asyn
376
await hover("~/notes.ts:5:2");
377
expect(canActivate("~/notes.ts:5:2")).toBe(true);
378
});
379
+
380
+it("resends a failed resize once in each writable session", async () => {
381
+ const { other: threadRef } = setup();
382
+ const resizes: unknown[] = [];
383
+ const failure = AsyncResult.failure(Cause.die(new Error("resize rejected")));
384
+ let failFirstResize = () => {};
385
+ fixture.runResize = (input) => {
386
+ resizes.push(input);
387
+ if (resizes.length > 1) return Promise.resolve(failure);
388
+ return new Promise((resolve) => {
389
+ failFirstResize = () => resolve(failure);
390
+ });
391
+ };
392
+ await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
393
+ await act(async () => {
394
+ fixture.pendingSurfaces.shift()?.();
395
+ });
396
+ await act(async () => {
397
+ fixture.reportedSize = { cols: 57, rows: 41 };
398
+ fixture.surfaceOptions.at(-1)!.onResize(57, 41);
399
+ });
400
+ // The first request fails while the attachment reconnects, so its retry is not sent.
401
+ await act(async () => {
402
+ fixture.setSession(threadRef, "running", 0, 1);
403
+ failFirstResize();
404
+ });
405
+ expect(resizes).toHaveLength(1);
406
+ await act(async () => {
407
+ fixture.setSession(threadRef, "running", 1, 2);
408
+ });
409
+ const resize = {
410
+ environmentId: threadRef.environmentId,
411
+ input: { threadId: threadRef.threadId, terminalId: "term-1", cols: 57, rows: 41 },
412
+ };
413
+ expect(resizes).toEqual([resize, resize, resize]);
414
+});
apps/web/src/components/ThreadTerminalDrawer.tsx
+13
-5
@@ -623,14 +623,22 @@ function TerminalSessionViewport({
623
input: { threadId, terminalId, data },
624
}),
625
);
626
- const resizeTerminal = useEffectEvent((cols: number, rows: number) => {
627
- if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) {
628
- return;
629
- }
630
- return runTerminalResize({
626
+ // The surface reports a resent grid like any other, so the next report is the retry.
627
+ const resizeRetryGenerationRef = useRef<number | null>(null);
628
+ const resizeTerminal = useEffectEvent(async (cols: number, rows: number) => {
629
+ const generation = writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess());
630
+ const retry = generation !== null && generation === resizeRetryGenerationRef.current;
631
+ resizeRetryGenerationRef.current = null;
632
+ if (generation === null) return;
633
+ const result = await runTerminalResize({
634
environmentId,
635
input: { threadId, terminalId, cols, rows },
636
});
637
+ // Resend the current grid, not this one: a newer resize may already be queued behind it.
638
+ if (!retry && result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
639
+ resizeRetryGenerationRef.current = generation;
640
+ terminalRef.current?.resendSize();
641
+ }
642
});
643
const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR);
644
const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed");
packages/client-runtime/src/state/terminal.test.ts
+72
-1
@@ -205,6 +205,74 @@ it("replays the measured grid on every new attachment generation", () => {
205
]);
206
});
207
208
+it("sends each failed resize again once, in every attachment generation", async () => {
209
+ // Resizes stay in flight until the test settles them, and every one fails.
210
+ const resizes: Array<() => void> = [];
211
+ const { session, attached, emit, detach, mount, of } = setup({
212
+ resizeFailure: () => true,
213
+ beforeCommand: (name) =>
214
+ name === "resize" ? new Promise<void>((resolve) => resizes.push(resolve)) : Promise.resolve(),
215
+ });
216
+ const failResize = async (index: number) => {
217
+ resizes[index]!();
218
+ // No promise marks the retry decision, so flush the command's continuation chain.
219
+ for (let tick = 0; tick < 20; tick++) await Promise.resolve();
220
+ };
221
+ mount(attached);
222
+ emit({ status: "running", version: 1 });
223
+ detach();
224
+ await failResize(0);
225
+ expect(of("resize")).toHaveLength(1);
226
+
227
+ emit({ status: "running", version: 1, generation: 2 });
228
+ await failResize(1);
229
+ expect(of("resize")).toHaveLength(3);
230
+ await failResize(2);
231
+ session.reportGridSize({ cols: 100, rows: 30 });
232
+ await failResize(3);
233
+ await failResize(4);
234
+ expect(of("resize")).toEqual([
235
+ { threadId, terminalId: "term-1", cols: 120, rows: 40 },
236
+ { threadId, terminalId: "term-1", cols: 120, rows: 40 },
237
+ { threadId, terminalId: "term-1", cols: 120, rows: 40 },
238
+ { threadId, terminalId: "term-1", cols: 100, rows: 30 },
239
+ { threadId, terminalId: "term-1", cols: 100, rows: 30 },
240
+ ]);
241
+});
242
+
243
+it("does not retry a failed resize that a newer one replaced", async () => {
244
+ const gates = [Promise.withResolvers<void>(), Promise.withResolvers<void>()];
245
+ const written = Promise.withResolvers<void>();
246
+ let resizes = 0;
247
+ let settling = -1;
248
+ const { session, attached, emit, mount, of, completeCommands } = setup({
249
+ initialInput: "pnpm dev\r",
250
+ // The newer resize succeeds; the superseded one, and any retry of it, fail.
251
+ resizeFailure: () => settling !== 1,
252
+ beforeCommand: async (name, input) => {
253
+ if (name === "resize") {
254
+ const call = resizes++;
255
+ await gates[call]?.promise;
256
+ settling = call;
257
+ }
258
+ if (name === "write" && "data" in input && input.data === "pnpm dev\r") written.resolve();
259
+ },
260
+ });
261
+ session.reportGridSize({ cols: 120, rows: 40 });
262
+ mount(attached);
263
+ emit({ status: "running", version: 1 });
264
+ session.reportGridSize({ cols: 100, rows: 30 });
265
+ gates[0]!.resolve();
266
+ await completeCommands(1);
267
+ gates[1]!.resolve();
268
+ await completeCommands();
269
+ await written.promise;
270
+ expect(of("resize")).toEqual([
271
+ { threadId, terminalId: "term-1", cols: 120, rows: 40 },
272
+ { threadId, terminalId: "term-1", cols: 100, rows: 30 },
273
+ ]);
274
+});
275
+
276
it("writes the launch's initial input once, after the measured resize lands", async () => {
277
const resize = Promise.withResolvers<void>();
278
const latestResize = Promise.withResolvers<void>();
@@ -260,7 +328,10 @@ it.each(["failed resize", "starting snapshot", "unmeasured grid"] as const)(
328
emit({ status: scenario === "starting snapshot" ? "starting" : "running", version: 1 });
329
await completeCommands();
330
expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
263
- expect(of("resize")).toHaveLength(scenario === "starting snapshot" ? 0 : 1);
331
+ // A failed resize is sent again once, and the retry fails too.
332
+ expect(of("resize")).toHaveLength(
333
+ { "failed resize": 2, "starting snapshot": 0, "unmeasured grid": 1 }[scenario],
334
+ );
335
336
failResize = false;
337
session.reportGridSize(
packages/client-runtime/src/state/terminal.ts
+13
-1
@@ -19,6 +19,7 @@ import {
19
createAtomCommandScheduler,
20
createEnvironmentRpcCommand,
21
createEnvironmentSubscriptionAtomFamily,
22
+ isAtomCommandInterrupted,
23
runAtomCommand,
24
} from "./runtime.ts";
25
import type { EnvironmentRegistry } from "../connection/registry.ts";
@@ -274,7 +275,7 @@ export function createTerminalSession(
275
// Only a successful resize of the current measured grid may release initial input.
276
let shellResized: ReturnType<typeof runAtomCommand> | null = null;
277
277
- const sendResize = () => {
278
+ const sendResize = (retry = false) => {
279
const registry = commandRegistry;
280
if (generation === null || registry === null || !options.canOperate()) return;
281
const resized = runAtomCommand(registry, atoms.resize, {
@@ -283,6 +284,17 @@ export function createTerminalSession(
284
});
285
shellResized = resized;
286
void resized.then((result) => {
287
+ // Only a new grid or generation sends again, so retry a failure once, unless a newer
288
+ // resize already replaced this one.
289
+ if (
290
+ !retry &&
291
+ resized === shellResized &&
292
+ result._tag === "Failure" &&
293
+ !isAtomCommandInterrupted(result)
294
+ ) {
295
+ sendResize(true);
296
+ return;
297
+ }
298
const data = options.initialInput;
299
if (
300
result._tag !== "Success" ||