Recover terminal rendering after risky output (#6949)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-30 15:51:45 -07:00
committed by GitHub
co-authored by Orca
parent bcb381e6ec
commit 945b270454
14 changed files with 564 additions and 153 deletions
@@ -121,7 +121,7 @@ import {
} from '@/components/terminal-quick-commands/TerminalQuickCommandDialog'
import { keybindingMatchesAction } from '../../../../shared/keybindings'
import { pasteTerminalClipboard } from './terminal-clipboard-paste'
import { scheduleImagePasteWebglAtlasRecovery } from './terminal-webgl-paste-recovery'
import { scheduleImagePasteWebglAtlasRecovery } from './terminal-webgl-atlas-recovery'
import { restoreTerminalFitToDesktop, restoreTerminalFitsToDesktop } from './terminal-fit-restore'
import { useVisibleTerminalTabClaim } from './use-visible-terminal-tab-claim'
@@ -157,6 +157,7 @@ type MockTransport = {
const scheduleRuntimeGraphSync = vi.fn()
const shouldSeedCacheTimerOnInitialTitle = vi.fn(() => false)
const scheduleTerminalWebglAtlasRecovery = vi.fn()
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
@@ -179,6 +180,10 @@ vi.mock('@/store', () => ({
}
}))
vi.mock('./terminal-webgl-atlas-recovery', () => ({
scheduleTerminalWebglAtlasRecovery
}))
function notifyStoreSubscribers(): void {
for (const listener of storeSubscribers.slice()) {
listener(mockStoreState)
@@ -7990,6 +7995,69 @@ describe('connectPanePty', () => {
expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled()
expect(refresh).toHaveBeenCalledWith(0, 39, true)
expect(scheduleTerminalWebglAtlasRecovery).toHaveBeenCalledTimes(1)
})
it('forces a viewport refresh for foreground CJK output without CSI', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
})
transportFactoryQueue.push(transport)
const pane = createPane(1)
const refresh = vi.fn()
const terminal = pane.terminal as typeof pane.terminal & {
_core?: { refresh: typeof refresh }
}
terminal._core = { refresh }
terminal.write = vi.fn((_data: string, callback?: () => void) => {
callback?.()
})
connectPanePty(pane as never, createManager(1) as never, createDeps() as never)
await flushAsyncTicks(6)
capturedDataCallback.current?.('没改什么(护城河)\r\n')
expect(refresh).toHaveBeenCalledWith(0, 39, true)
expect(scheduleTerminalWebglAtlasRecovery).toHaveBeenCalledTimes(1)
})
it('schedules WebGL atlas recovery after renderer-risk foreground output parses', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
})
transportFactoryQueue.push(transport)
const pane = createPane(1)
const refresh = vi.fn()
let parseCallback: (() => void) | undefined
const terminal = pane.terminal as typeof pane.terminal & {
_core?: { refresh: typeof refresh }
}
terminal._core = { refresh }
terminal.write = vi.fn((_data: string, callback?: () => void) => {
parseCallback = callback
})
connectPanePty(pane as never, createManager(1) as never, createDeps() as never)
await flushAsyncTicks(6)
capturedDataCallback.current?.('没改什么(护城河)\r\n')
expect(scheduleTerminalWebglAtlasRecovery).not.toHaveBeenCalled()
expect(refresh).not.toHaveBeenCalled()
parseCallback?.()
expect(refresh).toHaveBeenCalledWith(0, 39, true)
expect(scheduleTerminalWebglAtlasRecovery).toHaveBeenCalledTimes(1)
})
it('forces a viewport refresh when foreground background SGR is split across PTY chunks', async () => {
@@ -8023,6 +8091,41 @@ describe('connectPanePty', () => {
expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled()
expect(refresh).toHaveBeenCalledWith(0, 39, true)
expect(scheduleTerminalWebglAtlasRecovery).toHaveBeenCalledTimes(1)
})
it('forces a viewport refresh when the foreground CSI introducer is split across PTY chunks', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-id'
})
transportFactoryQueue.push(transport)
const pane = createPane(1)
const manager = createManager(1)
const refresh = vi.fn()
const terminal = pane.terminal as typeof pane.terminal & {
_core?: { refresh: typeof refresh }
}
terminal._core = { refresh }
terminal.write = vi.fn((_data: string, callback?: () => void) => {
callback?.()
})
connectPanePty(pane as never, manager as never, createDeps() as never)
await flushAsyncTicks(6)
capturedDataCallback.current?.('\x1b')
expect(refresh).not.toHaveBeenCalled()
capturedDataCallback.current?.('[48;2;52;52;52m codex block text \x1b[0m\r\n')
expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled()
expect(refresh).toHaveBeenCalledWith(0, 39, true)
expect(scheduleTerminalWebglAtlasRecovery).toHaveBeenCalledTimes(1)
})
it('does not keep forcing viewport refresh after completed background redraws', async () => {
@@ -8052,9 +8155,11 @@ describe('connectPanePty', () => {
expect(refresh).toHaveBeenCalledWith(0, 39, true)
refresh.mockClear()
scheduleTerminalWebglAtlasRecovery.mockClear()
capturedDataCallback.current?.('plain follow-up output\r\n')
expect(refresh).not.toHaveBeenCalled()
expect(scheduleTerminalWebglAtlasRecovery).not.toHaveBeenCalled()
})
it('forces a viewport refresh for native Windows CJK foreground output after terminal input', async () => {
@@ -8132,7 +8237,7 @@ describe('connectPanePty', () => {
}
})
it('does not force the Windows CJK repaint path for non-East-Asian Unicode input', async () => {
it('does not force renderer-risk repaint for ordinary non-ASCII output', async () => {
const restoreNavigator = temporarilySetNavigatorUserAgent(
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
)
@@ -8160,11 +8265,12 @@ describe('connectPanePty', () => {
connectPanePty(pane as never, createManager(1) as never, createDeps() as never)
await flushAsyncTicks(6)
sendTerminalInputThroughPane(pane, 'status 🚀')
sendTerminalInputThroughPane(pane, 'abc 123 ✓')
capturedDataCallback.current?.('status 🚀')
capturedDataCallback.current?.('abc 123 ✓')
expect(refresh).not.toHaveBeenCalled()
expect(scheduleTerminalWebglAtlasRecovery).not.toHaveBeenCalled()
} finally {
restoreNavigator()
}
@@ -8214,7 +8320,7 @@ describe('connectPanePty', () => {
}
})
it('does not apply the Windows CJK repaint path on non-Windows clients', async () => {
it('does not repaint ordinary non-ASCII output on non-Windows clients', async () => {
const restoreNavigator = temporarilySetNavigatorUserAgent('Mozilla/5.0 (Macintosh)')
try {
const { connectPanePty } = await import('./pty-connection')
@@ -8241,9 +8347,10 @@ describe('connectPanePty', () => {
connectPanePty(pane as never, createManager(1) as never, createDeps() as never)
await flushAsyncTicks(6)
capturedDataCallback.current?.('已经安装完成,软件已更新后重启。')
capturedDataCallback.current?.('abc 123 ✓')
expect(refresh).not.toHaveBeenCalled()
expect(scheduleTerminalWebglAtlasRecovery).not.toHaveBeenCalled()
} finally {
restoreNavigator()
}
@@ -115,6 +115,7 @@ import { createCommandCodeOutputStatusDetector } from './command-code-output-sta
import type { PtyDataMeta } from './pty-dispatcher'
import { getEagerPtyBufferHandle } from './pty-dispatcher'
import { createTerminalGitHubPRLinkDetector } from '@/lib/terminal-github-pr-link-detector'
import { scheduleTerminalWebglAtlasRecovery } from './terminal-webgl-atlas-recovery'
import {
CONPTY_DA1_RESPONSE,
createTerminalPixelSizeQueryResponder,
@@ -2946,11 +2947,17 @@ export function connectPanePty(
let foregroundRefreshRiskScanTail = ''
function trailingIncompleteCsiSequence(data: string): string {
const escapeIndex = data.lastIndexOf('\x1b[')
const escapeIndex = data.lastIndexOf('\x1b')
if (escapeIndex === -1) {
return ''
}
const tail = data.slice(escapeIndex)
if (tail === '\x1b') {
return tail
}
if (!tail.startsWith('\x1b[')) {
return ''
}
for (let index = 2; index < tail.length; index++) {
const code = tail.charCodeAt(index)
if (code >= 0x40 && code <= 0x7e) {
@@ -2960,7 +2967,7 @@ export function connectPanePty(
return tail.slice(-TERMINAL_RENDERER_RISK_SCAN_TAIL_CHARS)
}
function foregroundAnsiOutputPrefersRenderRefresh(data: string): boolean {
function foregroundRendererRiskOutputPrefersRenderRefresh(data: string): boolean {
if (!data) {
return false
}
@@ -2968,7 +2975,8 @@ export function connectPanePty(
? `${foregroundRefreshRiskScanTail}${data}`
: data
const prefersRefresh =
scanData.includes('\x1b[') && terminalOutputPrefersRenderRefresh(scanData)
(scanData.includes('\x1b[') || containsNonAsciiOutput(scanData)) &&
terminalOutputPrefersRenderRefresh(scanData)
foregroundRefreshRiskScanTail = trailingIncompleteCsiSequence(scanData)
return prefersRefresh
}
@@ -3188,19 +3196,22 @@ export function connectPanePty(
function shouldForceForegroundRenderRefresh(data: string): {
refresh: boolean
inPlaceRewrite: boolean
recoverWebglAtlasAfterParse: boolean
} {
const rewriteOutputPrefersRenderRefresh = foregroundRewriteOutputPrefersRenderRefresh(data)
const recentInput =
performance.now() - lastTerminalInputAt <= FOREGROUND_INTERACTIVE_REDRAW_WINDOW_MS
if (foregroundAnsiOutputPrefersRenderRefresh(data)) {
// Why: Codex-style background SGR panels can paint cell fills while
// glyphs lag behind; refresh only renderer-risk ANSI chunks, not all output.
return { refresh: true, inPlaceRewrite: rewriteOutputPrefersRenderRefresh }
if (foregroundRendererRiskOutputPrefersRenderRefresh(data)) {
return {
refresh: true,
inPlaceRewrite: rewriteOutputPrefersRenderRefresh,
recoverWebglAtlasAfterParse: true
}
}
if (rewriteOutputPrefersRenderRefresh) {
// Why: resize fixes these panes because xterm's buffer is right but
// in-place redraw cells can remain stale in the renderer until repaint.
return { refresh: true, inPlaceRewrite: true }
return { refresh: true, inPlaceRewrite: true, recoverWebglAtlasAfterParse: false }
}
if (
windowsEastAsianOutputPrefersRenderRefresh(data, {
@@ -3212,14 +3223,15 @@ export function connectPanePty(
) {
// Why: CJK/Korean from Microsoft Pinyin commits and native ConPTY agent
// output can leave stale wide-glyph cells in the local Windows DOM renderer.
return { refresh: true, inPlaceRewrite: false }
return { refresh: true, inPlaceRewrite: false, recoverWebglAtlasAfterParse: false }
}
return {
refresh:
shouldApplyNativeWindowsRewriteRefresh &&
containsNonAsciiOutput(data) &&
containsWindowsRewriteControl(data),
inPlaceRewrite: false
inPlaceRewrite: false,
recoverWebglAtlasAfterParse: false
}
}
@@ -3259,7 +3271,7 @@ export function connectPanePty(
const foregroundOutput = foreground || parseHiddenStartupOutput
const renderRefreshDecision = foregroundOutput
? shouldForceForegroundRenderRefresh(data)
: { refresh: false, inPlaceRewrite: false }
: { refresh: false, inPlaceRewrite: false, recoverWebglAtlasAfterParse: false }
const foregroundRenderRefreshNeeded = renderRefreshDecision.refresh
// Why: see nativeWindowsRewriteNeedsFollowupRenderRefresh — Claude Code's
// in-place prompt redraws on Windows ConPTY can paint one frame late, so a
@@ -3306,6 +3318,11 @@ export function connectPanePty(
foregroundRenderRefreshNeeded),
followupForegroundRefresh:
nativeWindowsCursorRestore || nativeWindowsInPlaceRewriteFollowup,
// Why: atlas recovery must repaint from the parsed xterm buffer, not
// a pre-write snapshot that a late TUI redraw can immediately stale.
onForegroundParsed: renderRefreshDecision.recoverWebglAtlasAfterParse
? scheduleTerminalWebglAtlasRecovery
: undefined,
stripTransientCursorShows: shouldProtectNativeWindowsSynchronizedOutput && foreground,
coalesceForeground: synchronizedForegroundOutput && synchronizedOutputEnded,
holdForeground: synchronizedForegroundOutput && nextSynchronizedForegroundOutputActive
@@ -1,12 +1,13 @@
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
import type { ScrollState } from '@/lib/pane-manager/pane-manager-types'
import { resetAllTerminalWebglAtlases } from '@/lib/pane-manager/pane-manager-registry'
import { resetAndRefreshAllTerminalWebglAtlases } from '@/lib/pane-manager/pane-manager-registry'
import {
flushTerminalOutput,
requestTerminalBacklogRecovery
} from '@/lib/pane-manager/pane-terminal-output-scheduler'
import { enforceTerminalCurrentScrollIntent } from '@/lib/pane-manager/terminal-scroll-intent'
import { fitAndFocusPanes, fitPanes, focusActivePane } from './pane-helpers'
import { scheduleTerminalWebglAtlasRecovery } from './terminal-webgl-atlas-recovery'
const VISIBLE_RESUME_FLUSH_CHARS = 256 * 1024
const WINDOW_WAKE_FLUSH_CHARS = 64 * 1024
@@ -61,6 +62,7 @@ export function resumeTerminalVisibility({
// overlay's delayed geometry fit. Still request hidden-output recovery:
// agent TUIs can suppress hidden bytes until the pane is foregrounded.
requestLightTabBacklogRecovery(manager)
scheduleTerminalWebglAtlasRecovery()
if (isActive) {
focusActivePane(manager)
}
@@ -70,8 +72,8 @@ export function resumeTerminalVisibility({
enforceTerminalViewportIntents(manager)
if (!shouldUseLightTabResume) {
// Why: this clear wipes the glyph atlas shared with other same-config
// terminals; the global reset rebuilds their render models too.
resetAllTerminalWebglAtlases()
// terminals; refresh after reset so rebuilt atlases repaint from xterm.
resetAndRefreshAllTerminalWebglAtlases()
}
})
}
@@ -130,8 +132,7 @@ export function recoverVisibleTerminalWindowWake({
fitPanes(manager)
}
enforceTerminalViewportIntents(manager)
resetAllTerminalWebglAtlases()
manager.refreshAllPanes?.()
resetAndRefreshAllTerminalWebglAtlases()
}
function requestLightTabBacklogRecovery(manager: PaneManager): void {
@@ -0,0 +1,181 @@
import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
import {
registerLivePaneManager,
unregisterLivePaneManager
} from '@/lib/pane-manager/pane-manager-registry'
import {
scheduleImagePasteWebglAtlasRecovery,
scheduleTerminalWebglAtlasRecovery
} from './terminal-webgl-atlas-recovery'
describe('terminal WebGL atlas recovery', () => {
const registeredManagers: { resetWebglTextureAtlases(): void }[] = []
function registerManager(): {
resetWebglTextureAtlases: Mock<() => void>
refreshAllPanes: Mock<() => void>
} {
const manager = {
resetWebglTextureAtlases: vi.fn<() => void>(),
refreshAllPanes: vi.fn<() => void>()
}
registerLivePaneManager(manager)
registeredManagers.push(manager)
return manager
}
afterEach(() => {
for (const manager of registeredManagers.splice(0)) {
unregisterLivePaneManager(manager)
}
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('clears atlases and refreshes panes through the post-paste redraw window', () => {
vi.useFakeTimers()
const rafCallbacks: FrameRequestCallback[] = []
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
rafCallbacks.push(callback)
return rafCallbacks.length
})
)
// Why: resets go through the live-manager registry so every terminal
// sharing the glyph atlas rebuilds and repaints, not just the paste target.
const manager = registerManager()
const otherManager = registerManager()
scheduleImagePasteWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
rafCallbacks[0]?.(0)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
expect(otherManager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(otherManager.refreshAllPanes).toHaveBeenCalledTimes(1)
vi.advanceTimersByTime(120)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(2)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(2)
vi.advanceTimersByTime(380)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(3)
})
it('refreshes after each scheduled atlas reset', () => {
vi.useFakeTimers()
const order: string[] = []
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(0)
return 1
})
)
const manager = {
resetWebglTextureAtlases: vi.fn(() => order.push('first-reset')),
refreshAllPanes: vi.fn(() => order.push('first-refresh'))
}
const otherManager = {
resetWebglTextureAtlases: vi.fn(() => order.push('second-reset')),
refreshAllPanes: vi.fn(() => order.push('second-refresh'))
}
registerLivePaneManager(manager)
registeredManagers.push(manager)
registerLivePaneManager(otherManager)
registeredManagers.push(otherManager)
scheduleImagePasteWebglAtlasRecovery()
vi.advanceTimersByTime(500)
expect(order).toEqual([
'first-reset',
'second-reset',
'first-refresh',
'second-refresh',
'first-reset',
'second-reset',
'first-refresh',
'second-refresh',
'first-reset',
'second-reset',
'first-refresh',
'second-refresh'
])
})
it('falls back to a timeout when animation frames are unavailable', () => {
vi.useFakeTimers()
vi.stubGlobal('requestAnimationFrame', undefined)
const manager = registerManager()
scheduleImagePasteWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
vi.advanceTimersByTime(0)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
})
it('continues recovery when a manager throws after scheduling', () => {
vi.useFakeTimers()
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(0)
return 1
})
)
const manager = {
resetWebglTextureAtlases: vi.fn(() => {
throw new Error('pane disposed')
}),
refreshAllPanes: vi.fn()
}
registerLivePaneManager(manager)
registeredManagers.push(manager)
const healthyManager = registerManager()
expect(() => scheduleImagePasteWebglAtlasRecovery()).not.toThrow()
expect(() => vi.runAllTimers()).not.toThrow()
expect(healthyManager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3)
expect(healthyManager.refreshAllPanes).toHaveBeenCalledTimes(3)
expect(manager.refreshAllPanes).not.toHaveBeenCalled()
})
it('coalesces terminal-output atlas recovery across a redraw burst', () => {
vi.useFakeTimers()
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(0)
return 1
})
)
const manager = registerManager()
scheduleTerminalWebglAtlasRecovery()
scheduleTerminalWebglAtlasRecovery()
scheduleTerminalWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
vi.advanceTimersByTime(120)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(2)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(2)
scheduleTerminalWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(2)
vi.advanceTimersByTime(380)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(3)
scheduleTerminalWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(4)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(4)
vi.advanceTimersByTime(500)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(6)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(6)
})
})
@@ -0,0 +1,53 @@
import { resetAndRefreshAllTerminalWebglAtlases } from '@/lib/pane-manager/pane-manager-registry'
const ATLAS_RECOVERY_DELAYS_MS = [120, 500]
let terminalOutputRecoveryScheduled = false
function scheduleNextFrame(callback: () => void): void {
if (typeof globalThis.requestAnimationFrame === 'function') {
globalThis.requestAnimationFrame(callback)
return
}
globalThis.setTimeout(callback, 0)
}
function resetAtlasesAndRefreshPanes(): void {
try {
// Why: the glyph atlas is shared across same-config terminals, so the
// recovery reset must be followed by repainting each rebuilt render model.
resetAndRefreshAllTerminalWebglAtlases()
} catch {
/* ignore - terminal pane may have unmounted after scheduling recovery */
}
}
function scheduleAtlasRecoveryBurst(onComplete?: () => void): void {
scheduleNextFrame(() => resetAtlasesAndRefreshPanes())
for (const [index, delayMs] of ATLAS_RECOVERY_DELAYS_MS.entries()) {
globalThis.setTimeout(() => {
resetAtlasesAndRefreshPanes()
if (index === ATLAS_RECOVERY_DELAYS_MS.length - 1) {
onComplete?.()
}
}, delayMs)
}
}
export function scheduleImagePasteWebglAtlasRecovery(): void {
// Why: image chips can redraw after bracketed paste parsing, so cover the
// short post-paste paint window with a few cheap atlas rebuilds.
scheduleAtlasRecoveryBurst()
}
export function scheduleTerminalWebglAtlasRecovery(): void {
if (terminalOutputRecoveryScheduled) {
return
}
terminalOutputRecoveryScheduled = true
// Why: TUI redraw bursts can corrupt xterm's shared WebGL glyph atlas without
// a context-loss event; coalesce resets so output storms do not queue timers.
scheduleAtlasRecoveryBurst(() => {
terminalOutputRecoveryScheduled = false
})
}
@@ -1,86 +0,0 @@
import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
import {
registerLivePaneManager,
unregisterLivePaneManager
} from '@/lib/pane-manager/pane-manager-registry'
import { scheduleImagePasteWebglAtlasRecovery } from './terminal-webgl-paste-recovery'
describe('terminal image paste WebGL recovery', () => {
const registeredManagers: { resetWebglTextureAtlases(): void }[] = []
function registerManager(): { resetWebglTextureAtlases: Mock<() => void> } {
const manager = { resetWebglTextureAtlases: vi.fn<() => void>() }
registerLivePaneManager(manager)
registeredManagers.push(manager)
return manager
}
afterEach(() => {
for (const manager of registeredManagers.splice(0)) {
unregisterLivePaneManager(manager)
}
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('clears atlases on the next frame and through the post-paste redraw window', () => {
vi.useFakeTimers()
const rafCallbacks: FrameRequestCallback[] = []
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
rafCallbacks.push(callback)
return rafCallbacks.length
})
)
// Why: resets go through the live-manager registry so every terminal
// sharing the glyph atlas rebuilds, not just the pasted-into pane.
const manager = registerManager()
const otherManager = registerManager()
scheduleImagePasteWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
rafCallbacks[0]?.(0)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(otherManager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
vi.advanceTimersByTime(120)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(2)
vi.advanceTimersByTime(380)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3)
})
it('falls back to a timeout when animation frames are unavailable', () => {
vi.useFakeTimers()
vi.stubGlobal('requestAnimationFrame', undefined)
const manager = registerManager()
scheduleImagePasteWebglAtlasRecovery()
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
vi.advanceTimersByTime(0)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
})
it('ignores resets after the pane has unmounted', () => {
vi.useFakeTimers()
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(0)
return 1
})
)
const manager = {
resetWebglTextureAtlases: vi.fn(() => {
throw new Error('pane disposed')
})
}
registerLivePaneManager(manager)
registeredManagers.push(manager)
expect(() => scheduleImagePasteWebglAtlasRecovery()).not.toThrow()
expect(() => vi.runAllTimers()).not.toThrow()
})
})
@@ -1,32 +0,0 @@
import { resetAllTerminalWebglAtlases } from '@/lib/pane-manager/pane-manager-registry'
const IMAGE_PASTE_ATLAS_RECOVERY_DELAYS_MS = [120, 500]
function scheduleNextFrame(callback: () => void): void {
if (typeof globalThis.requestAnimationFrame === 'function') {
globalThis.requestAnimationFrame(callback)
return
}
globalThis.setTimeout(callback, 0)
}
function resetAtlases(): void {
try {
// Why: the glyph atlas is shared across same-config terminals, so the
// recovery reset must rebuild every live terminal's render model — a
// single-manager reset would garble the others.
resetAllTerminalWebglAtlases()
} catch {
/* ignore - terminal pane may have unmounted after paste */
}
}
export function scheduleImagePasteWebglAtlasRecovery(): void {
// Why: Claude Code redraws its image chip immediately after bracketed paste,
// and xterm WebGL atlas corruption can appear after that redraw without a
// context-loss event. A few cheap resets cover the post-paste paint window.
scheduleNextFrame(() => resetAtlases())
for (const delayMs of IMAGE_PASTE_ATLAS_RECOVERY_DELAYS_MS) {
globalThis.setTimeout(() => resetAtlases(), delayMs)
}
}
@@ -23,7 +23,7 @@ import { resolveTerminalPasteRuntime } from './terminal-paste-runtime'
import { getTerminalPasteSshRemotePlatform } from './terminal-paste-ssh-platform'
import { isTerminalPanePasteTargetCurrent } from './terminal-paste-target-state'
import { writeTerminalPastePtyInput } from './terminal-pty-paste-writer'
import { scheduleImagePasteWebglAtlasRecovery } from './terminal-webgl-paste-recovery'
import { scheduleImagePasteWebglAtlasRecovery } from './terminal-webgl-atlas-recovery'
import {
REQUEST_ACTIVE_TERMINAL_PANE_SPLIT_EVENT,
type RequestActiveTerminalPaneSplitDetail
@@ -205,6 +205,7 @@ describe('useTerminalPaneGlobalEffects', () => {
for (const manager of registeredManagers.splice(0)) {
unregisterLivePaneManager(manager)
}
vi.useRealTimers()
vi.unstubAllGlobals()
delete (globalThis as unknown as { window?: unknown }).window
delete (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver
@@ -221,6 +222,7 @@ describe('useTerminalPaneGlobalEffects', () => {
]),
resumeRendering: vi.fn(() => order.push('resume')),
resetWebglTextureAtlases: vi.fn(() => order.push('reset-atlas')),
refreshAllPanes: vi.fn(() => order.push('refresh')),
suspendRendering: vi.fn(),
fitAllPanes: vi.fn(),
getActivePane: vi.fn(() => null),
@@ -277,7 +279,8 @@ describe('useTerminalPaneGlobalEffects', () => {
'fit-focus',
'intent:terminal-a',
'intent:terminal-b',
'reset-atlas'
'reset-atlas',
'refresh'
])
expect(mocks.restoreScrollStateAfterLayout).not.toHaveBeenCalled()
expect(mocks.flushTerminalOutput).toHaveBeenNthCalledWith(1, terminalA, {
@@ -292,11 +295,20 @@ describe('useTerminalPaneGlobalEffects', () => {
})
it('uses a light resume for tab switches while the worktree stays active', () => {
vi.useFakeTimers()
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(0)
return 1
})
)
const terminal = { name: 'terminal-a' }
const manager = {
getPanes: vi.fn(() => [{ id: 1, terminal }]),
resumeRendering: vi.fn(),
resetWebglTextureAtlases: vi.fn(),
refreshAllPanes: vi.fn(),
suspendRendering: vi.fn(),
fitAllPanes: vi.fn(),
getActivePane: vi.fn(() => null),
@@ -326,6 +338,7 @@ describe('useTerminalPaneGlobalEffects', () => {
manager.resumeRendering.mockClear()
manager.resetWebglTextureAtlases.mockClear()
manager.refreshAllPanes.mockClear()
manager.suspendRendering.mockClear()
mocks.fitAndFocusPanes.mockClear()
mocks.fitPanes.mockClear()
@@ -354,16 +367,27 @@ describe('useTerminalPaneGlobalEffects', () => {
expect(manager.resumeRendering).not.toHaveBeenCalled()
expect(mocks.fitAndFocusPanes).not.toHaveBeenCalled()
expect(mocks.fitPanes).not.toHaveBeenCalled()
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
expect(mocks.focusActivePane).toHaveBeenCalledWith(manager)
vi.advanceTimersByTime(500)
})
it('keeps visible active-state updates on the light resume path', () => {
vi.useFakeTimers()
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
callback(0)
return 1
})
)
const terminal = { name: 'terminal-a' }
const manager = {
getPanes: vi.fn(() => [{ id: 1, terminal }]),
resumeRendering: vi.fn(),
resetWebglTextureAtlases: vi.fn(),
refreshAllPanes: vi.fn(),
suspendRendering: vi.fn(),
fitAllPanes: vi.fn(),
getActivePane: vi.fn(() => null),
@@ -393,6 +417,7 @@ describe('useTerminalPaneGlobalEffects', () => {
manager.resumeRendering.mockClear()
manager.resetWebglTextureAtlases.mockClear()
manager.refreshAllPanes.mockClear()
mocks.fitAndFocusPanes.mockClear()
mocks.fitPanes.mockClear()
mocks.focusActivePane.mockClear()
@@ -411,8 +436,10 @@ describe('useTerminalPaneGlobalEffects', () => {
expect(manager.resumeRendering).not.toHaveBeenCalled()
expect(mocks.fitAndFocusPanes).not.toHaveBeenCalled()
expect(mocks.fitPanes).not.toHaveBeenCalled()
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
expect(mocks.focusActivePane).toHaveBeenCalledWith(manager)
vi.advanceTimersByTime(500)
})
it('suspends rendering when a terminal tab first mounts hidden', () => {
@@ -421,6 +448,7 @@ describe('useTerminalPaneGlobalEffects', () => {
getPanes: vi.fn(() => [{ id: 1, terminal }]),
resumeRendering: vi.fn(),
resetWebglTextureAtlases: vi.fn(),
refreshAllPanes: vi.fn(),
suspendRendering: vi.fn(),
fitAllPanes: vi.fn(),
getActivePane: vi.fn(() => null),
@@ -473,6 +501,7 @@ describe('useTerminalPaneGlobalEffects', () => {
getPanes: vi.fn(() => [{ id: 1, terminal }]),
resumeRendering: vi.fn(),
resetWebglTextureAtlases: vi.fn(),
refreshAllPanes: vi.fn(),
suspendRendering: vi.fn(),
fitAllPanes: vi.fn(),
getActivePane: vi.fn(() => null),
@@ -523,6 +552,7 @@ describe('useTerminalPaneGlobalEffects', () => {
manager.resumeRendering.mockClear()
manager.resetWebglTextureAtlases.mockClear()
manager.refreshAllPanes.mockClear()
mocks.fitAndFocusPanes.mockClear()
mocks.flushTerminalOutput.mockClear()
mocks.requestTerminalBacklogRecovery.mockClear()
@@ -540,6 +570,7 @@ describe('useTerminalPaneGlobalEffects', () => {
expect(manager.resumeRendering).toHaveBeenCalledTimes(1)
expect(mocks.fitAndFocusPanes).toHaveBeenCalledWith(manager)
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
})
it('reports the active local PTY to the main output scheduler', () => {
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
import {
refitAndRefreshAllTerminalPanes,
registerLivePaneManager,
resetAndRefreshAllTerminalWebglAtlases,
resetAllTerminalWebglAtlases,
unregisterLivePaneManager
} from './pane-manager-registry'
@@ -59,6 +60,50 @@ describe('pane manager registry', () => {
expect(healthy.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
})
it('refreshes managers after all atlas resets complete', () => {
const order: string[] = []
const first = {
resetWebglTextureAtlases: vi.fn<() => void>(() => order.push('first-reset')),
refreshAllPanes: vi.fn<() => void>(() => order.push('first-refresh'))
}
const second = {
resetWebglTextureAtlases: vi.fn<() => void>(() => order.push('second-reset')),
refreshAllPanes: vi.fn<() => void>(() => order.push('second-refresh'))
}
registerLivePaneManager(first)
registeredManagers.push(first)
registerLivePaneManager(second)
registeredManagers.push(second)
resetAndRefreshAllTerminalWebglAtlases()
expect(order).toEqual(['first-reset', 'second-reset', 'first-refresh', 'second-refresh'])
})
it('continues reset-and-refresh recovery when one manager throws', () => {
const broken = {
resetWebglTextureAtlases: vi.fn<() => void>(() => {
throw new Error('pane disposed')
}),
refreshAllPanes: vi.fn<() => void>()
}
registerLivePaneManager(broken)
registeredManagers.push(broken)
const healthy = {
resetWebglTextureAtlases: vi.fn<() => void>(),
refreshAllPanes: vi.fn<() => void>()
}
registerLivePaneManager(healthy)
registeredManagers.push(healthy)
expect(() => resetAndRefreshAllTerminalWebglAtlases()).not.toThrow()
expect(broken.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(broken.refreshAllPanes).not.toHaveBeenCalled()
expect(healthy.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
expect(healthy.refreshAllPanes).toHaveBeenCalledTimes(1)
})
it('fits and refreshes every registered manager', () => {
const first = {
resetWebglTextureAtlases: vi.fn<() => void>(),
@@ -34,6 +34,27 @@ export function resetAllTerminalWebglAtlases(): void {
}
}
export function resetAndRefreshAllTerminalWebglAtlases(): void {
const resetManagers: RegisteredPaneManager[] = []
for (const manager of liveManagers) {
try {
manager.resetWebglTextureAtlases()
resetManagers.push(manager)
} catch {
// Why: recovery is best-effort during pane teardown; a disposed manager
// should not block sibling terminals from rebuilding and repainting.
}
}
for (const manager of resetManagers) {
try {
manager.refreshAllPanes?.()
} catch {
// Why: a pane can unmount between atlas reset and repaint; later
// managers still need to repaint from their xterm buffers.
}
}
}
export function refitAndRefreshAllTerminalPanes(): void {
for (const manager of liveManagers) {
try {
@@ -69,6 +69,49 @@ describe('pane terminal output scheduler', () => {
expect(terminal.write).toHaveBeenCalledWith('foreground', expect.any(Function))
})
it('runs foreground parsed callbacks after immediate foreground output parses', async () => {
const { writeTerminalOutput } = await loadScheduler()
const terminal = createTerminal()
let parseCallback: (() => void) | undefined
terminal.write.mockImplementation((_data: string, callback?: () => void) => {
parseCallback = callback
})
const onForegroundParsed = vi.fn()
writeTerminalOutput(terminal, 'foreground', {
foreground: true,
onForegroundParsed
})
expect(onForegroundParsed).not.toHaveBeenCalled()
parseCallback?.()
expect(onForegroundParsed).toHaveBeenCalledTimes(1)
})
it('runs foreground parsed callbacks after queued foreground output parses', async () => {
vi.useFakeTimers()
const { writeTerminalOutput } = await loadScheduler()
const terminal = createTerminal()
let parseCallback: (() => void) | undefined
terminal.write.mockImplementation((_data: string, callback?: () => void) => {
parseCallback = callback
})
const onForegroundParsed = vi.fn()
writeTerminalOutput(terminal, 'queued', {
foreground: true,
latencySensitive: false,
onForegroundParsed
})
vi.advanceTimersByTime(0)
expect(terminal.write).toHaveBeenCalledWith('queued', expect.any(Function))
expect(onForegroundParsed).not.toHaveBeenCalled()
parseCallback?.()
expect(onForegroundParsed).toHaveBeenCalledTimes(1)
})
it('synchronously refreshes visible rows after foreground output parses', async () => {
const { writeTerminalOutput } = await loadScheduler()
const terminal = createForegroundTerminal()
@@ -16,10 +16,12 @@ type TerminalOutputTarget = ForegroundTerminalOutputTarget
type TerminalOutputBeforeWrite = (data: string) => void
type TerminalBacklogRecoveryRequest = () => boolean
type TerminalOutputParsedCallback = () => void
type WriteTerminalOutputOptions = {
foreground: boolean
beforeWrite?: TerminalOutputBeforeWrite
onForegroundParsed?: TerminalOutputParsedCallback
onBackgroundBacklogDropped?: () => void
latencySensitive?: boolean
forceForegroundRefresh?: boolean
@@ -35,6 +37,7 @@ type QueueChunk = {
forceForegroundRefresh: boolean
followupForegroundRefresh: boolean
stripTransientCursorShows: boolean
onForegroundParsed?: TerminalOutputParsedCallback
}
type QueuedWrite = {
@@ -43,6 +46,7 @@ type QueuedWrite = {
forceForegroundRefresh: boolean
followupForegroundRefresh: boolean
stripTransientCursorShows: boolean
onForegroundParsed?: TerminalOutputParsedCallback
}
type QueueEntry = {
@@ -479,6 +483,7 @@ function takeQueuedChunk(entry: QueueEntry, limit: number): QueuedWrite | null {
let forceForegroundRefresh = false
let followupForegroundRefresh = false
let stripTransientCursorShows = false
const parsedCallbacks: TerminalOutputParsedCallback[] = []
while (remaining > 0 && entry.chunkIndex < entry.chunks.length) {
const chunk = entry.chunks[entry.chunkIndex]
@@ -494,6 +499,9 @@ function takeQueuedChunk(entry: QueueEntry, limit: number): QueuedWrite | null {
remaining -= chunk.data.length
entry.queuedChars -= chunk.data.length
entry.chunkIndex += 1
if (chunk.foreground && chunk.onForegroundParsed) {
parsedCallbacks.push(chunk.onForegroundParsed)
}
continue
}
@@ -517,7 +525,15 @@ function takeQueuedChunk(entry: QueueEntry, limit: number): QueuedWrite | null {
foreground: foreground === true,
forceForegroundRefresh,
followupForegroundRefresh,
stripTransientCursorShows
stripTransientCursorShows,
onForegroundParsed:
parsedCallbacks.length > 0
? () => {
for (const callback of parsedCallbacks) {
callback()
}
}
: undefined
}
: null
}
@@ -545,6 +561,7 @@ function enqueueChunk(
forceForegroundRefresh?: boolean
followupForegroundRefresh?: boolean
stripTransientCursorShows?: boolean
onForegroundParsed?: TerminalOutputParsedCallback
}
): void {
entry.chunks.push({
@@ -552,7 +569,8 @@ function enqueueChunk(
foreground: options?.foreground === true,
forceForegroundRefresh: options?.forceForegroundRefresh === true,
followupForegroundRefresh: options?.followupForegroundRefresh === true,
stripTransientCursorShows: options?.stripTransientCursorShows === true
stripTransientCursorShows: options?.stripTransientCursorShows === true,
onForegroundParsed: options?.onForegroundParsed
})
entry.queuedChars += data.length
recordQueueDebugPressure()
@@ -632,13 +650,19 @@ function writeForegroundTerminalChunkWithIntent(
options: {
forceViewportRefresh: boolean
followupViewportRefresh: boolean
onParsed?: TerminalOutputParsedCallback
}
): void {
const scrollIntent = captureTerminalWriteScrollIntent(terminal)
writeForegroundTerminalChunk(terminal, data, {
forceViewportRefresh: options.forceViewportRefresh,
followupViewportRefresh: options.followupViewportRefresh,
onParsed: () => enforceTerminalWriteScrollIntent(terminal, scrollIntent)
onParsed: () => {
// Why: recovery must repaint from the scrolled buffer state that xterm
// will keep, not from a pre-intent-restored viewport snapshot.
enforceTerminalWriteScrollIntent(terminal, scrollIntent)
options.onParsed?.()
}
})
}
@@ -668,7 +692,8 @@ function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' | null
: queuedWrite.data,
{
forceViewportRefresh: queuedWrite.forceForegroundRefresh,
followupViewportRefresh: queuedWrite.followupForegroundRefresh
followupViewportRefresh: queuedWrite.followupForegroundRefresh,
onParsed: queuedWrite.onForegroundParsed
}
)
} else {
@@ -756,7 +781,8 @@ export function writeTerminalOutput(
foreground: true,
forceForegroundRefresh: options.forceForegroundRefresh,
followupForegroundRefresh: options.followupForegroundRefresh,
stripTransientCursorShows: options.stripTransientCursorShows
stripTransientCursorShows: options.stripTransientCursorShows,
onForegroundParsed: options.onForegroundParsed
})
if (debugEnabled) {
debugState.foregroundWriteCount++
@@ -822,7 +848,8 @@ export function writeTerminalOutput(
foreground: true,
forceForegroundRefresh: options.forceForegroundRefresh,
followupForegroundRefresh: options.followupForegroundRefresh,
stripTransientCursorShows: options.stripTransientCursorShows
stripTransientCursorShows: options.stripTransientCursorShows,
onForegroundParsed: options.onForegroundParsed
})
if (debugEnabled) {
debugState.foregroundWriteCount++
@@ -848,7 +875,8 @@ export function writeTerminalOutput(
foreground: true,
forceForegroundRefresh: options.forceForegroundRefresh,
followupForegroundRefresh: options.followupForegroundRefresh,
stripTransientCursorShows: options.stripTransientCursorShows
stripTransientCursorShows: options.stripTransientCursorShows,
onForegroundParsed: options.onForegroundParsed
})
if (debugEnabled) {
debugState.foregroundWriteCount++
@@ -870,7 +898,8 @@ export function writeTerminalOutput(
options.stripTransientCursorShows ? removeTransientCursorShowSequences(data) : data,
{
forceViewportRefresh: options.forceForegroundRefresh === true,
followupViewportRefresh: options.followupForegroundRefresh === true
followupViewportRefresh: options.followupForegroundRefresh === true,
onParsed: options.onForegroundParsed
}
)
return
@@ -945,7 +974,8 @@ export function flushTerminalOutput(
: queuedWrite.data,
{
forceViewportRefresh: queuedWrite.forceForegroundRefresh,
followupViewportRefresh: queuedWrite.followupForegroundRefresh
followupViewportRefresh: queuedWrite.followupForegroundRefresh,
onParsed: queuedWrite.onForegroundParsed
}
)
} else {