TypeScript
perf(acp): avoid re-encoding terminal output for every chunk (#19607)
Wout Stiens9d4038f73189
diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.tsindex 49f94117217..a10ac2c7e27 100644--- a/packages/provider-acp/src/server/runtimeModel.test.ts+++ b/packages/provider-acp/src/server/runtimeModel.test.ts@@ -1251,6 +1251,7 @@ describe("AcpRuntimeModel", () => {command: "pnpm test",cwd: "/workspace",output: "first line\nsecond line\n",+ outputBytes: 23,exitStatus: { exitCode: 0 },});});@@ -1274,6 +1275,51 @@ describe("AcpRuntimeModel", () => {expect(second.pendingOutputBytes).toBeUndefined();});+ it("keeps the newest 16 MiB of ACP terminal output at a UTF-8 boundary", () => {+ const cap = 16 * 1024 * 1024;+ const chunk = (text: string | Uint8Array) => ({+ sessionUpdate: "terminal_output_chunk" as const,+ terminalId: "terminal-cap",+ data: Buffer.from(text).toString("base64"),+ });+ const seeded = applyAcpAgentTerminalUpdate(undefined, {+ sessionUpdate: "terminal_update",+ terminalId: "terminal-cap",+ output: { data: Buffer.from(`é${"a".repeat(cap - 3)}`).toString("base64") },+ });+ expect(seeded.outputBytes).toBe(cap - 1);++ // One byte over the cap falls inside "é", so the whole character is dropped.+ const trimmed = applyAcpAgentTerminalUpdate(seeded, chunk("bc"));+ expect(trimmed.output.length).toBe(cap - 1);+ expect(trimmed.output.slice(0, 2)).toBe("aa");+ expect(trimmed.output.slice(-3)).toBe("abc");+ expect(trimmed.outputBytes).toBe(cap - 1);++ const emoji = applyAcpAgentTerminalUpdate(trimmed, chunk("🙂"));+ expect(emoji.output.slice(-5)).toBe("abc🙂");+ expect(emoji.outputBytes).toBe(cap);+ expect(Buffer.byteLength(emoji.output)).toBe(cap);++ // Exit flushes an incomplete trailing character and trims again.+ const pending = applyAcpAgentTerminalUpdate(emoji, chunk(Buffer.from("🙂").subarray(0, 2)));+ const exited = applyAcpAgentTerminalUpdate(pending, {+ sessionUpdate: "terminal_update",+ terminalId: "terminal-cap",+ exitStatus: { exitCode: 1 },+ });+ expect(exited.output.slice(-4)).toBe("c🙂\uFFFD");+ expect(exited.outputBytes).toBe(Buffer.byteLength(exited.output));+ expect(exited.outputBytes).toBeLessThanOrEqual(cap);++ const cleared = applyAcpAgentTerminalUpdate(exited, {+ sessionUpdate: "terminal_update",+ terminalId: "terminal-cap",+ output: null,+ });+ expect(cleared).toMatchObject({ output: "", outputBytes: 0, exitStatus: { exitCode: 1 } });+ });+it("drops malformed and oversized ACP terminal frames without decoding them", () => {const seeded = applyAcpAgentTerminalUpdate(undefined, {sessionUpdate: "terminal_output_chunk",diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.tsindex f940b9bf2c0..b6f6f1423ce 100644--- a/packages/provider-acp/src/server/runtimeModel.ts+++ b/packages/provider-acp/src/server/runtimeModel.ts@@ -50,6 +50,8 @@ export interface AcpAgentTerminalState {readonly command?: string;readonly cwd?: string;readonly output: string;+ /** UTF-8 byte length of `output`, so appending a chunk never re-encodes the buffer. */+ readonly outputBytes: number;readonly exitStatus?: EffectAcpSchema.TerminalExitStatus;readonly pendingOutputBytes?: Uint8Array;}@@ -126,26 +128,43 @@ function decodeTerminalOutputChunk(: { text, pendingOutputBytes: Uint8Array.from(bytes.subarray(completeEnd)) };}-function truncateTerminalOutput(output: string): string {- const bytes = Buffer.from(output, "utf8");- if (bytes.length <= MAX_ACP_TERMINAL_OUTPUT_BYTES) return output;- let start = bytes.length - MAX_ACP_TERMINAL_OUTPUT_BYTES;- while (start < bytes.length && (bytes[start]! & 0xc0) === 0x80) start += 1;- return bytes.subarray(start).toString("utf8");+/**+ * Appends decoded text to terminal output and keeps the newest+ * `MAX_ACP_TERMINAL_OUTPUT_BYTES`, dropping whole leading characters. Only the+ * appended text and the dropped prefix are measured, so per-chunk cost does not+ * grow with the retained output.+ */+function appendTerminalOutput(+ output: string,+ outputBytes: number,+ text: string,+): Pick<AcpAgentTerminalState, "output" | "outputBytes"> {+ const combined = `${output}${text}`;+ const combinedBytes = outputBytes + Buffer.byteLength(text, "utf8");+ const excess = combinedBytes - MAX_ACP_TERMINAL_OUTPUT_BYTES;+ if (excess <= 0) return { output: combined, outputBytes: combinedBytes };+ let start = 0;+ let dropped = 0;+ while (dropped < excess) {+ const codePoint = combined.codePointAt(start)!;+ dropped += codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;+ start += codePoint < 0x10000 ? 1 : 2;+ }+ return { output: combined.slice(start), outputBytes: combinedBytes - dropped };}export function applyAcpAgentTerminalUpdate(previous: AcpAgentTerminalState | undefined,update: AcpAgentTerminalUpdate,): AcpAgentTerminalState {- const current = previous ?? { output: "" };+ const current = previous ?? { output: "", outputBytes: 0 };if (update.sessionUpdate === "terminal_output_chunk") {const decoded = decodeTerminalOutputChunk(current.pendingOutputBytes, update.data);if (decoded === undefined) return current;const { pendingOutputBytes: _pendingOutputBytes, ...withoutPendingOutputBytes } = current;return {...withoutPendingOutputBytes,- output: truncateTerminalOutput(`${current.output}${decoded.text}`),+ ...appendTerminalOutput(current.output, current.outputBytes, decoded.text),...(decoded.pendingOutputBytes === undefined? {}: { pendingOutputBytes: decoded.pendingOutputBytes }),@@ -173,7 +192,7 @@ export function applyAcpAgentTerminalUpdate(const { pendingOutputBytes: _pendingOutputBytes, ...withoutPendingOutputBytes } = next;next = {...withoutPendingOutputBytes,- output: truncateTerminalOutput(decoded.text),+ ...appendTerminalOutput("", 0, decoded.text),...(decoded.pendingOutputBytes === undefined? {}: { pendingOutputBytes: decoded.pendingOutputBytes }),@@ -191,7 +210,7 @@ export function applyAcpAgentTerminalUpdate(const { pendingOutputBytes: _pendingOutputBytes, ...withoutPendingOutputBytes } = next;next = {...withoutPendingOutputBytes,- output: truncateTerminalOutput(`${next.output}${pendingText}`),+ ...appendTerminalOutput(next.output, next.outputBytes, pendingText),exitStatus: update.exitStatus,};}