The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): replace stateless PTY regex with tested PtyResumeSanitizer stream helper
灵越羽毛88e67508bc57
diff --git a/web/src/lib/pty-resume-sanitizer.test.ts b/web/src/lib/pty-resume-sanitizer.test.tsnew file mode 100644index 00000000000..85834da1ca3--- /dev/null+++ b/web/src/lib/pty-resume-sanitizer.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from "vitest";+import { applyPtyFilters, PtyResumeSanitizer } from "./pty-resume-sanitizer";++describe("applyPtyFilters", () => {+ it("passes through normal text unchanged", () => {+ const input = "hello world\nfoo bar\n";+ expect(applyPtyFilters(input)).toBe(input);+ });++ it("collapses pathological blank-line bursts (≥50 newlines)", () => {+ const burst = "a\n" + "\n".repeat(100) + "b\n";+ const result = applyPtyFilters(burst);+ // Burst collapsed to "\n\n", surrounding text preserved+ expect(result).toBe("a\n\nb\n");+ // Verify no CSI masking+ expect(result).not.toContain("\x1b");+ });++ it("leaves short blank-line runs untouched", () => {+ const short = "a\n\n\nb\n"; // 3 newlines+ expect(applyPtyFilters(short)).toBe(short);+ });++ it("strips erase-line CSI sequences", () => {+ expect(applyPtyFilters("hello\x1b[K world")).toBe("hello world");+ expect(applyPtyFilters("foo\x1b[2Kbar")).toBe("foobar");+ expect(applyPtyFilters("\x1b[K")).toBe("");+ });++ it("strips erase-char CSI sequences", () => {+ expect(applyPtyFilters("abc\x1b[3Xdef")).toBe("abcdef");+ expect(applyPtyFilters("\x1b[X")).toBe("");+ });++ it("leaves normal SGR sequences untouched", () => {+ // \x1b[31m (red), \x1b[0m (reset) — must not be removed+ const input = "\x1b[31mred text\x1b[0m\n";+ expect(applyPtyFilters(input)).toBe(input);+ });++ it("handles empty string", () => {+ expect(applyPtyFilters("")).toBe("");+ });++ it("handles mixed CSI and newlines correctly", () => {+ const input = "line1\x1b[K\n" + "\n".repeat(60) + "line2\x1b[2X\n";+ const result = applyPtyFilters(input);+ expect(result).toBe("line1\n\nline2\n");+ expect(result).not.toContain("\x1b");+ });+});++describe("PtyResumeSanitizer — stateful frame handling", () => {+ it("processes a complete chunk in one frame", () => {+ const s = new PtyResumeSanitizer();+ expect(s.next("hello\n")).toBe("hello\n");+ expect(s.flush()).toBe("");+ });++ it("buffers a trailing partial escape and resolves in next frame", () => {+ const s = new PtyResumeSanitizer();+ // Frame 1 ends mid-CSI+ const out1 = s.next("hello\x1b[");+ expect(out1).toBe("hello"); // partial buffered, not emitted++ // Frame 2 completes the CSI+ const out2 = s.next("2K world\n");+ expect(out2).toBe(" world\n"); // erase-line stripped+ expect(s.flush()).toBe("");+ });++ it("buffers bare \\x1b and resolves on completion", () => {+ const s = new PtyResumeSanitizer();+ expect(s.next("before\x1b")).toBe("before");+ expect(s.next("[Kafter")).toBe("after");+ });++ it("buffers \\x1b[\\d+ prefix and resolves", () => {+ const s = new PtyResumeSanitizer();+ expect(s.next("x\x1b[4")).toBe("x");+ expect(s.next("2Ky")).toBe("y");+ });++ it("passes through when no partial escape is buffered", () => {+ const s = new PtyResumeSanitizer();+ expect(s.next("chunk1\n")).toBe("chunk1\n");+ expect(s.next("chunk2\n")).toBe("chunk2\n");+ });++ it("collapses a pathological newline burst within a single frame", () => {+ const s = new PtyResumeSanitizer();+ // 60 newlines in one frame triggers the 50+ threshold+ const out = s.next("start\n" + "\n".repeat(60) + "end\n");+ expect(out).toBe("start\n\nend\n");+ });++ it("drains buffered partial on flush", () => {+ const s = new PtyResumeSanitizer();+ s.next("trailing\x1b[");+ // Connection closes — flush drains the incomplete partial.+ // Bare \x1b[ is not a complete CSI (missing terminal letter), so it passes through.+ expect(s.flush()).toBe("\x1b[");+ });++ it("resets state across instances", () => {+ const a = new PtyResumeSanitizer();+ a.next("\x1b[");+ const b = new PtyResumeSanitizer();+ // [K without \x1b prefix is literal text, not a CSI code+ expect(b.next("[Khello")).toBe("[Khello");+ expect(a.flush()).toBe("\x1b[");+ });++ it("handles empty chunk without disturbing pending buffer", () => {+ const s = new PtyResumeSanitizer();+ s.next("before\x1b[");+ expect(s.next("")).toBe(""); // empty → no output, pending preserved+ expect(s.next("2Kafter")).toBe("after");+ });++ it("handles consecutive split escapes across three frames", () => {+ const s = new PtyResumeSanitizer();+ expect(s.next("a\x1b")).toBe("a");+ expect(s.next("[")).toBe("");+ expect(s.next("2Kb")).toBe("b");+ });+});diff --git a/web/src/lib/pty-resume-sanitizer.ts b/web/src/lib/pty-resume-sanitizer.tsnew file mode 100644index 00000000000..773150fc933--- /dev/null+++ b/web/src/lib/pty-resume-sanitizer.ts@@ -0,0 +1,59 @@+/**+ * PTY resume output sanitizer — strips pathological ANSI sequences that+ * Ink's two-pass virtual scroll emits during session resume.+ *+ * The PTY is delivered as individual WebSocket frames. A CSI escape+ * sequence may be split across frames, and UTF-8 multi-byte chars may+ * span binary frames. This helper buffers incomplete payloads so the+ * regex transformers always operate on safely-completed input.+ */++const BLANK_LINE_BURST = /\n{50,}/g;+// eslint-disable-next-line no-control-regex -- intentional ESC byte in ANSI sequence parser+const ERASE_LINE = /\x1b\[\d*K/g;+// eslint-disable-next-line no-control-regex+const ERASE_CHAR = /\x1b\[\d*X/g;++/** Regex for a still-incomplete trailing escape: "\x1b", "\x1b[", "\x1b[\d*". */+// eslint-disable-next-line no-control-regex+const PARTIAL_ESC = /^\x1b(?:\[\d*)?$/;++/**+ * Apply all suppression rules to a safely-completed string.+ * Exported for focused unit-testing of filter behaviour.+ */+export function applyPtyFilters(input: string): string {+ return input+ .replace(BLANK_LINE_BURST, "\n\n")+ .replace(ERASE_LINE, "")+ .replace(ERASE_CHAR, "");+}++/** Stateful chunk processor that guards against cross-frame split sequences. */+export class PtyResumeSanitizer {+ #pending = "";++ /** Feed one decoded WebSocket frame payload. Returns the sanitized output. */+ next(chunk: string): string {+ const combined = this.#pending + chunk;+ const lastEsc = combined.lastIndexOf("\x1b");+ if (lastEsc === -1) {+ this.#pending = "";+ return applyPtyFilters(combined);+ }+ const tail = combined.slice(lastEsc);+ if (PARTIAL_ESC.test(tail)) {+ this.#pending = tail;+ return applyPtyFilters(combined.slice(0, lastEsc));+ }+ this.#pending = "";+ return applyPtyFilters(combined);+ }++ /** Drain and sanitize any remaining buffered partial escape. */+ flush(): string {+ const last = this.#pending;+ this.#pending = "";+ return applyPtyFilters(last);+ }+}diff --git a/web/src/pages/ChatPage.tsx b/web/src/pages/ChatPage.tsxindex 3c119c70b23..7727e9d9231 100644--- a/web/src/pages/ChatPage.tsx+++ b/web/src/pages/ChatPage.tsx@@ -37,6 +37,7 @@ import { useI18n } from "@/i18n";import { api } from "@/lib/api";import { latchChatActivation } from "@/lib/chat-activation";import { normalizeSessionTitle } from "@/lib/chat-title";+import { PtyResumeSanitizer } from "@/lib/pty-resume-sanitizer";import {PTY_CONNECTING_TIMEOUT_MS,PTY_RECONNECT_INPUT_MESSAGE,@@ -989,27 +990,25 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {}};- // Session resume: strip ANSI codes that Ink's two-pass virtual- // scroll unmount emits into the PTY stream (blank-line bursts,- // erase-line, erase-char). Gate on resumeParam so short/new- // sessions never see the filter.+ // Session resume: strip pathological ANSI sequences that Ink's+ // two-pass virtual scroll emits into the PTY stream.+ // See pty-resume-sanitizer.ts for the stateful stream helper.const decoder = new TextDecoder();- const sanitizeResumeOutput = (raw: string): string =>- resumeParam- ? raw.replace(/\n{3,}/g, "\n\n")- .replace(/\x1b\[\d*K/g, "")- .replace(/\x1b\[\d*X/g, "")- : raw;+ const sanitizer = new PtyResumeSanitizer();ws.onmessage = (ev) => {const text =typeof ev.data === "string"? ev.data- : decoder.decode(new Uint8Array(ev.data as ArrayBuffer));- term.write(sanitizeResumeOutput(text));+ : decoder.decode(new Uint8Array(ev.data as ArrayBuffer), {stream: true});+ term.write(resumeParam ? sanitizer.next(text) : text);};ws.onclose = (ev) => {+ // Flush any buffered partial escape sequence from the sanitizer.+ if (resumeParam) {+ try { term.write(sanitizer.flush()); } catch { /* ignore */ }+ }wsRef.current = null;connectInFlightRef.current = false;clearConnectingTimer();