The best way to control Claude Code, Codex and more from any computer or phone
fix(terminal): trimmed history no longer replays half of a control sequence (#36368)
Julius Marminge committed
Nov 13, 2026 at 13:22 UTC
93cbca3fcbd54f33ec2f56ce70e302b44579b49c
5 files changed
+289
-30
apps/server/src/terminal/Manager.test.ts
+49
-6
@@ -13,6 +13,8 @@ import {
13
ProviderDriverKind,
14
ProviderInstanceId,
15
retainedTerminalHistory,
16
+ terminalSequenceEnd,
17
+ terminalSequenceStateAfter,
18
TerminalProviderInstanceNotFoundError,
19
} from "@t3tools/contracts";
20
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -337,7 +339,6 @@ function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): s
339
if (terminated) lines.pop();
340
const retained = lines.slice(Math.max(0, lines.length - maxLines)).join("\n");
341
const capped = terminated ? `${retained}\n` : retained;
340
- if (Buffer.byteLength(capped) <= maxBytes) return capped;
342
const points = Array.from(capped);
343
let start = points.length;
344
let bytes = 0;
@@ -347,7 +348,11 @@ function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): s
348
bytes += next;
349
start -= 1;
350
}
350
- return points.slice(start).join("");
351
+ const kept = points.slice(start).join("");
352
+ if (maxLines <= 0 || maxBytes <= 0) return kept;
353
+ // A cut inside a control sequence drops the rest of that sequence too.
354
+ const state = terminalSequenceStateAfter(0, text, 0, text.length - kept.length);
355
+ return kept.slice(terminalSequenceEnd(state, kept));
356
}
357
358
it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequences, and clear", () => {
@@ -365,6 +370,10 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen
370
"\u001b[31m",
371
"\u001b[0m",
372
"\u001b]8;;url\u0007",
373
+ "\u001b]0;",
374
+ "\u001bP",
375
+ "\u0007",
376
+ "\u001b\\",
377
"\ud83d",
378
"\ude80",
379
];
@@ -375,7 +384,8 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen
384
385
for (const maxBytes of [0, 3, 8, 64, Infinity]) {
386
for (const maxLines of [0, 1, 3, 5, 5_000]) {
378
- let expected = retainedHistory("before\ninitial\n", maxLines, maxBytes);
387
+ let full = "before\ninitial\n";
388
+ let expected = retainedHistory(full, maxLines, maxBytes);
389
const history = new TerminalManager.BoundedTerminalHistory(
390
maxLines,
391
"before\ninitial\n",
@@ -386,18 +396,33 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen
396
for (let step = 0; step < 300; step += 1) {
397
if (step % 73 === 0) {
398
history.clear();
389
- expected = "";
390
- expect(history.value()).toBe(expected);
399
+ full = "";
400
+ expect(history.value()).toBe("");
401
}
402
const chunk = nextFragment() + nextFragment();
403
history.append(chunk);
394
- expected = retainedHistory(expected + chunk, maxLines, maxBytes);
404
+ full += chunk;
405
+ expected = retainedHistory(full, maxLines, maxBytes);
406
expect(history.value()).toBe(expected);
407
}
408
}
409
}
410
});
411
412
+it("does not retain the tail of a control sequence whose introducer was trimmed", () => {
413
+ for (const [text, maxBytes, retained] of [
414
+ ["prefix\u001b[31mOK", 6, "OK"],
415
+ ["prefix\u001b]0;HIDDEN\u0007OK", 10, "OK"],
416
+ ["prefix\u001b]0;🙂HIDDEN\u0007OK", 9, "OK"],
417
+ // libghostty leaves every string but OSC at the emoji's second byte, so HELLO was visible.
418
+ ["prefix\u001bP🙂HELLO\u001b\\OK", 9, "HELLO\u001b\\OK"],
419
+ ] as const) {
420
+ expect(new TerminalManager.BoundedTerminalHistory(5_000, text, maxBytes).value()).toBe(
421
+ retained,
422
+ );
423
+ }
424
+});
425
+
426
it("bounds long partial lines and joins surrogate pairs across chunk boundaries", () => {
427
const maxBytes = 65_539;
428
let expected = "";
@@ -1172,6 +1197,24 @@ it.layer(
1197
}),
1198
);
1199
1200
+ it.effect("restores a log tail that starts inside a control sequence without its remainder", () =>
1201
+ Effect.gen(function* () {
1202
+ const fs = yield* FileSystem.FileSystem;
1203
+ for (const [persisted, restored] of [
1204
+ ["\u001b]0;x\u0007ABCD", "ABCD"],
1205
+ ["名\u001b]0;名\u0007ABCD", "ABCD"],
1206
+ ["\u001b]0;x\u0007\u001b[31mABCD", "ABCD"],
1207
+ ] as const) {
1208
+ const { manager, logsDir } = yield* createManager(5, { historyByteLimit: 8 });
1209
+ const path = yield* historyLogPath(logsDir);
1210
+ yield* fs.makeDirectory(logsDir, { recursive: true });
1211
+ yield* fs.writeFileString(path, persisted);
1212
+ expect((yield* manager.open(openInput())).history).toBe(restored);
1213
+ expect(yield* fs.readFileString(path)).toBe(restored);
1214
+ }
1215
+ }),
1216
+ );
1217
+
1218
it.effect("persists small terminal updates without rewriting the retained history", () =>
1219
Effect.gen(function* () {
1220
const fs = yield* FileSystem.FileSystem;
apps/server/src/terminal/Manager.ts
+44
-5
@@ -6,6 +6,9 @@ import {
6
DEFAULT_TERMINAL_ID,
7
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
8
retainedTerminalHistory,
9
+ TERMINAL_SEQUENCE_GROUND,
10
+ terminalSequenceEnd,
11
+ terminalSequenceStateAfter,
12
TerminalCwdError,
13
TerminalCwdNotDirectoryError,
14
TerminalCwdNotFoundError,
@@ -888,6 +891,14 @@ interface TerminalHistoryPersistenceCursor {
891
readonly fileBytes: number;
892
}
893
894
+function countLineBreaks(data: string): number {
895
+ let lineBreaks = 0;
896
+ for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) {
897
+ lineBreaks += 1;
898
+ }
899
+ return lineBreaks;
900
+}
901
+
902
export class BoundedTerminalHistory {
903
private readonly maxLines: number;
904
private readonly maxBytes: number;
@@ -897,6 +908,8 @@ export class BoundedTerminalHistory {
908
private lineBreaks = 0;
909
// Reading the old string's tail on each append can force chunk concatenation.
910
private lastCodeUnit: number | undefined;
911
+ // The terminal parser's state at the first retained code unit, which is where a replay starts.
912
+ private sequenceState = TERMINAL_SEQUENCE_GROUND;
913
private cachedValue: string | null = "";
914
private generation = 0;
915
private appendedLength = 0;
@@ -961,10 +974,7 @@ export class BoundedTerminalHistory {
974
975
private appendChunk(data: string): void {
976
const byteLength = Buffer.byteLength(data);
964
- let lineBreaks = 0;
965
- for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) {
966
- lineBreaks += 1;
967
- }
977
+ const lineBreaks = countLineBreaks(data);
978
const previous = this.chunks.at(-1);
979
if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) {
980
previous.data += data;
@@ -981,6 +991,7 @@ export class BoundedTerminalHistory {
991
992
private discardChunk(): void {
993
const first = this.chunks[this.start]!;
994
+ this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data);
995
this.byteLength -= first.byteLength;
996
this.lineBreaks -= first.lineBreaks;
997
this.chunks[this.start++] = undefined;
@@ -992,6 +1003,7 @@ export class BoundedTerminalHistory {
1003
this.discardChunk();
1004
return;
1005
}
1006
+ this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data, 0, offset);
1007
first.data = first.data.slice(offset);
1008
first.byteLength -= byteLength;
1009
first.lineBreaks -= lineBreaks;
@@ -1039,6 +1051,12 @@ export class BoundedTerminalHistory {
1051
}
1052
this.trimChunk(offset, bytes, lineBreaks);
1053
}
1054
+ // A cut inside a control sequence would replay the rest of it as text.
1055
+ while (this.sequenceState !== TERMINAL_SEQUENCE_GROUND && this.start < this.chunks.length) {
1056
+ const first = this.chunks[this.start]!;
1057
+ const dropped = first.data.slice(0, terminalSequenceEnd(this.sequenceState, first.data));
1058
+ this.trimChunk(dropped.length, Buffer.byteLength(dropped), countLineBreaks(dropped));
1059
+ }
1060
if (
1061
this.start === this.chunks.length ||
1062
(this.start > 2_048 && this.start * 2 >= this.chunks.length)
@@ -1057,6 +1075,7 @@ export class BoundedTerminalHistory {
1075
this.byteLength = 0;
1076
this.lineBreaks = 0;
1077
this.lastCodeUnit = undefined;
1078
+ this.sequenceState = TERMINAL_SEQUENCE_GROUND;
1079
this.cachedValue = "";
1080
}
1081
@@ -2176,6 +2195,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2195
const info = yield* file.stat;
2196
const limit = BigInt(historyByteLimit);
2197
const offset = info.size > limit ? info.size - limit : 0n;
2198
+ // The tail can start inside a control sequence; only the bytes before it say which.
2199
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
2200
+ let sequenceState = TERMINAL_SEQUENCE_GROUND;
2201
+ const skipped = new Uint8Array(Math.min(Number(offset), 64 * 1024));
2202
+ for (let remaining = Number(offset); remaining > 0;) {
2203
+ const read = Number(yield* file.read(skipped.subarray(0, remaining)));
2204
+ if (read === 0) break;
2205
+ remaining -= read;
2206
+ sequenceState = terminalSequenceStateAfter(
2207
+ sequenceState,
2208
+ decoder.decode(skipped.subarray(0, read), { stream: true }),
2209
+ );
2210
+ }
2211
yield* file.seek(offset, "start");
2212
const bytes = new Uint8Array(Number(info.size - offset));
2213
let length = 0;
@@ -2189,8 +2221,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2221
// A tail read can start inside a UTF-8 code point. Skip its remaining bytes.
2222
while (start < length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start += 1;
2223
}
2224
+ sequenceState = terminalSequenceStateAfter(
2225
+ sequenceState,
2226
+ decoder.decode(bytes.subarray(0, start)),
2227
+ );
2228
+ const history = new TextDecoder("utf-8", { ignoreBOM: true }).decode(
2229
+ bytes.subarray(start, length),
2230
+ );
2231
return {
2193
- history: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(start, length)),
2232
+ history: history.slice(terminalSequenceEnd(sequenceState, history)),
2233
truncated: offset > 0n,
2234
};
2235
});
packages/client-runtime/src/state/terminalOutput.ts
+55
-17
@@ -1,4 +1,9 @@
1
-import { retainedTerminalHistory } from "@t3tools/contracts";
1
+import {
2
+ retainedTerminalHistory,
3
+ TERMINAL_SEQUENCE_GROUND,
4
+ terminalSequenceEnd,
5
+ terminalSequenceStateAfter,
6
+} from "@t3tools/contracts";
7
8
export interface TerminalOutputChunk {
9
readonly startOffset: number;
@@ -12,6 +17,9 @@ export interface TerminalOutputState {
17
readonly retainedBytes: number;
18
readonly resetVersion: number;
19
readonly nextOffset: number;
20
+ // The terminal parser's state at the first retained code unit. Trimming can cut a control
21
+ // sequence, and a replay has to skip the rest of it instead of printing it.
22
+ readonly sequenceState: number;
23
/** Chunks before this offset are replayed to emulators but are no longer displayed text. */
24
readonly textStartOffset: number;
25
}
@@ -20,12 +28,15 @@ export interface TerminalOutputCursor {
28
readonly generation: number;
29
readonly resetVersion: number;
30
readonly offset: number;
31
+ // The cut control sequence still open at `offset`, which the reader's terminal never entered.
32
+ readonly sequenceState: number;
33
}
34
35
export const INITIAL_TERMINAL_OUTPUT_CURSOR = Object.freeze<TerminalOutputCursor>({
36
generation: -1,
37
resetVersion: -1,
38
offset: 0,
39
+ sequenceState: TERMINAL_SEQUENCE_GROUND,
40
});
41
42
export type TerminalOutputUpdate =
@@ -56,6 +67,7 @@ export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze<TerminalOutputState>({
67
retainedBytes: 0,
68
resetVersion: 0,
69
nextOffset: 0,
70
+ sequenceState: TERMINAL_SEQUENCE_GROUND,
71
textStartOffset: 0,
72
});
73
@@ -178,6 +190,7 @@ function appendOutput(
190
retainedBytes: 0,
191
resetVersion: current.resetVersion + 1,
192
nextOffset: current.nextOffset + data.length,
193
+ sequenceState: TERMINAL_SEQUENCE_GROUND,
194
textStartOffset: current.textStartOffset,
195
};
196
}
@@ -189,12 +202,19 @@ function appendOutput(
202
203
const chunks = [...current.chunks, ...appended.chunks];
204
let retainedBytes = current.retainedBytes + appended.byteLength;
205
+ let sequenceState = current.sequenceState;
206
let firstRetainedIndex = 0;
207
while (retainedBytes > maxBufferBytes && firstRetainedIndex < chunks.length) {
208
const first = chunks[firstRetainedIndex]!;
209
const bytesToDrop = retainedBytes - maxBufferBytes;
210
if (bytesToDrop < first.byteLength) {
211
const trimmed = trimOutputChunkStart(first, bytesToDrop);
212
+ sequenceState = terminalSequenceStateAfter(
213
+ sequenceState,
214
+ first.data,
215
+ 0,
216
+ first.data.length - trimmed.data.length,
217
+ );
218
retainedBytes -= first.byteLength - trimmed.byteLength;
219
if (trimmed.byteLength > 0) {
220
chunks[firstRetainedIndex] = trimmed;
@@ -203,6 +223,7 @@ function appendOutput(
223
}
224
break;
225
}
226
+ sequenceState = terminalSequenceStateAfter(sequenceState, first.data);
227
retainedBytes -= first.byteLength;
228
firstRetainedIndex += 1;
229
}
@@ -213,6 +234,7 @@ function appendOutput(
234
const excessChunks = retainedChunks.length - MAX_TERMINAL_OUTPUT_CHUNKS;
235
if (excessChunks > 0) {
236
for (const chunk of retainedChunks.slice(0, excessChunks)) {
237
+ sequenceState = terminalSequenceStateAfter(sequenceState, chunk.data);
238
retainedBytes -= chunk.byteLength;
239
}
240
retainedChunks = retainedChunks.slice(excessChunks);
@@ -225,6 +247,7 @@ function appendOutput(
247
retainedBytes,
248
resetVersion: current.resetVersion,
249
nextOffset: appended.nextOffset,
250
+ sequenceState,
251
textStartOffset: current.textStartOffset,
252
};
253
}
@@ -246,6 +269,7 @@ function resetOutput(
269
retainedBytes: reset.byteLength,
270
resetVersion: current.resetVersion + 1,
271
nextOffset: reset.nextOffset,
272
+ sequenceState: TERMINAL_SEQUENCE_GROUND,
273
textStartOffset: 0,
274
};
275
}
@@ -267,23 +291,26 @@ function clearOutput(current: TerminalOutputState, maxBufferBytes: number): Term
291
return { ...cleared, textStartOffset: cleared.nextOffset };
292
}
293
270
-/** Everything retained, for an emulator that is fed the whole history. */
294
+/** Everything a fresh emulator replays: retained output from outside any control sequence. */
295
export function terminalOutputReplay(output: TerminalOutputState): string {
272
- return output.chunks.map((chunk) => chunk.data).join("");
296
+ const text = output.chunks.map((chunk) => chunk.data).join("");
297
+ return text.slice(terminalSequenceEnd(output.sequenceState, text));
298
}
299
300
/** The output as plain text, for surfaces that do not interpret escape sequences. */
301
export function terminalOutputText(output: TerminalOutputState): string {
277
- return output.chunks
278
- .map((chunk) => chunk.data.slice(Math.max(0, output.textStartOffset - chunk.startOffset)))
279
- .join("");
302
+ const text = output.chunks.map((chunk) => chunk.data).join("");
303
+ const firstOffset = output.chunks[0]?.startOffset ?? output.nextOffset;
304
+ return text.slice(
305
+ Math.max(terminalSequenceEnd(output.sequenceState, text), output.textStartOffset - firstOffset),
306
+ );
307
}
308
309
export function readTerminalOutputUpdate(
310
output: TerminalOutputState,
311
cursor: TerminalOutputCursor,
312
): TerminalOutputUpdate {
286
- const nextCursor = {
313
+ const position = {
314
generation: output.generation,
315
resetVersion: output.resetVersion,
316
offset: output.nextOffset,
@@ -294,7 +321,16 @@ export function readTerminalOutputUpdate(
321
cursor.resetVersion !== output.resetVersion ||
322
cursor.offset < (firstChunk?.startOffset ?? output.nextOffset)
323
) {
297
- return { type: "reset", data: terminalOutputReplay(output), cursor: nextCursor };
324
+ const text = output.chunks.map((chunk) => chunk.data).join("");
325
+ const start = terminalSequenceEnd(output.sequenceState, text);
326
+ return {
327
+ type: "reset",
328
+ data: text.slice(start),
329
+ cursor: {
330
+ ...position,
331
+ sequenceState: terminalSequenceStateAfter(output.sequenceState, text, 0, start),
332
+ },
333
+ };
334
}
335
336
// Appends and compaction preserve offset order, so unread chunks form a suffix.
@@ -304,17 +340,19 @@ export function readTerminalOutputUpdate(
340
if (!(chunk.startOffset + chunk.data.length > cursor.offset)) break;
341
firstUnread -= 1;
342
}
307
- const appended = output.chunks.slice(firstUnread);
308
- if (appended.length === 0) {
343
+ const text = output.chunks
344
+ .slice(firstUnread)
345
+ .map((chunk) => chunk.data.slice(Math.max(0, cursor.offset - chunk.startOffset)))
346
+ .join("");
347
+ const start = terminalSequenceEnd(cursor.sequenceState, text);
348
+ const nextCursor = {
349
+ ...position,
350
+ sequenceState: terminalSequenceStateAfter(cursor.sequenceState, text, 0, start),
351
+ };
352
+ if (start === text.length) {
353
return { type: "none", cursor: nextCursor };
354
}
311
- return {
312
- type: "append",
313
- data: appended
314
- .map((chunk) => chunk.data.slice(Math.max(0, cursor.offset - chunk.startOffset)))
315
- .join(""),
316
- cursor: nextCursor,
317
- };
355
+ return { type: "append", data: text.slice(start), cursor: nextCursor };
356
}
357
358
export { appendOutput, clearOutput, resetOutput };
packages/client-runtime/src/state/terminalSession.test.ts
+41
@@ -159,6 +159,47 @@ describe("terminal session reducers", () => {
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",
packages/contracts/src/terminal.ts
+100
-2
@@ -9,7 +9,98 @@ const historyEncoder = new TextEncoder();
9
// A BOM at a retained chunk boundary is terminal data, not an encoding marker.
10
const historyDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
11
12
-/** The final `maxBytes` of UTF-8 a client retains, starting at a code point boundary. */
12
+// libghostty-vt's parser states, merged where the same input takes them back to ground.
13
+export const TERMINAL_SEQUENCE_GROUND = 0;
14
+const SEQUENCE_ESCAPE = 1;
15
+const SEQUENCE_ESCAPE_INTERMEDIATE = 2;
16
+const SEQUENCE_CSI = 3;
17
+const SEQUENCE_DCS = 4;
18
+const SEQUENCE_SOS_PM_APC = 5;
19
+const SEQUENCE_OSC = 6;
20
+
21
+// Bits above the low three hold a high surrogate until its other half arrives.
22
+function nextTerminalSequenceState(state: number, unit: number): number {
23
+ if (unit === 0x1b) return SEQUENCE_ESCAPE;
24
+ if (state === TERMINAL_SEQUENCE_GROUND || unit === 0x18 || unit === 0x1a) {
25
+ return TERMINAL_SEQUENCE_GROUND;
26
+ }
27
+ let mode = state & 7;
28
+ if (unit < 0x80) {
29
+ switch (mode) {
30
+ case SEQUENCE_ESCAPE:
31
+ if (unit < 0x20 || unit === 0x7f) return mode;
32
+ if (unit < 0x30) return SEQUENCE_ESCAPE_INTERMEDIATE;
33
+ if (unit === 0x5b) return SEQUENCE_CSI;
34
+ if (unit === 0x5d) return SEQUENCE_OSC;
35
+ if (unit === 0x50) return SEQUENCE_DCS;
36
+ return unit === 0x58 || unit === 0x5e || unit === 0x5f
37
+ ? SEQUENCE_SOS_PM_APC
38
+ : TERMINAL_SEQUENCE_GROUND;
39
+ case SEQUENCE_ESCAPE_INTERMEDIATE:
40
+ return unit >= 0x30 && unit !== 0x7f ? TERMINAL_SEQUENCE_GROUND : mode;
41
+ case SEQUENCE_CSI:
42
+ return unit >= 0x40 && unit !== 0x7f ? TERMINAL_SEQUENCE_GROUND : mode;
43
+ case SEQUENCE_OSC:
44
+ return unit === 0x07 ? TERMINAL_SEQUENCE_GROUND : mode;
45
+ default:
46
+ return mode;
47
+ }
48
+ }
49
+ if (mode === SEQUENCE_OSC) return mode;
50
+ if (unit >= 0xd800 && unit <= 0xdbff) return mode | (unit << 3);
51
+ let codePoint = unit;
52
+ if (unit >= 0xdc00 && unit <= 0xdfff) {
53
+ if (state < 8) return mode;
54
+ codePoint = 0x10000 + (((state >> 3) - 0xd800) << 10) + (unit - 0xdc00);
55
+ }
56
+ // Outside ground and OSC the parser reads UTF-8 bytes one at a time, so a continuation
57
+ // byte in 0x80-0x9F acts as a C1 control: most end the sequence, five start another.
58
+ for (let shift = codePoint > 0xffff ? 12 : codePoint > 0x7ff ? 6 : 0; shift >= 0; shift -= 6) {
59
+ const byte = 0x80 | ((codePoint >> shift) & 0x3f);
60
+ if (byte >= 0xa0) continue;
61
+ if (byte === 0x9d) return SEQUENCE_OSC;
62
+ if (byte === 0x90) mode = SEQUENCE_DCS;
63
+ else if (byte === 0x9b) mode = SEQUENCE_CSI;
64
+ else if (byte === 0x98 || byte >= 0x9e) mode = SEQUENCE_SOS_PM_APC;
65
+ else return TERMINAL_SEQUENCE_GROUND;
66
+ }
67
+ return mode;
68
+}
69
+
70
+/** The parser state after `text.slice(start, end)`, for a terminal that entered it in `state`. */
71
+export function terminalSequenceStateAfter(
72
+ state: number,
73
+ text: string,
74
+ start = 0,
75
+ end = text.length,
76
+): number {
77
+ if (end <= start) return state;
78
+ // ESC enters the escape state from every state, so only what follows the last one matters.
79
+ const escape = text.lastIndexOf("\u001b", end - 1);
80
+ if (escape >= start) {
81
+ state = SEQUENCE_ESCAPE;
82
+ start = escape + 1;
83
+ }
84
+ for (let index = start; index < end && state !== TERMINAL_SEQUENCE_GROUND; index += 1) {
85
+ state = nextTerminalSequenceState(state, text.charCodeAt(index));
86
+ }
87
+ return state;
88
+}
89
+
90
+/** Where in `text` a terminal that entered it in `state` is first back in ground state. */
91
+export function terminalSequenceEnd(state: number, text: string): number {
92
+ let index = 0;
93
+ while (state !== TERMINAL_SEQUENCE_GROUND && index < text.length) {
94
+ state = nextTerminalSequenceState(state, text.charCodeAt(index));
95
+ index += 1;
96
+ }
97
+ return index;
98
+}
99
+
100
+/**
101
+ * The final `maxBytes` of UTF-8 a client retains, starting at a code point boundary and
102
+ * outside any control sequence the cut went through.
103
+ */
104
export function retainedTerminalHistory(history: string, maxBytes: number): string {
105
if (maxBytes <= 0) {
106
return "";
@@ -29,7 +120,14 @@ export function retainedTerminalHistory(history: string, maxBytes: number): stri
120
start += 1;
121
}
122
32
- return historyDecoder.decode(encoded.subarray(start));
123
+ const retained = historyDecoder.decode(encoded.subarray(start));
124
+ const state = terminalSequenceStateAfter(
125
+ TERMINAL_SEQUENCE_GROUND,
126
+ history,
127
+ 0,
128
+ history.length - retained.length,
129
+ );
130
+ return retained.slice(terminalSequenceEnd(state, retained));
131
}
132
133
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;