From b8502b21bbcc50280aa088ad1f5dff98ff9f3ba4 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 17 Jul 2026 23:57:24 -0700 Subject: [PATCH] perf(terminal): bound recent-PTY-output with a chunk deque (drop per-chunk 64KB concat) (#9291) Co-authored-by: Orca --- src/main/runtime/orca-runtime.test.ts | 19 +- src/main/runtime/orca-runtime.ts | 25 +-- .../runtime/recent-pty-output-buffer.test.ts | 184 ++++++++++++++++++ src/main/runtime/recent-pty-output-buffer.ts | 72 +++++++ 4 files changed, 280 insertions(+), 20 deletions(-) create mode 100644 src/main/runtime/recent-pty-output-buffer.test.ts create mode 100644 src/main/runtime/recent-pty-output-buffer.ts diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index aaf705c45..44bb1117c 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -47,7 +47,6 @@ import type { OrchestrationDb } from './orchestration/db' import type { MessagePriority, MessageRow, MessageType } from './orchestration/types' import { appendNormalizedToTailBuffer, - appendRecentPtyOutput, appendRecentPtyPathCandidates, buildPreview, OrcaRuntimeService, @@ -55,6 +54,7 @@ import { recentTerminalOutputIncludesPath, type RuntimeTerminalAgentStatusEvent } from './orca-runtime' +import { RecentPtyOutputBuffer } from './recent-pty-output-buffer' import { HeadlessEmulator } from '../daemon/headless-emulator' import { HEADLESS_RUNTIME_WINDOW_ID, @@ -13549,11 +13549,20 @@ describe('OrcaRuntimeService', () => { const previous = 'old-output'.repeat(1000) const data = 'new-output'.repeat(1000) const outputLimit = 64 * 1024 - const expected = `${previous}${data}`.slice(-outputLimit) - expect(appendRecentPtyOutput(previous, 'tail')).toBe(`${previous}tail`.slice(-outputLimit)) - expect(appendRecentPtyOutput(previous, data)).toBe(expected) - expect(appendRecentPtyOutput(undefined, data)).toBe(data.slice(-outputLimit)) + const smallTail = new RecentPtyOutputBuffer() + smallTail.append(previous) + smallTail.append('tail') + expect(smallTail.read()).toBe(`${previous}tail`.slice(-outputLimit)) + + const combined = new RecentPtyOutputBuffer() + combined.append(previous) + combined.append(data) + expect(combined.read()).toBe(`${previous}${data}`.slice(-outputLimit)) + + const fresh = new RecentPtyOutputBuffer() + fresh.append(data) + expect(fresh.read()).toBe(data.slice(-outputLimit)) }) it('keeps mobile-visible artifact paths in bounded PTY path candidates', () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9a7f29cef..60160117a 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -345,6 +345,7 @@ import type { import type { AutomationService } from '../automations/service' import { RuntimeBrowserCommands } from './orca-runtime-browser' import { buildHeadlessTerminalSplitLayout } from './headless-terminal-split-layout' +import { RecentPtyOutputBuffer } from './recent-pty-output-buffer' import { buildHeadlessTabGroupMove, buildHeadlessTabGroupSplit @@ -1320,7 +1321,6 @@ const BRACKETED_PASTE_QUIET_MS = 1500 const DRAFT_PASTE_READY_TIMEOUT_MS = 8000 const MOBILE_TERMINAL_SURFACE_TIMEOUT_MS = 10_000 const MOBILE_TERMINAL_READY_FALLBACK_MS = 1000 -const RECENT_PTY_OUTPUT_LIMIT = 64 * 1024 const RECENT_PTY_PATH_CANDIDATE_LIMIT = 1024 const RECENT_PTY_PATH_CANDIDATE_MAX_BYTES = 4 * 1024 const RECENT_PTY_PATH_CANDIDATE_TOTAL_BYTES = 64 * 1024 @@ -2283,7 +2283,7 @@ export class OrcaRuntimeService { >() // Why: startup draft paste can subscribe after the agent already emitted its // ready marker. Keep a bounded raw buffer so fast startup output is replayed. - private recentPtyOutputById = new Map() + private recentPtyOutputById = new Map() // Why: mobile clients need to know when the desktop restores a terminal // from mobile-fit so they can update their UI. These listeners are // invoked from resizeForClient and onClientDisconnected/onPtyExit. @@ -8119,10 +8119,12 @@ export class OrcaRuntimeService { } private recordRecentPtyOutputForPathProvenance(ptyId: string, data: string): void { - this.recentPtyOutputById.set( - ptyId, - appendRecentPtyOutput(this.recentPtyOutputById.get(ptyId), data) - ) + let recentOutputBuffer = this.recentPtyOutputById.get(ptyId) + if (!recentOutputBuffer) { + recentOutputBuffer = new RecentPtyOutputBuffer() + this.recentPtyOutputById.set(ptyId, recentOutputBuffer) + } + recentOutputBuffer.append(data) this.recentPtyPathCandidatesById.set( ptyId, appendRecentPtyPathCandidates(this.recentPtyPathCandidatesById.get(ptyId), data) @@ -8160,7 +8162,7 @@ export class OrcaRuntimeService { hasRecentTerminalOutputPath(handle: string, pathText: string, absolutePath: string): boolean { const ptyId = this.resolveLeafForHandle(handle)?.ptyId - const recentOutput = ptyId ? this.recentPtyOutputById.get(ptyId) : null + const recentOutput = ptyId ? this.recentPtyOutputById.get(ptyId)?.read() : null if (recentOutput && recentTerminalOutputIncludesPath(recentOutput, pathText, absolutePath)) { return true } @@ -15785,7 +15787,7 @@ export class OrcaRuntimeService { } unsubscribe = this.subscribeToTerminalData(ptyId, observeData) - const replay = this.recentPtyOutputById.get(ptyId) + const replay = this.recentPtyOutputById.get(ptyId)?.read() if (replay) { observeData(replay) } @@ -26417,13 +26419,6 @@ function withTimeoutResult( ) } -export function appendRecentPtyOutput(previous: string | undefined, data: string): string { - if (data.length >= RECENT_PTY_OUTPUT_LIMIT) { - return data.slice(-RECENT_PTY_OUTPUT_LIMIT) - } - return `${previous ?? ''}${data}`.slice(-RECENT_PTY_OUTPUT_LIMIT) -} - export function appendRecentPtyPathCandidates( previous: string[] | undefined, data: string diff --git a/src/main/runtime/recent-pty-output-buffer.test.ts b/src/main/runtime/recent-pty-output-buffer.test.ts new file mode 100644 index 000000000..1778c7aee --- /dev/null +++ b/src/main/runtime/recent-pty-output-buffer.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it, vi } from 'vitest' +import { RECENT_PTY_OUTPUT_LIMIT, RecentPtyOutputBuffer } from './recent-pty-output-buffer' + +// Reference implementation: the old eager rolling-string append the buffer +// replaced. read() must stay byte-identical to this for any chunk sequence. +function referenceAppend(previous: string | undefined, data: string): string { + if (data.length >= RECENT_PTY_OUTPUT_LIMIT) { + return data.slice(-RECENT_PTY_OUTPUT_LIMIT) + } + return `${previous ?? ''}${data}`.slice(-RECENT_PTY_OUTPUT_LIMIT) +} + +function referenceTail(chunks: string[]): string { + let tail: string | undefined + for (const chunk of chunks) { + tail = referenceAppend(tail, chunk) + } + return tail ?? '' +} + +function bufferTail(chunks: string[]): string { + const buffer = new RecentPtyOutputBuffer() + for (const chunk of chunks) { + buffer.append(chunk) + } + return buffer.read() +} + +function expectEquivalent(chunks: string[]): void { + expect(bufferTail(chunks)).toBe(referenceTail(chunks)) +} + +function mulberry32(seed: number): () => number { + let a = seed >>> 0 + return () => { + a = (a + 0x6d2b79f5) | 0 + let t = Math.imul(a ^ (a >>> 15), 1 | a) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +describe('RecentPtyOutputBuffer', () => { + it('returns an empty string before any append', () => { + expect(new RecentPtyOutputBuffer().read()).toBe('') + expectEquivalent([]) + }) + + it('accumulates chunks below the cap verbatim', () => { + const chunks = ['hello ', 'world', '\r\n', 'prompt $ '] + expect(bufferTail(chunks)).toBe('hello world\r\nprompt $ ') + expectEquivalent(chunks) + }) + + it('ignores empty chunks', () => { + expectEquivalent(['', 'abc', '', 'def', '']) + }) + + it('trims exactly at a chunk boundary when the cap is crossed', () => { + const half = 'a'.repeat(RECENT_PTY_OUTPUT_LIMIT / 2) + // Third half-cap chunk should evict the first chunk entirely. + const chunks = [half, 'b'.repeat(RECENT_PTY_OUTPUT_LIMIT / 2), 'c'.repeat(half.length)] + const tail = bufferTail(chunks) + expect(tail.length).toBe(RECENT_PTY_OUTPUT_LIMIT) + expect(tail.startsWith('b')).toBe(true) + expectEquivalent(chunks) + }) + + it('truncates the boundary chunk when the cap is crossed mid-chunk', () => { + const chunks = ['x'.repeat(RECENT_PTY_OUTPUT_LIMIT - 10), `head-tail-${'y'.repeat(20)}`] + const tail = bufferTail(chunks) + expect(tail.length).toBe(RECENT_PTY_OUTPUT_LIMIT) + expect(tail.endsWith('y'.repeat(20))).toBe(true) + expectEquivalent(chunks) + }) + + it('keeps only the last cap-sized slice of a single oversized chunk', () => { + const oversized = `${'z'.repeat(RECENT_PTY_OUTPUT_LIMIT)}${'w'.repeat(100)}` + expect(bufferTail([oversized])).toBe(oversized.slice(-RECENT_PTY_OUTPUT_LIMIT)) + expectEquivalent([oversized]) + // An oversized chunk must also discard everything buffered before it. + expectEquivalent(['earlier output', oversized, 'later']) + // Exactly cap-sized hits the old fast path too. + expectEquivalent(['before', 'q'.repeat(RECENT_PTY_OUTPUT_LIMIT)]) + }) + + it('stays byte-identical across many small chunks that trim repeatedly', () => { + const rng = mulberry32(0x5eed) + const chunks = Array.from({ length: 5000 }, (_, i) => { + const len = 1 + Math.floor(rng() * 120) + return `${i}:${String.fromCharCode(97 + (i % 26)).repeat(len)}\n` + }) + expectEquivalent(chunks) + }) + + it('matches the old UTF-16 slice behavior for multi-byte content at the boundary', () => { + // JS string .slice counts UTF-16 code units, so trimming can split a + // surrogate pair; the buffer must reproduce that split exactly. + const emoji = '\u{1f600}' // 2 code units + const filler = 'f'.repeat(RECENT_PTY_OUTPUT_LIMIT - 1) + const chunks = [emoji.repeat(3), filler] + const tail = bufferTail(chunks) + expect(tail).toBe(referenceTail(chunks)) + // The old code left a lone trailing low surrogate at the front. + expect(tail.charCodeAt(0)).toBe(0xde00) + expectEquivalent(['多字节内容', emoji.repeat(2000), filler, emoji]) + }) + + it('read() is idempotent and append continues correctly after a read', () => { + const buffer = new RecentPtyOutputBuffer() + buffer.append('one') + buffer.append('two') + expect(buffer.read()).toBe('onetwo') + expect(buffer.read()).toBe('onetwo') + buffer.append('three') + expect(buffer.read()).toBe('onetwothree') + buffer.append('x'.repeat(RECENT_PTY_OUTPUT_LIMIT)) + expect(buffer.read()).toBe('x'.repeat(RECENT_PTY_OUTPUT_LIMIT)) + }) + + it('trims after an interspersed read without slicing the head per append', () => { + const buffer = new RecentPtyOutputBuffer() + const fill = 'f'.repeat(RECENT_PTY_OUTPUT_LIMIT) + buffer.append(fill) + // Collapse to a single cap-sized head chunk, the reviewer's scenario. + expect(buffer.read()).toBe(fill) + + const appendCount = 1000 + const smallChunks = Array.from({ length: appendCount }, (_, i) => + String.fromCharCode(33 + (i % 90)) + ) + let reference = fill + for (const chunk of smallChunks) { + reference = referenceAppend(reference, chunk) + } + + // Every append now trims one code unit off the full head; none of them + // may allocate a head substring — the trim must be a deferred offset. + const sliceSpy = vi.spyOn(String.prototype, 'slice') + try { + for (const chunk of smallChunks) { + buffer.append(chunk) + } + expect(sliceSpy).not.toHaveBeenCalled() + } finally { + sliceSpy.mockRestore() + } + + expect(buffer.read()).toBe(reference) + expect(buffer.read().length).toBe(RECENT_PTY_OUTPUT_LIMIT) + }) + + it('stays byte-identical when reads intersperse repeated partial head trims', () => { + const buffer = new RecentPtyOutputBuffer() + let reference: string | undefined + const rng = mulberry32(0xdeadbeef) + for (let i = 0; i < 400; i++) { + const chunk = String.fromCharCode(97 + (i % 26)).repeat(1 + Math.floor(rng() * 300)) + buffer.append(chunk) + reference = referenceAppend(reference, chunk) + if (i % 7 === 0) { + expect(buffer.read()).toBe(reference ?? '') + } + } + expect(buffer.read()).toBe(reference ?? '') + }) + + it('stays equivalent under randomized chunk sizes straddling the cap', () => { + const rng = mulberry32(0xc0ffee) + for (let round = 0; round < 5; round++) { + const chunks: string[] = [] + const count = 20 + Math.floor(rng() * 60) + for (let i = 0; i < count; i++) { + const roll = rng() + const len = + roll < 0.1 + ? RECENT_PTY_OUTPUT_LIMIT + Math.floor(rng() * 200) - 100 + : Math.floor(rng() * 9000) + chunks.push(String.fromCharCode(33 + (i % 90)).repeat(Math.max(0, len))) + } + expectEquivalent(chunks) + } + }) +}) diff --git a/src/main/runtime/recent-pty-output-buffer.ts b/src/main/runtime/recent-pty-output-buffer.ts new file mode 100644 index 000000000..29af04f1d --- /dev/null +++ b/src/main/runtime/recent-pty-output-buffer.ts @@ -0,0 +1,72 @@ +export const RECENT_PTY_OUTPUT_LIMIT = 64 * 1024 + +// Compact the backing array once this many fully-dropped head slots accumulate, +// so the array itself stays bounded under long chunk floods. +const DROPPED_HEAD_COMPACT_THRESHOLD = 1024 + +/** + * Bounded deque of raw PTY output chunks retaining exactly the last + * RECENT_PTY_OUTPUT_LIMIT UTF-16 code units. + * + * Why: eagerly rebuilding a rolling 64KB string per PTY chunk flattened a + * ~128KB rope on every write; keep chunks and defer the join to rare readers. + */ +export class RecentPtyOutputBuffer { + private chunks: string[] = [] + private headIndex = 0 + // Code units already trimmed off the front of the head chunk. Deferred to + // read() so repeated small trims never allocate a substring per append. + private headOffset = 0 + private totalLen = 0 + + append(data: string): void { + if (data.length >= RECENT_PTY_OUTPUT_LIMIT) { + this.chunks = [data.slice(-RECENT_PTY_OUTPUT_LIMIT)] + this.headIndex = 0 + this.headOffset = 0 + this.totalLen = RECENT_PTY_OUTPUT_LIMIT + return + } + if (data.length === 0) { + return + } + this.chunks.push(data) + this.totalLen += data.length + while (this.totalLen > RECENT_PTY_OUTPUT_LIMIT) { + const headRemaining = this.chunks[this.headIndex].length - this.headOffset + const excess = this.totalLen - RECENT_PTY_OUTPUT_LIMIT + if (headRemaining <= excess) { + // Release the dropped chunk's reference; the slot is reclaimed on compaction. + this.chunks[this.headIndex] = '' + this.headIndex += 1 + this.headOffset = 0 + this.totalLen -= headRemaining + } else { + this.headOffset += excess + this.totalLen -= excess + } + } + if (this.headIndex >= DROPPED_HEAD_COMPACT_THRESHOLD) { + this.chunks = this.chunks.slice(this.headIndex) + this.headIndex = 0 + } + } + + read(): string { + if (this.chunks.length - this.headIndex > 1) { + // Collapse to the joined tail so repeated reads stay O(1). + const retained = this.chunks.slice(this.headIndex) + if (this.headOffset > 0) { + retained[0] = retained[0].slice(this.headOffset) + this.headOffset = 0 + } + this.chunks = [retained.join('')] + this.headIndex = 0 + } else if (this.headOffset > 0) { + // Single retained chunk: apply the deferred head trim once, here. + this.chunks[this.headIndex] = this.chunks[this.headIndex].slice(this.headOffset) + this.headOffset = 0 + } + return this.chunks[this.headIndex] ?? '' + } +}