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

terminal.test.ts

360 lines12.7 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("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);
229 emit({ status: "running", version: 1 });
230 emit({ status: "running", version: 2 });
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​
245it.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​
281it("closes and reports a shell that exits while attached", () => {
282 const { attached, emit, mount, of, exits, live } = setup();
283 mount(attached);
284 emit({ status: "running", version: 1, lifecycleVersion: 0 });
285 emit({ status: "exited", version: 2 });
286 expect(of("close")).toEqual([{ threadId, terminalId: "term-1" }]);
287 expect(of("open")).toEqual([]);
288 expect(exits).toHaveLength(1);
289 expect(live).toEqual([true, false]);
290});
291​
292it("does not reopen an ended shell after a viewer is granted operate", () => {
293 const { attached, flush, access, emit, observe, mount, of } = setup();
294 access.canOperate = false;
295 const unmountViewer = mount({ kind: "observing" });
296 observe({ status: "exited", version: 1 });
297 access.canOperate = true;
298 unmountViewer();
299 flush();
300 mount(attached);
301 emit({ status: "exited", version: 1 });
302 expect(of("open")).toEqual([]);
303});
304​
305it("does not reopen on grant when the viewer had no snapshot yet", () => {
306 const { attached, flush, access, emit, mount, of } = setup();
307 access.canOperate = false;
308 const unmountViewer = mount({ kind: "observing" });
309 access.canOperate = true;
310 unmountViewer();
311 flush();
312 mount(attached);
313 emit({ status: "exited", version: 1 });
314 expect(of("open")).toEqual([]);
315});
316​
317it("leaves a shell that exited after operate was revoked mid-run", () => {
318 const { attached, flush, access, detach, emit, mount, of, exits } = setup();
319 const unmountAttached = mount(attached);
320 emit({ status: "running", version: 1 });
321 access.canOperate = false;
322 unmountAttached();
323 flush();
324 detach();
325 access.canOperate = true;
326 mount(attached);
327 emit({ status: "exited", version: 2 });
328 expect(of("open")).toEqual([]);
329 expect(of("close")).toEqual([]);
330 expect(exits).toEqual([]);
331});
332​
333it("reopens instead of closing a shell that ended while detached", () => {
334 const { attached, flush, detach, emit, mount, of, exits } = setup();
335 const unmountAttached = mount(attached);
336 emit({ status: "running", version: 1 });
337 unmountAttached();
338 flush();
339 detach();
340 mount(attached);
341 emit({ status: "exited", version: 2 });
342 expect(of("close")).toEqual([]);
343 expect(exits).toEqual([]);
344 expect(of("open")).toHaveLength(1);
345});
346​
347it("keeps one attached driver, so a remount before release keeps its state", () => {
348 const { session, attached, flush, emit, mount, of, exits } = setup();
349 const driver = session.driver(attached);
350 expect(session.driver({ ...attached })).toBe(driver);
351 const unmountFirst = mount(attached);
352 emit({ status: "running", version: 1 });
353 // A brief disconnect unmounts and remounts the driver before its release runs.
354 unmountFirst();
355 mount(attached);
356 flush();
357 emit({ status: "exited", version: 2 });
358 expect(of("close")).toHaveLength(1);
359 expect(exits).toHaveLength(1);
360});