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

main
ts 435 lines 15.5 KB
Raw
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 Effect from "effect/Effect";
10 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11 import { expect, it } from "vite-plus/test";
12
13 import {
14 createTerminalSession,
15 INITIAL_TERMINAL_LIFECYCLE,
16 transitionTerminalLifecycle,
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>) {
24 let state = INITIAL_TERMINAL_LIFECYCLE;
25 const commands: Array<string> = [];
26 for (const event of events) {
27 const step = transitionTerminalLifecycle(state, event);
28 state = step.state;
29 if (step.command !== null) commands.push(step.command);
30 }
31 return commands;
32 }
33
34 const status = (value: TerminalBufferState["status"], version = 1): TerminalLifecycleEvent => ({
35 type: "status",
36 status: value,
37 version,
38 });
39
40 it("does not respawn a terminal that exited after operate was revoked", () => {
41 expect(
42 run([status("running"), { type: "detached", canOperate: false }, status("exited")]),
43 ).toEqual([]);
44 });
45
46 it("reopens an ended terminal on an explicit visit, once until it runs again", () => {
47 expect(run([status("exited"), status("exited", 2)])).toEqual(["reopen"]);
48 expect(run([status("exited"), status("running", 3), status("exited", 4)])).toEqual([
49 "reopen",
50 "exit",
51 ]);
52 expect(run([status("exited"), { type: "reopen-failed" }, status("exited", 2)])).toEqual([
53 "reopen",
54 "reopen",
55 ]);
56 });
57
58 it("keeps a detached terminal from being mistaken for a live exit", () => {
59 expect(
60 run([status("running"), { type: "detached", canOperate: true }, status("exited")]),
61 ).toEqual(["reopen"]);
62 });
63
64 it("leaves the history a viewer was reading when operate is granted", () => {
65 expect(run([{ type: "observed" }, status("exited")])).toEqual([]);
66 });
67
68 const environmentId = EnvironmentId.make("environment");
69 const threadId = ThreadId.make("thread");
70
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({
87 scheduleTask: (task) => {
88 scheduled.push(task);
89 return () => {};
90 },
91 });
92 const flush = () => {
93 for (const task of scheduled.splice(0)) task();
94 };
95 const attachment = Atom.make<AsyncResult.AsyncResult<TerminalBufferState, unknown>>(
96 AsyncResult.initial(true),
97 );
98 const observation = Atom.make<AsyncResult.AsyncResult<TerminalBufferState, unknown>>(
99 AsyncResult.initial(true),
100 );
101 const access = { canOperate: true };
102 const calls: Array<{ readonly command: string; readonly input: CommandInput }> = [];
103 const pending: Promise<unknown>[] = [];
104 const command = (name: string) => ({
105 label: name,
106 run: (_registry: AtomRegistry.AtomRegistry, value: { readonly input: CommandInput }) => {
107 const settled = Promise.withResolvers<void>();
108 pending.push(settled.promise);
109 return Effect.promise(async () => {
110 calls.push({ command: name, input: value.input });
111 if (options.beforeCommand) await options.beforeCommand(name, value.input);
112 }).pipe(
113 Effect.flatMap(() =>
114 name === "resize" && options.resizeFailure?.()
115 ? Effect.fail("resize rejected")
116 : Effect.void,
117 ),
118 Effect.ensuring(Effect.sync(settled.resolve)),
119 );
120 },
121 });
122 const write = command("write");
123 // Await command completion, then a normal input receipt through the same command runner.
124 const completeCommands = async (count = pending.length) => {
125 await Promise.all(pending.slice(0, count));
126 await runAtomCommand(registry, write, {
127 input: { threadId, terminalId: "term-1", data: "typed" },
128 });
129 };
130 const exits: Array<true> = [];
131 const live: Array<boolean> = [];
132 const session = createTerminalSession(
133 {
134 attach: () => attachment,
135 observe: () => observation,
136 open: command("open"),
137 resize: command("resize"),
138 write,
139 close: command("close"),
140 },
141 {
142 target: { environmentId, threadId, terminalId: "term-1" },
143 gridSize: { cols: 120, rows: 40 },
144 initialInput: options.initialInput,
145 canOperate: () => access.canOperate,
146 onExit: () => exits.push(true),
147 onLiveChange: (value) => live.push(value),
148 },
149 );
150 const attached: TerminalSessionMode = {
151 kind: "attached",
152 input: { threadId, terminalId: "term-1", cwd: "/repo", cols: 80, rows: 24 },
153 };
154 const snapshot = (state: Partial<TerminalBufferState> & { readonly generation?: number }) => {
155 const { generation = 1, ...rest } = state;
156 return AsyncResult.success({
157 ...EMPTY_TERMINAL_BUFFER_STATE,
158 output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation },
159 ...rest,
160 });
161 };
162 const emit = (state: Partial<TerminalBufferState> & { readonly generation?: number }) =>
163 registry.set(attachment, snapshot(state));
164 // A new attach subscription starts from an empty seed.
165 const detach = () => registry.set(attachment, AsyncResult.initial(true));
166 const observe = (state: Partial<TerminalBufferState>) =>
167 registry.set(observation, snapshot(state));
168 const mount = (mode: TerminalSessionMode) => registry.mount(session.driver(mode));
169 const of = (name: string) => calls.filter((call) => call.command === name).map((c) => c.input);
170 return {
171 session,
172 attached,
173 access,
174 flush,
175 detach,
176 emit,
177 observe,
178 mount,
179 calls,
180 of,
181 exits,
182 live,
183 completeCommands,
184 };
185 }
186
187 it("replays the measured grid on every new attachment generation", () => {
188 const { session, attached, emit, mount, of } = setup();
189 mount(attached);
190 emit({ status: "running", version: 1 });
191 expect(of("resize")).toEqual([{ threadId, terminalId: "term-1", cols: 120, rows: 40 }]);
192
193 session.reportGridSize({ cols: 100, rows: 30 });
194 expect(of("resize")).toHaveLength(2);
195 session.reportGridSize({ cols: 100, rows: 30 });
196 expect(of("resize")).toHaveLength(2);
197
198 // A reconnect seeds an empty state first, then the new generation's snapshot.
199 emit({ status: "running", version: 0, generation: 2 });
200 expect(of("resize")).toHaveLength(2);
201 emit({ status: "running", version: 1, generation: 2 });
202 expect(of("resize")).toHaveLength(3);
203 emit({ status: "running", version: 2, generation: 3 });
204 expect(of("resize")).toEqual([
205 { threadId, terminalId: "term-1", cols: 120, rows: 40 },
206 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
207 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
208 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
209 ]);
210 });
211
212 it("sends each failed resize again once, in every attachment generation", async () => {
213 // Resizes stay in flight until the test settles them, and every one fails.
214 const resizes: Array<() => void> = [];
215 const { session, attached, emit, detach, mount, of } = setup({
216 resizeFailure: () => true,
217 beforeCommand: (name) =>
218 name === "resize" ? new Promise<void>((resolve) => resizes.push(resolve)) : Promise.resolve(),
219 });
220 const failResize = async (index: number) => {
221 resizes[index]!();
222 // No promise marks the retry decision, so flush the command's continuation chain.
223 for (let tick = 0; tick < 20; tick++) await Promise.resolve();
224 };
225 mount(attached);
226 emit({ status: "running", version: 1 });
227 detach();
228 await failResize(0);
229 expect(of("resize")).toHaveLength(1);
230
231 emit({ status: "running", version: 1, generation: 2 });
232 await failResize(1);
233 expect(of("resize")).toHaveLength(3);
234 await failResize(2);
235 session.reportGridSize({ cols: 100, rows: 30 });
236 await failResize(3);
237 await failResize(4);
238 expect(of("resize")).toEqual([
239 { threadId, terminalId: "term-1", cols: 120, rows: 40 },
240 { threadId, terminalId: "term-1", cols: 120, rows: 40 },
241 { threadId, terminalId: "term-1", cols: 120, rows: 40 },
242 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
243 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
244 ]);
245 });
246
247 it("does not retry a failed resize that a newer one replaced", async () => {
248 const gates = [Promise.withResolvers<void>(), Promise.withResolvers<void>()];
249 const written = Promise.withResolvers<void>();
250 let resizes = 0;
251 let settling = -1;
252 const { session, attached, emit, mount, of, completeCommands } = setup({
253 initialInput: "pnpm dev\r",
254 // The newer resize succeeds; the superseded one, and any retry of it, fail.
255 resizeFailure: () => settling !== 1,
256 beforeCommand: async (name, input) => {
257 if (name === "resize") {
258 const call = resizes++;
259 await gates[call]?.promise;
260 settling = call;
261 }
262 if (name === "write" && "data" in input && input.data === "pnpm dev\r") written.resolve();
263 },
264 });
265 session.reportGridSize({ cols: 120, rows: 40 });
266 mount(attached);
267 emit({ status: "running", version: 1 });
268 session.reportGridSize({ cols: 100, rows: 30 });
269 gates[0]!.resolve();
270 await completeCommands(1);
271 gates[1]!.resolve();
272 await completeCommands();
273 await written.promise;
274 expect(of("resize")).toEqual([
275 { threadId, terminalId: "term-1", cols: 120, rows: 40 },
276 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
277 ]);
278 });
279
280 it("writes the launch's initial input once, after the measured resize lands", async () => {
281 const resize = Promise.withResolvers<void>();
282 const latestResize = Promise.withResolvers<void>();
283 const written = Promise.withResolvers<void>();
284 let shellCols = 80;
285 let resizes = 0;
286 const commandWidths: number[] = [];
287 const { session, attached, emit, mount, calls, of, completeCommands } = setup({
288 initialInput: "stty size\r",
289 beforeCommand: async (name, input) => {
290 if (name === "resize") {
291 await (++resizes === 1 ? resize : latestResize).promise;
292 if ("cols" in input && input.cols !== undefined) shellCols = input.cols;
293 }
294 if (name === "write" && "data" in input && input.data === "stty size\r") {
295 commandWidths.push(shellCols);
296 written.resolve();
297 }
298 },
299 });
300 mount(attached);
301 emit({ status: "running", version: 1 });
302 emit({ status: "running", version: 2 });
303 session.reportGridSize({ cols: 100, rows: 30 });
304 resize.resolve();
305 await completeCommands(1);
306 expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
307 latestResize.resolve();
308 await written.promise;
309 expect(commandWidths).toEqual([100]);
310 expect(of("write")).toEqual([
311 { threadId, terminalId: "term-1", data: "typed" },
312 { threadId, terminalId: "term-1", data: "stty size\r" },
313 ]);
314 expect(calls.map((call) => call.command)).toEqual(["resize", "resize", "write", "write"]);
315 });
316
317 it.each(["failed resize", "starting snapshot", "unmeasured grid"] as const)(
318 "keeps launch input pending after a %s until a running shell is successfully resized",
319 async (scenario) => {
320 let failResize = scenario === "failed resize";
321 const written = Promise.withResolvers<void>();
322 const { session, attached, emit, mount, of, completeCommands } = setup({
323 initialInput: "pnpm dev\r",
324 resizeFailure: () => failResize,
325 beforeCommand: async (name, input) => {
326 if (name === "write" && "data" in input && input.data === "pnpm dev\r") written.resolve();
327 },
328 });
329 // The seeded grid is 120x40; only "unmeasured grid" never hears from the surface.
330 if (scenario !== "unmeasured grid") session.reportGridSize({ cols: 120, rows: 40 });
331 mount(attached);
332 emit({ status: scenario === "starting snapshot" ? "starting" : "running", version: 1 });
333 await completeCommands();
334 expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
335 // A failed resize is sent again once, and the retry fails too.
336 expect(of("resize")).toHaveLength(
337 { "failed resize": 2, "starting snapshot": 0, "unmeasured grid": 1 }[scenario],
338 );
339
340 failResize = false;
341 session.reportGridSize(
342 scenario === "unmeasured grid" ? { cols: 120, rows: 40 } : { cols: 100, rows: 30 },
343 );
344 emit({ status: "running", version: 2 });
345 await written.promise;
346 emit({ status: "running", version: 3 });
347 await completeCommands();
348 expect(of("write")).toEqual([
349 { threadId, terminalId: "term-1", data: "typed" },
350 { threadId, terminalId: "term-1", data: "pnpm dev\r" },
351 { threadId, terminalId: "term-1", data: "typed" },
352 ]);
353 },
354 );
355
356 it("closes and reports a shell that exits while attached", () => {
357 const { attached, emit, mount, of, exits, live } = setup();
358 mount(attached);
359 emit({ status: "running", version: 1, lifecycleVersion: 0 });
360 emit({ status: "exited", version: 2 });
361 expect(of("close")).toEqual([{ threadId, terminalId: "term-1" }]);
362 expect(of("open")).toEqual([]);
363 expect(exits).toHaveLength(1);
364 expect(live).toEqual([true, false]);
365 });
366
367 it("does not reopen an ended shell after a viewer is granted operate", () => {
368 const { attached, flush, access, emit, observe, mount, of } = setup();
369 access.canOperate = false;
370 const unmountViewer = mount({ kind: "observing" });
371 observe({ status: "exited", version: 1 });
372 access.canOperate = true;
373 unmountViewer();
374 flush();
375 mount(attached);
376 emit({ status: "exited", version: 1 });
377 expect(of("open")).toEqual([]);
378 });
379
380 it("does not reopen on grant when the viewer had no snapshot yet", () => {
381 const { attached, flush, access, emit, mount, of } = setup();
382 access.canOperate = false;
383 const unmountViewer = mount({ kind: "observing" });
384 access.canOperate = true;
385 unmountViewer();
386 flush();
387 mount(attached);
388 emit({ status: "exited", version: 1 });
389 expect(of("open")).toEqual([]);
390 });
391
392 it("leaves a shell that exited after operate was revoked mid-run", () => {
393 const { attached, flush, access, detach, emit, mount, of, exits } = setup();
394 const unmountAttached = mount(attached);
395 emit({ status: "running", version: 1 });
396 access.canOperate = false;
397 unmountAttached();
398 flush();
399 detach();
400 access.canOperate = true;
401 mount(attached);
402 emit({ status: "exited", version: 2 });
403 expect(of("open")).toEqual([]);
404 expect(of("close")).toEqual([]);
405 expect(exits).toEqual([]);
406 });
407
408 it("reopens instead of closing a shell that ended while detached", () => {
409 const { attached, flush, detach, emit, mount, of, exits } = setup();
410 const unmountAttached = mount(attached);
411 emit({ status: "running", version: 1 });
412 unmountAttached();
413 flush();
414 detach();
415 mount(attached);
416 emit({ status: "exited", version: 2 });
417 expect(of("close")).toEqual([]);
418 expect(exits).toEqual([]);
419 expect(of("open")).toHaveLength(1);
420 });
421
422 it("keeps one attached driver, so a remount before release keeps its state", () => {
423 const { session, attached, flush, emit, mount, of, exits } = setup();
424 const driver = session.driver(attached);
425 expect(session.driver({ ...attached })).toBe(driver);
426 const unmountFirst = mount(attached);
427 emit({ status: "running", version: 1 });
428 // A brief disconnect unmounts and remounts the driver before its release runs.
429 unmountFirst();
430 mount(attached);
431 flush();
432 emit({ status: "exited", version: 2 });
433 expect(of("close")).toHaveLength(1);
434 expect(exits).toHaveLength(1);
435 });