Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminal.test.ts

431 lines15.3 KB

1import {
2 EnvironmentId,
3 ThreadId,
4 type TerminalOpenInput,
5 type TerminalResizeInput,
6 type TerminalWriteInput,
7 type TerminalCloseInput,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11import { expect, it } from "vite-plus/test";
12​
13import {
14 createTerminalSession,
15 INITIAL_TERMINAL_LIFECYCLE,
16 transitionTerminalLifecycle,
17 type TerminalLifecycleEvent,
18 type TerminalSessionMode,
19} from "./terminal.ts";
20import { runAtomCommand } from "./runtime.ts";
21import { EMPTY_TERMINAL_BUFFER_STATE, type TerminalBufferState } from "./terminalSession.ts";
22​
23function 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;
33​
34const status = (value: TerminalBufferState["status"], version = 1): TerminalLifecycleEvent => ({
35 type: "status",
36 status: value,
37 version,
38});
39​
40it("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​
46it("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​
58it("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​
64it("leaves the history a viewer was reading when operate is granted", () => {
65 expect(run([{ type: "observed" }, status("exited")])).toEqual([]);
66});
67​
68const environmentId = EnvironmentId.make("environment");
69const threadId = ThreadId.make("thread");
70​
71type CommandInput =
72 | TerminalOpenInput
73 | TerminalResizeInput
74 | TerminalWriteInput
75 | TerminalCloseInput;
76​
77function 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 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(
129 {
130 attach: () => attachment,
131 observe: () => observation,
132 open: command("open"),
133 resize: command("resize"),
134 write,
135 close: command("close"),
136 },
137 {
138 target: { environmentId, threadId, terminalId: "term-1" },
139 gridSize: { cols: 120, rows: 40 },
140 initialInput: options.initialInput,
141 canOperate: () => access.canOperate,
142 onExit: () => exits.push(true),
143 onLiveChange: (value) => live.push(value),
144 },
145 );
146 const attached: TerminalSessionMode = {
147 kind: "attached",
148 input: { threadId, terminalId: "term-1", cwd: "/repo", cols: 80, rows: 24 },
149 };
150 const snapshot = (state: Partial<TerminalBufferState> & { readonly generation?: number }) => {
151 const { generation = 1, ...rest } = state;
152 return AsyncResult.success({
153 ...EMPTY_TERMINAL_BUFFER_STATE,
154 output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation },
155 ...rest,
156 });
157 };
158 const emit = (state: Partial<TerminalBufferState> & { readonly generation?: number }) =>
159 registry.set(attachment, snapshot(state));
160 // A new attach subscription starts from an empty seed.
161 const detach = () => registry.set(attachment, AsyncResult.initial(true));
162 const observe = (state: Partial<TerminalBufferState>) =>
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);
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 };
182​
183it("replays the measured grid on every new attachment generation", () => {
184 const { session, attached, emit, mount, of } = setup();
185 mount(attached);
186 emit({ status: "running", version: 1 });
187 expect(of("resize")).toEqual([{ threadId, terminalId: "term-1", cols: 120, rows: 40 }]);
188​
189 session.reportGridSize({ cols: 100, rows: 30 });
190 expect(of("resize")).toHaveLength(2);
191 session.reportGridSize({ cols: 100, rows: 30 });
192 expect(of("resize")).toHaveLength(2);
193​
194 // A reconnect seeds an empty state first, then the new generation's snapshot.
195 emit({ status: "running", version: 0, generation: 2 });
196 expect(of("resize")).toHaveLength(2);
197 emit({ status: "running", version: 1, generation: 2 });
198 expect(of("resize")).toHaveLength(3);
199 emit({ status: "running", version: 2, generation: 3 });
200 expect(of("resize")).toEqual([
201 { threadId, terminalId: "term-1", cols: 120, rows: 40 },
202 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
203 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
204 { threadId, terminalId: "term-1", cols: 100, rows: 30 },
205 ]);
206});
207​
208it("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​
243it("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​
276it("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>();
279 const written = Promise.withResolvers<void>();
280 let shellCols = 80;
281 let resizes = 0;
282 const commandWidths: number[] = [];
283 const { session, attached, emit, mount, calls, of, completeCommands } = setup({
284 initialInput: "stty size\r",
285 beforeCommand: async (name, input) => {
286 if (name === "resize") {
287 await (++resizes === 1 ? resize : latestResize).promise;
288 if ("cols" in input && input.cols !== undefined) shellCols = input.cols;
289 }
290 if (name === "write" && "data" in input && input.data === "stty size\r") {
291 commandWidths.push(shellCols);
292 written.resolve();
293 }
294 },
295 });
296 mount(attached);
297 emit({ status: "running", version: 1 });
298 emit({ status: "running", version: 2 });
299 session.reportGridSize({ cols: 100, rows: 30 });
300 resize.resolve();
301 await completeCommands(1);
302 expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
303 latestResize.resolve();
304 await written.promise;
305 expect(commandWidths).toEqual([100]);
306 expect(of("write")).toEqual([
307 { threadId, terminalId: "term-1", data: "typed" },
308 { threadId, terminalId: "term-1", data: "stty size\r" },
309 ]);
310 expect(calls.map((call) => call.command)).toEqual(["resize", "resize", "write", "write"]);
311});
312​
313it.each(["failed resize", "starting snapshot", "unmeasured grid"] as const)(
314 "keeps launch input pending after a %s until a running shell is successfully resized",
315 async (scenario) => {
316 let failResize = scenario === "failed resize";
317 const written = Promise.withResolvers<void>();
318 const { session, attached, emit, mount, of, completeCommands } = setup({
319 initialInput: "pnpm dev\r",
320 resizeFailure: () => failResize,
321 beforeCommand: async (name, input) => {
322 if (name === "write" && "data" in input && input.data === "pnpm dev\r") written.resolve();
323 },
324 });
325 // The seeded grid is 120x40; only "unmeasured grid" never hears from the surface.
326 if (scenario !== "unmeasured grid") session.reportGridSize({ cols: 120, rows: 40 });
327 mount(attached);
328 emit({ status: scenario === "starting snapshot" ? "starting" : "running", version: 1 });
329 await completeCommands();
330 expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "typed" }]);
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(
338 scenario === "unmeasured grid" ? { cols: 120, rows: 40 } : { cols: 100, rows: 30 },
339 );
340 emit({ status: "running", version: 2 });
341 await written.promise;
342 emit({ status: "running", version: 3 });
343 await completeCommands();
344 expect(of("write")).toEqual([
345 { threadId, terminalId: "term-1", data: "typed" },
346 { threadId, terminalId: "term-1", data: "pnpm dev\r" },
347 { threadId, terminalId: "term-1", data: "typed" },
348 ]);
349 },
350);
351​
352it("closes and reports a shell that exits while attached", () => {
353 const { attached, emit, mount, of, exits, live } = setup();
354 mount(attached);
355 emit({ status: "running", version: 1, lifecycleVersion: 0 });
356 emit({ status: "exited", version: 2 });
357 expect(of("close")).toEqual([{ threadId, terminalId: "term-1" }]);
358 expect(of("open")).toEqual([]);
359 expect(exits).toHaveLength(1);
360 expect(live).toEqual([true, false]);
361});
362​
363it("does not reopen an ended shell after a viewer is granted operate", () => {
364 const { attached, flush, access, emit, observe, mount, of } = setup();
365 access.canOperate = false;
366 const unmountViewer = mount({ kind: "observing" });
367 observe({ status: "exited", version: 1 });
368 access.canOperate = true;
369 unmountViewer();
370 flush();
371 mount(attached);
372 emit({ status: "exited", version: 1 });
373 expect(of("open")).toEqual([]);
374});
375​
376it("does not reopen on grant when the viewer had no snapshot yet", () => {
377 const { attached, flush, access, emit, mount, of } = setup();
378 access.canOperate = false;
379 const unmountViewer = mount({ kind: "observing" });
380 access.canOperate = true;
381 unmountViewer();
382 flush();
383 mount(attached);
384 emit({ status: "exited", version: 1 });
385 expect(of("open")).toEqual([]);
386});
387​
388it("leaves a shell that exited after operate was revoked mid-run", () => {
389 const { attached, flush, access, detach, emit, mount, of, exits } = setup();
390 const unmountAttached = mount(attached);
391 emit({ status: "running", version: 1 });
392 access.canOperate = false;
393 unmountAttached();
394 flush();
395 detach();
396 access.canOperate = true;
397 mount(attached);
398 emit({ status: "exited", version: 2 });
399 expect(of("open")).toEqual([]);
400 expect(of("close")).toEqual([]);
401 expect(exits).toEqual([]);
402});
403​
404it("reopens instead of closing a shell that ended while detached", () => {
405 const { attached, flush, detach, emit, mount, of, exits } = setup();
406 const unmountAttached = mount(attached);
407 emit({ status: "running", version: 1 });
408 unmountAttached();
409 flush();
410 detach();
411 mount(attached);
412 emit({ status: "exited", version: 2 });
413 expect(of("close")).toEqual([]);
414 expect(exits).toEqual([]);
415 expect(of("open")).toHaveLength(1);
416});
417​
418it("keeps one attached driver, so a remount before release keeps its state", () => {
419 const { session, attached, flush, emit, mount, of, exits } = setup();
420 const driver = session.driver(attached);
421 expect(session.driver({ ...attached })).toBe(driver);
422 const unmountFirst = mount(attached);
423 emit({ status: "running", version: 1 });
424 // A brief disconnect unmounts and remounts the driver before its release runs.
425 unmountFirst();
426 mount(attached);
427 flush();
428 emit({ status: "exited", version: 2 });
429 expect(of("close")).toHaveLength(1);
430 expect(exits).toHaveLength(1);
431});