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

terminalSession.test.ts

501 lines18.2 KB

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