Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 107 additions & 1 deletion src/main/ipc/pty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,21 @@ describe('registerPtyHandlers', () => {
afterEach(() => {
_resetWslCachesForTests()
vi.useRealTimers()
unregisterSshPtyProvider('ssh-1')
// Why: sshProviders is module-level state; any id left registered leaks
// into later tests (pty:listSessions sweeps every registered provider).
for (const leakedConnectionId of [
'ssh-1',
'ssh-a',
'ssh-b',
'ssh-expired-runtime',
'ssh-fresh-fail',
'ssh-reattach-1',
'ssh-reattach-fail',
'ssh-reattach-ok',
'ssh-runtime-env'
]) {
unregisterSshPtyProvider(leakedConnectionId)
}
setLocalPtyProvider(new LocalPtyProvider())
if (savedProcessPlatform) {
Object.defineProperty(process, 'platform', savedProcessPlatform)
Expand Down Expand Up @@ -6728,6 +6742,70 @@ describe('registerPtyHandlers', () => {
}
})

it('caps per-PTY pending output while the renderer is starved and heals via a droppedOutput sentinel', async () => {
vi.useFakeTimers()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const mockProc = createMockProc()
spawnMock.mockReturnValue(mockProc.proc)

try {
registerPtyHandlers(mainWindow as never)
const spawn = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp'
})) as { id: string }
const ackData = getPtyAckDataListener()
mainWindow.webContents.send.mockClear()

// Saturate the renderer in-flight window (512 KB) with no ACKs — the
// frozen/starved-renderer shape from the field reports.
mockProc.emitData('x'.repeat(600 * 1024))
vi.advanceTimersByTime(8)
for (let index = 0; index < 32; index++) {
vi.advanceTimersByTime(1)
}

// Keep flooding well past the 2 MB per-PTY pending cap. Main must not
// buffer this unboundedly (previously: unbounded string concat).
mockProc.emitData('y'.repeat(3 * 1024 * 1024))
expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({
pendingPtyCount: 1,
pendingChars: 0
})

// Later output while dropped must stay O(1), not start re-accumulating.
mockProc.emitData('z'.repeat(64 * 1024))
expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({
pendingPtyCount: 1,
pendingChars: 0
})

// Renderer recovers and ACKs: the flush must deliver the droppedOutput
// sentinel so the pane repaints from the main-owned snapshot.
mainWindow.webContents.send.mockClear()
ackData(null, { id: spawn.id, charCount: 512 * 1024 })
vi.advanceTimersByTime(8)
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: spawn.id,
data: '',
droppedOutput: true
})

// Fresh output after the sentinel flows normally again.
mainWindow.webContents.send.mockClear()
mockProc.emitData('back to normal')
vi.advanceTimersByTime(8)
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: spawn.id,
data: 'back to normal'
})
} finally {
errorSpy.mockRestore()
vi.useRealTimers()
}
})

it('forwards only actually in-flight bytes to provider ACK backpressure', async () => {
vi.useFakeTimers()
const acknowledgeDataEvent = vi.fn()
Expand Down Expand Up @@ -7166,6 +7244,34 @@ describe('registerPtyHandlers', () => {
expect(mockProc.proc.write).not.toHaveBeenCalled()
})

it('silently drops writes to a live PTY after ownership loss until pty:listSessions rebuilds it (frozen-terminal repro)', async () => {
const mockProc = createMockProc()
spawnMock.mockReturnValue(mockProc.proc)
registerPtyHandlers(mainWindow as never)
const result = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24
})) as { id: string }
const write = getPtyWriteListener()

write(mainWindowIpcEvent, { id: result.id, data: 'alive' })
expect(mockProc.proc.write).toHaveBeenCalledWith('alive')

// Field failure shape (Discord #performance / #2836): a pane can keep
// rendering with a ptyId whose ownership entry is gone while the provider
// still holds the live PTY — every keystroke then vanishes with no error,
// no log, and no signal back to the renderer.
deletePtyOwnership(result.id)
write(mainWindowIpcEvent, { id: result.id, data: 'dropped' })
expect(mockProc.proc.write).not.toHaveBeenCalledWith('dropped')

// pty:listSessions rebuilds ownership from provider sessions — the
// revival lever the frozen-pane e2e probes depend on.
await handlers.get('pty:listSessions')!(null, undefined)
write(mainWindowIpcEvent, { id: result.id, data: 'revived' })
expect(mockProc.proc.write).toHaveBeenCalledWith('revived')
})

