From aa726382e805eace33e819d5c4ba8e37eadfdd44 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 2 Jun 2026 00:40:16 -0700 Subject: [PATCH] Revert "perf: keep hidden terminal output off typing path" (#4456) --- src/main/ipc/pty.test.ts | 152 ------------------ src/main/ipc/pty.ts | 88 +--------- .../terminal-pane/pty-connection.test.ts | 112 ++----------- .../terminal-pane/pty-connection.ts | 12 -- 4 files changed, 23 insertions(+), 341 deletions(-) diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 4da15a14b..2992a3496 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -3006,158 +3006,6 @@ describe('registerPtyHandlers', () => { } }) - it('holds background PTY output briefly after foreground input', async () => { - vi.useFakeTimers() - const activeProc = createMockProc() - const backgroundProc = createMockProc() - spawnMock.mockReturnValueOnce(activeProc.proc).mockReturnValueOnce(backgroundProc.proc) - - try { - registerPtyHandlers(mainWindow as never) - const activeSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const backgroundSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const writeListener = getPtyWriteListener() - mainWindow.webContents.send.mockClear() - - backgroundProc.emitData('background output') - writeListener(null, { - id: activeSpawn.id, - data: 'a' - }) - - vi.advanceTimersByTime(8) - expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - - activeProc.emitData('\x1b[20;2Hredraw') - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: activeSpawn.id, - data: '\x1b[20;2Hredraw' - }) - expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - - vi.advanceTimersByTime(41) - expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - - vi.advanceTimersByTime(1) - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - } finally { - vi.useRealTimers() - } - }) - - it('does not hold foreground PTY batch output behind background output', async () => { - vi.useFakeTimers() - const activeProc = createMockProc() - const backgroundProc = createMockProc() - spawnMock.mockReturnValueOnce(activeProc.proc).mockReturnValueOnce(backgroundProc.proc) - - try { - registerPtyHandlers(mainWindow as never) - const activeSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const backgroundSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const writeListener = getPtyWriteListener() - mainWindow.webContents.send.mockClear() - - backgroundProc.emitData('background output') - writeListener(null, { - id: activeSpawn.id, - data: 'a' - }) - const foregroundOutput = 'x'.repeat(1025) - activeProc.emitData(foregroundOutput) - - vi.advanceTimersByTime(8) - - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: activeSpawn.id, - data: foregroundOutput - }) - expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - } finally { - vi.useRealTimers() - } - }) - - it('does not starve background PTY output during continuous input', async () => { - vi.useFakeTimers() - const activeProc = createMockProc() - const backgroundProc = createMockProc() - spawnMock.mockReturnValueOnce(activeProc.proc).mockReturnValueOnce(backgroundProc.proc) - - try { - registerPtyHandlers(mainWindow as never) - const activeSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const backgroundSpawn = (await handlers.get('pty:spawn')!(null, { - cols: 80, - rows: 24, - cwd: '/tmp' - })) as { id: string } - const writeListener = getPtyWriteListener() - mainWindow.webContents.send.mockClear() - - backgroundProc.emitData('background output') - for (let index = 0; index < 7; index++) { - writeListener(null, { - id: activeSpawn.id, - data: 'a' - }) - vi.advanceTimersByTime(40) - } - expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - - writeListener(null, { - id: activeSpawn.id, - data: 'a' - }) - vi.advanceTimersByTime(10) - - expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', { - id: backgroundSpawn.id, - data: 'background output' - }) - } finally { - vi.useRealTimers() - } - }) - it('ignores PTY input for unknown sessions', async () => { vi.useFakeTimers() const mockProc = createMockProc() diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index f6a576ab9..db02bc40f 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -984,11 +984,6 @@ export function registerPtyHandlers( const INTERACTIVE_OUTPUT_MAX_CHARS = 1024 const INTERACTIVE_REDRAW_MAX_CHARS = PTY_BATCH_FLUSH_CHUNK_CHARS const INTERACTIVE_OUTPUT_BUDGET_CHARS = 32 * 1024 - const BACKGROUND_OUTPUT_INPUT_QUIET_MS = 50 - const BACKGROUND_OUTPUT_MAX_INPUT_HOLD_MS = 250 - let lastRendererInputAt = Number.NEGATIVE_INFINITY - let lastRendererInputPtyId: string | null = null - let backgroundFlushHeldSince: number | null = null function isLikelyInteractiveRedraw(data: string): boolean { if (data.length <= INTERACTIVE_OUTPUT_MAX_CHARS) { @@ -1060,32 +1055,15 @@ export function registerPtyHandlers( flushTimer = setTimeout(flushPendingData, delayMs) } - function hasRecentRendererInput(now: number): boolean { - return now - lastRendererInputAt < BACKGROUND_OUTPUT_INPUT_QUIET_MS - } - - function hasPendingDataOutsideRecentInputPty(): boolean { - for (const id of pendingData.keys()) { - if (id !== lastRendererInputPtyId) { - return true - } + function flushPendingData(): void { + flushTimer = null + if (mainWindow.isDestroyed()) { + pendingData.clear() + return } - return false - } - - function drainPendingDataEntries( - maxWrites: number, - shouldDrain: (id: string) => boolean = () => true - ): number { let writes = 0 - while (writes < maxWrites) { - let next: [string, PendingPtyData] | undefined - for (const entry of pendingData.entries()) { - if (shouldDrain(entry[0])) { - next = entry - break - } - } + while (pendingData.size > 0 && writes < PTY_BATCH_FLUSH_MAX_WRITES) { + const next = pendingData.entries().next().value if (!next) { break } @@ -1104,51 +1082,6 @@ export function registerPtyHandlers( mainWindow.webContents.send('pty:data', makePtyDataPayload(id, chunk, pending.startSeq)) writes++ } - return writes - } - - function shouldHoldBackgroundFlushForInput(now: number): boolean { - if ( - pendingData.size === 0 || - !hasRecentRendererInput(now) || - !hasPendingDataOutsideRecentInputPty() - ) { - backgroundFlushHeldSince = null - return false - } - backgroundFlushHeldSince ??= now - if (now - backgroundFlushHeldSince >= BACKGROUND_OUTPUT_MAX_INPUT_HOLD_MS) { - backgroundFlushHeldSince = null - return false - } - return true - } - - function flushPendingData(): void { - flushTimer = null - if (mainWindow.isDestroyed()) { - pendingData.clear() - return - } - const now = performance.now() - let writes = 0 - if (hasRecentRendererInput(now) && lastRendererInputPtyId !== null) { - writes += drainPendingDataEntries( - PTY_BATCH_FLUSH_MAX_WRITES, - (id) => id === lastRendererInputPtyId - ) - } - if (shouldHoldBackgroundFlushForInput(now)) { - // Why: hidden PTYs can keep producing output while the user types in a - // foreground TUI. Holding background IPC briefly lets those bytes - // coalesce instead of flooding the renderer ahead of key echo frames. - const quietDelay = Math.max(1, BACKGROUND_OUTPUT_INPUT_QUIET_MS - (now - lastRendererInputAt)) - schedulePendingDataFlush(quietDelay) - return - } - if (writes < PTY_BATCH_FLUSH_MAX_WRITES) { - writes += drainPendingDataEntries(PTY_BATCH_FLUSH_MAX_WRITES - writes) - } if (pendingData.size > 0) { // Why: a background terminal can dump megabytes at once. Yield between // small IPC slices so keystroke writes are not stuck behind one flush. @@ -1244,9 +1177,6 @@ export function registerPtyHandlers( } lastInputAtByPty.delete(payload.id) interactiveOutputCharsByPty.delete(payload.id) - if (lastRendererInputPtyId === payload.id) { - lastRendererInputPtyId = null - } mainWindow.webContents.send('pty:exit', payload) } }) @@ -2225,8 +2155,6 @@ export function registerPtyHandlers( } try { const now = performance.now() - lastRendererInputAt = now - lastRendererInputPtyId = args.id lastInputAtByPty.set(args.id, now) interactiveOutputCharsByPty.set(args.id, 0) provider.write(args.id, args.data) @@ -2253,8 +2181,6 @@ export function registerPtyHandlers( } try { const now = performance.now() - lastRendererInputAt = now - lastRendererInputPtyId = args.id lastInputAtByPty.set(args.id, now) interactiveOutputCharsByPty.set(args.id, 0) provider.write(args.id, args.data) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 9cef039f0..24d20009b 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -2759,42 +2759,18 @@ describe('connectPanePty', () => { ) }) - it('restores visible pane PTY bytes from the main snapshot when the document was hidden', async () => { - const visibilityListeners = new Set<() => void>() - const documentStub = { - visibilityState: 'hidden' as DocumentVisibilityState, - addEventListener: vi.fn((type: string, listener: EventListenerOrEventListenerObject) => { - if (type === 'visibilitychange' && typeof listener === 'function') { - visibilityListeners.add(listener as () => void) - } - }), - removeEventListener: vi.fn((type: string, listener: EventListenerOrEventListenerObject) => { - if (type === 'visibilitychange' && typeof listener === 'function') { - visibilityListeners.delete(listener as () => void) - } - }) + it('routes visible pane PTY bytes through the background scheduler when the document is hidden', async () => { + ;(globalThis as { document?: Pick }).document = { + visibilityState: 'hidden' } - ;(globalThis as { document?: Document }).document = documentStub as unknown as Document const { connectPanePty } = await import('./pty-connection') - const transport = createMockTransport('pty-id') - const capturedDataCallback: { - current: ((data: string, meta?: { seq?: number; rawLength?: number }) => void) | null - } = { current: null } + const transport = createMockTransport() + const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { capturedDataCallback.current = callbacks.onData ?? null return 'pty-id' }) transportFactoryQueue.push(transport) - const getMainBufferSnapshot = window.api.pty.getMainBufferSnapshot as unknown as ReturnType< - typeof vi.fn - > - const backgroundedOutput = 'backgrounded document output\r\n' - getMainBufferSnapshot.mockResolvedValue({ - data: backgroundedOutput, - cols: 120, - rows: 40, - seq: backgroundedOutput.length - }) const pane = createPane(1) const manager = createManager(1) @@ -2808,73 +2784,15 @@ describe('connectPanePty', () => { expect(capturedDataCallback.current).not.toBeNull() vi.useFakeTimers() - capturedDataCallback.current?.(backgroundedOutput, { - seq: backgroundedOutput.length, - rawLength: backgroundedOutput.length - }) + capturedDataCallback.current?.('backgrounded document output\r\n') - expect(pane.terminal.write).not.toHaveBeenCalledWith(backgroundedOutput, expect.any(Function)) + expect(pane.terminal.write).not.toHaveBeenCalledWith( + 'backgrounded document output\r\n', + expect.any(Function) + ) vi.advanceTimersByTime(50) - expect(pane.terminal.write).not.toHaveBeenCalledWith(backgroundedOutput, expect.any(Function)) - - documentStub.visibilityState = 'visible' - for (const listener of visibilityListeners) { - listener() - } - await flushAsyncTicks(20) - - expect(getMainBufferSnapshot).toHaveBeenCalledWith('pty-id', { scrollbackRows: 5000 }) - expect(pane.terminal.write).toHaveBeenCalledWith(backgroundedOutput, expect.any(Function)) - }) - - it('restores ordinary hidden pane output from the main snapshot on foreground output', async () => { - const { connectPanePty } = await import('./pty-connection') - const transport = createMockTransport('pty-id') - const capturedDataCallback: { - current: ((data: string, meta?: { seq?: number; rawLength?: number }) => void) | null - } = { current: null } - transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - }) - transportFactoryQueue.push(transport) - const getMainBufferSnapshot = window.api.pty.getMainBufferSnapshot as unknown as ReturnType< - typeof vi.fn - > - const hidden = 'hidden output\r\n' - const live = 'visible-after\r\n' - getMainBufferSnapshot.mockResolvedValue({ - data: `${hidden}${live}`, - cols: 120, - rows: 40, - seq: hidden.length + live.length - }) - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps({ - isVisibleRef: { current: false } - }) - const disposable = connectPanePty(pane as never, manager as never, deps as never) - await flushAsyncTicks(6) - - capturedDataCallback.current?.(hidden, { seq: hidden.length, rawLength: hidden.length }) - vi.useFakeTimers() - vi.advanceTimersByTime(50) - expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden, expect.any(Function)) - - ;(deps.isVisibleRef as { current: boolean }).current = true - capturedDataCallback.current?.(live, { - seq: hidden.length + live.length, - rawLength: live.length - }) - await flushAsyncTicks(20) - - expect(getMainBufferSnapshot).toHaveBeenCalledWith('pty-id', { scrollbackRows: 5000 }) - expect(pane.terminal.write).toHaveBeenCalledWith(`${hidden}${live}`, expect.any(Function)) - expect(pane.terminal.write).not.toHaveBeenCalledWith(hidden, expect.any(Function)) - disposable.dispose() + expect(pane.terminal.write).toHaveBeenCalledWith('backgrounded document output\r\n') }) it('keeps hidden Codex telemetry startup output parsing briefly', async () => { @@ -2986,7 +2904,7 @@ describe('connectPanePty', () => { binding.dispose() }) - it('answers mode 2031 in hidden snapshot-backed chunks skipped from xterm parsing', async () => { + it('writes mode 2031 through hidden xterm parsing', async () => { const { connectPanePty } = await import('./pty-connection') const transport = createMockTransport('pty-id') const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } @@ -3009,10 +2927,12 @@ describe('connectPanePty', () => { ) await flushAsyncTicks(6) + vi.useFakeTimers() capturedDataCallback.current?.('\x1b[?2031h') + vi.advanceTimersByTime(50) - expect(transport.sendInput).toHaveBeenCalledWith('\x1b[?997;2n') - expect(pane.terminal.write).not.toHaveBeenCalledWith('\x1b[?2031h', expect.any(Function)) + expect(transport.sendInput).not.toHaveBeenCalledWith('\x1b[?997;2n') + expect(pane.terminal.write).toHaveBeenCalledWith('\x1b[?2031h') binding.dispose() }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index aebc15a1b..764de7343 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -1684,18 +1684,6 @@ export function connectPanePty( !foreground && canUseMainBufferSnapshot(transport.getPtyId()) && isHiddenStartupRendererQueryWindowActive() - if ( - !foreground && - canUseMainBufferSnapshot(transport.getPtyId()) && - !parseHiddenStartupOutput - ) { - respondToSkippedMode2031Subscribe(data) - // Why: hidden panes do not need live xterm parsing. Main already - // retains the PTY buffer, so defer display work until the pane is - // visible and restore from that snapshot instead. - markHiddenOutputRestoreNeeded() - return - } if (hiddenMode2031ScanTail) { respondToSkippedMode2031Subscribe(data) }