Skip to content
TypeScript

fix(shared): command output no longer prints the final byte of escape sequences with intermediates (#30724)

TheGuyWithHATcd890ba34699
diff --git a/packages/shared/src/terminalOutput.test.ts b/packages/shared/src/terminalOutput.test.ts
index adb4ae061bc..e174e936b17 100644
--- a/packages/shared/src/terminalOutput.test.ts
+++ b/packages/shared/src/terminalOutput.test.ts
@@ -131,6 +131,24 @@ describe("appendTerminalOutput under adversarial output", () => {
}
});
+ it("drops escape sequences with intermediate bytes without printing their final byte", () => {
+ for (const sequence of ["#8", "#6", "%G", " F", "-A", ".A", "(%5", "(B"]) {
+ const input = `a\u001b${sequence}b`;
+ expect(feed([input]).text).toBe("ab");
+ for (let cut = 1; cut < input.length; cut += 1) {
+ expect(feed([input.slice(0, cut), input.slice(cut)]).text).toBe("ab");
+ }
+ }
+ for (const [interrupted, expected] of [
+ ["a\u001b#\u001b[31mb", feed(["a\u001b[31mb"]).text],
+ ["a\u001b#\n8b", "a\n8b"],
+ ] as const) {
+ for (let cut = 0; cut < interrupted.length; cut += 1) {
+ expect(feed([interrupted.slice(0, cut), interrupted.slice(cut)]).text).toBe(expected);
+ }
+ }
+ });
+
it("gives the same result however the output is split into chunks", () => {
const input =
"abcdef\rX\u001b[31mred\u001b[0m\nnext line\r\u001b[2Kdone\n" +
diff --git a/packages/shared/src/terminalOutput.ts b/packages/shared/src/terminalOutput.ts
index 5edeb250971..a43e7377d82 100644
--- a/packages/shared/src/terminalOutput.ts
+++ b/packages/shared/src/terminalOutput.ts
@@ -268,11 +268,20 @@ function escapeLength(input: string, index: number): number {
}
return -1;
}
- // Charset designations take three bytes; other sequences take two.
- if (next === "(" || next === ")" || next === "*" || next === "+") {
- return index + 2 < input.length ? 3 : -1;
+ // ECMA-35: any intermediate bytes (0x20-0x2F, e.g. charset designations, DECALN) precede one final byte.
+ let cursor = index + 1;
+ while (
+ cursor < input.length &&
+ input.charCodeAt(cursor) >= 0x20 &&
+ input.charCodeAt(cursor) <= 0x2f
+ ) {
+ cursor += 1;
}
- return 2;
+ if (cursor >= input.length) return -1;
+ // After intermediates, a control or ESC is not a final byte; end before it so it is still processed.
+ const final = input.charCodeAt(cursor);
+ if (cursor > index + 1 && (final < 0x30 || final > 0x7e)) return cursor - index;
+ return cursor - index + 1;
}
const penTransitions = new Map<string, string>();