Merge PR #7153 (combined #7150 terminal freeze/memory fixes + #7139 cooperative drain) into orca-performance for extended testing
This commit is contained in:
+143
-1
@@ -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)
|
||||
@@ -6936,6 +6950,106 @@ 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('scales the pending-output cap with the scrollback setting', async () => {
|
||||
vi.useFakeTimers()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const mockProc = createMockProc()
|
||||
spawnMock.mockReturnValue(mockProc.proc)
|
||||
|
||||
try {
|
||||
// 50k-row scrollback ⇒ 6 MB pending cap instead of the 2 MB floor.
|
||||
registerPtyHandlers(mainWindow as never, undefined, undefined, (() => ({
|
||||
terminalScrollbackRows: 50_000
|
||||
})) as never)
|
||||
await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24, cwd: '/tmp' })
|
||||
mainWindow.webContents.send.mockClear()
|
||||
|
||||
// Saturate the in-flight window with no ACKs, then buffer 3 MB — over
|
||||
// the floor, under the scaled cap: it must be retained, not dropped.
|
||||
mockProc.emitData('x'.repeat(600 * 1024))
|
||||
vi.advanceTimersByTime(8)
|
||||
for (let index = 0; index < 32; index++) {
|
||||
vi.advanceTimersByTime(1)
|
||||
}
|
||||
mockProc.emitData('y'.repeat(3 * 1024 * 1024))
|
||||
expect(getPtyRendererDeliveryDebugSnapshot().pendingChars).toBeGreaterThan(3 * 1024 * 1024)
|
||||
|
||||
// The scaled cap still bounds a runaway flood.
|
||||
mockProc.emitData('z'.repeat(4 * 1024 * 1024))
|
||||
expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({
|
||||
pendingPtyCount: 1,
|
||||
pendingChars: 0
|
||||
})
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards only actually in-flight bytes to provider ACK backpressure', async () => {
|
||||
vi.useFakeTimers()
|
||||
const acknowledgeDataEvent = vi.fn()
|
||||
@@ -7374,6 +7488,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)
|
||||
|
||||
+60
-5
@@ -17,6 +17,8 @@ export { getBashShellReadyRcfileContent } from '../providers/local-pty-shell-rea
|
||||
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
|
||||
import type { Store } from '../persistence'
|
||||
import type { GlobalSettings, TuiAgent } from '../../shared/types'
|
||||
import { terminalOutputBacklogCapChars } from '../../shared/terminal-scrollback-policy'
|
||||
import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store'
|
||||
import type { SleepingAgentLaunchConfig } from '../../shared/agent-session-resume'
|
||||
import type { ProjectExecutionRuntimeResolution } from '../../shared/project-execution-runtime'
|
||||
import {
|
||||
@@ -1355,6 +1357,7 @@ export function registerPtyHandlers(
|
||||
data: string
|
||||
startSeq?: number
|
||||
containsBackgroundOutput?: boolean
|
||||
droppedOutput?: true
|
||||
}
|
||||
|
||||
type PtyDataPayload = {
|
||||
@@ -1363,6 +1366,7 @@ export function registerPtyHandlers(
|
||||
seq?: number
|
||||
rawLength?: number
|
||||
background?: boolean
|
||||
droppedOutput?: boolean
|
||||
}
|
||||
|
||||
const pendingData = new Map<string, PendingPtyData>()
|
||||
@@ -1376,6 +1380,15 @@ 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).
|
||||
// Why read settings live: the cap scales with the user's scrollback setting
|
||||
// so power users don't lose lines their scrollback would have retained.
|
||||
const pendingDataCapChars = (): number =>
|
||||
terminalOutputBacklogCapChars(getSettings?.().terminalScrollbackRows)
|
||||
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.
|
||||
@@ -1564,27 +1577,60 @@ export function registerPtyHandlers(
|
||||
return [...active, ...background]
|
||||
}
|
||||
|
||||
const pendingDataDropWarnedPtys = new Set<string>()
|
||||
|
||||
function dropOversizedPendingPtyData(id: string, pending: PendingPtyData): PendingPtyData {
|
||||
const capChars = pendingDataCapChars()
|
||||
if (pending.droppedOutput === true || pending.data.length <= capChars) {
|
||||
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: field visibility for cap tuning — drop frequency and size decide
|
||||
// whether the cap is too small (issue #2836 / #7017). No pty id: session
|
||||
// ids can embed workspace paths.
|
||||
recordCrashBreadcrumb('terminal_pending_output_dropped', {
|
||||
droppedChars: pending.data.length,
|
||||
capChars
|
||||
})
|
||||
}
|
||||
// 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 }
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -1593,7 +1639,7 @@ export function registerPtyHandlers(
|
||||
if (typeof existing.startSeq === 'number') {
|
||||
next.startSeq = existing.startSeq
|
||||
}
|
||||
return next
|
||||
return dropOversizedPendingPtyData(id, next)
|
||||
}
|
||||
|
||||
function schedulePendingDataFlush(delayMs: number): void {
|
||||
@@ -1621,6 +1667,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)
|
||||
@@ -1782,6 +1836,7 @@ export function registerPtyHandlers(
|
||||
}
|
||||
const existing = pendingData.get(payload.id)
|
||||
const pending = appendPendingPtyData(
|
||||
payload.id,
|
||||
existing,
|
||||
rendererData,
|
||||
startSeq,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -890,6 +890,7 @@ const api = {
|
||||
seq?: number
|
||||
rawLength?: number
|
||||
background?: boolean
|
||||
droppedOutput?: boolean
|
||||
}) => void
|
||||
): (() => void) => {
|
||||
const listener = (
|
||||
@@ -900,6 +901,7 @@ const api = {
|
||||
seq?: number
|
||||
rawLength?: number
|
||||
background?: boolean
|
||||
droppedOutput?: boolean
|
||||
}
|
||||
) => callback(data)
|
||||
ipcRenderer.on('pty:data', listener)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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')
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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>()
|
||||
@@ -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)
|
||||
|
||||
@@ -82,6 +82,37 @@ describe('createIpcPtyTransport', () => {
|
||||
transport.disconnect()
|
||||
})
|
||||
|
||||
it('leaves the transport silently unbound after a failed connect — sendInput drops with no write IPC (frozen-terminal repro)', async () => {
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
|
||||
const write = window.api.pty.write as unknown as ReturnType<typeof vi.fn>
|
||||
const transport = createIpcPtyTransport({})
|
||||
|
||||
// Generic spawn failure (e.g. daemon not ready during a startup restore):
|
||||
// the error IS surfaced via onError, but the transport stays unbound and
|
||||
// every later keystroke is dropped with no further signal.
|
||||
spawn.mockRejectedValueOnce(new Error('daemon socket not ready'))
|
||||
const onError = vi.fn()
|
||||
await transport.connect({ url: '', callbacks: { onError } })
|
||||
expect(onError).toHaveBeenCalled()
|
||||
expect(transport.isConnected()).toBe(false)
|
||||
expect(transport.sendInput('echo hello\r')).toBe(false)
|
||||
await flushPtySideEffects()
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
|
||||
// The tombstoned-session rejection is swallowed with NO callback at all —
|
||||
// a restored pane that hits it renders persisted content while eating
|
||||
// keystrokes with zero user-visible signal (Discord #performance / #2836).
|
||||
spawn.mockRejectedValueOnce(new Error('TerminalKilledError: session xyz was explicitly killed'))
|
||||
const onErrorKilled = vi.fn()
|
||||
await transport.connect({ url: '', callbacks: { onError: onErrorKilled } })
|
||||
expect(onErrorKilled).not.toHaveBeenCalled()
|
||||
expect(transport.isConnected()).toBe(false)
|
||||
expect(transport.sendInput('echo hello\r')).toBe(false)
|
||||
await flushPtySideEffects()
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignores a stale exit for a previous PTY after reconnecting the same transport', async () => {
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const spawn = window.api.pty.spawn as unknown as ReturnType<typeof vi.fn>
|
||||
|
||||
@@ -1,6 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ManagedPane } from '@/lib/pane-manager/pane-manager'
|
||||
import { isPaneReplaying, replayIntoTerminal, type ReplayingPanesRef } from './replay-guard'
|
||||
import {
|
||||
isPaneReplaying,
|
||||
replayIntoTerminal,
|
||||
replayIntoTerminalAsync,
|
||||
type ReplayingPanesRef
|
||||
} from './replay-guard'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
recordRendererCrashBreadcrumb: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/crash-breadcrumb-recorder', () => ({
|
||||
recordRendererCrashBreadcrumb: mocks.recordRendererCrashBreadcrumb
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.recordRendererCrashBreadcrumb.mockClear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function makeRef(): ReplayingPanesRef {
|
||||
return { current: new Map() } as ReplayingPanesRef
|
||||
@@ -169,3 +190,164 @@ describe('replay-guard', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('replay-guard stall handling (probe-certified release)', () => {
|
||||
it('HOLDS the guard while a slow replay is still parsing — a probe is queued, never a blind release', () => {
|
||||
// Why this is the load-bearing safety test: a time-based release here
|
||||
// would leak xterm auto-replies into the shell (and a leaked ESC into an
|
||||
// agent TUI reads as the user pressing Escape). The guard must only
|
||||
// release when the pipeline itself proves the replay parsed.
|
||||
vi.useFakeTimers()
|
||||
const ref = makeRef()
|
||||
const { pane, terminal } = makeFakePane(1)
|
||||
|
||||
replayIntoTerminal(pane, ref, 'slow but alive', 1_000)
|
||||
expect(isPaneReplaying(ref, 1)).toBe(true)
|
||||
|
||||
// Stall check fires: an empty probe write is enqueued behind the replay.
|
||||
vi.advanceTimersByTime(1_000)
|
||||
expect(terminal.lastData).toEqual(['slow but alive', ''])
|
||||
// Probe is pending → replay genuinely still parsing → guard holds.
|
||||
expect(isPaneReplaying(ref, 1)).toBe(true)
|
||||
vi.advanceTimersByTime(999)
|
||||
expect(isPaneReplaying(ref, 1)).toBe(true)
|
||||
|
||||
// Parsing finishes: FIFO runs the replay completion first (normal
|
||||
// release), then the probe completion as a no-op.
|
||||
terminal.flush()
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
expect(ref.current.has(1)).toBe(false)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(120_000)
|
||||
expect(ref.current.has(1)).toBe(false)
|
||||
})
|
||||
|
||||
it('releases when the probe parses but the replay completion was lost, and reports it', () => {
|
||||
vi.useFakeTimers()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const ref = makeRef()
|
||||
const { pane, terminal } = makeFakePane(1)
|
||||
|
||||
replayIntoTerminal(pane, ref, 'restored bytes', 1_000)
|
||||
terminal.pendingCallbacks.shift() // xterm lost the replay's completion
|
||||
vi.advanceTimersByTime(1_000) // stall check → probe enqueued
|
||||
|
||||
// The probe's completion firing certifies every earlier replay byte
|
||||
// parsed — releasing now cannot leak auto-replies.
|
||||
terminal.flush()
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_replay_guard_lost_completion',
|
||||
{ paneId: 1 }
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('releases after the probe itself never parses (wedged pipeline) and reports it', () => {
|
||||
vi.useFakeTimers()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const ref = makeRef()
|
||||
const { pane } = makeFakePane(1)
|
||||
|
||||
replayIntoTerminal(pane, ref, 'restored bytes', 1_000)
|
||||
vi.advanceTimersByTime(1_000) // stall check → probe enqueued
|
||||
expect(isPaneReplaying(ref, 1)).toBe(true)
|
||||
|
||||
// A wedged parser will never run the probe callback — and can never
|
||||
// emit auto-replies either, so this bounded release cannot leak input.
|
||||
vi.advanceTimersByTime(1_000)
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_replay_guard_wedged_release',
|
||||
{ paneId: 1 }
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('releases immediately when the probe write throws (terminal disposed mid-replay)', () => {
|
||||
vi.useFakeTimers()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const ref = makeRef()
|
||||
const { pane, terminal } = makeFakePane(1)
|
||||
|
||||
replayIntoTerminal(pane, ref, 'restored bytes', 1_000)
|
||||
terminal.write = () => {
|
||||
throw new Error('terminal disposed')
|
||||
}
|
||||
vi.advanceTimersByTime(1_000)
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_replay_guard_wedged_release',
|
||||
{ paneId: 1 }
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps overlapping engagements independent through a lost completion', () => {
|
||||
vi.useFakeTimers()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const ref = makeRef()
|
||||
const { pane, terminal } = makeFakePane(1)
|
||||
|
||||
replayIntoTerminal(pane, ref, 'lost completion', 1_000)
|
||||
replayIntoTerminal(pane, ref, 'healthy completion', 60_000)
|
||||
terminal.pendingCallbacks.shift() // drop only the first completion
|
||||
vi.advanceTimersByTime(1_000) // first engagement's probe enqueued
|
||||
|
||||
terminal.flush() // healthy completion + probe both parse
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
expect(ref.current.has(1)).toBe(false)
|
||||
|
||||
vi.advanceTimersByTime(120_000)
|
||||
expect(ref.current.has(1)).toBe(false)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('never probes after a normal completion', () => {
|
||||
vi.useFakeTimers()
|
||||
const ref = makeRef()
|
||||
const { pane, terminal } = makeFakePane(1)
|
||||
|
||||
replayIntoTerminal(pane, ref, 'healthy', 1_000)
|
||||
terminal.flush()
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
|
||||
vi.advanceTimersByTime(60_000)
|
||||
expect(terminal.lastData).toEqual(['healthy'])
|
||||
expect(mocks.recordRendererCrashBreadcrumb).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves replayIntoTerminalAsync via the wedged path so restore chains cannot hang', async () => {
|
||||
vi.useFakeTimers()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const ref = makeRef()
|
||||
const { pane } = makeFakePane(1)
|
||||
|
||||
const replayDone = replayIntoTerminalAsync(pane, ref, 'restored bytes', 1_000)
|
||||
let resolved = false
|
||||
void replayDone.then(() => {
|
||||
resolved = true
|
||||
})
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
expect(resolved).toBe(true)
|
||||
expect(isPaneReplaying(ref, 1)).toBe(false)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ManagedPane } from '@/lib/pane-manager/pane-manager'
|
||||
import { writeForegroundTerminalChunk } from '@/lib/pane-manager/pane-terminal-foreground-render-settle'
|
||||
import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder'
|
||||
|
||||
// Why: xterm.js auto-responds to terminal query sequences (DA1 `CSI c`,
|
||||
// DECRQM `CSI ? Ps $ p`, OSC 10/11 color queries, focus events, CPR) by
|
||||
@@ -27,10 +28,100 @@ import { writeForegroundTerminalChunk } from '@/lib/pane-manager/pane-terminal-f
|
||||
|
||||
export type ReplayingPanesRef = React.RefObject<Map<number, number>>
|
||||
|
||||
// Why stall handling exists: the decrement above only runs when xterm
|
||||
// completes the write. A wedged WriteBuffer (sync throw escaping a parse
|
||||
// handler or a write-completion callback — see
|
||||
// xterm-write-buffer-stall.repro.test.ts) or a disposed-terminal race can
|
||||
// drop that completion forever, leaving the guard latched on a live pane —
|
||||
// which silently eats every keystroke (Discord #performance / issue #2836).
|
||||
//
|
||||
// Why release is probe-certified, never time-based: a blind timeout release
|
||||
// while a slow replay is still parsing would let xterm's auto-replies leak
|
||||
// into the shell — and into agent TUIs, where a leaked ESC reads as the user
|
||||
// pressing Escape. Instead, when a completion looks overdue we enqueue an
|
||||
// empty probe write. xterm parses writes in order, so only three states are
|
||||
// possible, and release is provably safe in every state that releases:
|
||||
// 1. probe completes, replay callback already ran → normal release won.
|
||||
// 2. probe completes, replay callback never ran → every replay byte has
|
||||
// parsed (FIFO), so no further auto-replies can exist; the completion
|
||||
// was genuinely lost. Release.
|
||||
// 3. probe never completes → the pipeline is
|
||||
// wedged; a dead parser can never emit auto-replies, so releasing after
|
||||
// a bounded wait cannot leak anything — and the pane needs recovery,
|
||||
// which the breadcrumb reports.
|
||||
// While the probe is pending (slow-but-alive replay), the guard HOLDS.
|
||||
const REPLAY_GUARD_STALL_CHECK_MS = 10_000
|
||||
|
||||
export function isPaneReplaying(ref: ReplayingPanesRef, paneId: number): boolean {
|
||||
return (ref.current.get(paneId) ?? 0) > 0
|
||||
}
|
||||
|
||||
type ReplayGuardWriteTarget = Pick<ManagedPane['terminal'], 'write'>
|
||||
|
||||
/**
|
||||
* Engage the replay counter for one write and return the release function.
|
||||
* Release runs exactly once — from xterm's write completion or, failing
|
||||
* that, from the probe-certified stall path — so a lost completion cannot
|
||||
* latch the guard.
|
||||
*/
|
||||
function engageReplayGuard(
|
||||
map: Map<number, number>,
|
||||
paneId: number,
|
||||
terminal: ReplayGuardWriteTarget,
|
||||
stallCheckMs: number,
|
||||
onRelease?: () => void
|
||||
): () => void {
|
||||
map.set(paneId, (map.get(paneId) ?? 0) + 1)
|
||||
let released = false
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
const release = (reason: 'parsed' | 'lost-completion' | 'wedged'): void => {
|
||||
if (released) {
|
||||
return
|
||||
}
|
||||
released = true
|
||||
if (timer !== null) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
const remaining = (map.get(paneId) ?? 1) - 1
|
||||
if (remaining <= 0) {
|
||||
map.delete(paneId)
|
||||
} else {
|
||||
map.set(paneId, remaining)
|
||||
}
|
||||
if (reason === 'lost-completion') {
|
||||
console.error(
|
||||
`[terminal] replay guard released for pane ${paneId} — the probe write parsed but the replay completion never arrived (lost write callback)`
|
||||
)
|
||||
recordRendererCrashBreadcrumb('terminal_replay_guard_lost_completion', { paneId })
|
||||
} else if (reason === 'wedged') {
|
||||
console.error(
|
||||
`[terminal] replay guard released for pane ${paneId} — the probe write never parsed (wedged xterm write pipeline; pane likely needs recovery)`
|
||||
)
|
||||
recordRendererCrashBreadcrumb('terminal_replay_guard_wedged_release', { paneId })
|
||||
}
|
||||
onRelease?.()
|
||||
}
|
||||
const probeForStall = (): void => {
|
||||
if (released) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// FIFO certification: this callback can only run after every replay
|
||||
// byte queued before it has parsed (state 2 above).
|
||||
terminal.write('', () => release('lost-completion'))
|
||||
} catch {
|
||||
// write threw (terminal disposed mid-replay): nothing will ever parse,
|
||||
// so no auto-replies can leak.
|
||||
release('wedged')
|
||||
return
|
||||
}
|
||||
timer = setTimeout(() => release('wedged'), stallCheckMs)
|
||||
}
|
||||
timer = setTimeout(probeForStall, stallCheckMs)
|
||||
return () => release('parsed')
|
||||
}
|
||||
|
||||
/** Writes `data` into the pane's terminal with the replay guard engaged,
|
||||
* so xterm's auto-replies to embedded query sequences do not leak to the
|
||||
* shell as input. The counter increments/decrements so nested replays
|
||||
@@ -38,53 +129,50 @@ export function isPaneReplaying(ref: ReplayingPanesRef, paneId: number): boolean
|
||||
export function replayIntoTerminal(
|
||||
pane: ManagedPane,
|
||||
replayingPanesRef: ReplayingPanesRef,
|
||||
data: string
|
||||
data: string,
|
||||
stallCheckMs: number = REPLAY_GUARD_STALL_CHECK_MS
|
||||
): void {
|
||||
if (!data) {
|
||||
return
|
||||
}
|
||||
const map = replayingPanesRef.current
|
||||
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
|
||||
const onParsed = (): void => {
|
||||
const remaining = (map.get(pane.id) ?? 1) - 1
|
||||
if (remaining <= 0) {
|
||||
map.delete(pane.id)
|
||||
} else {
|
||||
map.set(pane.id, remaining)
|
||||
}
|
||||
}
|
||||
const releaseParsed = engageReplayGuard(
|
||||
replayingPanesRef.current,
|
||||
pane.id,
|
||||
pane.terminal,
|
||||
stallCheckMs
|
||||
)
|
||||
// Why: hidden/snapshot replay bypasses the live foreground write path, but
|
||||
// WebGL/canvas renderers still need a post-parse repaint to drop stale cells.
|
||||
writeForegroundTerminalChunk(pane.terminal, data, {
|
||||
forceViewportRefresh: true,
|
||||
followupViewportRefresh: true,
|
||||
onParsed
|
||||
onParsed: releaseParsed
|
||||
})
|
||||
}
|
||||
|
||||
export function replayIntoTerminalAsync(
|
||||
pane: ManagedPane,
|
||||
replayingPanesRef: ReplayingPanesRef,
|
||||
data: string
|
||||
data: string,
|
||||
stallCheckMs: number = REPLAY_GUARD_STALL_CHECK_MS
|
||||
): Promise<void> {
|
||||
if (!data) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
const map = replayingPanesRef.current
|
||||
map.set(pane.id, (map.get(pane.id) ?? 0) + 1)
|
||||
return new Promise((resolve) => {
|
||||
// Why resolve on either release path: callers await this to sequence
|
||||
// restore steps; a lost write completion must not hang the restore chain.
|
||||
const releaseParsed = engageReplayGuard(
|
||||
replayingPanesRef.current,
|
||||
pane.id,
|
||||
pane.terminal,
|
||||
stallCheckMs,
|
||||
resolve
|
||||
)
|
||||
writeForegroundTerminalChunk(pane.terminal, data, {
|
||||
forceViewportRefresh: true,
|
||||
followupViewportRefresh: true,
|
||||
onParsed: () => {
|
||||
const remaining = (map.get(pane.id) ?? 1) - 1
|
||||
if (remaining <= 0) {
|
||||
map.delete(pane.id)
|
||||
} else {
|
||||
map.set(pane.id, remaining)
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
onParsed: releaseParsed
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveEffectiveTerminalAppearance
|
||||
} from '@/lib/terminal-theme'
|
||||
import { buildFontFamily } from './layout-serialization'
|
||||
import { guardParserHandler } from './terminal-parser-handler-guard'
|
||||
import { captureScrollState, restoreScrollState, safeFit } from '@/lib/pane-manager/pane-tree-ops'
|
||||
import {
|
||||
normalizeTerminalFastScrollSensitivity,
|
||||
@@ -55,50 +56,56 @@ export function installMode2031Handlers(deps: Mode2031HandlerDeps): IDisposable[
|
||||
// continue processing the same sequence, so compound sequences like
|
||||
// `CSI ?25;2031h` still update cursor visibility correctly.
|
||||
return [
|
||||
deps.parser.registerCsiHandler({ prefix: '?', final: 'h' }, (params) => {
|
||||
if (hasMode2031(params)) {
|
||||
// Why: a restored xterm buffer may contain `CSI ?2031h` emitted by
|
||||
// the previous session's TUI (e.g. Claude Code). Replaying that
|
||||
// buffer runs this handler, and without the guard we'd push
|
||||
// `CSI ?997;1n` via transport.sendInput into a fresh shell that has
|
||||
// no TUI consuming it — zsh then echoes the literal escape sequence
|
||||
// onto the prompt. The replay guard in pty-connection.ts only covers
|
||||
// xterm's own onData auto-replies, not handler-triggered sends, so
|
||||
// gate explicitly here. We also skip recording the subscribe bit:
|
||||
// the fresh shell is not actually subscribed, so a later theme flip
|
||||
// must not push either. A real TUI that starts up after restore will
|
||||
// re-emit `?2031h` itself and register normally.
|
||||
//
|
||||
// Why this broad guard is safe across all replay sources: the only
|
||||
// replay path that can carry raw `?2031h` is cold-restore scrollback
|
||||
// (pty-connection.ts), which is disk-replayed PTY output against a
|
||||
// fresh shell — the case this guard targets. Daemon snapshot payloads
|
||||
// (`rehydrateSequences + SerializeAddon.serialize()`) and persisted
|
||||
// scrollback (`SerializeAddon.serialize()`) never contain `?2031`:
|
||||
// SerializeAddon's _serializeModes whitelists only ?1h/?66h/?2004h/
|
||||
// [4h/?6h/?45h/?1004h/?7l/mouse modes/?25l, and buildRehydrateSequences
|
||||
// emits only ?1049h/?2004h/?1h/mouse reporting modes. If xterm ever
|
||||
// adds ?2031 to that whitelist, this guard would start suppressing
|
||||
// legitimate subscribes during snapshot reattach — revisit then.
|
||||
if (deps.isReplaying()) {
|
||||
return false
|
||||
deps.parser.registerCsiHandler(
|
||||
{ prefix: '?', final: 'h' },
|
||||
guardParserHandler('csi-mode2031-subscribe', (params) => {
|
||||
if (hasMode2031(params)) {
|
||||
// Why: a restored xterm buffer may contain `CSI ?2031h` emitted by
|
||||
// the previous session's TUI (e.g. Claude Code). Replaying that
|
||||
// buffer runs this handler, and without the guard we'd push
|
||||
// `CSI ?997;1n` via transport.sendInput into a fresh shell that has
|
||||
// no TUI consuming it — zsh then echoes the literal escape sequence
|
||||
// onto the prompt. The replay guard in pty-connection.ts only covers
|
||||
// xterm's own onData auto-replies, not handler-triggered sends, so
|
||||
// gate explicitly here. We also skip recording the subscribe bit:
|
||||
// the fresh shell is not actually subscribed, so a later theme flip
|
||||
// must not push either. A real TUI that starts up after restore will
|
||||
// re-emit `?2031h` itself and register normally.
|
||||
//
|
||||
// Why this broad guard is safe across all replay sources: the only
|
||||
// replay path that can carry raw `?2031h` is cold-restore scrollback
|
||||
// (pty-connection.ts), which is disk-replayed PTY output against a
|
||||
// fresh shell — the case this guard targets. Daemon snapshot payloads
|
||||
// (`rehydrateSequences + SerializeAddon.serialize()`) and persisted
|
||||
// scrollback (`SerializeAddon.serialize()`) never contain `?2031`:
|
||||
// SerializeAddon's _serializeModes whitelists only ?1h/?66h/?2004h/
|
||||
// [4h/?6h/?45h/?1004h/?7l/mouse modes/?25l, and buildRehydrateSequences
|
||||
// emits only ?1049h/?2004h/?1h/mouse reporting modes. If xterm ever
|
||||
// adds ?2031 to that whitelist, this guard would start suppressing
|
||||
// legitimate subscribes during snapshot reattach — revisit then.
|
||||
if (deps.isReplaying()) {
|
||||
return false
|
||||
}
|
||||
deps.paneMode2031.set(deps.paneId, true)
|
||||
deps.onSubscribe()
|
||||
}
|
||||
deps.paneMode2031.set(deps.paneId, true)
|
||||
deps.onSubscribe()
|
||||
}
|
||||
return false
|
||||
}),
|
||||
return false
|
||||
})
|
||||
),
|
||||
// Why no replay guard on the unsubscribe branch: clearing stale bookkeeping
|
||||
// is harmless. We only push CSI 997 on subscribe, never on unsubscribe, so
|
||||
// even if a cold-restore replay carries `?2031l`, this handler just deletes
|
||||
// map entries that a later real `?2031h` will re-populate normally.
|
||||
deps.parser.registerCsiHandler({ prefix: '?', final: 'l' }, (params) => {
|
||||
if (hasMode2031(params)) {
|
||||
deps.paneMode2031.delete(deps.paneId)
|
||||
deps.paneLastThemeMode.delete(deps.paneId)
|
||||
}
|
||||
return false
|
||||
})
|
||||
deps.parser.registerCsiHandler(
|
||||
{ prefix: '?', final: 'l' },
|
||||
guardParserHandler('csi-mode2031-unsubscribe', (params) => {
|
||||
if (hasMode2031(params)) {
|
||||
deps.paneMode2031.delete(deps.paneId)
|
||||
deps.paneLastThemeMode.delete(deps.paneId)
|
||||
}
|
||||
return false
|
||||
})
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
terminalOscColorQuerySlotsForBody,
|
||||
type TerminalOscColorQuerySlot
|
||||
} from '../../../../shared/terminal-osc-color-reply'
|
||||
import { guardParserHandler } from './terminal-parser-handler-guard'
|
||||
|
||||
export const DEFAULT_DA1_RESPONSE = '\x1b[?1;2c'
|
||||
export const CONPTY_DA1_RESPONSE = '\x1b[?61;4c'
|
||||
@@ -118,37 +119,46 @@ export function installTerminalCapabilityReplyHandlers(
|
||||
deps: TerminalCapabilityRepliesDeps
|
||||
): IDisposable {
|
||||
const disposables = [
|
||||
deps.parser.registerCsiHandler({ final: 'c' }, (params) => {
|
||||
if (!isPrimaryDeviceAttributesQuery(params)) {
|
||||
return false
|
||||
}
|
||||
// Why: restored scrollback may contain old DA1 queries; answering those
|
||||
// into the fresh shell recreates the stray-input leak this handler fixes.
|
||||
if (!deps.isReplaying()) {
|
||||
deps.sendInput(deps.da1Response ?? DEFAULT_DA1_RESPONSE)
|
||||
}
|
||||
return true
|
||||
}),
|
||||
deps.parser.registerOscHandler(10, (data) => {
|
||||
const slots = terminalOscColorQuerySlotsForBody(10, data.trim())
|
||||
if (!slots) {
|
||||
return false
|
||||
}
|
||||
if (deps.isReplaying()) {
|
||||
deps.parser.registerCsiHandler(
|
||||
{ final: 'c' },
|
||||
guardParserHandler('csi-da1', (params) => {
|
||||
if (!isPrimaryDeviceAttributesQuery(params)) {
|
||||
return false
|
||||
}
|
||||
// Why: restored scrollback may contain old DA1 queries; answering those
|
||||
// into the fresh shell recreates the stray-input leak this handler fixes.
|
||||
if (!deps.isReplaying()) {
|
||||
deps.sendInput(deps.da1Response ?? DEFAULT_DA1_RESPONSE)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return sendTerminalOscColorQueryRepliesForSlots(slots, deps.terminal, deps.sendInput)
|
||||
}),
|
||||
deps.parser.registerOscHandler(11, (data) => {
|
||||
const slots = terminalOscColorQuerySlotsForBody(11, data.trim())
|
||||
if (!slots) {
|
||||
return false
|
||||
}
|
||||
if (deps.isReplaying()) {
|
||||
return true
|
||||
}
|
||||
return sendTerminalOscColorQueryRepliesForSlots(slots, deps.terminal, deps.sendInput)
|
||||
})
|
||||
})
|
||||
),
|
||||
deps.parser.registerOscHandler(
|
||||
10,
|
||||
guardParserHandler('osc-10-color-query', (data) => {
|
||||
const slots = terminalOscColorQuerySlotsForBody(10, data.trim())
|
||||
if (!slots) {
|
||||
return false
|
||||
}
|
||||
if (deps.isReplaying()) {
|
||||
return true
|
||||
}
|
||||
return sendTerminalOscColorQueryRepliesForSlots(slots, deps.terminal, deps.sendInput)
|
||||
})
|
||||
),
|
||||
deps.parser.registerOscHandler(
|
||||
11,
|
||||
guardParserHandler('osc-11-color-query', (data) => {
|
||||
const slots = terminalOscColorQuerySlotsForBody(11, data.trim())
|
||||
if (!slots) {
|
||||
return false
|
||||
}
|
||||
if (deps.isReplaying()) {
|
||||
return true
|
||||
}
|
||||
return sendTerminalOscColorQueryRepliesForSlots(slots, deps.terminal, deps.sendInput)
|
||||
})
|
||||
)
|
||||
]
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Terminal } from '@xterm/headless'
|
||||
import {
|
||||
_resetParserHandlerReportsForTests,
|
||||
guardParserHandler
|
||||
} from './terminal-parser-handler-guard'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
recordRendererCrashBreadcrumb: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/crash-breadcrumb-recorder', () => ({
|
||||
recordRendererCrashBreadcrumb: mocks.recordRendererCrashBreadcrumb
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.recordRendererCrashBreadcrumb.mockClear()
|
||||
_resetParserHandlerReportsForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('guardParserHandler', () => {
|
||||
it('passes arguments and return value through for healthy handlers', () => {
|
||||
const handler = vi.fn((data: string) => data === 'handled')
|
||||
const guarded = guardParserHandler('test-handler', handler)
|
||||
expect(guarded('handled')).toBe(true)
|
||||
expect(guarded('other')).toBe(false)
|
||||
expect(handler).toHaveBeenCalledTimes(2)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('degrades a throwing handler to "not handled" and reports a breadcrumb', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const guarded = guardParserHandler('exploding-handler', () => {
|
||||
throw new TypeError('synthetic handler failure')
|
||||
})
|
||||
expect(guarded()).toBe(false)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_parser_handler_error',
|
||||
expect.objectContaining({
|
||||
handler: 'exploding-handler',
|
||||
errorName: 'TypeError',
|
||||
errorMessage: 'synthetic handler failure'
|
||||
})
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('caps repeated reports per handler', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const guarded = guardParserHandler('spammy-handler', () => {
|
||||
throw new Error('always fails')
|
||||
})
|
||||
for (let i = 0; i < 20; i++) {
|
||||
guarded()
|
||||
}
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledTimes(5)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the real xterm write pipeline alive through a throwing handler (inverse of the wedge repro)', () => {
|
||||
// Why: xterm-write-buffer-stall.repro.test.ts proves an UNguarded throwing
|
||||
// handler permanently wedges the WriteBuffer. This is the fix's proof:
|
||||
// the same poison sequence through a GUARDED handler keeps completing
|
||||
// writes.
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
vi.useFakeTimers()
|
||||
const term = new Terminal({ allowProposedApi: true })
|
||||
const completed: string[] = []
|
||||
term.parser.registerCsiHandler(
|
||||
{ final: 'z' },
|
||||
guardParserHandler('poisoned-csi', () => {
|
||||
throw new Error('synthetic parser handler failure')
|
||||
})
|
||||
)
|
||||
|
||||
term.write('\x1b[z', () => {
|
||||
completed.push('poisoned')
|
||||
})
|
||||
term.write('after', () => {
|
||||
completed.push('after')
|
||||
})
|
||||
expect(() => vi.runAllTimers()).not.toThrow()
|
||||
|
||||
term.write('later', () => {
|
||||
completed.push('later')
|
||||
})
|
||||
vi.runAllTimers()
|
||||
expect(completed).toEqual(['poisoned', 'after', 'later'])
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_parser_handler_error',
|
||||
expect.objectContaining({ handler: 'poisoned-csi' })
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder'
|
||||
|
||||
// Why: xterm's EscapeSequenceParser invokes custom CSI/OSC handlers
|
||||
// synchronously inside WriteBuffer._innerWrite, which has no try/catch. A
|
||||
// handler throw skips the loop's tail re-schedule, and write() only re-arms
|
||||
// on an EMPTY buffer — one throw permanently freezes the pane (output stops;
|
||||
// a pending replay guard never releases and silently eats keystrokes).
|
||||
// Verified against vendored xterm 6.1.0-beta.287 in
|
||||
// xterm-write-buffer-stall.repro.test.ts. Same escape class as
|
||||
// terminal-link-provider-guard.ts, applied to parser handlers.
|
||||
const MAX_REPORTS_PER_HANDLER = 5
|
||||
const reportCountsByHandler = new Map<string, number>()
|
||||
|
||||
/**
|
||||
* Wrap a custom parser handler so a synchronous throw is reported and
|
||||
* degraded to "not handled" (xterm falls through to the previous/default
|
||||
* handler) instead of wedging the terminal's write pipeline.
|
||||
*/
|
||||
export function guardParserHandler<HandlerArgs extends unknown[]>(
|
||||
handlerName: string,
|
||||
handler: (...args: HandlerArgs) => boolean
|
||||
): (...args: HandlerArgs) => boolean {
|
||||
return (...args: HandlerArgs): boolean => {
|
||||
try {
|
||||
return handler(...args)
|
||||
} catch (error: unknown) {
|
||||
const reported = reportCountsByHandler.get(handlerName) ?? 0
|
||||
if (reported < MAX_REPORTS_PER_HANDLER) {
|
||||
reportCountsByHandler.set(handlerName, reported + 1)
|
||||
console.error(`[terminal] parser handler "${handlerName}" threw`, error)
|
||||
recordRendererCrashBreadcrumb('terminal_parser_handler_error', {
|
||||
handler: handlerName,
|
||||
errorName: error instanceof Error ? error.name : typeof error,
|
||||
errorMessage: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function _resetParserHandlerReportsForTests(): void {
|
||||
reportCountsByHandler.clear()
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
resolveTerminalCursorInactiveStyle
|
||||
} from '@/lib/pane-manager/pane-terminal-options'
|
||||
import { normalizeDesktopTerminalScrollbackRows } from '../../../../shared/terminal-scrollback-policy'
|
||||
import { configureTerminalOutputBacklogCap } from '@/lib/pane-manager/pane-terminal-output-scheduler'
|
||||
import { normalizeTerminalTuiMouseWheelMultiplier } from '@/lib/pane-manager/pane-terminal-mouse-wheel'
|
||||
import { buildWindowsPtyCompatibilityOptions } from '@/lib/pane-manager/windows-pty-compatibility'
|
||||
import { buildTerminalKeyboardProtocolOptions } from '@/lib/pane-manager/terminal-keyboard-protocol'
|
||||
@@ -58,6 +59,7 @@ import {
|
||||
import { handleOsc52ClipboardRequest } from './osc52-clipboard'
|
||||
import { showOsc52ClipboardBlockedToast } from './osc52-clipboard-blocked-toast'
|
||||
import { parseOsc7 } from './parse-osc7'
|
||||
import { guardParserHandler } from './terminal-parser-handler-guard'
|
||||
import { resolveTerminalJisYenInput } from './terminal-jis-yen-input'
|
||||
import { installTerminalImeCompositionTracker } from './terminal-ime-composition-tracker'
|
||||
import {
|
||||
@@ -537,6 +539,10 @@ export function useTerminalPaneLifecycle({
|
||||
const terminalScrollbackRows = normalizeDesktopTerminalScrollbackRows(
|
||||
settings?.terminalScrollbackRows
|
||||
)
|
||||
// Why here: the output scheduler's backlog cap scales with the same
|
||||
// scrollback setting; applying it where the setting is read keeps the two
|
||||
// in lockstep without a separate settings subscription.
|
||||
configureTerminalOutputBacklogCap(settings?.terminalScrollbackRows)
|
||||
const systemPrefersDarkRef = useRef(systemPrefersDark)
|
||||
systemPrefersDarkRef.current = systemPrefersDark
|
||||
const previousVisibleForReconcileRef = useRef<TerminalPaneVisibilitySnapshot | null>(null)
|
||||
@@ -780,12 +786,15 @@ export function useTerminalPaneLifecycle({
|
||||
// both the enabled and disabled paths so xterm doesn't fall
|
||||
// through to any other OSC 52 handler and so our intentional drop
|
||||
// in the disabled path is explicit.
|
||||
const osc52Disposable = pane.terminal.parser.registerOscHandler(52, (data) =>
|
||||
handleOsc52ClipboardRequest(data, {
|
||||
allowClipboardWrite: settingsRef.current?.terminalAllowOsc52Clipboard === true,
|
||||
writeClipboardText: window.api.ui.writeClipboardText,
|
||||
onBlockedWrite: showOsc52ClipboardBlockedToast
|
||||
})
|
||||
const osc52Disposable = pane.terminal.parser.registerOscHandler(
|
||||
52,
|
||||
guardParserHandler('osc-52-clipboard', (data) =>
|
||||
handleOsc52ClipboardRequest(data, {
|
||||
allowClipboardWrite: settingsRef.current?.terminalAllowOsc52Clipboard === true,
|
||||
writeClipboardText: window.api.ui.writeClipboardText,
|
||||
onBlockedWrite: showOsc52ClipboardBlockedToast
|
||||
})
|
||||
)
|
||||
)
|
||||
osc52DisposablesRef.current.set(pane.id, osc52Disposable)
|
||||
|
||||
@@ -811,14 +820,17 @@ export function useTerminalPaneLifecycle({
|
||||
confirmed: false
|
||||
})
|
||||
}
|
||||
const osc7Disposable = pane.terminal.parser.registerOscHandler(7, (data) => {
|
||||
const parsedCwd = parseOsc7(data, { uncHost: osc7UncHost })
|
||||
if (parsedCwd) {
|
||||
const confirmed = !isPaneReplaying(replayingPanesRef, pane.id)
|
||||
paneCwdRef.current.set(pane.id, { cwd: parsedCwd, confirmed })
|
||||
}
|
||||
return true
|
||||
})
|
||||
const osc7Disposable = pane.terminal.parser.registerOscHandler(
|
||||
7,
|
||||
guardParserHandler('osc-7-cwd', (data) => {
|
||||
const parsedCwd = parseOsc7(data, { uncHost: osc7UncHost })
|
||||
if (parsedCwd) {
|
||||
const confirmed = !isPaneReplaying(replayingPanesRef, pane.id)
|
||||
paneCwdRef.current.set(pane.id, { cwd: parsedCwd, confirmed })
|
||||
}
|
||||
return true
|
||||
})
|
||||
)
|
||||
osc7DisposablesRef.current.set(pane.id, osc7Disposable)
|
||||
|
||||
// Why: let host-handled keys bypass xterm's kitty CSI-u encoder.
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Repro for the frozen-terminal investigation (Discord #performance / #2836).
|
||||
*
|
||||
* The vendored xterm WriteBuffer (6.1.0-beta.287) permanently wedges when a
|
||||
* synchronous exception escapes a write-completion callback: `_innerWrite`
|
||||
* has no try/catch around `cb()`, the tail `_scheduleInnerWrite()` never
|
||||
* runs, and later `write()` calls only re-schedule processing when the
|
||||
* buffer is EMPTY — which a stalled buffer never is again.
|
||||
*
|
||||
* In Orca, write-completion callbacks run settleForegroundRender → refresh →
|
||||
* renderer/WebGL code (pane-terminal-foreground-render-settle.ts) and the
|
||||
* replay-guard decrement (replay-guard.ts). So one renderer exception during
|
||||
* write completion freezes that pane's output forever AND latches the replay
|
||||
* guard, whose gate in pty-connection.ts onData then silently drops every
|
||||
* keystroke — the exact live-shell/flat-output.log/frozen-pane state the
|
||||
* field reports describe. @xterm/headless shares the same WriteBuffer as
|
||||
* @xterm/xterm at the same pinned version.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Terminal } from '@xterm/headless'
|
||||
|
||||
describe('xterm WriteBuffer stall (vendored 6.1.0-beta.287)', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('permanently stops completing writes after a sync throw in a write-completion callback', () => {
|
||||
vi.useFakeTimers()
|
||||
const term = new Terminal({ allowProposedApi: true })
|
||||
const completed: string[] = []
|
||||
|
||||
term.write('first', () => {
|
||||
completed.push('first')
|
||||
throw new Error('synthetic renderer failure during write completion')
|
||||
})
|
||||
term.write('second', () => {
|
||||
completed.push('second')
|
||||
})
|
||||
|
||||
expect(() => vi.runAllTimers()).toThrow('synthetic renderer failure')
|
||||
|
||||
// The wedge: the stalled buffer is never empty again, so new writes only
|
||||
// enqueue — no drain is ever scheduled and no callback ever fires.
|
||||
term.write('third', () => {
|
||||
completed.push('third')
|
||||
})
|
||||
vi.runAllTimers()
|
||||
expect(completed).toEqual(['first'])
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('permanently stops completing writes after a sync throw in a custom parser handler', () => {
|
||||
// Orca registers custom CSI/OSC handlers (capability replies, titles,
|
||||
// agent status). The parser does NOT isolate sync handler exceptions:
|
||||
// they escape _action and wedge the buffer exactly like the callback
|
||||
// case — custom handlers are a second freeze vector.
|
||||
vi.useFakeTimers()
|
||||
const term = new Terminal({ allowProposedApi: true })
|
||||
const completed: string[] = []
|
||||
term.parser.registerCsiHandler({ final: 'z' }, () => {
|
||||
throw new Error('synthetic parser handler failure')
|
||||
})
|
||||
|
||||
term.write('\x1b[z', () => {
|
||||
completed.push('poisoned')
|
||||
})
|
||||
term.write('after', () => {
|
||||
completed.push('after')
|
||||
})
|
||||
expect(() => vi.runAllTimers()).toThrow('synthetic parser handler failure')
|
||||
|
||||
term.write('later', () => {
|
||||
completed.push('later')
|
||||
})
|
||||
vi.runAllTimers()
|
||||
expect(completed).toEqual([])
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting'
|
||||
|
||||
// Why a leaf module: terminal modules (replay-guard, output scheduler, parser
|
||||
// guards) record breadcrumbs, and e2e specs import those modules' constants —
|
||||
// Playwright loads spec imports at collection time under a transform that
|
||||
// cannot handle crash-diagnostics.ts (top-level `import.meta.hot` plus the
|
||||
// webview-registry import chain). Keep this file free of value imports and
|
||||
// import.meta so it stays loadable from any context.
|
||||
|
||||
/** Best-effort breadcrumb recording; must never create or mask failures. */
|
||||
export function recordRendererCrashBreadcrumb(
|
||||
name: string,
|
||||
data?: CrashReportBreadcrumbData
|
||||
): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const api = (window as Window & { api?: Window['api'] }).api
|
||||
api?.crashReports.recordBreadcrumb({ name, ...(data ? { data } : {}) })
|
||||
} catch {
|
||||
// Best-effort crash evidence only.
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
CrashReportDetailValue
|
||||
} from '../../../shared/crash-reporting'
|
||||
import { getBrowserWebviewMemoryProfile } from '../components/browser-pane/webview-registry'
|
||||
import { recordRendererCrashBreadcrumb } from './crash-breadcrumb-recorder'
|
||||
|
||||
const RENDERER_MEMORY_SAMPLE_INTERVAL_MS = 60_000
|
||||
const BYTES_PER_MEGABYTE = 1024 * 1024
|
||||
@@ -16,22 +17,10 @@ type BrowserPerformanceMemory = {
|
||||
let rendererCrashDiagnosticsInstalled = false
|
||||
let rendererMemoryInterval: number | null = null
|
||||
|
||||
export function recordRendererCrashBreadcrumb(
|
||||
name: string,
|
||||
data?: CrashReportBreadcrumbData
|
||||
): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Why: crash diagnostics must never create or mask renderer startup failures.
|
||||
const api = (window as Window & { api?: Window['api'] }).api
|
||||
api?.crashReports.recordBreadcrumb({ name, ...(data ? { data } : {}) })
|
||||
} catch {
|
||||
// Best-effort crash evidence only.
|
||||
}
|
||||
}
|
||||
// Why re-exported from a leaf module: terminal modules and their e2e-visible
|
||||
// import chains need breadcrumb recording without this file's import.meta /
|
||||
// webview-registry baggage. See crash-breadcrumb-recorder.ts.
|
||||
export { recordRendererCrashBreadcrumb } from './crash-breadcrumb-recorder'
|
||||
|
||||
export function installRendererCrashDiagnostics(): void {
|
||||
if (rendererCrashDiagnosticsInstalled || typeof window === 'undefined') {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { runGuardedWriteCompletionStep } from './xterm-write-callback-guard'
|
||||
|
||||
export type ForegroundTerminalOutputTarget = {
|
||||
buffer?: {
|
||||
active?: {
|
||||
@@ -131,18 +133,24 @@ export function writeForegroundTerminalChunk(
|
||||
const beforeWriteViewport = options.forceViewportRefresh
|
||||
? captureViewportSnapshot(terminal)
|
||||
: null
|
||||
try {
|
||||
terminal.write(data, () => {
|
||||
if (beforeWriteViewport) {
|
||||
settleForegroundRender(terminal, beforeWriteViewport, options)
|
||||
}
|
||||
options.onParsed?.()
|
||||
})
|
||||
} catch {
|
||||
// Why guarded steps: this callback runs inside xterm's WriteBuffer loop,
|
||||
// where an escaping throw permanently wedges the terminal (see
|
||||
// xterm-write-callback-guard.ts). Guard settle and onParsed separately so a
|
||||
// renderer/WebGL failure during settle can't starve the replay-guard release.
|
||||
const runCompletionSteps = (): void => {
|
||||
if (beforeWriteViewport) {
|
||||
settleForegroundRender(terminal, beforeWriteViewport, options)
|
||||
runGuardedWriteCompletionStep('foreground-render-settle', () =>
|
||||
settleForegroundRender(terminal, beforeWriteViewport, options)
|
||||
)
|
||||
}
|
||||
options.onParsed?.()
|
||||
if (options.onParsed) {
|
||||
runGuardedWriteCompletionStep('foreground-on-parsed', options.onParsed)
|
||||
}
|
||||
}
|
||||
try {
|
||||
terminal.write(data, runCompletionSteps)
|
||||
} catch {
|
||||
runCompletionSteps()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,14 @@ vi.mock('@/lib/e2e-config', () => ({
|
||||
e2eConfig: { exposeStore: true }
|
||||
}))
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
recordRendererCrashBreadcrumb: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/crash-breadcrumb-recorder', () => ({
|
||||
recordRendererCrashBreadcrumb: mocks.recordRendererCrashBreadcrumb
|
||||
}))
|
||||
|
||||
function createTerminal() {
|
||||
const classes = new Set<string>()
|
||||
return {
|
||||
@@ -51,6 +59,7 @@ async function loadScheduler() {
|
||||
describe('pane terminal output scheduler', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('window', globalThis)
|
||||
mocks.recordRendererCrashBreadcrumb.mockClear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -898,10 +907,66 @@ describe('pane terminal output scheduler', () => {
|
||||
expect(terminal.write).not.toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(0)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(16)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(2)
|
||||
|
||||
vi.advanceTimersByTime(1)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(32)
|
||||
vi.advanceTimersByTime(4)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('yields high-priority backlog drains when writes spend the frame budget', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { writeTerminalOutput } = await loadScheduler()
|
||||
const terminal = createTerminal()
|
||||
const chunk = 'x'.repeat(16 * 1024)
|
||||
let now = 0
|
||||
const nowSpy = vi.spyOn(performance, 'now').mockImplementation(() => now)
|
||||
terminal.write.mockImplementation((_data: string, callback?: () => void) => {
|
||||
now += 9
|
||||
callback?.()
|
||||
})
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 64; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: false })
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(0)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.advanceTimersByTime(4)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
nowSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('uses Date.now for drain budgeting when performance is unavailable', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('performance', undefined)
|
||||
const { writeTerminalOutput } = await loadScheduler()
|
||||
const terminal = createTerminal()
|
||||
const chunk = 'x'.repeat(16 * 1024)
|
||||
let now = 0
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now)
|
||||
terminal.write.mockImplementation((_data: string, callback?: () => void) => {
|
||||
now += 9
|
||||
callback?.()
|
||||
})
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 64; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: false })
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(0)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(1)
|
||||
expect(nowSpy).toHaveBeenCalled()
|
||||
|
||||
vi.advanceTimersByTime(4)
|
||||
expect(terminal.write).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
nowSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('caps hidden backlog memory and writes a warning instead of retaining all output', async () => {
|
||||
@@ -923,6 +988,95 @@ describe('pane terminal output scheduler', () => {
|
||||
expect(output).not.toContain('x'.repeat(1024))
|
||||
})
|
||||
|
||||
it('caps a visible pane backlog the drain cannot keep up with and writes a warning', async () => {
|
||||
// Why: the foreground path was previously uncapped — a flooding visible
|
||||
// TUI on a starved renderer grew queuedChars without bound (field
|
||||
// reports of ~1.5 GB renderer RSS before terminals froze).
|
||||
vi.useFakeTimers()
|
||||
const { writeTerminalOutput } = await loadScheduler()
|
||||
const terminal = createTerminal()
|
||||
const chunk = 'x'.repeat(512 * 1024)
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: true, latencySensitive: false })
|
||||
}
|
||||
writeTerminalOutput(terminal, 'after-cap\r\n', { foreground: true, latencySensitive: false })
|
||||
|
||||
vi.advanceTimersByTime(0)
|
||||
|
||||
const output = terminal.write.mock.calls.map(([data]) => data).join('')
|
||||
expect(output).toContain('Orca skipped a burst of terminal output')
|
||||
expect(output).toContain('after-cap')
|
||||
expect(output).not.toContain('x'.repeat(1024))
|
||||
})
|
||||
|
||||
it('records a drop breadcrumb with sizes when the cap replaces a backlog', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { writeTerminalOutput } = await loadScheduler()
|
||||
const terminal = createTerminal()
|
||||
const chunk = 'x'.repeat(512 * 1024)
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: false })
|
||||
}
|
||||
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_output_backlog_dropped',
|
||||
expect.objectContaining({
|
||||
foreground: false,
|
||||
droppedChars: expect.any(Number),
|
||||
capChars: 2 * 1024 * 1024
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('scales the backlog cap with the scrollback setting', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { writeTerminalOutput, configureTerminalOutputBacklogCap } = await loadScheduler()
|
||||
const terminal = createTerminal()
|
||||
const chunk = 'x'.repeat(512 * 1024)
|
||||
|
||||
// 50k-row scrollback ⇒ 6 MB cap: a 2.5 MB flood that would trip the
|
||||
// 2 MB floor must survive intact.
|
||||
configureTerminalOutputBacklogCap(50_000)
|
||||
for (let i = 0; i < 5; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: true, latencySensitive: false })
|
||||
}
|
||||
vi.advanceTimersByTime(0)
|
||||
|
||||
let output = terminal.write.mock.calls.map(([data]) => data).join('')
|
||||
expect(output).not.toContain('Orca skipped')
|
||||
expect(output).toContain('x'.repeat(1024))
|
||||
|
||||
// But the scaled cap still bounds a runaway flood.
|
||||
terminal.write.mockClear()
|
||||
for (let i = 0; i < 13; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: true, latencySensitive: false })
|
||||
}
|
||||
vi.advanceTimersByTime(0)
|
||||
output = terminal.write.mock.calls.map(([data]) => data).join('')
|
||||
expect(output).toContain('Orca skipped a burst of terminal output')
|
||||
})
|
||||
|
||||
it('caps a held/coalesced foreground backlog as well', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { writeTerminalOutput } = await loadScheduler()
|
||||
const terminal = createForegroundTerminal()
|
||||
const chunk = 'y'.repeat(512 * 1024)
|
||||
|
||||
// holdForeground engages the synchronized-output hold — the branch a
|
||||
// flooding TUI in sync mode exercises.
|
||||
for (let i = 0; i < 5; i++) {
|
||||
writeTerminalOutput(terminal, chunk, { foreground: true, holdForeground: true })
|
||||
}
|
||||
|
||||
vi.advanceTimersByTime(1_000)
|
||||
|
||||
const output = terminal.write.mock.calls.map(([data]) => data).join('')
|
||||
expect(output).toContain('Orca skipped a burst of terminal output')
|
||||
expect(output).not.toContain('y'.repeat(1024))
|
||||
})
|
||||
|
||||
it('caps hidden backlog chunk count even when each chunk is tiny', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { writeTerminalOutput } = await loadScheduler()
|
||||
|
||||
@@ -11,6 +11,12 @@ import {
|
||||
captureTerminalWriteScrollIntent,
|
||||
enforceTerminalWriteScrollIntent
|
||||
} from './terminal-scroll-intent'
|
||||
import { runGuardedWriteCompletionStep } from './xterm-write-callback-guard'
|
||||
import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder'
|
||||
import {
|
||||
TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS,
|
||||
terminalOutputBacklogCapChars
|
||||
} from '../../../../shared/terminal-scrollback-policy'
|
||||
|
||||
type TerminalOutputTarget = ForegroundTerminalOutputTarget
|
||||
|
||||
@@ -68,14 +74,23 @@ type QueueEntry = {
|
||||
|
||||
const BACKGROUND_FLUSH_DELAY_MS = 50
|
||||
const BACKGROUND_DRAIN_INTERVAL_MS = 16
|
||||
const HIGH_PRIORITY_DRAIN_INTERVAL_MS = 1
|
||||
const HIGH_PRIORITY_DRAIN_INTERVAL_MS = 4
|
||||
const BACKGROUND_CHUNK_CHARS = 16 * 1024
|
||||
const MAX_WRITES_PER_DRAIN = 2
|
||||
const HIGH_PRIORITY_MAX_WRITES_PER_DRAIN = 16
|
||||
const HIGH_PRIORITY_MAX_WRITES_PER_DRAIN = 2
|
||||
const DRAIN_TIME_BUDGET_MS = 8
|
||||
const LARGE_BACKLOG_CHARS = 512 * 1024
|
||||
const SYNC_FOREGROUND_FLUSH_CHARS = 256 * 1024
|
||||
const MAX_BACKGROUND_QUEUE_CHARS = 2 * 1024 * 1024
|
||||
// Why mutable: the cap scales with the user's scrollback setting (see
|
||||
// terminalOutputBacklogCapChars); the terminal lifecycle configures it when
|
||||
// settings are applied. The chunk-count cap stays fixed — it bounds queue
|
||||
// bookkeeping, not retained content.
|
||||
let maxQueueChars = TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS
|
||||
const MAX_BACKGROUND_QUEUE_CHUNKS = 4096
|
||||
|
||||
export function configureTerminalOutputBacklogCap(scrollbackRows: unknown): void {
|
||||
maxQueueChars = terminalOutputBacklogCapChars(scrollbackRows)
|
||||
}
|
||||
const PARSE_SETTLE_TIMEOUT_MS = 250
|
||||
const FOREGROUND_COALESCE_DELAY_MS = 1000
|
||||
const FOREGROUND_HOLD_SAFETY_DELAY_MS = 250
|
||||
@@ -87,9 +102,15 @@ const CURSOR_SHOW_SEQUENCE = '\x1b[?25h'
|
||||
const CURSOR_HIDE_SEQUENCE = '\x1b[?25l'
|
||||
const SYNCHRONIZED_OUTPUT_END_SEQUENCE = '\x1b[?2026l'
|
||||
// Why: CAN aborts a partial escape sequence before resetting style and showing
|
||||
// the lossy-backlog warning.
|
||||
// the lossy-backlog warning. Cap-agnostic wording: the byte limit scales with
|
||||
// the scrollback setting.
|
||||
const BACKGROUND_BACKLOG_WARNING =
|
||||
'\x18\x1b[0m\r\n[Orca skipped hidden terminal output because the backlog exceeded 2 MB.]\r\n'
|
||||
'\x18\x1b[0m\r\n[Orca skipped hidden terminal output because the backlog grew too large.]\r\n'
|
||||
// Why a separate foreground message: a visible pane hitting the cap means the
|
||||
// drain could not keep up with a flood (starved renderer) — the output was
|
||||
// skipped, not merely produced while hidden.
|
||||
const FOREGROUND_BACKLOG_WARNING =
|
||||
'\x18\x1b[0m\r\n[Orca skipped a burst of terminal output because the backlog grew too large.]\r\n'
|
||||
|
||||
const queuedByTerminal = new Map<TerminalOutputTarget, QueueEntry>()
|
||||
const backlogRecoveryByTerminal = new WeakMap<
|
||||
@@ -579,12 +600,31 @@ function enqueueChunk(
|
||||
recordQueueDebugPressure()
|
||||
}
|
||||
|
||||
function replaceBacklogWithWarning(entry: QueueEntry): void {
|
||||
function queueCapExceeded(entry: QueueEntry): boolean {
|
||||
return (
|
||||
entry.queuedChars > maxQueueChars ||
|
||||
entry.chunks.length - entry.chunkIndex > MAX_BACKGROUND_QUEUE_CHUNKS
|
||||
)
|
||||
}
|
||||
|
||||
function replaceBacklogWithWarning(
|
||||
entry: QueueEntry,
|
||||
warning: string = BACKGROUND_BACKLOG_WARNING
|
||||
): void {
|
||||
const shouldNotify = !entry.backgroundBacklogDropped
|
||||
if (shouldNotify) {
|
||||
// Why: field visibility for cap tuning — how often drops happen and at
|
||||
// what size decides whether the cap is too small (issue #2836 / #7017).
|
||||
recordRendererCrashBreadcrumb('terminal_output_backlog_dropped', {
|
||||
foreground: warning === FOREGROUND_BACKLOG_WARNING,
|
||||
droppedChars: entry.queuedChars,
|
||||
capChars: maxQueueChars
|
||||
})
|
||||
}
|
||||
clearForegroundHoldSafety(entry)
|
||||
entry.chunks = [
|
||||
{
|
||||
data: BACKGROUND_BACKLOG_WARNING,
|
||||
data: warning,
|
||||
foreground: false,
|
||||
forceForegroundRefresh: false,
|
||||
followupForegroundRefresh: false,
|
||||
@@ -592,7 +632,7 @@ function replaceBacklogWithWarning(entry: QueueEntry): void {
|
||||
}
|
||||
]
|
||||
entry.chunkIndex = 0
|
||||
entry.queuedChars = BACKGROUND_BACKLOG_WARNING.length
|
||||
entry.queuedChars = warning.length
|
||||
entry.backgroundBacklogDropped = true
|
||||
entry.highPriority = true
|
||||
entry.foregroundHold = false
|
||||
@@ -636,26 +676,34 @@ function writeBackgroundTerminalChunk(
|
||||
data: string,
|
||||
onParsed?: TerminalOutputParsedCallback
|
||||
): void {
|
||||
// Why guarded: these callbacks run inside xterm's WriteBuffer loop, where an
|
||||
// escaping throw permanently wedges the terminal (see
|
||||
// xterm-write-callback-guard.ts).
|
||||
const runOnParsed = onParsed
|
||||
? (): void => runGuardedWriteCompletionStep('background-on-parsed', onParsed)
|
||||
: undefined
|
||||
const scrollIntent = captureTerminalWriteScrollIntent(terminal)
|
||||
if (!scrollIntent) {
|
||||
if (!onParsed || terminal.write.length < 2) {
|
||||
if (!runOnParsed || terminal.write.length < 2) {
|
||||
terminal.write(data)
|
||||
onParsed?.()
|
||||
runOnParsed?.()
|
||||
return
|
||||
}
|
||||
terminal.write(data, onParsed)
|
||||
terminal.write(data, runOnParsed)
|
||||
return
|
||||
}
|
||||
const runScrollIntentThenParsed = (): void => {
|
||||
runGuardedWriteCompletionStep('background-scroll-intent', () =>
|
||||
enforceTerminalWriteScrollIntent(terminal, scrollIntent)
|
||||
)
|
||||
runOnParsed?.()
|
||||
}
|
||||
if (terminal.write.length < 2) {
|
||||
terminal.write(data)
|
||||
enforceTerminalWriteScrollIntent(terminal, scrollIntent)
|
||||
onParsed?.()
|
||||
runScrollIntentThenParsed()
|
||||
return
|
||||
}
|
||||
terminal.write(data, () => {
|
||||
enforceTerminalWriteScrollIntent(terminal, scrollIntent)
|
||||
onParsed?.()
|
||||
})
|
||||
terminal.write(data, runScrollIntentThenParsed)
|
||||
}
|
||||
|
||||
function writeForegroundTerminalChunkWithIntent(
|
||||
@@ -728,10 +776,18 @@ function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' | null
|
||||
return queuedWrite.foreground ? 'foreground' : 'background'
|
||||
}
|
||||
|
||||
function getDrainNow(): number {
|
||||
if (typeof performance !== 'undefined') {
|
||||
return performance.now()
|
||||
}
|
||||
return Date.now()
|
||||
}
|
||||
|
||||
function drainQueuedOutput(): void {
|
||||
drainTimer = null
|
||||
drainTimerDelayMs = null
|
||||
let writes = 0
|
||||
const startedAt = getDrainNow()
|
||||
const maxWrites = hasHighPriorityBacklog()
|
||||
? HIGH_PRIORITY_MAX_WRITES_PER_DRAIN
|
||||
: MAX_WRITES_PER_DRAIN
|
||||
@@ -760,6 +816,11 @@ function drainQueuedOutput(): void {
|
||||
clearForegroundCoalesce(entry)
|
||||
clearForegroundHoldSafety(entry)
|
||||
}
|
||||
// Why: xterm parsing and DOM work share the renderer thread with input.
|
||||
// Keep backlog draining cooperative so WSL/agent output cannot pin the UI.
|
||||
if (writes > 0 && getDrainNow() - startedAt >= DRAIN_TIME_BUDGET_MS) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (debugEnabled && writes > 0) {
|
||||
@@ -802,6 +863,13 @@ export function writeTerminalOutput(
|
||||
debugState.foregroundWriteCount++
|
||||
debugState.deferredForegroundEnqueueCount++
|
||||
}
|
||||
// Why: a visible pane's queue was previously uncapped — a flood the
|
||||
// drain can't keep up with ballooned renderer memory without bound.
|
||||
if (queueCapExceeded(queued)) {
|
||||
replaceBacklogWithWarning(queued, FOREGROUND_BACKLOG_WARNING)
|
||||
scheduleDrain(0)
|
||||
return
|
||||
}
|
||||
if (options.holdForeground) {
|
||||
// Why: synchronized-output start/body chunks contain transient cursor
|
||||
// moves. Holding them prevents Chromium from rasterizing those states.
|
||||
@@ -869,6 +937,9 @@ export function writeTerminalOutput(
|
||||
debugState.foregroundWriteCount++
|
||||
debugState.deferredForegroundEnqueueCount++
|
||||
}
|
||||
if (queueCapExceeded(entry)) {
|
||||
replaceBacklogWithWarning(entry, FOREGROUND_BACKLOG_WARNING)
|
||||
}
|
||||
// Why: returning from a hidden window can have megabytes queued. Keep
|
||||
// byte order, but drain it asynchronously so the first foreground frame
|
||||
// is not pinned behind the entire backlog.
|
||||
@@ -896,6 +967,9 @@ export function writeTerminalOutput(
|
||||
debugState.foregroundWriteCount++
|
||||
debugState.deferredForegroundEnqueueCount++
|
||||
}
|
||||
if (queueCapExceeded(queued)) {
|
||||
replaceBacklogWithWarning(queued, FOREGROUND_BACKLOG_WARNING)
|
||||
}
|
||||
// Why: visible command floods are throughput work, not keystroke echo.
|
||||
// Queue them behind a zero-delay drain so one IPC callback cannot pin
|
||||
// the renderer in xterm.write while input and paint are waiting.
|
||||
@@ -931,10 +1005,7 @@ export function writeTerminalOutput(
|
||||
enqueueChunk(entry, data, {
|
||||
onParsed: options.onParsed
|
||||
})
|
||||
if (
|
||||
entry.queuedChars > MAX_BACKGROUND_QUEUE_CHARS ||
|
||||
entry.chunks.length - entry.chunkIndex > MAX_BACKGROUND_QUEUE_CHUNKS
|
||||
) {
|
||||
if (queueCapExceeded(entry)) {
|
||||
replaceBacklogWithWarning(entry)
|
||||
}
|
||||
if (debugEnabled) {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
_resetWriteCompletionReportsForTests,
|
||||
runGuardedWriteCompletionStep
|
||||
} from './xterm-write-callback-guard'
|
||||
import { writeForegroundTerminalChunk } from './pane-terminal-foreground-render-settle'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
recordRendererCrashBreadcrumb: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/crash-breadcrumb-recorder', () => ({
|
||||
recordRendererCrashBreadcrumb: mocks.recordRendererCrashBreadcrumb
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.recordRendererCrashBreadcrumb.mockClear()
|
||||
_resetWriteCompletionReportsForTests()
|
||||
})
|
||||
|
||||
describe('runGuardedWriteCompletionStep', () => {
|
||||
it('contains a synchronous throw and reports a breadcrumb', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
expect(() =>
|
||||
runGuardedWriteCompletionStep('test-step', () => {
|
||||
throw new RangeError('synthetic settle failure')
|
||||
})
|
||||
).not.toThrow()
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_write_completion_error',
|
||||
expect.objectContaining({
|
||||
context: 'test-step',
|
||||
errorName: 'RangeError',
|
||||
errorMessage: 'synthetic settle failure'
|
||||
})
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('caps repeated reports per context so a throw-per-write loop cannot spam breadcrumbs', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
runGuardedWriteCompletionStep('spammy-step', () => {
|
||||
throw new Error('always fails')
|
||||
})
|
||||
}
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledTimes(5)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('runs non-throwing steps transparently', () => {
|
||||
const step = vi.fn()
|
||||
runGuardedWriteCompletionStep('ok-step', step)
|
||||
expect(step).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeForegroundTerminalChunk completion guarding', () => {
|
||||
it('still releases onParsed when the settle step throws (replay-guard latch protection)', () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const pendingCallbacks: (() => void)[] = []
|
||||
// Why a getter that throws only after the write is dispatched: it
|
||||
// models renderer/buffer state failing between parse start and the
|
||||
// post-parse viewport settle (refreshVisibleRowsNow self-catches, so
|
||||
// the viewport comparison is the escaping surface).
|
||||
let bufferAccessPoisoned = false
|
||||
const realBuffer = { active: { cursorY: 0, baseY: 0, viewportY: 0 } }
|
||||
const terminal = {
|
||||
rows: 24,
|
||||
get buffer() {
|
||||
if (bufferAccessPoisoned) {
|
||||
throw new Error('synthetic buffer access failure')
|
||||
}
|
||||
return realBuffer
|
||||
},
|
||||
write: (_data: string, cb?: () => void) => {
|
||||
if (cb) {
|
||||
pendingCallbacks.push(cb)
|
||||
}
|
||||
}
|
||||
}
|
||||
const onParsed = vi.fn()
|
||||
|
||||
writeForegroundTerminalChunk(terminal, 'restored bytes', {
|
||||
forceViewportRefresh: true,
|
||||
onParsed
|
||||
})
|
||||
bufferAccessPoisoned = true
|
||||
// Simulate xterm completing the parse: the completion callback must not
|
||||
// let the settle throw escape into the WriteBuffer, and onParsed (the
|
||||
// replay-guard release) must still run.
|
||||
expect(() => pendingCallbacks.forEach((cb) => cb())).not.toThrow()
|
||||
expect(onParsed).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith(
|
||||
'terminal_write_completion_error',
|
||||
expect.objectContaining({ context: 'foreground-render-settle' })
|
||||
)
|
||||
} finally {
|
||||
errorSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder'
|
||||
|
||||
// Why: xterm's WriteBuffer._innerWrite invokes write-completion callbacks with
|
||||
// no try/catch; a synchronous throw skips the loop's tail re-schedule, and
|
||||
// write() only re-arms processing when the buffer is EMPTY — which a stalled
|
||||
// buffer never is again. One escaping throw therefore permanently freezes the
|
||||
// pane: output stops rendering and a pending replay guard never releases, so
|
||||
// the pane silently eats every keystroke while the shell stays alive
|
||||
// (Discord #performance / issue #2836). Verified against the vendored xterm
|
||||
// 6.1.0-beta.287 in xterm-write-buffer-stall.repro.test.ts.
|
||||
const MAX_REPORTS_PER_CONTEXT = 5
|
||||
const reportCountsByContext = new Map<string, number>()
|
||||
|
||||
/**
|
||||
* Run one step of a write-completion callback so a synchronous throw cannot
|
||||
* escape into xterm's WriteBuffer. Steps are guarded individually so an
|
||||
* earlier step's failure (e.g. a WebGL refresh during viewport settle) cannot
|
||||
* starve a later step (e.g. the replay-guard release).
|
||||
*/
|
||||
export function runGuardedWriteCompletionStep(context: string, step: () => void): void {
|
||||
try {
|
||||
step()
|
||||
} catch (error: unknown) {
|
||||
const reported = reportCountsByContext.get(context) ?? 0
|
||||
if (reported >= MAX_REPORTS_PER_CONTEXT) {
|
||||
return
|
||||
}
|
||||
reportCountsByContext.set(context, reported + 1)
|
||||
console.error(`[terminal] write-completion step "${context}" threw`, error)
|
||||
recordRendererCrashBreadcrumb('terminal_write_completion_error', {
|
||||
context,
|
||||
errorName: error instanceof Error ? error.name : typeof error,
|
||||
errorMessage: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function _resetWriteCompletionReportsForTests(): void {
|
||||
reportCountsByContext.clear()
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
DESKTOP_TERMINAL_SCROLLBACK_ROWS_MIN,
|
||||
legacyTerminalScrollbackBytesToRows,
|
||||
normalizeDesktopTerminalScrollbackRows,
|
||||
normalizeDesktopTerminalSnapshotRows
|
||||
normalizeDesktopTerminalSnapshotRows,
|
||||
TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS,
|
||||
terminalOutputBacklogCapChars
|
||||
} from './terminal-scrollback-policy'
|
||||
|
||||
describe('terminal scrollback policy', () => {
|
||||
@@ -35,6 +37,18 @@ describe('terminal scrollback policy', () => {
|
||||
expect(normalizeDesktopTerminalSnapshotRows(100_000)).toBe(50_000)
|
||||
})
|
||||
|
||||
it('scales the output backlog cap with scrollback rows above a 2 MB floor', () => {
|
||||
// Default and small scrollbacks stay on the floor; large scrollbacks get
|
||||
// proportionally more so the cap never drops lines scrollback would keep.
|
||||
expect(terminalOutputBacklogCapChars(undefined)).toBe(TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS)
|
||||
expect(terminalOutputBacklogCapChars(5_000)).toBe(TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS)
|
||||
expect(terminalOutputBacklogCapChars('garbage')).toBe(TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS)
|
||||
expect(terminalOutputBacklogCapChars(25_000)).toBe(3_000_000)
|
||||
expect(terminalOutputBacklogCapChars(50_000)).toBe(6_000_000)
|
||||
// Values beyond the settings max clamp like the setting itself does.
|
||||
expect(terminalOutputBacklogCapChars(1_000_000)).toBe(6_000_000)
|
||||
})
|
||||
|
||||
it('migrates legacy decimal MB buckets by intent, not byte-to-row math', () => {
|
||||
expect(legacyTerminalScrollbackBytesToRows(undefined)).toBe(5_000)
|
||||
expect(legacyTerminalScrollbackBytesToRows(0)).toBe(5_000)
|
||||
|
||||
@@ -28,6 +28,23 @@ export function normalizeDesktopTerminalScrollbackRows(value: unknown): number {
|
||||
return clampRows(value, DESKTOP_TERMINAL_SCROLLBACK_ROWS_MIN)
|
||||
}
|
||||
|
||||
// Why the backlog cap scales with scrollback: pending-output caps exist to
|
||||
// bound memory while a starved display catches up, but a user who raised
|
||||
// scrollback to 50k rows can retain more history than the flat 2 MB floor —
|
||||
// dropping at the floor would discard lines their scrollback would have kept.
|
||||
// 120 chars/row ≈ 80-col text plus escape-sequence overhead; the cap is a
|
||||
// memory bound, not an exact retention guarantee.
|
||||
export const TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS = 2 * 1024 * 1024
|
||||
const OUTPUT_BACKLOG_CHARS_PER_SCROLLBACK_ROW = 120
|
||||
|
||||
export function terminalOutputBacklogCapChars(scrollbackRows: unknown): number {
|
||||
const rows = normalizeDesktopTerminalScrollbackRows(scrollbackRows)
|
||||
return Math.max(
|
||||
TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS,
|
||||
rows * OUTPUT_BACKLOG_CHARS_PER_SCROLLBACK_ROW
|
||||
)
|
||||
}
|
||||
|
||||
export function normalizeDesktopTerminalSnapshotRows(value: unknown): number | undefined {
|
||||
if (!isFiniteNumber(value)) {
|
||||
return undefined
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* Layer-discriminating input probes for frozen-terminal repro specs.
|
||||
*
|
||||
* The field failure (Discord #performance / GitHub #2836 family) is a pane
|
||||
* that shows content while keystrokes silently vanish. Both drop layers are
|
||||
* silent today:
|
||||
* - renderer: transport.sendInput returns false when `!connected || !ptyId`
|
||||
* (pty-transport.ts)
|
||||
* - main: pty:write drops when `ptyOwnership` misses the id or the provider
|
||||
* lookup fails (src/main/ipc/pty.ts writePtyInput)
|
||||
*
|
||||
* Direct `window.api.pty.write` bypasses the renderer transport, so:
|
||||
* direct dead → MAIN-side drop (ownership/provider routing)
|
||||
* direct alive, transport dead → RENDERER transport unbound
|
||||
* The ownership-rebuild probe invokes pty:listSessions, which repopulates
|
||||
* `ptyOwnership` as a side effect — input reviving after it is a smoking gun
|
||||
* for the missing-ownership drop path.
|
||||
*
|
||||
* Two probe families:
|
||||
* - Page-based (Playwright CDP): for specs whose renderer never crashes.
|
||||
* - Main-process-based (webContents.executeJavaScript): for post-crash
|
||||
* phases — a crashed target severs Playwright's CDP session even though
|
||||
* the app recovers, so the harness must drive the renderer from main.
|
||||
*/
|
||||
|
||||
import { expect, type ElectronApplication, type Page } from '@stablyai/playwright-test'
|
||||
import { sendToTerminal, waitForTerminalOutput } from './terminal'
|
||||
|
||||
// ─── Page-based probes (healthy CDP session) ────────────────────────
|
||||
|
||||
export async function probeDirectWrite(
|
||||
page: Page,
|
||||
ptyId: string,
|
||||
marker: string,
|
||||
timeoutMs = 10_000
|
||||
): Promise<boolean> {
|
||||
// \x03\x15 = ETX+NAK (interrupt + kill-line) so a TUI or half-typed line on
|
||||
// the shell doesn't swallow the probe — same trick discoverActivePtyId uses.
|
||||
await sendToTerminal(page, ptyId, `\x03\x15echo ${marker}\r`)
|
||||
try {
|
||||
await waitForTerminalOutput(page, marker, timeoutMs)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Probe the full chain: focus the visible xterm and type through the keyboard. */
|
||||
export async function probeKeyboardType(
|
||||
page: Page,
|
||||
marker: string,
|
||||
timeoutMs = 10_000
|
||||
): Promise<boolean> {
|
||||
await page.locator('.xterm:visible').first().click()
|
||||
await page.keyboard.type(`echo ${marker}`, { delay: 20 })
|
||||
await page.keyboard.press('Enter')
|
||||
try {
|
||||
// Any appearance of the marker proves the roundtrip: xterm does not local-
|
||||
// echo, so typed characters only render after the PTY echoes them back.
|
||||
await waitForTerminalOutput(page, marker, timeoutMs)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeOwnershipRebuildRevival(
|
||||
page: Page,
|
||||
ptyId: string,
|
||||
marker: string
|
||||
): Promise<boolean> {
|
||||
await page.evaluate(async () => {
|
||||
await window.api.pty.listSessions()
|
||||
})
|
||||
return probeDirectWrite(page, ptyId, marker)
|
||||
}
|
||||
|
||||
export async function getStorePtyIds(page: Page): Promise<string[]> {
|
||||
return page.evaluate(() => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
return []
|
||||
}
|
||||
return Object.values(store.getState().ptyIdsByTabId).flat()
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Main-process-based probes (post-renderer-crash) ────────────────
|
||||
|
||||
async function mainRendererEval<T>(
|
||||
electronApp: ElectronApplication,
|
||||
expression: string
|
||||
): Promise<T> {
|
||||
return electronApp.evaluate(async ({ BrowserWindow }, expr) => {
|
||||
const win = BrowserWindow.getAllWindows()[0]
|
||||
if (!win || win.isDestroyed() || win.webContents.isDestroyed()) {
|
||||
throw new Error('no live window for executeJavaScript probe')
|
||||
}
|
||||
return (await win.webContents.executeJavaScript(expr, true)) as T
|
||||
}, expression) as Promise<T>
|
||||
}
|
||||
|
||||
export async function mainRendererStoreReady(electronApp: ElectronApplication): Promise<boolean> {
|
||||
try {
|
||||
return await mainRendererEval<boolean>(
|
||||
electronApp,
|
||||
`Boolean(window.__store && window.__store.getState().workspaceSessionReady === true)`
|
||||
)
|
||||
} catch {
|
||||
// executeJavaScript rejects while the document is loading or the window
|
||||
// is mid-recovery; callers poll, so a false here is just "not yet".
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function mainGetStorePtyIds(electronApp: ElectronApplication): Promise<string[]> {
|
||||
try {
|
||||
return await mainRendererEval<string[]>(
|
||||
electronApp,
|
||||
`(() => {
|
||||
const store = window.__store
|
||||
if (!store) { return [] }
|
||||
return Object.values(store.getState().ptyIdsByTabId).flat()
|
||||
})()`
|
||||
)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialize every mounted pane's buffer; marker search doesn't need per-pane precision. */
|
||||
export async function mainGetAllTerminalContent(electronApp: ElectronApplication): Promise<string> {
|
||||
try {
|
||||
return await mainRendererEval<string>(
|
||||
electronApp,
|
||||
`(() => {
|
||||
const managers = window.__paneManagers
|
||||
if (!managers) { return '' }
|
||||
let combined = ''
|
||||
for (const manager of managers.values()) {
|
||||
for (const pane of manager.getPanes?.() ?? []) {
|
||||
combined += '\\n' + (pane.serializeAddon?.serialize?.() ?? '')
|
||||
}
|
||||
}
|
||||
return combined.slice(-8000)
|
||||
})()`
|
||||
)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function mainWaitForPaneMounted(
|
||||
electronApp: ElectronApplication,
|
||||
timeoutMs = 30_000
|
||||
): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
try {
|
||||
return await mainRendererEval<number>(
|
||||
electronApp,
|
||||
`(() => {
|
||||
const managers = window.__paneManagers
|
||||
if (!managers) { return 0 }
|
||||
let count = 0
|
||||
for (const manager of managers.values()) {
|
||||
count += (manager.getPanes?.() ?? []).length
|
||||
}
|
||||
return count
|
||||
})()`
|
||||
)
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
},
|
||||
{ timeout: timeoutMs, message: 'no terminal pane mounted after renderer recovery' }
|
||||
)
|
||||
.toBeGreaterThan(0)
|
||||
}
|
||||
|
||||
async function mainWaitForMarker(
|
||||
electronApp: ElectronApplication,
|
||||
marker: string,
|
||||
timeoutMs: number
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await expect
|
||||
.poll(async () => (await mainGetAllTerminalContent(electronApp)).includes(marker), {
|
||||
timeout: timeoutMs
|
||||
})
|
||||
.toBe(true)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-chain probe without CDP: xterm's input() feeds terminal.onData →
|
||||
* transport.sendInput → pty:write, the identical path keystrokes take past
|
||||
* the DOM keyboard layer (which the pre-crash Playwright baseline covers).
|
||||
* Why input() and not paste(): bracketed paste mode would wrap the payload
|
||||
* and make the shell insert the control chars literally instead of executing.
|
||||
*/
|
||||
export async function mainProbeTransportPaste(
|
||||
electronApp: ElectronApplication,
|
||||
marker: string,
|
||||
timeoutMs = 10_000
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const fed = await mainRendererEval<boolean>(
|
||||
electronApp,
|
||||
`(() => {
|
||||
const managers = window.__paneManagers
|
||||
if (!managers) { return false }
|
||||
for (const manager of managers.values()) {
|
||||
const pane = manager.getActivePane?.() ?? (manager.getPanes?.() ?? [])[0]
|
||||
if (pane?.terminal?.input) {
|
||||
pane.terminal.input('\\x03\\x15echo ${marker}\\r', true)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})()`
|
||||
)
|
||||
if (!fed) {
|
||||
return false
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return mainWaitForMarker(electronApp, marker, timeoutMs)
|
||||
}
|
||||
|
||||
export async function mainProbeDirectWrite(
|
||||
electronApp: ElectronApplication,
|
||||
ptyId: string,
|
||||
marker: string,
|
||||
timeoutMs = 10_000
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await mainRendererEval<void>(
|
||||
electronApp,
|
||||
`window.api.pty.write(${JSON.stringify(ptyId)}, ${JSON.stringify(`\x03\x15echo ${marker}\r`)})`
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return mainWaitForMarker(electronApp, marker, timeoutMs)
|
||||
}
|
||||
|
||||
export async function mainProbeOwnershipRebuildRevival(
|
||||
electronApp: ElectronApplication,
|
||||
ptyId: string,
|
||||
marker: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await mainRendererEval<void>(electronApp, `window.api.pty.listSessions()`)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
return mainProbeDirectWrite(electronApp, ptyId, marker)
|
||||
}
|
||||
|
||||
// ─── Failure report ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Assemble the failure report for a reproduced frozen pane. Kept in one place
|
||||
* so every repro spec reports the same layer discrimination.
|
||||
*/
|
||||
export function buildFrozenPaneReport(
|
||||
context: string,
|
||||
probes: {
|
||||
directAlive: boolean
|
||||
transportAlive: boolean
|
||||
revivedByOwnershipRebuild: boolean
|
||||
ptyIds: string[]
|
||||
terminalTail: string
|
||||
}
|
||||
): string {
|
||||
return [
|
||||
`REPRODUCED frozen terminal (${context}):`,
|
||||
` direct pty:write probe alive: ${probes.directAlive} (false ⇒ MAIN-side drop: ptyOwnership/provider)`,
|
||||
` transport (onData→sendInput) probe alive: ${probes.transportAlive} (false with direct alive ⇒ RENDERER transport unbound)`,
|
||||
` revived by pty:listSessions ownership rebuild: ${probes.revivedByOwnershipRebuild}`,
|
||||
` pane ptyIds: ${JSON.stringify(probes.ptyIds)}`,
|
||||
` terminal tail:\n${probes.terminalTail.slice(-600)}`
|
||||
].join('\n')
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Repro spec for the frozen-terminal-after-renderer-recovery report
|
||||
* (Discord #performance, GitHub #2836 family).
|
||||
*
|
||||
* Field evidence: pane shows content, shell is alive, daemon output.log does
|
||||
* not grow while typing — i.e. keystrokes silently vanish somewhere between
|
||||
* xterm and the PTY. This spec forces the suspected trigger — renderer
|
||||
* process death followed by the automatic recovery reload
|
||||
* (createMainWindow.ts scheduleRendererRecovery) — then discriminates which
|
||||
* layer drops input via the probes in helpers/terminal-input-probes.ts.
|
||||
*
|
||||
* Post-crash phases are driven from the MAIN process: a crashed target
|
||||
* severs Playwright's CDP session even though the app recovers, so page.*
|
||||
* calls can never observe the recovered renderer (verified empirically —
|
||||
* main saw did-finish-load while every window handle stayed dead).
|
||||
*/
|
||||
|
||||
import type { ElectronApplication } from '@stablyai/playwright-test'
|
||||
import { test, expect } from './helpers/orca-app'
|
||||
import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store'
|
||||
import {
|
||||
discoverActivePtyId,
|
||||
waitForActiveTerminalManager,
|
||||
waitForPaneCount
|
||||
} from './helpers/terminal'
|
||||
import {
|
||||
buildFrozenPaneReport,
|
||||
mainGetAllTerminalContent,
|
||||
mainGetStorePtyIds,
|
||||
mainProbeDirectWrite,
|
||||
mainProbeOwnershipRebuildRevival,
|
||||
mainProbeTransportPaste,
|
||||
mainRendererStoreReady,
|
||||
mainWaitForPaneMounted,
|
||||
probeKeyboardType
|
||||
} from './helpers/terminal-input-probes'
|
||||
|
||||
// Why 2, not more: the renderer recovery circuit breaker allows 3 recoveries
|
||||
// per 60s window (DEFAULT_RENDERER_RECOVERY_MAX_RECOVERIES); a third forced
|
||||
// crash risks tripping it and testing the breaker instead of the reattach.
|
||||
const CRASH_CYCLES = 2
|
||||
|
||||
// Recovery = 250ms reload timer + full document reload + session hydration.
|
||||
const RECOVERY_TIMEOUT_MS = 60_000
|
||||
|
||||
type CrashProbe = {
|
||||
processGone: { reason: string; exitCode: number } | null
|
||||
recoveredLoads: number
|
||||
}
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line no-var -- main-process global probe for this spec
|
||||
var __crashProbe: CrashProbe | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe the crash/recovery lifecycle from the MAIN process. Re-arming
|
||||
* replaces the probe object, so counts reset per cycle; stale listeners from
|
||||
* a previous arm write only to their own superseded probe object.
|
||||
*/
|
||||
async function armMainProcessCrashProbe(electronApp: ElectronApplication): Promise<void> {
|
||||
await electronApp.evaluate(({ BrowserWindow }) => {
|
||||
const probe: CrashProbe = { processGone: null, recoveredLoads: 0 }
|
||||
globalThis.__crashProbe = probe
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
win.webContents.on('render-process-gone', (_event, details) => {
|
||||
probe.processGone = { reason: details.reason, exitCode: details.exitCode ?? -1 }
|
||||
})
|
||||
win.webContents.on('did-finish-load', () => {
|
||||
probe.recoveredLoads += 1
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function readMainProcessCrashProbe(electronApp: ElectronApplication): Promise<CrashProbe> {
|
||||
return electronApp.evaluate(
|
||||
() => globalThis.__crashProbe ?? { processGone: null, recoveredLoads: 0 }
|
||||
)
|
||||
}
|
||||
|
||||
async function waitForRendererRecovery(electronApp: ElectronApplication): Promise<void> {
|
||||
await expect
|
||||
.poll(async () => (await readMainProcessCrashProbe(electronApp)).recoveredLoads, {
|
||||
timeout: RECOVERY_TIMEOUT_MS,
|
||||
message:
|
||||
'Main process never observed a recovery reload (did-finish-load) after the forced crash — scheduleRendererRecovery did not fire'
|
||||
})
|
||||
.toBeGreaterThan(0)
|
||||
await expect
|
||||
.poll(async () => mainRendererStoreReady(electronApp), {
|
||||
timeout: RECOVERY_TIMEOUT_MS,
|
||||
message: 'Recovered renderer never reached workspaceSessionReady'
|
||||
})
|
||||
.toBe(true)
|
||||
await mainWaitForPaneMounted(electronApp)
|
||||
}
|
||||
|
||||
test.describe('Renderer crash recovery keeps terminal input alive', () => {
|
||||
test('typing still reaches the PTY after forced renderer crash + auto-reload', async ({
|
||||
orcaPage,
|
||||
electronApp
|
||||
}) => {
|
||||
test.setTimeout(300_000)
|
||||
|
||||
await waitForSessionReady(orcaPage)
|
||||
await waitForActiveWorktree(orcaPage)
|
||||
await ensureTerminalVisible(orcaPage)
|
||||
await waitForActiveTerminalManager(orcaPage, 30_000)
|
||||
await waitForPaneCount(orcaPage, 1, 30_000)
|
||||
|
||||
// Baseline: both the DOM keyboard layer (Playwright-driven, only possible
|
||||
// pre-crash) and the PTY roundtrip must work before we crash anything,
|
||||
// otherwise a post-crash failure would be uninterpretable.
|
||||
const baselinePtyId = await discoverActivePtyId(orcaPage)
|
||||
expect(
|
||||
await probeKeyboardType(orcaPage, 'KB_BASELINE_OK'),
|
||||
'baseline keyboard input must reach the PTY before any crash is forced'
|
||||
).toBe(true)
|
||||
|
||||
for (let cycle = 0; cycle < CRASH_CYCLES; cycle++) {
|
||||
await armMainProcessCrashProbe(electronApp)
|
||||
await electronApp.evaluate(({ BrowserWindow }) => {
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
win.webContents.forcefullyCrashRenderer()
|
||||
}
|
||||
})
|
||||
|
||||
await expect
|
||||
.poll(async () => (await readMainProcessCrashProbe(electronApp)).processGone?.reason, {
|
||||
timeout: 15_000,
|
||||
message: 'forcefullyCrashRenderer never produced a render-process-gone event'
|
||||
})
|
||||
.toBeTruthy()
|
||||
|
||||
await waitForRendererRecovery(electronApp)
|
||||
|
||||
// Daemon-backed sessions survive renderer death by design, so the pane
|
||||
// should reattach to the same session rather than spawn a fresh shell.
|
||||
const postPtyIds = await mainGetStorePtyIds(electronApp)
|
||||
|
||||
const transportAlive = await mainProbeTransportPaste(electronApp, `PASTE_POST_${cycle}_OK`)
|
||||
const directAlive =
|
||||
postPtyIds.length > 0 &&
|
||||
(await mainProbeDirectWrite(electronApp, postPtyIds[0], `DIRECT_POST_${cycle}_OK`))
|
||||
|
||||
if (!transportAlive || !directAlive) {
|
||||
const revived =
|
||||
postPtyIds.length > 0 &&
|
||||
(await mainProbeOwnershipRebuildRevival(
|
||||
electronApp,
|
||||
postPtyIds[0],
|
||||
`REVIVED_POST_${cycle}_OK`
|
||||
))
|
||||
const crashReason =
|
||||
(await readMainProcessCrashProbe(electronApp)).processGone?.reason ?? 'unknown'
|
||||
throw new Error(
|
||||
buildFrozenPaneReport(
|
||||
`crash cycle ${cycle}, baseline ptyId ${baselinePtyId}, crash reason ${crashReason}`,
|
||||
{
|
||||
directAlive,
|
||||
transportAlive,
|
||||
revivedByOwnershipRebuild: revived,
|
||||
ptyIds: postPtyIds,
|
||||
terminalTail: await mainGetAllTerminalContent(electronApp)
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,259 @@
|
||||
/**
|
||||
* Repro spec for the "starts frozen right after an update" report
|
||||
* (Discord #performance, GitHub #2836 family).
|
||||
*
|
||||
* Field evidence: after an app update + relaunch the terminal pane shows
|
||||
* restored content but typing produces nothing — daemon output.log never
|
||||
* grows. Restore paints the persisted buffer synchronously BEFORE the
|
||||
* deferred PTY reattach runs (use-terminal-pane-lifecycle.ts →
|
||||
* pty-connection.ts), and every reattach-failure branch swallows into null,
|
||||
* so a failed/stalled attach leaves a live-looking, input-dead pane.
|
||||
*
|
||||
* Existing coverage (daemon-live-session-preservation.spec.ts,
|
||||
* terminal-restart-persistence.spec.ts) asserts restored CONTENT after
|
||||
* relaunch, but never that INPUT still works. These tests close that gap for
|
||||
* three real relaunch shapes:
|
||||
* 1. clean restart with a live daemon session (the update model)
|
||||
* 2. daemon wedged (SIGSTOP) across the relaunch — the attach stalls while
|
||||
* restore has already painted; input must recover once the daemon does
|
||||
* 3. daemon killed between launches — cold-restore + fresh spawn must yield
|
||||
* a typeable pane
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import type { ElectronApplication, Page } from '@stablyai/playwright-test'
|
||||
import { test, expect } from './helpers/orca-app'
|
||||
import { TEST_REPO_PATH_FILE } from './global-setup'
|
||||
import {
|
||||
discoverActivePtyId,
|
||||
execInTerminal,
|
||||
getTerminalContent,
|
||||
waitForActiveTerminalManager,
|
||||
waitForPaneCount,
|
||||
waitForTerminalOutput
|
||||
} from './helpers/terminal'
|
||||
import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store'
|
||||
import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart'
|
||||
import {
|
||||
buildFrozenPaneReport,
|
||||
getStorePtyIds,
|
||||
probeDirectWrite,
|
||||
probeKeyboardType,
|
||||
probeOwnershipRebuildRevival
|
||||
} from './helpers/terminal-input-probes'
|
||||
import { PROTOCOL_VERSION } from '../../src/main/daemon/types'
|
||||
import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/pty-session-id-format'
|
||||
|
||||
function readDaemonPid(userDataDir: string): number {
|
||||
const raw = readFileSync(
|
||||
path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`),
|
||||
'utf8'
|
||||
)
|
||||
const parsed = JSON.parse(raw) as { pid?: unknown }
|
||||
if (typeof parsed.pid !== 'number') {
|
||||
throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`)
|
||||
}
|
||||
return parsed.pid
|
||||
}
|
||||
|
||||
function seededRepoPathOrSkip(): string {
|
||||
const repoPath = existsSync(TEST_REPO_PATH_FILE)
|
||||
? readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim()
|
||||
: ''
|
||||
test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo')
|
||||
return repoPath
|
||||
}
|
||||
|
||||
async function bootstrapFirstLaunch(
|
||||
page: Page,
|
||||
repoPath: string
|
||||
): Promise<{ ptyId: string; marker: string }> {
|
||||
await attachRepoAndOpenTerminal(page, repoPath)
|
||||
await waitForSessionReady(page)
|
||||
await waitForActiveWorktree(page)
|
||||
await ensureTerminalVisible(page)
|
||||
await waitForActiveTerminalManager(page, 30_000)
|
||||
await waitForPaneCount(page, 1, 30_000)
|
||||
const ptyId = await discoverActivePtyId(page)
|
||||
// Why: the separator only appears in daemon session ids. If e2e silently
|
||||
// ran the local provider, these tests would exercise the wrong restore path.
|
||||
expect(ptyId, 'expected a daemon-backed PTY session').toContain(PTY_SESSION_ID_SEPARATOR)
|
||||
const marker = `RESTORE_INPUT_PRE_${Date.now()}`
|
||||
await execInTerminal(page, ptyId, `echo ${marker}`)
|
||||
await waitForTerminalOutput(page, marker)
|
||||
return { ptyId, marker }
|
||||
}
|
||||
|
||||
async function settleRestoredLaunch(page: Page): Promise<void> {
|
||||
await waitForSessionReady(page)
|
||||
await waitForActiveWorktree(page)
|
||||
await ensureTerminalVisible(page)
|
||||
await waitForActiveTerminalManager(page, 30_000)
|
||||
await waitForPaneCount(page, 1, 30_000)
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared assertion: a restored pane must accept input. Reports layer
|
||||
* discrimination when it doesn't.
|
||||
*/
|
||||
async function expectRestoredPaneAcceptsInput(page: Page, context: string): Promise<void> {
|
||||
const ptyIds = await getStorePtyIds(page)
|
||||
const kbAlive = await probeKeyboardType(page, 'KB_RESTORED_OK', 15_000)
|
||||
const directAlive =
|
||||
ptyIds.length > 0 && (await probeDirectWrite(page, ptyIds[0], 'DIRECT_RESTORED_OK', 15_000))
|
||||
if (!kbAlive || !directAlive) {
|
||||
const revived =
|
||||
ptyIds.length > 0 &&
|
||||
(await probeOwnershipRebuildRevival(page, ptyIds[0], 'REVIVED_RESTORED_OK'))
|
||||
throw new Error(
|
||||
buildFrozenPaneReport(context, {
|
||||
directAlive,
|
||||
transportAlive: kbAlive,
|
||||
revivedByOwnershipRebuild: revived,
|
||||
ptyIds,
|
||||
terminalTail: await getTerminalContent(page)
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
test.describe.configure({ mode: 'serial' })
|
||||
|
||||
test('restored pane accepts typing after a clean restart with a live daemon session', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set.
|
||||
{}, testInfo) => {
|
||||
test.setTimeout(300_000)
|
||||
const repoPath = seededRepoPathOrSkip()
|
||||
const session = createRestartSession(testInfo)
|
||||
let firstApp: ElectronApplication | null = null
|
||||
let secondApp: ElectronApplication | null = null
|
||||
try {
|
||||
const first = await session.launch()
|
||||
firstApp = first.app
|
||||
const { marker } = await bootstrapFirstLaunch(first.page, repoPath)
|
||||
const daemonPid = readDaemonPid(session.userDataDir)
|
||||
|
||||
await session.close(firstApp)
|
||||
firstApp = null
|
||||
|
||||
const second = await session.launch()
|
||||
secondApp = second.app
|
||||
await settleRestoredLaunch(second.page)
|
||||
await waitForTerminalOutput(second.page, marker, 15_000)
|
||||
expect(readDaemonPid(session.userDataDir), 'daemon must survive the restart').toBe(daemonPid)
|
||||
|
||||
await expectRestoredPaneAcceptsInput(second.page, 'clean restart, live daemon session')
|
||||
} finally {
|
||||
if (secondApp) {
|
||||
await session.close(secondApp)
|
||||
}
|
||||
if (firstApp) {
|
||||
await session.close(firstApp)
|
||||
}
|
||||
await session.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test('restored pane recovers input after the daemon un-wedges', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set.
|
||||
{}, testInfo) => {
|
||||
test.skip(process.platform === 'win32', 'SIGSTOP/SIGCONT are POSIX-only')
|
||||
test.setTimeout(300_000)
|
||||
const repoPath = seededRepoPathOrSkip()
|
||||
const session = createRestartSession(testInfo)
|
||||
let firstApp: ElectronApplication | null = null
|
||||
let secondApp: ElectronApplication | null = null
|
||||
let stoppedDaemonPid: number | null = null
|
||||
try {
|
||||
const first = await session.launch()
|
||||
firstApp = first.app
|
||||
const { marker } = await bootstrapFirstLaunch(first.page, repoPath)
|
||||
const daemonPid = readDaemonPid(session.userDataDir)
|
||||
|
||||
await session.close(firstApp)
|
||||
firstApp = null
|
||||
|
||||
// Wedge the daemon: it stays alive (socket exists, sessions retained) but
|
||||
// cannot accept or answer — the shape of a busy/hung daemon during launch.
|
||||
process.kill(daemonPid, 'SIGSTOP')
|
||||
stoppedDaemonPid = daemonPid
|
||||
|
||||
const second = await session.launch()
|
||||
secondApp = second.app
|
||||
await settleRestoredLaunch(second.page)
|
||||
|
||||
// Field-fidelity check, not a hard gate: does the pane paint restored
|
||||
// content while its PTY attach cannot complete? That visible-but-dead
|
||||
// window is exactly what the reporter sees at startup.
|
||||
const paintedWhileWedged = (await getTerminalContent(second.page)).includes(marker)
|
||||
|
||||
// The relaunching app may classify the stopped daemon as unreachable and
|
||||
// kill+replace it (daemon hardening) — then SIGCONT throws ESRCH and the
|
||||
// old sessions are gone. Both shapes must leave the pane typeable, so
|
||||
// record which one we're in and keep probing.
|
||||
let daemonReplacedWhileWedged = false
|
||||
try {
|
||||
process.kill(daemonPid, 'SIGCONT')
|
||||
} catch {
|
||||
daemonReplacedWhileWedged = true
|
||||
}
|
||||
stoppedDaemonPid = null
|
||||
|
||||
await expectRestoredPaneAcceptsInput(
|
||||
second.page,
|
||||
`daemon wedged during relaunch (painted while wedged: ${paintedWhileWedged}, ` +
|
||||
`wedged daemon killed+replaced by relaunch: ${daemonReplacedWhileWedged})`
|
||||
)
|
||||
} finally {
|
||||
if (stoppedDaemonPid !== null) {
|
||||
try {
|
||||
process.kill(stoppedDaemonPid, 'SIGCONT')
|
||||
} catch {
|
||||
// daemon already gone
|
||||
}
|
||||
}
|
||||
if (secondApp) {
|
||||
await session.close(secondApp)
|
||||
}
|
||||
if (firstApp) {
|
||||
await session.close(firstApp)
|
||||
}
|
||||
await session.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test('cold-restored pane accepts typing after the daemon died between launches', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set.
|
||||
{}, testInfo) => {
|
||||
test.skip(process.platform === 'win32', 'POSIX signal semantics keep this deterministic')
|
||||
test.setTimeout(300_000)
|
||||
const repoPath = seededRepoPathOrSkip()
|
||||
const session = createRestartSession(testInfo)
|
||||
let firstApp: ElectronApplication | null = null
|
||||
let secondApp: ElectronApplication | null = null
|
||||
try {
|
||||
const first = await session.launch()
|
||||
firstApp = first.app
|
||||
await bootstrapFirstLaunch(first.page, repoPath)
|
||||
const daemonPid = readDaemonPid(session.userDataDir)
|
||||
|
||||
await session.close(firstApp)
|
||||
firstApp = null
|
||||
|
||||
// The daemon dies uncleanly between runs (crash, reboot, force-kill). The
|
||||
// persisted session now references sessions no living daemon holds.
|
||||
process.kill(daemonPid, 'SIGKILL')
|
||||
|
||||
const second = await session.launch()
|
||||
secondApp = second.app
|
||||
await settleRestoredLaunch(second.page)
|
||||
|
||||
await expectRestoredPaneAcceptsInput(second.page, 'daemon killed between launches')
|
||||
} finally {
|
||||
if (secondApp) {
|
||||
await session.close(secondApp)
|
||||
}
|
||||
if (firstApp) {
|
||||
await session.close(firstApp)
|
||||
}
|
||||
await session.dispose()
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user