@devries-cameron20 / t3code-1 / commits / 0fee26d5bf
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): launch terminal commands after the measured resize (#36584)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 14, 2026 at 10:49 UTC 0fee26d5bf69084e17ee8869c48e428f84a1e378
2 files changed +161 -29
packages/client-runtime/src/state/terminal.test.ts
+127 -14
@@ -1,4 +1,12 @@
1 -import { EnvironmentId, ThreadId } from "@t3tools/contracts";
1 +import {
2 + EnvironmentId,
3 + ThreadId,
4 + type TerminalOpenInput,
5 + type TerminalResizeInput,
6 + type TerminalWriteInput,
7 + type TerminalCloseInput,
8 +} from "@t3tools/contracts";
9 +import * as Cause from "effect/Cause";
10 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11 import { expect, it } from "vite-plus/test";
12
@@ -9,6 +17,7 @@ import {
17 type TerminalLifecycleEvent,
18 type TerminalSessionMode,
19 } from "./terminal.ts";
20 +import { runAtomCommand } from "./runtime.ts";
21 import { EMPTY_TERMINAL_BUFFER_STATE, type TerminalBufferState } from "./terminalSession.ts";
22
23 function run(events: ReadonlyArray<TerminalLifecycleEvent>) {
@@ -59,7 +68,19 @@ it("leaves the history a viewer was reading when operate is granted", () => {
68 const environmentId = EnvironmentId.make("environment");
69 const threadId = ThreadId.make("thread");
70
62 -function setup(options: { readonly initialInput?: string } = {}) {
71 +type CommandInput =
72 + | TerminalOpenInput
73 + | TerminalResizeInput
74 + | TerminalWriteInput
75 + | TerminalCloseInput;
76 +
77 +function setup(
78 + options: {
79 + readonly initialInput?: string;
80 + readonly beforeCommand?: (name: string, input: CommandInput) => Promise<void>;
81 + readonly resizeFailure?: () => boolean;
82 + } = {},
83 +) {
84 // Tests flush the registry's scheduled work to control when driver finalizers run.
85 const scheduled: Array<() => void> = [];
86 const registry = AtomRegistry.make({
@@ -78,14 +99,30 @@ function setup(options: { readonly initialInput?: string } = {}) {
99 AsyncResult.initial(true),
100 );
101 const access = { canOperate: true };
81 - const calls: Array<{ readonly command: string; readonly input: unknown }> = [];
102 + const calls: Array<{ readonly command: string; readonly input: CommandInput }> = [];
103 + const pending: Promise<unknown>[] = [];
104 const command = (name: string) => ({
105 label: name,
84 - run: async (_registry: AtomRegistry.AtomRegistry, value: { readonly input: unknown }) => {
85 - calls.push({ command: name, input: value.input });
86 - return AsyncResult.success(undefined);
106 + run: (_registry: AtomRegistry.AtomRegistry, value: { readonly input: CommandInput }) => {
107 + const result = (async () => {
108 + calls.push({ command: name, input: value.input });
109 + if (options.beforeCommand) await options.beforeCommand(name, value.input);
110 + return name === "resize" && options.resizeFailure?.()
111 + ? AsyncResult.failure(Cause.fail("resize rejected"))
112 + : AsyncResult.success(undefined);
113 + })();
114 + pending.push(result);
115 + return result;
116 },
117 });
118 + const write = command("write");
119 + // Await command completion, then a normal input receipt through the same command runner.
120 + const completeCommands = async (count = pending.length) => {
121 + await Promise.all(pending.slice(0, count));
122 + await runAtomCommand(registry, write, {
123 + input: { threadId, terminalId: "term-1", data: "typed" },
124 + });
125 + };
126 const exits: Array<true> = [];
127 const live: Array<boolean> = [];
128 const session = createTerminalSession(
@@ -94,7 +131,7 @@ function setup(options: { readonly initialInput?: string } = {}) {
131 observe: () => observation,
132 open: command("open"),
133 resize: command("resize"),
97 - write: command("write"),
134 + write,
135 close: command("close"),
136 },
137 {
@@ -126,7 +163,21 @@ function setup(options: { readonly initialInput?: string } = {}) {
163 registry.set(observation, snapshot(state));
164 const mount = (mode: TerminalSessionMode) => registry.mount(session.driver(mode));
165 const of = (name: string) => calls.filter((call) => call.command === name).map((c) => c.input);
129 - return { session, attached, access, flush, detach, emit, observe, mount, calls, of, exits, live };
166 + return {
167 + session,
168 + attached,
169 + access,
170 + flush,
171 + detach,
172 + emit,
173 + observe,
174 + mount,
175 + calls,
176 + of,
177 + exits,
178 + live,
179 + completeCommands,
180 + };
181 }
182
183 it("replays the measured grid on every new attachment generation", () => {
@@ -154,17 +205,79 @@ it("replays the measured grid on every new attachment generation", () => {
205 ]);
206 });
207
157 -it("writes the launch's initial input once the first snapshot lands", () => {
158 - const { attached, emit, mount, calls, of } = setup({ initialInput: "pnpm dev\r" });
208 +it("writes the launch's initial input once, after the measured resize lands", async () => {
209 + const resize = Promise.withResolvers<void>();
210 + const latestResize = Promise.withResolvers<void>();
211 + const written = Promise.withResolvers<void>();
212 + let shellCols = 80;
213 + let resizes = 0;
214 + const commandWidths: number[] = [];
215 + const { session, attached, emit, mount, calls, of, completeCommands } = setup({
216 + initialInput: "stty size\r",
217 + beforeCommand: async (name, input) => {
218 + if (name === "resize") {
219 + await (++resizes === 1 ? resize : latestResize).promise;
220 + if ("cols" in input && input.cols !== undefined) shellCols = input.cols;
221 + }
222 + if (name === "write" && "data" in input && input.data === "stty size\r") {
223 + commandWidths.push(shellCols);
224 + written.resolve();
225 + }
226 + },
227 + });
228 mount(attached);
160 - expect(of("write")).toEqual([]);
229 emit({ status: "running", version: 1 });
230 emit({ status: "running", version: 2 });
163 - expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "pnpm dev\r" }]);
164 - // The shell gets the measured grid before the launched command runs.
165 - expect(calls.map((call) => call.command)).toEqual(["resize", "write"]);
231 + session.reportGridSize({ cols: 100, rows: 30 });
232 + resize.resolve();
233 + await completeCommands(1);
234 + expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
235 + latestResize.resolve();
236 + await written.promise;
237 + expect(commandWidths).toEqual([100]);
238 + expect(of("write")).toEqual([
239 + { threadId, terminalId: "term-1", data: "typed" },
240 + { threadId, terminalId: "term-1", data: "stty size\r" },
241 + ]);
242 + expect(calls.map((call) => call.command)).toEqual(["resize", "resize", "write", "write"]);
243 });
244
245 +it.each(["failed resize", "starting snapshot", "unmeasured grid"] as const)(
246 + "keeps launch input pending after a %s until a running shell is successfully resized",
247 + async (scenario) => {
248 + let failResize = scenario === "failed resize";
249 + const written = Promise.withResolvers<void>();
250 + const { session, attached, emit, mount, of, completeCommands } = setup({
251 + initialInput: "pnpm dev\r",
252 + resizeFailure: () => failResize,
253 + beforeCommand: async (name, input) => {
254 + if (name === "write" && "data" in input && input.data === "pnpm dev\r") written.resolve();
255 + },
256 + });
257 + // The seeded grid is 120x40; only "unmeasured grid" never hears from the surface.
258 + if (scenario !== "unmeasured grid") session.reportGridSize({ cols: 120, rows: 40 });
259 + mount(attached);
260 + emit({ status: scenario === "starting snapshot" ? "starting" : "running", version: 1 });
261 + await completeCommands();
262 + expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
263 + expect(of("resize")).toHaveLength(scenario === "starting snapshot" ? 0 : 1);
264 +
265 + failResize = false;
266 + session.reportGridSize(
267 + scenario === "unmeasured grid" ? { cols: 120, rows: 40 } : { cols: 100, rows: 30 },
268 + );
269 + emit({ status: "running", version: 2 });
270 + await written.promise;
271 + emit({ status: "running", version: 3 });
272 + await completeCommands();
273 + expect(of("write")).toEqual([
274 + { threadId, terminalId: "term-1", data: "typed" },
275 + { threadId, terminalId: "term-1", data: "pnpm dev\r" },
276 + { threadId, terminalId: "term-1", data: "typed" },
277 + ]);
278 + },
279 +);
280 +
281 it("closes and reports a shell that exits while attached", () => {
282 const { attached, emit, mount, of, exits, live } = setup();
283 mount(attached);
packages/client-runtime/src/state/terminal.ts
+34 -15
@@ -226,7 +226,7 @@ export interface TerminalSessionOptions {
226 readonly terminalId: string;
227 };
228 readonly gridSize: TerminalGridSize;
229 - /** Written once, as soon as the first attachment snapshot lands. */
229 + /** Written once, after the first attachment snapshot lands and the shell has the measured grid. */
230 readonly initialInput?: string | undefined;
231 /** Read right before every command, so revoking operate stops them at once. */
232 readonly canOperate: () => boolean;
@@ -252,7 +252,7 @@ export interface TerminalSession {
252 * Owns one shown terminal's lifecycle: it reopens an ended shell on an explicit
253 * visit, closes and reports a shell that exits while attached, replays the
254 * measured grid whenever the server starts a new output generation, and writes
255 - * the launch's initial input once.
255 + * the launch's initial input once that grid has reached the shell.
256 */
257 export function createTerminalSession(
258 atoms: TerminalSessionAtoms,
@@ -261,19 +261,43 @@ export function createTerminalSession(
261 const { environmentId, threadId, terminalId } = options.target;
262 let lifecycle = INITIAL_TERMINAL_LIFECYCLE;
263 let gridSize = options.gridSize;
264 + // The seeded grid is a cache or default guess; launch input waits for the surface's own measurement.
265 + let gridMeasured = false;
266 let generation: number | null = null;
267 let liveLifecycleVersion: number | null = null;
268 let initialInputPending = Boolean(options.initialInput);
269 let lastStatus: TerminalBufferState["status"] | null = null;
270 let loggedFirstOutput = false;
269 - let resizeRegistry: AtomRegistry.AtomRegistry | null = null;
271 + let commandRegistry: AtomRegistry.AtomRegistry | null = null;
272 + // Only a successful resize of the current measured grid may release initial input.
273 + let shellResized: ReturnType<typeof runAtomCommand> | null = null;
274
275 const sendResize = () => {
272 - if (generation === null || resizeRegistry === null || !options.canOperate()) return;
273 - void runAtomCommand(resizeRegistry, atoms.resize, {
276 + const registry = commandRegistry;
277 + if (generation === null || registry === null || !options.canOperate()) return;
278 + const resized = runAtomCommand(registry, atoms.resize, {
279 environmentId,
280 input: { threadId, terminalId, cols: gridSize.cols, rows: gridSize.rows },
281 });
282 + shellResized = resized;
283 + void resized.then((result) => {
284 + const data = options.initialInput;
285 + if (
286 + result._tag !== "Success" ||
287 + resized !== shellResized ||
288 + !gridMeasured ||
289 + generation === null ||
290 + !initialInputPending ||
291 + !data ||
292 + !options.canOperate()
293 + )
294 + return;
295 + initialInputPending = false;
296 + void runAtomCommand(registry, atoms.write, {
297 + environmentId,
298 + input: { threadId, terminalId, data },
299 + });
300 + });
301 };
302
303 const setLive = (next: number | null) => {
@@ -326,7 +350,7 @@ export function createTerminalSession(
350 input: TerminalAttachInput,
351 result: AsyncResult.AsyncResult<TerminalBufferState, unknown>,
352 ) => {
329 - resizeRegistry = registry;
353 + commandRegistry = registry;
354 const buffer = AsyncResult.getOrElse(result, () => EMPTY_TERMINAL_BUFFER_STATE);
355 const status = result._tag === "Failure" ? "error" : buffer.status;
356 if (status !== lastStatus) {
@@ -357,17 +381,10 @@ export function createTerminalSession(
381 buffer.version > 0 && status === "running" ? buffer.output.generation : null;
382 if (nextGeneration !== generation) {
383 generation = nextGeneration;
384 + shellResized = null;
385 sendResize();
386 }
387
363 - if (initialInputPending && buffer.version > 0 && options.initialInput && options.canOperate()) {
364 - initialInputPending = false;
365 - void runAtomCommand(registry, atoms.write, {
366 - environmentId,
367 - input: { threadId, terminalId, data: options.initialInput },
368 - });
369 - }
370 -
388 apply({ type: "status", status, version: buffer.version }, registry, input);
389 };
390
@@ -391,6 +408,7 @@ export function createTerminalSession(
408 const registry = get.registry;
409 get.addFinalizer(() => {
410 generation = null;
411 + shellResized = null;
412 lastStatus = null;
413 setLive(null);
414 lifecycle = transitionTerminalLifecycle(lifecycle, {
@@ -414,7 +432,8 @@ export function createTerminalSession(
432 return attached;
433 },
434 reportGridSize: (size) => {
417 - if (size.cols === gridSize.cols && size.rows === gridSize.rows) return;
435 + if (gridMeasured && size.cols === gridSize.cols && size.rows === gridSize.rows) return;
436 + gridMeasured = true;
437 gridSize = size;
438 sendResize();
439 },