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

terminalSession.test.ts

524 lines19.0 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("keeps skipping a clipped CSI after replaying the line breaks it ran", () => {
127 let state = applyTerminalAttachStreamEvent(
128 EMPTY_TERMINAL_BUFFER_STATE,
129 {
130 type: "snapshot",
131 snapshot: { ...BASE_SNAPSHOT, ...retainTerminalSnapshotHistory("\u001b[3\r\n1234", 6) },
132 },
133 8_192,
134 );
135 let update = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
136 let replayed = "data" in update ? update.data : "";
137 for (const data of ["\r\n1", "mREADY"]) {
138 state = applyTerminalAttachStreamEvent(
139 state,
140 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data },
141 8_192,
142 );
143 update = readTerminalOutputUpdate(state.output, update.cursor);
144 replayed += "data" in update ? update.data : "";
145 }
146 expect(replayed).toBe("\r\n\r\nREADY");
147 });
148​
149 it("prefers live attach status over stale metadata after the attach stream starts", () => {
150 const summary = applyTerminalMetadataStreamEvent([], {
151 type: "snapshot",
152 terminals: [
153 {
154 threadId: BASE_SNAPSHOT.threadId,
155 terminalId: BASE_SNAPSHOT.terminalId,
156 cwd: BASE_SNAPSHOT.cwd,
157 worktreePath: BASE_SNAPSHOT.worktreePath,
158 status: "running",
159 pid: BASE_SNAPSHOT.pid,
160 exitCode: BASE_SNAPSHOT.exitCode,
161 exitSignal: BASE_SNAPSHOT.exitSignal,
162 updatedAt: BASE_SNAPSHOT.updatedAt,
163 hasRunningSubprocess: false,
164 label: BASE_SNAPSHOT.label,
165 },
166 ],
167 })[0]!;
168 const attached = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
169 type: "error",
170 threadId: TARGET.threadId,
171 terminalId: TARGET.terminalId,
172 message: "Terminal disconnected.",
173 });
174​
175 expect(combineTerminalSessionState(summary, attached)).toMatchObject({
176 status: "error",
177 error: "Terminal disconnected.",
178 version: 1,
179 });
180 });
181​
182 it("keeps a startup failure carried by an attach snapshot", () => {
183 const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
184 type: "snapshot",
185 snapshot: { ...BASE_SNAPSHOT, status: "error", pid: null, error: "Failed to spawn PTY." },
186 });
187​
188 expect(attached).toMatchObject({ status: "error", error: "Failed to spawn PTY." });
189 });
190​
191 it("follows the shared PTY grid from snapshots and activity without disturbing output", () => {
192 const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
193 type: "snapshot",
194 snapshot: { ...BASE_SNAPSHOT, cols: 130, rows: 15 },
195 });
196 const activity = {
197 type: "activity",
198 threadId: TARGET.threadId,
199 terminalId: TARGET.terminalId,
200 hasRunningSubprocess: false,
201 label: "Terminal 1",
202 } as const;
203 const narrowed = applyTerminalAttachStreamEvent(attached, { ...activity, cols: 54, rows: 15 });
204 // Activity from a server without geometry, or a repeat, must not reset the renderer.
205 const unchanged = applyTerminalAttachStreamEvent(
206 applyTerminalAttachStreamEvent(narrowed, activity),
207 { ...activity, cols: 54, rows: 15 },
208 );
209​
210 expect(attached.grid).toEqual({ cols: 130, rows: 15 });
211 expect(narrowed).toEqual({ ...attached, grid: { cols: 54, rows: 15 } });
212 expect(unchanged).toBe(narrowed);
213 });
214​
215 it("preserves a BOM code point at a new output chunk boundary", () => {
216 const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
217 type: "snapshot",
218 snapshot: { ...BASE_SNAPSHOT, history: "" },
219 });
220 const cursor = readTerminalOutputUpdate(initial.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
221 const data = `${"x".repeat(16_384)}\uFEFF${"y".repeat(20)}`;
222 const state = applyTerminalAttachStreamEvent(initial, {
223 type: "output",
224 threadId: TARGET.threadId,
225 terminalId: TARGET.terminalId,
226 data,
227 });
228​
229 expect(terminalOutputText(state.output)).toBe(data);
230 expect(readTerminalOutputUpdate(state.output, cursor)).toMatchObject({ type: "append", data });
231 expect(state.output.retainedBytes).toBe(new TextEncoder().encode(data).byteLength);
232 });
233​
234 it("preserves a leading BOM in the retained snapshot tail", () => {
235 const state = applyTerminalAttachStreamEvent(
236 EMPTY_TERMINAL_BUFFER_STATE,
237 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: "discard\uFEFFtail" } },
238 7,
239 );
240​
241 expect(terminalOutputText(state.output)).toBe("\uFEFFtail");
242 expect(state.output.retainedBytes).toBe(7);
243 const serverTail = retainedTerminalHistory("discardtail", 7);
244 expect(
245 applyTerminalAttachStreamEvent(
246 EMPTY_TERMINAL_BUFFER_STATE,
247 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: serverTail } },
248 7,
249 ),
250 ).toEqual(state);
251 });
252​
253 it("trims whole Unicode code points from a partially retained chunk", () => {
254 let state = applyTerminalAttachStreamEvent(
255 EMPTY_TERMINAL_BUFFER_STATE,
256 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: "é界🙂end" } },
257 12,
258 );
259 let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
260 for (const [data, expected, retainedBytes] of [
261 ["x", "界🙂endx", 11],
262 ["yz", "🙂endxyz", 10],
263 ["abc", "endxyzabc", 9],
264 ] as const) {
265 state = applyTerminalAttachStreamEvent(
266 state,
267 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data },
268 12,
269 );
270 const update = readTerminalOutputUpdate(state.output, cursor);
271 expect(update).toMatchObject({ type: "append", data });
272 expect(terminalOutputText(state.output)).toBe(expected);
273 expect(state.output.retainedBytes).toBe(retainedBytes);
274 cursor = update.cursor;
275 }
276 });
277​
278 it("does not retain the tail of a control sequence whose introducer was trimmed", () => {
279 for (const [history, maxBytes, replayable] of [
280 ["prefix\u001b[31mOK", 6, /^(?:[a-z]*\u001b\[31mOK|O?K?)$/],
281 ["prefix\u001b]0;HIDDEN\u0007OK", 10, /^(?:[a-z]*\u001b\]0;HIDDEN\u0007OK|O?K?)$/],
282 ["prefix\u001b]0;HIDDEN\u0007OK", 4, /^(?:[a-z]*\u001b\]0;HIDDEN\u0007OK|O?K?)$/],
283 ] as const) {
284 const state = applyTerminalAttachStreamEvent(
285 EMPTY_TERMINAL_BUFFER_STATE,
286 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history } },
287 maxBytes,
288 );
289 expect(terminalOutputText(state.output)).toBe("OK");
290​
291 // The same text as live output: a mounted terminal still receives every byte, while one
292 // that mounts later, even inside the sequence, never prints the rest of it.
293 let live = applyTerminalAttachStreamEvent(
294 EMPTY_TERMINAL_BUFFER_STATE,
295 { type: "snapshot", snapshot: { ...BASE_SNAPSHOT, history: "" } },
296 maxBytes,
297 );
298 const readers = [{ cursor: INITIAL_TERMINAL_OUTPUT_CURSOR, written: "" }];
299 for (const data of history) {
300 live = applyTerminalAttachStreamEvent(
301 live,
302 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data },
303 maxBytes,
304 );
305 readers.push({ cursor: INITIAL_TERMINAL_OUTPUT_CURSOR, written: "" });
306 for (const reader of readers) {
307 const update = readTerminalOutputUpdate(live.output, reader.cursor);
308 if (update.type === "reset") reader.written = update.data;
309 if (update.type === "append") reader.written += update.data;
310 reader.cursor = update.cursor;
311 }
312 }
313 expect(readers[0]!.written).toBe(history);
314 for (const reader of readers) expect(reader.written).toMatch(replayable);
315 expect(terminalOutputText(live.output)).toBe("OK");
316 }
317 });
318​
319 it("delivers all output when several events arrive before a renderer reads", () => {
320 const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
321 type: "snapshot",
322 snapshot: BASE_SNAPSHOT,
323 });
324 const cursor = readTerminalOutputUpdate(initial.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
325 let state = initial;
326 for (const data of [" one", " two", " three"]) {
327 state = applyTerminalAttachStreamEvent(state, {
328 type: "output",
329 threadId: TARGET.threadId,
330 terminalId: TARGET.terminalId,
331 data,
332 });
333 }
334 const update = readTerminalOutputUpdate(state.output, cursor);
335 expect(update).toMatchObject({ type: "append", data: " one two three" });
336 expect(readTerminalOutputUpdate(state.output, update.cursor).type).toBe("none");
337 });
338​
339 it("bounds historical chunk inspection when reading new tail output", () => {
340 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
341 type: "snapshot",
342 snapshot: { ...BASE_SNAPSHOT, history: "" },
343 });
344 for (let index = 0; index < 512; index += 1) {
345 state = applyTerminalAttachStreamEvent(state, {
346 type: "output",
347 threadId: TARGET.threadId,
348 terminalId: TARGET.terminalId,
349 data: "history\r\n",
350 });
351 }
352 const cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
353 const next = applyTerminalAttachStreamEvent(state, {
354 type: "output",
355 threadId: TARGET.threadId,
356 terminalId: TARGET.terminalId,
357 data: "latest\r\n",
358 });
359 let historicalChunkReads = 0;
360 const chunks = next.output.chunks.map((chunk, index) =>
361 index < state.output.chunks.length
362 ? {
363 ...chunk,
364 get startOffset() {
365 historicalChunkReads += 1;
366 return chunk.startOffset;
367 },
368 }
369 : chunk,
370 );
371​
372 expect(readTerminalOutputUpdate({ ...next.output, chunks }, cursor)).toMatchObject({
373 type: "append",
374 data: "latest\r\n",
375 });
376 expect(historicalChunkReads).toBeLessThanOrEqual(2);
377 });
378​
379 it("preserves the byte-limited tail and resets a cursor before a partially trimmed chunk", () => {
380 const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
381 type: "snapshot",
382 snapshot: { ...BASE_SNAPSHOT, history: "" },
383 });
384 const staleCursor = readTerminalOutputUpdate(
385 initial.output,
386 INITIAL_TERMINAL_OUTPUT_CURSOR,
387 ).cursor;
388 const first = applyTerminalAttachStreamEvent(initial, {
389 type: "output",
390 threadId: TARGET.threadId,
391 terminalId: TARGET.terminalId,
392 data: "hello",
393 });
394 const caughtUpCursor = readTerminalOutputUpdate(first.output, staleCursor).cursor;
395 const state = applyTerminalAttachStreamEvent(
396 first,
397 { type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data: " world" },
398 8,
399 );
400​
401 expect(readTerminalOutputUpdate(state.output, caughtUpCursor)).toMatchObject({
402 type: "append",
403 data: " world",
404 });
405 expect(readTerminalOutputUpdate(state.output, staleCursor)).toMatchObject({
406 type: "reset",
407 data: "lo world",
408 });
409 expect(state.output.retainedBytes).toBe(8);
410 });
411​
412 it("skips the rest of an unfinished title when reading text after a clear", () => {
413 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
414 type: "snapshot",
415 snapshot: BASE_SNAPSHOT,
416 });
417 state = applyTerminalAttachStreamEvent(state, {
418 type: "cleared",
419 ...TARGET,
420 pendingControlSequence: "\u001b]0;Build ",
421 });
422 for (const data of ["pro", "gress"]) {
423 state = applyTerminalAttachStreamEvent(state, { type: "output", ...TARGET, data });
424 expect(terminalOutputText(state.output)).toBe("");
425 }
426 state = applyTerminalAttachStreamEvent(state, {
427 type: "output",
428 ...TARGET,
429 data: "\u0007ready",
430 });
431 expect(terminalOutputText(state.output)).toBe("ready");
432 });
433​
434 it("resets for repeated snapshots and restart even when output text repeats, and erases on clear", () => {
435 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
436 type: "snapshot",
437 snapshot: BASE_SNAPSHOT,
438 });
439 let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
440 const attachedGeneration = state.output.generation;
441 // A socket reconnect resubscribes the same stream, so the server's new snapshot gets no seed.
442 state = applyTerminalAttachStreamEvent(state, { type: "snapshot", snapshot: BASE_SNAPSHOT });
443 const repeated = readTerminalOutputUpdate(state.output, cursor);
444 expect(repeated).toMatchObject({ type: "reset", data: "hello" });
445 expect(state.version).toBe(2);
446 // Viewers replay their measured grid once per generation; the new attachment holds the old size.
447 expect(state.output.generation).not.toBe(attachedGeneration);
448 cursor = repeated.cursor;
449​
450 state = applyTerminalAttachStreamEvent(state, {
451 type: "cleared",
452 threadId: TARGET.threadId,
453 terminalId: TARGET.terminalId,
454 });
455 // Clear erases text in place: a full reset would drop the running program's modes.
456 const erase = "\u001b[H\u001b[2J\u001b[3J";
457 const cleared = readTerminalOutputUpdate(state.output, cursor);
458 expect(cleared).toMatchObject({ type: "append", data: erase });
459 expect(readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR)).toMatchObject({
460 type: "reset",
461 data: `hello${erase}`,
462 });
463 expect(terminalOutputText(state.output)).toBe("");
464 const afterClear = applyTerminalAttachStreamEvent(state, {
465 type: "output",
466 threadId: TARGET.threadId,
467 terminalId: TARGET.terminalId,
468 data: "next",
469 });
470 expect(terminalOutputText(afterClear.output)).toBe("next");
471 state = applyTerminalAttachStreamEvent(state, {
472 type: "restarted",
473 threadId: TARGET.threadId,
474 terminalId: TARGET.terminalId,
475 snapshot: BASE_SNAPSHOT,
476 });
477 expect(readTerminalOutputUpdate(state.output, cleared.cursor)).toMatchObject({
478 type: "reset",
479 data: "hello",
480 });
481 expect(state.lifecycleVersion).toBe(2);
482 });
483​
484 it("does not reuse a renderer cursor when a fresh attach has matching counters", () => {
485 const first = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
486 type: "snapshot",
487 snapshot: BASE_SNAPSHOT,
488 });
489 const cursor = readTerminalOutputUpdate(first.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
490 const next = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
491 type: "snapshot",
492 snapshot: { ...BASE_SNAPSHOT, history: "other" },
493 });
494 expect(next.output.resetVersion).toBe(first.output.resetVersion);
495 expect(next.output.nextOffset).toBe(first.output.nextOffset);
496 expect(readTerminalOutputUpdate(next.output, cursor)).toMatchObject({
497 type: "reset",
498 data: "other",
499 });
500 expect(next.lifecycleVersion).toBe(0);
501 });
502​
503 it("appends every unread character across a compaction boundary", () => {
504 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
505 type: "snapshot",
506 snapshot: { ...BASE_SNAPSHOT, history: "" },
507 });
508 let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
509 const writes = Array.from({ length: 1200 }, (_, index) => ["x", "é", "界", "🙂"][index % 4]!);
510 for (const [index, data] of writes.entries()) {
511 state = applyTerminalAttachStreamEvent(state, {
512 type: "output",
513 threadId: TARGET.threadId,
514 terminalId: TARGET.terminalId,
515 data,
516 });
517 if (index === 99) cursor = readTerminalOutputUpdate(state.output, cursor).cursor;
518 }
519 expect(readTerminalOutputUpdate(state.output, cursor)).toMatchObject({
520 type: "append",
521 data: writes.slice(100).join(""),
522 });
523 });
524});