Revert "perf: pause hidden terminal renderer output" (#4314)
This reverts commit c608e65d00.
This commit is contained in:
+1
-5
@@ -86,8 +86,7 @@ import {
|
||||
getPtyIdForPaneKey,
|
||||
registerPaneKeyTeardownListener,
|
||||
getLocalPtyProvider,
|
||||
registerHeadlessPtyRuntime,
|
||||
isRendererPtyOutputPaused
|
||||
registerHeadlessPtyRuntime
|
||||
} from './ipc/pty'
|
||||
import { AgentBrowserBridge } from './browser/agent-browser-bridge'
|
||||
import { browserManager } from './browser/browser-manager'
|
||||
@@ -923,9 +922,6 @@ function sendSyntheticTitle(ptyId: string, data: string, options: { force?: bool
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
return
|
||||
}
|
||||
if (options.force !== true && isRendererPtyOutputPaused(ptyId)) {
|
||||
return
|
||||
}
|
||||
// Why: repeated working-spinner frames are decorative and can arrive every
|
||||
// 80ms per agent. Final/permission frames are forced because they drive BEL.
|
||||
if (
|
||||
|
||||
@@ -2972,162 +2972,6 @@ describe('registerPtyHandlers', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('does not send renderer PTY data while renderer output is paused', async () => {
|
||||
vi.useFakeTimers()
|
||||
const mockProc = createMockProc()
|
||||
spawnMock.mockReturnValue(mockProc.proc)
|
||||
|
||||
try {
|
||||
registerPtyHandlers(mainWindow as never)
|
||||
const spawnResult = (await handlers.get('pty:spawn')!(null, {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: '/tmp'
|
||||
})) as { id: string }
|
||||
const pauseCall = onMock.mock.calls.find((call: unknown[]) => call[0] === 'pty:pauseOutput')
|
||||
if (!pauseCall) {
|
||||
throw new Error('missing pty:pauseOutput listener')
|
||||
}
|
||||
const pauseRendererOutput = pauseCall[1] as (
|
||||
event: unknown,
|
||||
args: { id: string; paused: boolean }
|
||||
) => void
|
||||
mainWindow.webContents.send.mockClear()
|
||||
|
||||
pauseRendererOutput(null, { id: spawnResult.id, paused: true })
|
||||
mockProc.emitData('hidden output')
|
||||
vi.advanceTimersByTime(50)
|
||||
|
||||
expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', {
|
||||
id: spawnResult.id,
|
||||
data: 'hidden output'
|
||||
})
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('answers mode 2031 subscribes while renderer PTY output is paused', async () => {
|
||||
const mockProc = createMockProc()
|
||||
spawnMock.mockReturnValue(mockProc.proc)
|
||||
|
||||
registerPtyHandlers(mainWindow as never)
|
||||
const spawnResult = (await handlers.get('pty:spawn')!(null, {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: '/tmp'
|
||||
})) as { id: string }
|
||||
const pauseCall = onMock.mock.calls.find((call: unknown[]) => call[0] === 'pty:pauseOutput')
|
||||
if (!pauseCall) {
|
||||
throw new Error('missing pty:pauseOutput listener')
|
||||
}
|
||||
const pauseRendererOutput = pauseCall[1] as (
|
||||
event: unknown,
|
||||
args: { id: string; paused: boolean }
|
||||
) => void
|
||||
mainWindow.webContents.send.mockClear()
|
||||
|
||||
pauseRendererOutput(null, { id: spawnResult.id, paused: true })
|
||||
mockProc.emitData('\x1b[?2031h')
|
||||
|
||||
expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b[?997;1n')
|
||||
expect(mainWindow.webContents.send).not.toHaveBeenCalledWith(
|
||||
'pty:data',
|
||||
expect.objectContaining({ id: spawnResult.id })
|
||||
)
|
||||
})
|
||||
|
||||
it('answers split paused mode 2031 subscribes using current app color scheme', async () => {
|
||||
const mockProc = createMockProc()
|
||||
spawnMock.mockReturnValue(mockProc.proc)
|
||||
|
||||
registerPtyHandlers(mainWindow as never, undefined, undefined, (() => ({
|
||||
theme: 'light'
|
||||
})) as never)
|
||||
const spawnResult = (await handlers.get('pty:spawn')!(null, {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: '/tmp'
|
||||
})) as { id: string }
|
||||
const pauseCall = onMock.mock.calls.find((call: unknown[]) => call[0] === 'pty:pauseOutput')
|
||||
if (!pauseCall) {
|
||||
throw new Error('missing pty:pauseOutput listener')
|
||||
}
|
||||
const pauseRendererOutput = pauseCall[1] as (
|
||||
event: unknown,
|
||||
args: { id: string; paused: boolean }
|
||||
) => void
|
||||
|
||||
pauseRendererOutput(null, { id: spawnResult.id, paused: true })
|
||||
mockProc.emitData('\x1b[?20')
|
||||
expect(mockProc.proc.write).not.toHaveBeenCalled()
|
||||
|
||||
mockProc.emitData('31h')
|
||||
expect(mockProc.proc.write).toHaveBeenCalledWith('\x1b[?997;2n')
|
||||
})
|
||||
|
||||
it('keeps 250 paused background PTYs off the renderer input path', async () => {
|
||||
vi.useFakeTimers()
|
||||
const backgroundCount = 250
|
||||
const procs = Array.from({ length: backgroundCount + 1 }, () => createMockProc())
|
||||
let spawnIndex = 0
|
||||
spawnMock.mockImplementation(() => procs[spawnIndex++].proc)
|
||||
|
||||
try {
|
||||
registerPtyHandlers(mainWindow as never)
|
||||
const activeSpawn = (await handlers.get('pty:spawn')!(null, {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: '/tmp'
|
||||
})) as { id: string }
|
||||
const backgroundSpawns: { id: string }[] = []
|
||||
for (let index = 0; index < backgroundCount; index++) {
|
||||
backgroundSpawns.push(
|
||||
(await handlers.get('pty:spawn')!(null, {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: '/tmp'
|
||||
})) as { id: string }
|
||||
)
|
||||
}
|
||||
const pauseCall = onMock.mock.calls.find((call: unknown[]) => call[0] === 'pty:pauseOutput')
|
||||
if (!pauseCall) {
|
||||
throw new Error('missing pty:pauseOutput listener')
|
||||
}
|
||||
const pauseRendererOutput = pauseCall[1] as (
|
||||
event: unknown,
|
||||
args: { id: string; paused: boolean }
|
||||
) => void
|
||||
for (const spawn of backgroundSpawns) {
|
||||
pauseRendererOutput(null, { id: spawn.id, paused: true })
|
||||
}
|
||||
mainWindow.webContents.send.mockClear()
|
||||
|
||||
for (let index = 0; index < backgroundCount; index++) {
|
||||
procs[index + 1].emitData(`hidden ${index}\n`)
|
||||
}
|
||||
vi.advanceTimersByTime(100)
|
||||
|
||||
for (let index = 0; index < backgroundCount; index++) {
|
||||
expect(mainWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', {
|
||||
id: backgroundSpawns[index].id,
|
||||
data: `hidden ${index}\n`
|
||||
})
|
||||
}
|
||||
|
||||
const writeListener = getPtyWriteListener()
|
||||
writeListener(null, { id: activeSpawn.id, data: 'a' })
|
||||
procs[0].emitData('redraw')
|
||||
|
||||
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
|
||||
id: activeSpawn.id,
|
||||
data: 'redraw'
|
||||
})
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('sends small PTY redraws immediately after terminal input', async () => {
|
||||
vi.useFakeTimers()
|
||||
const mockProc = createMockProc()
|
||||
|
||||
+1
-68
@@ -5,7 +5,7 @@ boundary. Splitting it by line count would scatter tightly coupled terminal
|
||||
process behavior across files without a cleaner ownership seam. */
|
||||
import { join, delimiter } from 'path'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { type BrowserWindow, type WebContents, ipcMain, app, nativeTheme } from 'electron'
|
||||
import { type BrowserWindow, type WebContents, ipcMain, app } from 'electron'
|
||||
export { getBashShellReadyRcfileContent } from '../providers/local-pty-shell-ready'
|
||||
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
|
||||
import type { Store } from '../persistence'
|
||||
@@ -47,11 +47,6 @@ import {
|
||||
} from '../../shared/telemetry-events'
|
||||
import { isRemoteAgentHooksEnabled } from '../../shared/agent-hook-relay'
|
||||
import { createTerminalSessionStateSaveFailureMessage } from '../../shared/terminal-session-state-save-failure'
|
||||
import {
|
||||
mode2031SequenceFor,
|
||||
resolveTerminalColorSchemeMode,
|
||||
scanMode2031Sequences
|
||||
} from '../../shared/terminal-color-scheme-protocol'
|
||||
import { readShellStartupEnvVar } from '../pty/shell-startup-env'
|
||||
import {
|
||||
isTerminalLeafId,
|
||||
@@ -89,10 +84,6 @@ const ptySizes = new Map<string, { cols: number; rows: number }>()
|
||||
// daemon shutdowns that do not flow through the local provider exit listener.
|
||||
const lastInputAtByPty = new Map<string, number>()
|
||||
const interactiveOutputCharsByPty = new Map<string, number>()
|
||||
// Why: hidden renderer panes restore from main-owned snapshots, so ordinary
|
||||
// PTY bytes do not need to wake the renderer while a pane is hidden.
|
||||
const rendererPausedOutputPtys = new Set<string>()
|
||||
const rendererPausedMode2031ScanTailByPty = new Map<string, string>()
|
||||
// Why: the agent-hooks server caches per-paneKey state (last prompt, last
|
||||
// tool) that otherwise grows unbounded as panes come and go. Track the
|
||||
// spawn-time paneKey so clearProviderPtyState can clear that cache on PTY
|
||||
@@ -120,10 +111,6 @@ export function getPtyIdForPaneKey(paneKey: string): string | undefined {
|
||||
return paneKeyPtyId.get(paneKey)
|
||||
}
|
||||
|
||||
export function isRendererPtyOutputPaused(ptyId: string): boolean {
|
||||
return rendererPausedOutputPtys.has(ptyId)
|
||||
}
|
||||
|
||||
// Why: consumers (currently the cursor-agent synthesized-spinner loop in
|
||||
// main/index.ts) need to tear down paneKey-scoped state when a PTY exits so
|
||||
// intervals / timers cannot leak for the process lifetime. A callback
|
||||
@@ -774,8 +761,6 @@ export function clearProviderPtyState(id: string): void {
|
||||
ptySizes.delete(id)
|
||||
lastInputAtByPty.delete(id)
|
||||
interactiveOutputCharsByPty.delete(id)
|
||||
rendererPausedOutputPtys.delete(id)
|
||||
rendererPausedMode2031ScanTailByPty.delete(id)
|
||||
const paneKey = ptyPaneKey.get(id)
|
||||
const stillOwnsPaneKey = paneKey ? paneKeyPtyId.get(paneKey) === id : false
|
||||
// Why: drop the memory-collector registration so a dead PTY does not keep
|
||||
@@ -910,7 +895,6 @@ export function registerPtyHandlers(
|
||||
ipcMain.removeHandler('pty:getMainBufferSnapshot')
|
||||
ipcMain.removeHandler('pty:writeAccepted')
|
||||
ipcMain.removeAllListeners('pty:write')
|
||||
ipcMain.removeAllListeners('pty:pauseOutput')
|
||||
ipcMain.removeAllListeners('pty:ackColdRestore')
|
||||
ipcMain.removeAllListeners('pty:serializeBuffer:response')
|
||||
|
||||
@@ -1180,42 +1164,6 @@ export function registerPtyHandlers(
|
||||
flushTimer = null
|
||||
}
|
||||
|
||||
function setRendererPtyOutputPaused(id: string, paused: boolean): void {
|
||||
if (paused) {
|
||||
rendererPausedOutputPtys.add(id)
|
||||
pendingData.delete(id)
|
||||
clearFlushTimerIfIdle()
|
||||
return
|
||||
}
|
||||
rendererPausedOutputPtys.delete(id)
|
||||
rendererPausedMode2031ScanTailByPty.delete(id)
|
||||
}
|
||||
|
||||
function respondToPausedRendererMode2031Subscribe(id: string, data: string): void {
|
||||
const scan = scanMode2031Sequences(rendererPausedMode2031ScanTailByPty.get(id) ?? '', data)
|
||||
if (scan.tail) {
|
||||
rendererPausedMode2031ScanTailByPty.set(id, scan.tail)
|
||||
} else {
|
||||
rendererPausedMode2031ScanTailByPty.delete(id)
|
||||
}
|
||||
if (!scan.subscribe) {
|
||||
return
|
||||
}
|
||||
const provider = tryGetProviderForPty(id)
|
||||
if (!provider) {
|
||||
return
|
||||
}
|
||||
const mode = resolveTerminalColorSchemeMode(getSettings?.(), nativeTheme.shouldUseDarkColors)
|
||||
try {
|
||||
// Why: paused renderer panes still need protocol replies that affect how
|
||||
// TUIs draw into the main-owned snapshot. Without this, Codex starts in a
|
||||
// fallback prompt style and the restored composer loses its background.
|
||||
provider.write(id, mode2031SequenceFor(mode))
|
||||
} catch {
|
||||
// Best effort; renderer restore will continue from whatever the TUI emits.
|
||||
}
|
||||
}
|
||||
|
||||
// Why: extracted so the "Restart daemon" flow can rebind against the fresh
|
||||
// adapter after replaceDaemonProvider runs. Both the startup registration
|
||||
// and the post-restart rebind go through the same code path — no risk of
|
||||
@@ -1248,12 +1196,6 @@ export function registerPtyHandlers(
|
||||
pendingData.clear()
|
||||
return
|
||||
}
|
||||
if (rendererPausedOutputPtys.has(payload.id)) {
|
||||
respondToPausedRendererMode2031Subscribe(payload.id, payload.data)
|
||||
pendingData.delete(payload.id)
|
||||
clearFlushTimerIfIdle()
|
||||
return
|
||||
}
|
||||
const existing = pendingData.get(payload.id)
|
||||
const pending = appendPendingPtyData(existing, payload.data, startSeq)
|
||||
const nextData = pending.data
|
||||
@@ -1305,7 +1247,6 @@ export function registerPtyHandlers(
|
||||
if (lastRendererInputPtyId === payload.id) {
|
||||
lastRendererInputPtyId = null
|
||||
}
|
||||
rendererPausedOutputPtys.delete(payload.id)
|
||||
mainWindow.webContents.send('pty:exit', payload)
|
||||
}
|
||||
})
|
||||
@@ -2326,14 +2267,6 @@ export function registerPtyHandlers(
|
||||
ipcMain.on('pty:write', (_event, args: { id: string; data: string }) => {
|
||||
writePtyInput(args)
|
||||
})
|
||||
|
||||
ipcMain.on('pty:pauseOutput', (_event, args: { id?: string; paused?: boolean }) => {
|
||||
if (typeof args?.id !== 'string') {
|
||||
return
|
||||
}
|
||||
setRendererPtyOutputPaused(args.id, args.paused === true)
|
||||
})
|
||||
|
||||
ipcMain.handle('pty:writeAccepted', (_event, args: { id: string; data: string }): boolean => {
|
||||
return writePtyInputAccepted(args)
|
||||
})
|
||||
|
||||
@@ -58,7 +58,6 @@ vi.mock('../ipc/pty', () => ({
|
||||
clearPtyOwnershipForConnection: vi.fn(),
|
||||
clearProviderPtyState: vi.fn(),
|
||||
deletePtyOwnership: vi.fn(),
|
||||
isRendererPtyOutputPaused: vi.fn(() => false),
|
||||
setPtyOwnership: vi.fn()
|
||||
}))
|
||||
|
||||
|
||||
@@ -69,7 +69,6 @@ vi.mock('../ipc/pty', () => ({
|
||||
clearPtyOwnershipForConnection: vi.fn(),
|
||||
clearProviderPtyState: vi.fn(),
|
||||
deletePtyOwnership: vi.fn(),
|
||||
isRendererPtyOutputPaused: vi.fn(() => false),
|
||||
setPtyOwnership: vi.fn()
|
||||
}))
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ import {
|
||||
clearPtyOwnershipForConnection,
|
||||
clearProviderPtyState,
|
||||
deletePtyOwnership,
|
||||
isRendererPtyOutputPaused,
|
||||
setPtyOwnership
|
||||
} from '../ipc/pty'
|
||||
import {
|
||||
@@ -906,7 +905,7 @@ export class SshRelaySession {
|
||||
ptyProvider.onData((payload) => {
|
||||
const seq = this.runtime?.onPtyData(payload.id, payload.data, Date.now())
|
||||
const win = this.getMainWindow()
|
||||
if (win && !win.isDestroyed() && !isRendererPtyOutputPaused(payload.id)) {
|
||||
if (win && !win.isDestroyed()) {
|
||||
win.webContents.send('pty:data', {
|
||||
...payload,
|
||||
...(typeof seq === 'number' ? { seq, rawLength: payload.data.length } : {})
|
||||
|
||||
@@ -850,7 +850,6 @@ export type PreloadApi = {
|
||||
signal: (id: string, signal: string) => void
|
||||
kill: (id: string, opts?: { keepHistory?: boolean }) => Promise<void>
|
||||
ackColdRestore: (id: string) => void
|
||||
pauseOutput: (id: string, paused: boolean) => void
|
||||
hasChildProcesses: (id: string) => Promise<boolean>
|
||||
getForegroundProcess: (id: string) => Promise<string | null>
|
||||
getCwd: (id: string) => Promise<string>
|
||||
|
||||
@@ -671,10 +671,6 @@ const api = {
|
||||
ipcRenderer.send('pty:ackColdRestore', { id })
|
||||
},
|
||||
|
||||
pauseOutput: (id: string, paused: boolean): void => {
|
||||
ipcRenderer.send('pty:pauseOutput', { id, paused })
|
||||
},
|
||||
|
||||
kill: (id: string, opts?: { keepHistory?: boolean }): Promise<void> =>
|
||||
ipcRenderer.invoke('pty:kill', { id, keepHistory: opts?.keepHistory ?? false }),
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import type * as React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
POST_REPLAY_LIVE_SNAPSHOT_RESET,
|
||||
POST_REPLAY_MODE_RESET,
|
||||
POST_REPLAY_REATTACH_RESET,
|
||||
RESET_TERMINAL_CURSOR_STYLE
|
||||
@@ -462,7 +461,6 @@ describe('connectPanePty', () => {
|
||||
},
|
||||
pty: {
|
||||
signal: vi.fn(),
|
||||
pauseOutput: vi.fn(),
|
||||
getMainBufferSnapshot: vi.fn().mockResolvedValue(null),
|
||||
getForegroundProcess: vi.fn().mockResolvedValue(null),
|
||||
hasChildProcesses: vi.fn().mockResolvedValue(false),
|
||||
@@ -2879,120 +2877,47 @@ describe('connectPanePty', () => {
|
||||
disposable.dispose()
|
||||
})
|
||||
|
||||
it('pauses renderer PTY output while hidden and restores from main snapshot on show', async () => {
|
||||
it('keeps hidden Codex telemetry startup output parsing briefly', async () => {
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
const transport = createMockTransport('pty-id')
|
||||
transport.connect.mockResolvedValue('pty-id')
|
||||
transportFactoryQueue.push(transport)
|
||||
const getMainBufferSnapshot = window.api.pty.getMainBufferSnapshot as unknown as ReturnType<
|
||||
typeof vi.fn
|
||||
>
|
||||
const pauseOutput = window.api.pty.pauseOutput as unknown as ReturnType<typeof vi.fn>
|
||||
getMainBufferSnapshot.mockResolvedValue({
|
||||
data: 'hidden while paused\r\n',
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
seq: 21
|
||||
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 pane = createPane(1)
|
||||
const manager = createManager(1)
|
||||
const deps = createDeps({
|
||||
isVisibleRef: { current: false }
|
||||
})
|
||||
const binding = connectPanePty(pane as never, manager as never, deps as never)
|
||||
const binding = connectPanePty(
|
||||
pane as never,
|
||||
manager as never,
|
||||
createDeps({
|
||||
isVisibleRef: { current: false },
|
||||
startup: {
|
||||
command: 'wrapped-agent',
|
||||
telemetry: {
|
||||
agent_kind: 'codex',
|
||||
launch_source: 'tab_bar_quick_launch',
|
||||
request_kind: 'new'
|
||||
}
|
||||
}
|
||||
}) as never
|
||||
)
|
||||
await flushAsyncTicks(6)
|
||||
|
||||
expect(pauseOutput).toHaveBeenCalledWith('pty-id', true)
|
||||
expect(capturedDataCallback.current).not.toBeNull()
|
||||
|
||||
;(deps.isVisibleRef as { current: boolean }).current = true
|
||||
binding.syncRendererOutputVisibility()
|
||||
await flushAsyncTicks(20)
|
||||
capturedDataCallback.current?.('\x1b]11;?\x1b\\startup frame\r\n')
|
||||
|
||||
expect(pauseOutput).toHaveBeenCalledWith('pty-id', false)
|
||||
expect(getMainBufferSnapshot).toHaveBeenCalledWith('pty-id', { scrollbackRows: 5000 })
|
||||
expect(pane.terminal.write).toHaveBeenCalledWith(
|
||||
'hidden while paused\r\n',
|
||||
expect.any(Function)
|
||||
)
|
||||
expect(pane.terminal.write).toHaveBeenCalledWith(
|
||||
POST_REPLAY_LIVE_SNAPSHOT_RESET,
|
||||
expect.any(Function)
|
||||
)
|
||||
expect(pane.terminal.write).not.toHaveBeenCalledWith(
|
||||
POST_REPLAY_REATTACH_RESET,
|
||||
'\x1b]11;?\x1b\\startup frame\r\n',
|
||||
expect.any(Function)
|
||||
)
|
||||
|
||||
binding.dispose()
|
||||
})
|
||||
|
||||
it('keeps hidden Codex telemetry startup output parsing briefly before pausing renderer output', async () => {
|
||||
const originalSetTimeout = globalThis.setTimeout
|
||||
const originalClearTimeout = globalThis.clearTimeout
|
||||
const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(0)
|
||||
const scheduledTimers: { callback: () => void; delay: number }[] = []
|
||||
globalThis.setTimeout = vi.fn((callback: () => void, delay?: number) => {
|
||||
scheduledTimers.push({ callback, delay: typeof delay === 'number' ? delay : 0 })
|
||||
return scheduledTimers.length as unknown as ReturnType<typeof setTimeout>
|
||||
}) as unknown as typeof setTimeout
|
||||
globalThis.clearTimeout = vi.fn() as unknown as typeof clearTimeout
|
||||
let binding: { dispose: () => void } | null = null
|
||||
try {
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
const transport = createMockTransport('pty-id')
|
||||
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 pauseOutput = window.api.pty.pauseOutput as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
const pane = createPane(1)
|
||||
const manager = createManager(1)
|
||||
binding = connectPanePty(
|
||||
pane as never,
|
||||
manager as never,
|
||||
createDeps({
|
||||
isVisibleRef: { current: false },
|
||||
startup: {
|
||||
command: 'wrapped-agent',
|
||||
telemetry: {
|
||||
agent_kind: 'codex',
|
||||
launch_source: 'tab_bar_quick_launch',
|
||||
request_kind: 'new'
|
||||
}
|
||||
}
|
||||
}) as never
|
||||
)
|
||||
await flushAsyncTicks(6)
|
||||
|
||||
expect(capturedDataCallback.current).not.toBeNull()
|
||||
expect(pauseOutput).not.toHaveBeenCalledWith('pty-id', true)
|
||||
|
||||
capturedDataCallback.current?.('\x1b]11;?\x1b\\startup frame\r\n')
|
||||
|
||||
expect(pane.terminal.write).toHaveBeenCalledWith(
|
||||
'\x1b]11;?\x1b\\startup frame\r\n',
|
||||
expect.any(Function)
|
||||
)
|
||||
|
||||
dateNowSpy.mockReturnValue(10_001)
|
||||
scheduledTimers.find((timer) => timer.delay === 10_000)?.callback()
|
||||
await flushAsyncTicks()
|
||||
|
||||
expect(pauseOutput).toHaveBeenCalledWith('pty-id', true)
|
||||
} finally {
|
||||
binding?.dispose()
|
||||
globalThis.setTimeout = originalSetTimeout
|
||||
globalThis.clearTimeout = originalClearTimeout
|
||||
dateNowSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps hidden bare Codex startup commands parsing briefly', async () => {
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
const transport = createMockTransport('pty-id')
|
||||
@@ -3002,7 +2927,6 @@ describe('connectPanePty', () => {
|
||||
return 'pty-id'
|
||||
})
|
||||
transportFactoryQueue.push(transport)
|
||||
const pauseOutput = window.api.pty.pauseOutput as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
const pane = createPane(1)
|
||||
const manager = createManager(1)
|
||||
@@ -3017,7 +2941,6 @@ describe('connectPanePty', () => {
|
||||
await flushAsyncTicks(6)
|
||||
|
||||
expect(capturedDataCallback.current).not.toBeNull()
|
||||
expect(pauseOutput).not.toHaveBeenCalledWith('pty-id', true)
|
||||
|
||||
capturedDataCallback.current?.('\x1b]11;?\x1b\\startup frame\r\n')
|
||||
|
||||
@@ -3029,7 +2952,7 @@ describe('connectPanePty', () => {
|
||||
binding.dispose()
|
||||
})
|
||||
|
||||
it('pauses arbitrary hidden startup commands immediately', async () => {
|
||||
it('skips arbitrary hidden startup output parsing', async () => {
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
const transport = createMockTransport('pty-id')
|
||||
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
|
||||
@@ -3038,7 +2961,6 @@ describe('connectPanePty', () => {
|
||||
return 'pty-id'
|
||||
})
|
||||
transportFactoryQueue.push(transport)
|
||||
const pauseOutput = window.api.pty.pauseOutput as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
const pane = createPane(1)
|
||||
const manager = createManager(1)
|
||||
@@ -3053,7 +2975,6 @@ describe('connectPanePty', () => {
|
||||
await flushAsyncTicks(6)
|
||||
|
||||
expect(capturedDataCallback.current).not.toBeNull()
|
||||
expect(pauseOutput).toHaveBeenCalledWith('pty-id', true)
|
||||
|
||||
capturedDataCallback.current?.('hidden startup output\r\n')
|
||||
|
||||
|
||||
@@ -130,8 +130,7 @@ let codexRestartNoticePresenceSource: Record<
|
||||
> | null = null
|
||||
let codexRestartNoticePresence = false
|
||||
|
||||
export type PanePtyBinding = IDisposable & {
|
||||
syncRendererOutputVisibility: () => void
|
||||
type PanePtyBinding = IDisposable & {
|
||||
syncProcessTracking: () => void
|
||||
}
|
||||
|
||||
@@ -1353,10 +1352,6 @@ export function connectPanePty(
|
||||
if (geometryReportObserver && pane.container instanceof Element) {
|
||||
geometryReportObserver.observe(pane.container)
|
||||
}
|
||||
let rendererOutputPausedPtyId: string | null = null
|
||||
let syncRendererOutputVisibility = (): void => {}
|
||||
let clearHiddenStartupRendererQueryTimer = (): void => {}
|
||||
|
||||
// Defer PTY spawn/attach to next frame so FitAddon has time to calculate
|
||||
// the correct terminal dimensions from the laid-out container.
|
||||
connectFrame = requestAnimationFrame(() => {
|
||||
@@ -1474,7 +1469,6 @@ export function connectPanePty(
|
||||
if (typeof gen === 'number' && resolvedPtyId) {
|
||||
if (!isRemoteRuntimePtyId(resolvedPtyId)) {
|
||||
registerPaneSerializerFor(resolvedPtyId)
|
||||
syncRendererOutputVisibility()
|
||||
void window.api.pty.settlePaneSerializer(cacheKey, gen).catch(() => {})
|
||||
}
|
||||
} else if (typeof gen === 'number') {
|
||||
@@ -1552,7 +1546,6 @@ export function connectPanePty(
|
||||
let hiddenOutputRestorePtyId: string | null = null
|
||||
let hiddenOutputRestoreGeneration = 0
|
||||
let hiddenMode2031ScanTail = ''
|
||||
let hiddenStartupRendererQueryTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const hiddenStartupRendererQueryUntil = shouldKeepHiddenStartupRendererQueriesLive(paneStartup)
|
||||
? Date.now() + HIDDEN_STARTUP_RENDERER_QUERY_WINDOW_MS
|
||||
: 0
|
||||
@@ -1561,22 +1554,6 @@ export function connectPanePty(
|
||||
return Boolean(ptyId) && !isRemoteRuntimePtyId(ptyId)
|
||||
}
|
||||
|
||||
function canPauseRendererOutput(ptyId: string | null): ptyId is string {
|
||||
return canUseMainBufferSnapshot(ptyId) && typeof window.api.pty.pauseOutput === 'function'
|
||||
}
|
||||
|
||||
function setRendererOutputPaused(ptyId: string, paused: boolean): void {
|
||||
window.api.pty.pauseOutput(ptyId, paused)
|
||||
rendererOutputPausedPtyId = paused ? ptyId : null
|
||||
}
|
||||
|
||||
clearHiddenStartupRendererQueryTimer = (): void => {
|
||||
if (hiddenStartupRendererQueryTimer !== null) {
|
||||
clearTimeout(hiddenStartupRendererQueryTimer)
|
||||
hiddenStartupRendererQueryTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function isHiddenStartupRendererQueryWindowActive(): boolean {
|
||||
return (
|
||||
paneStartup !== null &&
|
||||
@@ -1585,17 +1562,6 @@ export function connectPanePty(
|
||||
)
|
||||
}
|
||||
|
||||
function scheduleHiddenStartupRendererQueryExpiry(): void {
|
||||
if (hiddenStartupRendererQueryTimer !== null) {
|
||||
return
|
||||
}
|
||||
const delay = Math.max(0, hiddenStartupRendererQueryUntil - Date.now())
|
||||
hiddenStartupRendererQueryTimer = setTimeout(() => {
|
||||
hiddenStartupRendererQueryTimer = null
|
||||
syncRendererOutputVisibility()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function respondToSkippedMode2031Subscribe(data: string): void {
|
||||
const scan = scanMode2031Sequences(hiddenMode2031ScanTail, data)
|
||||
hiddenMode2031ScanTail = scan.tail
|
||||
@@ -1609,42 +1575,6 @@ export function connectPanePty(
|
||||
// theme-dependent styling they would have used in a visible pane.
|
||||
transport.sendInput(mode2031SequenceFor(mode))
|
||||
}
|
||||
|
||||
syncRendererOutputVisibility = (): void => {
|
||||
const ptyId = transport.getPtyId()
|
||||
if (rendererOutputPausedPtyId !== null && rendererOutputPausedPtyId !== ptyId) {
|
||||
setRendererOutputPaused(rendererOutputPausedPtyId, false)
|
||||
}
|
||||
if (!canPauseRendererOutput(ptyId)) {
|
||||
return
|
||||
}
|
||||
const shouldPause = !shouldWritePtyOutputForeground(deps.isVisibleRef.current)
|
||||
if (shouldPause) {
|
||||
if (isHiddenStartupRendererQueryWindowActive()) {
|
||||
// Why: startup TUIs often query OSC 10/11 and DEC color-scheme state
|
||||
// before their first stable frame. Let xterm parse that short window
|
||||
// so its theme-aware auto-replies reach the PTY.
|
||||
scheduleHiddenStartupRendererQueryExpiry()
|
||||
if (rendererOutputPausedPtyId === ptyId) {
|
||||
setRendererOutputPaused(ptyId, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
clearHiddenStartupRendererQueryTimer()
|
||||
if (rendererOutputPausedPtyId !== ptyId) {
|
||||
// Why: main owns the retained terminal buffer for snapshot-capable
|
||||
// PTYs, so hidden panes can stop receiving live bytes entirely.
|
||||
setRendererOutputPaused(ptyId, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
clearHiddenStartupRendererQueryTimer()
|
||||
if (rendererOutputPausedPtyId === ptyId) {
|
||||
setRendererOutputPaused(ptyId, false)
|
||||
markHiddenOutputRestoreNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
function beforeTerminalOutputWrite(chunk: string): void {
|
||||
// Why: hidden tab output is coalesced by the scheduler. Run per-byte
|
||||
// renderer checks at the xterm write boundary so background PTY bursts
|
||||
@@ -2051,7 +1981,6 @@ export function connectPanePty(
|
||||
typeof document.removeEventListener === 'function'
|
||||
) {
|
||||
const onDocumentVisibilityChange = (): void => {
|
||||
syncRendererOutputVisibility()
|
||||
if (shouldWritePtyOutputForeground(deps.isVisibleRef.current)) {
|
||||
requestHiddenOutputRestoreIfNeeded()
|
||||
}
|
||||
@@ -2062,7 +1991,6 @@ export function connectPanePty(
|
||||
}
|
||||
|
||||
const dataCallback = (data: string, meta?: PtyDataMeta): void => {
|
||||
syncRendererOutputVisibility()
|
||||
resetHiddenOutputRestoreIfPtyChanged()
|
||||
observeTerminalBracketedPasteModeOutput(pane.terminal, data)
|
||||
for (const link of observeTerminalGitHubPRLink(data)) {
|
||||
@@ -2172,7 +2100,6 @@ export function connectPanePty(
|
||||
// serializer and the onTitleChange-driven lastTitle source so the
|
||||
// main-process hydration path has full status parity.
|
||||
registerPaneSerializerFor(ptyId)
|
||||
syncRendererOutputVisibility()
|
||||
|
||||
// Strict precedence: snapshot > replay > coldRestore. Paint exactly
|
||||
// one source per reattach. Painting snapshot AND replay produced the
|
||||
@@ -2640,7 +2567,6 @@ export function connectPanePty(
|
||||
deps.syncPanePtyLayoutBinding(pane.id, attachPtyId)
|
||||
deps.updateTabPtyId(deps.tabId, attachPtyId)
|
||||
agentCompletionCoordinator.startProcessTracking()
|
||||
syncRendererOutputVisibility()
|
||||
} catch (err) {
|
||||
reportError(err instanceof Error ? err.message : String(err))
|
||||
deps.clearTabPtyId(deps.tabId, attachPtyId)
|
||||
@@ -2691,7 +2617,6 @@ export function connectPanePty(
|
||||
// Why: attach sets the transport's PTY id; starting process
|
||||
// tracking before this point no-ops because getPtyId() is empty.
|
||||
agentCompletionCoordinator.startProcessTracking()
|
||||
syncRendererOutputVisibility()
|
||||
})
|
||||
.catch((err) => {
|
||||
reportError(err instanceof Error ? err.message : String(err))
|
||||
@@ -2705,9 +2630,6 @@ export function connectPanePty(
|
||||
})
|
||||
|
||||
return {
|
||||
syncRendererOutputVisibility() {
|
||||
syncRendererOutputVisibility()
|
||||
},
|
||||
syncProcessTracking() {
|
||||
agentCompletionCoordinator.startProcessTracking()
|
||||
},
|
||||
@@ -2740,11 +2662,6 @@ export function connectPanePty(
|
||||
unregisterBacklogRecovery = null
|
||||
unregisterDocumentVisibilityRecovery?.()
|
||||
unregisterDocumentVisibilityRecovery = null
|
||||
clearHiddenStartupRendererQueryTimer()
|
||||
if (rendererOutputPausedPtyId !== null) {
|
||||
window.api.pty.pauseOutput(rendererOutputPausedPtyId, false)
|
||||
rendererOutputPausedPtyId = null
|
||||
}
|
||||
clearPanePtyFitBinding()
|
||||
discardTerminalOutput(pane.terminal)
|
||||
if (agentTaskCompleteSettingsUnsubscribe !== null) {
|
||||
|
||||
@@ -1232,13 +1232,11 @@ export function useTerminalPaneLifecycle({
|
||||
isVisibleRef.current = isVisible
|
||||
for (const panePtyBinding of panePtyBindingsRef.current.values()) {
|
||||
const bindingWithVisibility = panePtyBinding as IDisposable & {
|
||||
syncRendererOutputVisibility?: () => void
|
||||
syncProcessTracking?: () => void
|
||||
}
|
||||
bindingWithVisibility.syncRendererOutputVisibility?.()
|
||||
bindingWithVisibility.syncProcessTracking?.()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- Why: visibility flips must notify existing PTY bindings even though the ref object identity is stable.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- Why: visibility flips must refresh existing PTY process tracking even though the ref object identity is stable.
|
||||
}, [isVisible, isVisibleRef, panePtyBindingsRef])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -2030,7 +2030,6 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
|
||||
signal: () => {},
|
||||
kill: () => Promise.resolve(),
|
||||
ackColdRestore: () => {},
|
||||
pauseOutput: () => {},
|
||||
hasChildProcesses: () => Promise.resolve(false),
|
||||
getForegroundProcess: () => Promise.resolve(null),
|
||||
getCwd: () => Promise.resolve('~'),
|
||||
|
||||
Reference in New Issue
Block a user