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

terminalSession.test.ts

386 lines14.4 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import {
4 EnvironmentId,
5 retainedTerminalHistory,
6 TerminalSessionSnapshot,
7 ThreadId,
8} from "@t3tools/contracts";
9​
10import {
11 applyTerminalAttachStreamEvent,
12 applyTerminalMetadataStreamEvent,
13 combineTerminalSessionState,
14 EMPTY_TERMINAL_BUFFER_STATE,
15 INITIAL_TERMINAL_OUTPUT_CURSOR,
16 nextTerminalAttachSeedState,
17 readTerminalOutputUpdate,
18 terminalOutputText,
19} from "./terminalSession.ts";
20​
21const TARGET = {
22 environmentId: EnvironmentId.make("env-local"),
23 threadId: ThreadId.make("thread-1"),
24 terminalId: "term-1",
25} as const;
26​
27const BASE_SNAPSHOT: TerminalSessionSnapshot = {
28 threadId: TARGET.threadId,
29 terminalId: TARGET.terminalId,
30 cwd: "/repo",
31 worktreePath: null,
32 status: "running",
33 pid: 123,
34 history: "hello",
35 exitCode: null,
36 exitSignal: null,
37 label: "Terminal 1",
38 updatedAt: "2026-04-01T00:00:00.000Z",
39};
40​
41describe("terminal session reducers", () => {
42 it("prefers live attach status over stale metadata after the attach stream starts", () => {
43 const summary = applyTerminalMetadataStreamEvent([], {
44 type: "snapshot",
45 terminals: [
46 {
47 threadId: BASE_SNAPSHOT.threadId,
48 terminalId: BASE_SNAPSHOT.terminalId,
49 cwd: BASE_SNAPSHOT.cwd,
50 worktreePath: BASE_SNAPSHOT.worktreePath,
51 status: "running",
52 pid: BASE_SNAPSHOT.pid,
53 exitCode: BASE_SNAPSHOT.exitCode,
54 exitSignal: BASE_SNAPSHOT.exitSignal,
55 updatedAt: BASE_SNAPSHOT.updatedAt,
56 hasRunningSubprocess: false,
57 label: BASE_SNAPSHOT.label,
58 },
59 ],
60 })[0]!;
61 const attached = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
62 type: "error",
63 threadId: TARGET.threadId,
64 terminalId: TARGET.terminalId,
65 message: "Terminal disconnected.",
66 });
67​
68 expect(combineTerminalSessionState(summary, attached)).toMatchObject({
69 status: "error",
70 error: "Terminal disconnected.",
71 version: 1,
72 });
73 });
74​
75 it("follows the shared PTY grid from snapshots and activity without disturbing output", () => {
76 const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
77 type: "snapshot",
78 snapshot: { ...BASE_SNAPSHOT, cols: 130, rows: 15 },
79 });
80 const activity = {
81 type: "activity",
82 threadId: TARGET.threadId,
83 terminalId: TARGET.terminalId,
84 hasRunningSubprocess: false,
85 label: "Terminal 1",
86 } as const;
87 const narrowed = applyTerminalAttachStreamEvent(attached, { ...activity, cols: 54, rows: 15 });
88 // Activity from a server without geometry, or a repeat, must not reset the renderer.
89 const unchanged = applyTerminalAttachStreamEvent(
90 applyTerminalAttachStreamEvent(narrowed, activity),
91 { ...activity, cols: 54, rows: 15 },
92 );
93​
94 expect(attached.grid).toEqual({ cols: 130, rows: 15 });
95 expect(narrowed).toEqual({ ...attached, grid: { cols: 54, rows: 15 } });
96 expect(unchanged).toBe(narrowed);
97 });
98​
99 it("preserves a BOM code point at a new output chunk boundary", () => {
100 const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
101 type: "snapshot",
102 snapshot: { ...BASE_SNAPSHOT, history: "" },
103 });
104 const cursor = readTerminalOutputUpdate(initial.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
105 const data = `${"x".repeat(16_384)}\uFEFF${"y".repeat(20)}`;
106 const state = applyTerminalAttachStreamEvent(initial, {
107 type: "output",
108 threadId: TARGET.threadId,
109 terminalId: TARGET.terminalId,
110 data,
111 });
112​
113 expect(terminalOutputText(state.output)).toBe(data);
114 expect(readTerminalOutputUpdate(state.output, cursor)).toMatchObject({ type: "append", data });
115 expect(state.output.retainedBytes).toBe(new TextEncoder().encode(data).byteLength);
116 });
117​
118 it("preserves a leading BOM in the retained snapshot tail", () => {
119 const state = applyTerminalAttachStreamEvent(
120 EMPTY_TERMINAL_BUFFER_STATE,
121 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: "discard\uFEFFtail" } },
122 7,
123 );
124​
125 expect(terminalOutputText(state.output)).toBe("\uFEFFtail");
126 expect(state.output.retainedBytes).toBe(7);
127 const serverTail = retainedTerminalHistory("discardtail", 7);
128 expect(
129 applyTerminalAttachStreamEvent(
130 EMPTY_TERMINAL_BUFFER_STATE,
131 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: serverTail } },
132 7,
133 ),
134 ).toEqual(state);
135 });
136​
137 it("trims whole Unicode code points from a partially retained chunk", () => {
138 let state = applyTerminalAttachStreamEvent(
139 EMPTY_TERMINAL_BUFFER_STATE,
140 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: "é界🙂end" } },
141 12,
142 );
143 let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
144 for (const [data, expected, retainedBytes] of [
145 ["x", "界🙂endx", 11],
146 ["yz", "🙂endxyz", 10],
147 ["abc", "endxyzabc", 9],
148 ] as const) {
149 state = applyTerminalAttachStreamEvent(
150 state,
151 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data },
152 12,
153 );
154 const update = readTerminalOutputUpdate(state.output, cursor);
155 expect(update).toMatchObject({ type: "append", data });
156 expect(terminalOutputText(state.output)).toBe(expected);
157 expect(state.output.retainedBytes).toBe(retainedBytes);
158 cursor = update.cursor;
159 }
160 });
161​
162 it("does not retain the tail of a control sequence whose introducer was trimmed", () => {
163 for (const [history, maxBytes, replayable] of [
164 ["prefix\u001b[31mOK", 6, /^(?:[a-z]*\u001b\[31mOK|O?K?)$/],
165 ["prefix\u001b]0;HIDDEN\u0007OK", 10, /^(?:[a-z]*\u001b\]0;HIDDEN\u0007OK|O?K?)$/],
166 ["prefix\u001b]0;HIDDEN\u0007OK", 4, /^(?:[a-z]*\u001b\]0;HIDDEN\u0007OK|O?K?)$/],
167 ] as const) {
168 const state = applyTerminalAttachStreamEvent(
169 EMPTY_TERMINAL_BUFFER_STATE,
170 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history } },
171 maxBytes,
172 );
173 expect(terminalOutputText(state.output)).toBe("OK");
174​
175 // The same text as live output: a mounted terminal still receives every byte, while one
176 // that mounts later, even inside the sequence, never prints the rest of it.
177 let live = applyTerminalAttachStreamEvent(
178 EMPTY_TERMINAL_BUFFER_STATE,
179 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: "" } },
180 maxBytes,
181 );
182 const readers = [{ cursor: INITIAL_TERMINAL_OUTPUT_CURSOR, written: "" }];
183 for (const data of history) {
184 live = applyTerminalAttachStreamEvent(
185 live,
186 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data },
187 maxBytes,
188 );
189 readers.push({ cursor: INITIAL_TERMINAL_OUTPUT_CURSOR, written: "" });
190 for (const reader of readers) {
191 const update = readTerminalOutputUpdate(live.output, reader.cursor);
192 if (update.type === "reset") reader.written = update.data;
193 if (update.type === "append") reader.written += update.data;
194 reader.cursor = update.cursor;
195 }
196 }
197 expect(readers[0]!.written).toBe(history);
198 for (const reader of readers) expect(reader.written).toMatch(replayable);
199 expect(terminalOutputText(live.output)).toBe("OK");
200 }
201 });
202​
203 it("delivers all output when several events arrive before a renderer reads", () => {
204 const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
205 type: "snapshot",
206 snapshot: BASE_SNAPSHOT,
207 });
208 const cursor = readTerminalOutputUpdate(initial.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
209 let state = initial;
210 for (const data of [" one", " two", " three"]) {
211 state = applyTerminalAttachStreamEvent(state, {
212 type: "output",
213 threadId: TARGET.threadId,
214 terminalId: TARGET.terminalId,
215 data,
216 });
217 }
218 const update = readTerminalOutputUpdate(state.output, cursor);
219 expect(update).toMatchObject({ type: "append", data: " one two three" });
220 expect(readTerminalOutputUpdate(state.output, update.cursor).type).toBe("none");
221 });
222​
223 it("bounds historical chunk inspection when reading new tail output", () => {
224 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
225 type: "snapshot",
226 snapshot: { ...BASE_SNAPSHOT, history: "" },
227 });
228 for (let index = 0; index < 512; index += 1) {
229 state = applyTerminalAttachStreamEvent(state, {
230 type: "output",
231 threadId: TARGET.threadId,
232 terminalId: TARGET.terminalId,
233 data: "history\r\n",
234 });
235 }
236 const cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
237 const next = applyTerminalAttachStreamEvent(state, {
238 type: "output",
239 threadId: TARGET.threadId,
240 terminalId: TARGET.terminalId,
241 data: "latest\r\n",
242 });
243 let historicalChunkReads = 0;
244 const chunks = next.output.chunks.map((chunk, index) =>
245 index < state.output.chunks.length
246 ? {
247 ...chunk,
248 get startOffset() {
249 historicalChunkReads += 1;
250 return chunk.startOffset;
251 },
252 }
253 : chunk,
254 );
255​
256 expect(readTerminalOutputUpdate({ ...next.output, chunks }, cursor)).toMatchObject({
257 type: "append",
258 data: "latest\r\n",
259 });
260 expect(historicalChunkReads).toBeLessThanOrEqual(2);
261 });
262​
263 it("preserves the byte-limited tail and resets a cursor before a partially trimmed chunk", () => {
264 const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
265 type: "snapshot",
266 snapshot: { ...BASE_SNAPSHOT, history: "" },
267 });
268 const staleCursor = readTerminalOutputUpdate(
269 initial.output,
270 INITIAL_TERMINAL_OUTPUT_CURSOR,
271 ).cursor;
272 const first = applyTerminalAttachStreamEvent(initial, {
273 type: "output",
274 threadId: TARGET.threadId,
275 terminalId: TARGET.terminalId,
276 data: "hello",
277 });
278 const caughtUpCursor = readTerminalOutputUpdate(first.output, staleCursor).cursor;
279 const state = applyTerminalAttachStreamEvent(
280 first,
281 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data: " world" },
282 8,
283 );
284​
285 expect(readTerminalOutputUpdate(state.output, caughtUpCursor)).toMatchObject({
286 type: "append",
287 data: " world",
288 });
289 expect(readTerminalOutputUpdate(state.output, staleCursor)).toMatchObject({
290 type: "reset",
291 data: "lo world",
292 });
293 expect(state.output.retainedBytes).toBe(8);
294 });
295​
296 it("resets for repeated snapshots and restart even when output text repeats, and erases on clear", () => {
297 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
298 type: "snapshot",
299 snapshot: BASE_SNAPSHOT,
300 });
301 let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
302 const attachedGeneration = state.output.generation;
303 // A socket reconnect resubscribes the same stream, so the server's new snapshot gets no seed.
304 state = applyTerminalAttachStreamEvent(state, { type: "snapshot", snapshot: BASE_SNAPSHOT });
305 const repeated = readTerminalOutputUpdate(state.output, cursor);
306 expect(repeated).toMatchObject({ type: "reset", data: "hello" });
307 expect(state.version).toBe(2);
308 // Viewers replay their measured grid once per generation; the new attachment holds the old size.
309 expect(state.output.generation).not.toBe(attachedGeneration);
310 cursor = repeated.cursor;
311​
312 state = applyTerminalAttachStreamEvent(state, {
313 type: "cleared",
314 threadId: TARGET.threadId,
315 terminalId: TARGET.terminalId,
316 });
317 // Clear erases text in place: a full reset would drop the running program's modes.
318 const erase = "\u001b[H\u001b[2J\u001b[3J";
319 const cleared = readTerminalOutputUpdate(state.output, cursor);
320 expect(cleared).toMatchObject({ type: "append", data: erase });
321 expect(readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR)).toMatchObject({
322 type: "reset",
323 data: `hello${erase}`,
324 });
325 expect(terminalOutputText(state.output)).toBe("");
326 const afterClear = applyTerminalAttachStreamEvent(state, {
327 type: "output",
328 threadId: TARGET.threadId,
329 terminalId: TARGET.terminalId,
330 data: "next",
331 });
332 expect(terminalOutputText(afterClear.output)).toBe("next");
333 state = applyTerminalAttachStreamEvent(state, {
334 type: "restarted",
335 threadId: TARGET.threadId,
336 terminalId: TARGET.terminalId,
337 snapshot: BASE_SNAPSHOT,
338 });
339 expect(readTerminalOutputUpdate(state.output, cleared.cursor)).toMatchObject({
340 type: "reset",
341 data: "hello",
342 });
343 expect(state.lifecycleVersion).toBe(2);
344 });
345​
346 it("does not reuse a renderer cursor when a fresh attach has matching counters", () => {
347 const first = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
348 type: "snapshot",
349 snapshot: BASE_SNAPSHOT,
350 });
351 const cursor = readTerminalOutputUpdate(first.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
352 const next = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
353 type: "snapshot",
354 snapshot: { ...BASE_SNAPSHOT, history: "other" },
355 });
356 expect(next.output.resetVersion).toBe(first.output.resetVersion);
357 expect(next.output.nextOffset).toBe(first.output.nextOffset);
358 expect(readTerminalOutputUpdate(next.output, cursor)).toMatchObject({
359 type: "reset",
360 data: "other",
361 });
362 expect(next.lifecycleVersion).toBe(0);
363 });
364​
365 it("appends every unread character across a compaction boundary", () => {
366 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
367 type: "snapshot",
368 snapshot: { ...BASE_SNAPSHOT, history: "" },
369 });
370 let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
371 const writes = Array.from({ length: 1200 }, (_, index) => ["x", "é", "界", "🙂"][index % 4]!);
372 for (const [index, data] of writes.entries()) {
373 state = applyTerminalAttachStreamEvent(state, {
374 type: "output",
375 threadId: TARGET.threadId,
376 terminalId: TARGET.terminalId,
377 data,
378 });
379 if (index === 99) cursor = readTerminalOutputUpdate(state.output, cursor).cursor;
380 }
381 expect(readTerminalOutputUpdate(state.output, cursor)).toMatchObject({
382 type: "append",
383 data: writes.slice(100).join(""),
384 });
385 });
386});