it('chunks large acknowledged pty writes before provider writes', async () => {
const mockProc = createMockProc()
spawnMock.mockReturnValue(mockProc.proc)
Expand Down
55 changes: 50 additions & 5 deletions src/main/ipc/pty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1352,6 +1352,7 @@ export function registerPtyHandlers(
data: string
startSeq?: number
containsBackgroundOutput?: boolean
droppedOutput?: true
}

type PtyDataPayload = {
Expand All @@ -1360,6 +1361,7 @@ export function registerPtyHandlers(
seq?: number
rawLength?: number
background?: boolean
droppedOutput?: boolean
}

const pendingData = new Map<string, PendingPtyData>()
Expand All @@ -1373,6 +1375,12 @@ export function registerPtyHandlers(
const PTY_BATCH_FLUSH_MAX_WRITES = 2
const PTY_RENDERER_IN_FLIGHT_HIGH_WATER_CHARS = 512 * 1024
const PTY_RENDERER_TOTAL_IN_FLIGHT_HIGH_WATER_CHARS = 8 * 1024 * 1024
// Why: while the renderer cannot receive (frozen, starved, mid-reload), a
// chatty PTY used to grow its pendingData string without bound — main-process
// heap ballooning that a renderer reload cannot clear. Beyond this cap the
// buffered bytes are dropped and the pane heals from the main-owned buffer
// snapshot via the droppedOutput sentinel (renderer hidden-output restore).
const PTY_PENDING_DATA_MAX_CHARS_PER_PTY = 2 * 1024 * 1024
const PTY_RENDERER_INTERACTIVE_RESERVE_CHARS = 256 * 1024
// Why: active panes need a bounded lane through old hidden bulk output so a
// keystroke redraw can reach the renderer before every background ACK lands.
Expand Down Expand Up @@ -1561,27 +1569,55 @@ export function registerPtyHandlers(
return [...active, ...background]
}

const pendingDataDropWarnedPtys = new Set<string>()

function dropOversizedPendingPtyData(id: string, pending: PendingPtyData): PendingPtyData {
if (
pending.droppedOutput === true ||
pending.data.length <= PTY_PENDING_DATA_MAX_CHARS_PER_PTY
) {
return pending
}
if (!pendingDataDropWarnedPtys.has(id)) {
pendingDataDropWarnedPtys.add(id)
console.error(
`[pty] dropped ${pending.data.length} buffered chars for ${id}: renderer not receiving and per-PTY pending cap exceeded; pane will restore from the main-owned snapshot`
)
}
// Why empty data, not a trimmed tail: a mid-stream gap would silently
// corrupt the pane. The droppedOutput sentinel routes the pane through
// hidden-output restore, which repaints from the authoritative main-owned
// buffer and realigns with the live stream by sequence.
return { data: '', droppedOutput: true }
}
Comment on lines +1577 to +1602

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

pendingDataDropWarnedPtys is never cleaned up on PTY exit.

Every other per-PTY map populated in this file (lastInputAtByPty, interactiveOutputCharsByPty, rendererInFlightCharsByPty) is explicitly deleted for payload.id in localExitUnsub's onExit handler. pendingDataDropWarnedPtys has no matching cleanup, so an entry persists for the lifetime of the window/session for every PTY that ever hit the pending-cap warning once, even after the PTY exits.

🧹 Proposed fix: clean up on PTY exit
   localExitUnsub = localProvider.onExit((payload) => {
     ...
         lastInputAtByPty.delete(payload.id)
         interactiveOutputCharsByPty.delete(payload.id)
+        pendingDataDropWarnedPtys.delete(payload.id)
         rendererInFlightTotalChars = Math.max(


function appendPendingPtyData(
id: string,
existing: PendingPtyData | undefined,
data: string,
startSeq: number | undefined,
preservesSeq: boolean,
containsBackgroundOutput: boolean
): PendingPtyData {
// Why: once over the cap, stay dropped at O(1) memory until the renderer
// can receive again — the restore sentinel supersedes any interim bytes.
if (existing?.droppedOutput === true) {
return existing
}
const nextContainsBackgroundOutput =
existing?.containsBackgroundOutput === true || containsBackgroundOutput
if (!preservesSeq) {
return {
return dropOversizedPendingPtyData(id, {
data: (existing?.data ?? '') + data,
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})
}
})
}
if (!existing) {
return {
return dropOversizedPendingPtyData(id, {
data,
...(typeof startSeq === 'number' ? { startSeq } : {}),
...(nextContainsBackgroundOutput ? { containsBackgroundOutput: true } : {})
}
})
}
const next: PendingPtyData = {
data: existing.data + data,
Expand All @@ -1590,7 +1626,7 @@ export function registerPtyHandlers(
if (typeof existing.startSeq === 'number') {
next.startSeq = existing.startSeq
}
return next
return dropOversizedPendingPtyData(id, next)
}

function schedulePendingDataFlush(delayMs: number): void {
Expand Down Expand Up @@ -1618,6 +1654,14 @@ export function registerPtyHandlers(
continue
}
pendingData.delete(id)
if (pending.droppedOutput === true) {
// Why: the buffered bytes were dropped at the pending cap; tell the
// renderer so the pane repaints from the main-owned buffer snapshot
// instead of continuing a stream with a silent gap.
sendPtyDataToRenderer(id, { id, data: '', droppedOutput: true })
writes++
continue
}
const { data } = pending
const chunk = data.slice(0, PTY_BATCH_FLUSH_CHUNK_CHARS)
const remaining = data.slice(PTY_BATCH_FLUSH_CHUNK_CHARS)
Expand Down Expand Up @@ -1703,6 +1747,7 @@ export function registerPtyHandlers(
}
const existing = pendingData.get(payload.id)
const pending = appendPendingPtyData(
payload.id,
existing,
rendererData,
startSeq,
Expand Down
1 change: 1 addition & 0 deletions src/preload/api-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1196,6 +1196,7 @@ export type PreloadApi = {
seq?: number
rawLength?: number
background?: boolean
droppedOutput?: boolean
}) => void
) => () => void
onReplay: (callback: (data: { id: string; data: string }) => void) => () => void
Expand Down
2 changes: 2 additions & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,7 @@ const api = {
seq?: number
rawLength?: number
background?: boolean
droppedOutput?: boolean
}) => void
): (() => void) => {
const listener = (
Expand All @@ -900,6 +901,7 @@ const api = {
seq?: number
rawLength?: number
background?: boolean
droppedOutput?: boolean
}
) => callback(data)
ipcRenderer.on('pty:data', listener)
Expand Down
52 changes: 51 additions & 1 deletion src/renderer/src/components/terminal-pane/pty-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ type StoreState = {
}

type ConnectCallbacks = {
onData?: (data: string, meta?: { seq?: number; rawLength?: number; background?: boolean }) => void
onData?: (
data: string,
meta?: { seq?: number; rawLength?: number; background?: boolean; droppedOutput?: boolean }
) => void
onReplayData?: (data: string, meta?: { clearBeforeReplay?: boolean }) => void
onError?: (msg: string) => void
}
Expand Down Expand Up @@ -6716,6 +6719,53 @@ describe('connectPanePty', () => {
}
})

it('repaints from the main-owned snapshot when main drops pending output at the cap', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
const capturedDataCallback: {
current: ((data: string, meta?: { droppedOutput?: boolean }) => 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
>
getMainBufferSnapshot.mockResolvedValue({
data: 'healed from snapshot\r\n',
cols: 100,
rows: 30
})

const pane = createPane(1)
const manager = createManager(1)
const binding = connectPanePty(
pane as never,
manager as never,
createDeps({ isVisibleRef: { current: true } }) as never
)
try {
await flushAsyncTicks(6)
getMainBufferSnapshot.mockClear()

// Main hit the per-PTY pending cap while the renderer was starved and
// sent the droppedOutput sentinel: the stream has a gap, so the pane
// must repaint from the authoritative main-owned buffer.
capturedDataCallback.current?.('', { droppedOutput: true })
await flushAsyncTicks(20)

expect(getMainBufferSnapshot).toHaveBeenCalled()
expect(pane.terminal.write).toHaveBeenCalledWith(
expect.stringContaining('healed from snapshot'),
expect.any(Function)
)
} finally {
binding.dispose()
}
})

it('keeps split stateful Codex queries live after becoming visible', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport('pty-id')
Expand Down
7 changes: 7 additions & 0 deletions src/renderer/src/components/terminal-pane/pty-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4607,6 +4607,13 @@ export function connectPanePty(
}
observeStartupDraftPasteReadiness(data)
resetHiddenOutputRestoreIfPtyChanged()
if (meta?.droppedOutput === true) {
// Why: main dropped this PTY's buffered output at the pending cap
// (renderer was not receiving). The stream has a gap, so repaint the
// pane from the main-owned buffer snapshot instead of writing on.
markHiddenOutputRestoreNeeded()
return
}
respondToTerminalPixelSizeQueries(data)
observeTerminalBracketedPasteModeOutput(pane.terminal, data)
for (const link of observeTerminalGitHubPRLink(data)) {
Expand Down
7 changes: 7 additions & 0 deletions src/renderer/src/components/terminal-pane/pty-dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export type PtyDataMeta = {
seq?: number
rawLength?: number
background?: boolean
/** Main dropped this PTY's buffered output at the pending cap; the pane
* must repaint from the main-owned snapshot instead of the live stream. */
droppedOutput?: boolean
}

export const ptyDataHandlers = new Map<string, (data: string, meta?: PtyDataMeta) => void>()
Expand Down Expand Up @@ -120,6 +123,10 @@ export function ensurePtyDispatcher(): void {
meta ??= {}
meta.background = true
}
if (payload.droppedOutput === true) {
meta ??= {}
meta.droppedOutput = true
}
const handler = ptyDataHandlers.get(payload.id)
if (handler) {
handler(payload.data, meta)
Expand Down
Loading
Loading