Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/superpowers/plans/2026-09-05-terminal-atlas-repaint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Terminal atlas repaint

Status: implemented and locally verified; awaiting PR review/CI. Refs #789.

## Evidence and scope

The user reports stale terminal cells after scrolling interactive Claude output.
The screenshot alone cannot distinguish stale GPU pixels from stale buffer data.
An isolated Electron reproduction with our pinned xterm 6.0.0/WebGL 0.19.0 proves
that atlas page merges can leave rendered pixels inconsistent with the unchanged
buffer, including during scrollback navigation. A subsequent refresh repairs them.

## Implementation

1. Keep this hotfix separate from the ongoing workspace/reactivity audit.
2. Subscribe to public atlas layout events in the shared WebGL attachment helper.
Coalesce texture-binding invalidation and a full viewport refresh after the
current render call finishes, using xterm's existing frame scheduler. Do not
clear history, change PTY bytes, or disable acceleration globally.
A fresh independently cached pixel oracle disproved the refresh-only approach:
per-page version collisions can leave stale GPU textures even after cell
coordinates are repaired. The stable addon has no public binding-invalidation
API, so use one shape-checked private bridge to setAtlas with the existing atlas,
isolated in the addon loader. No glyph-cache eviction or theme/OSC palette reset.
Remove the bridge once a stable addon includes upstream xterm.js #5883.
3. Fence deferred repaint work on teardown/context loss; dispose all listeners.
4. Add lifecycle regression tests and an opt-in real Electron regression script
with colored output, two terminals, scrollback, stable buffer contents, and a
fresh independently cached reference. Verify the unwrapped-addon control fails
the pixel comparison and the actual production loader passes.
5. Run focused host tests/type checks, review, open a resolving/contributing PR as
supported by the evidence, and wait for explicit merge confirmation.

## Constraints

No live app restarts or process kills. Main's existing package-lock changes and
the broader session-update-isolation worktree remain untouched. Preserve WebGL
performance: no per-byte, periodic, or unconditional per-scroll full repaint.
The exact reported screenshot still needs user confirmation after deployment.

## Verification

- Type-check and 25 focused unit/mounted-terminal tests passed.
- Test-contract check and whitespace validation passed.
- Opt-in real Electron control reproduced 33 output-frame mismatches, one
scroll-frame mismatch, and 1,264,868 differing pixel channels against a fresh
independent atlas. Production loader: zero mismatches in the same workload,
including the independent reference; WebGL remained active.
- The smoke script is repeatable and keeps synthetic screenshots/JSON in its
printed temporary artifact directory. No live sessions or app profile touched.
93 changes: 93 additions & 0 deletions scripts/smoke-terminal-renderer.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#!/usr/bin/env node
// Real GPU coverage is intentionally opt-in: happy-dom cannot exercise texture
// uploads, and a headless CI worker without a display must not silently bless it.
// Run: node scripts/smoke-terminal-renderer.mjs [--control]
// --control bypasses our wrapper and must expose the pinned addon's corruption.
import { mkdtemp, writeFile, copyFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { spawn } from 'node:child_process'
import { createRequire } from 'node:module'

const root = resolve(fileURLToPath(new URL('..', import.meta.url)))
const require = createRequire(import.meta.url)

if (!process.versions.electron) {
const { build } = await import('vite')
const dir = await mkdtemp(join(tmpdir(), 'agent-code-terminal-renderer-'))
// Preserve artifacts for inspection, but never use the developer's app
// profile. This process loads only synthetic terminals, not Agent Code.
console.log(`Terminal renderer artifacts: ${dir}`)
await build({
configFile: false,
root,
logLevel: 'warn',
build: {
outDir: dir,
emptyOutDir: false,
lib: {
entry: join(root, 'testing/fixtures/terminal-renderer/smoke.ts'),
name: 'terminalRendererSmoke',
formats: ['iife'],
fileName: () => 'renderer.js',
},
},
})
await copyFile(join(root, 'node_modules/@xterm/xterm/css/xterm.css'), join(dir, 'xterm.css'))
await writeFile(join(dir, 'index.html'), `<!doctype html>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<link rel="stylesheet" href="xterm.css">
<style>body{margin:0;background:#17191d;display:flex}.host{width:750px;height:650px;overflow:hidden}</style>
<div id="a" class="host"></div><div id="b" class="host"></div><script src="renderer.js"></script>`)
const env = { ...process.env }
delete env.ELECTRON_RUN_AS_NODE
const child = spawn(require('electron'), [fileURLToPath(import.meta.url), dir, ...process.argv.slice(2)], { env, stdio: 'inherit' })
const stop = signal => child.kill(signal)
const interrupt = () => stop('SIGINT')
const terminate = () => stop('SIGTERM')
process.once('SIGINT', interrupt)
process.once('SIGTERM', terminate)
try {
process.exitCode = await new Promise((done, reject) => {
child.once('error', reject)
child.once('exit', code => done(code ?? 1))
})
} finally {
process.removeListener('SIGINT', interrupt)
process.removeListener('SIGTERM', terminate)
}
} else {
const { app, BrowserWindow } = require('electron')
const dir = process.argv[2]
app.setPath('userData', join(dir, 'profile'))
// Electron waits for its ESM entry to finish before readiness. A top-level
// await here would deadlock startup; register the continuation and return.
void app.whenReady().then(async () => {
const window = new BrowserWindow({
width: 1500, height: 700, show: false,
webPreferences: { sandbox: true, backgroundThrottling: false },
})
let status = 1
// Bound hangs in GPU startup/rendering without touching other Electron apps.
const timeout = setTimeout(() => { window.destroy(); app.exit(1) }, 120_000)
try {
await window.loadFile(join(dir, 'index.html'))
const control = process.argv.includes('--control')
const report = await window.webContents.executeJavaScript(`terminalRendererSmoke.run(${control})`)
await writeFile(join(dir, 'report.json'), JSON.stringify(report, null, 2))
await writeFile(join(dir, 'terminal.png'), (await window.webContents.capturePage()).toPNG())
console.log(JSON.stringify(report))
const corrupt = report.differences.length > 0 || report.referenceDifference > 0
if (report.removedPages === 0) throw new Error('Workload did not exercise atlas merges')
if (control ? !corrupt : corrupt) throw new Error(control ? 'Control did not reproduce corruption' : 'Rendered pixels differ from unchanged buffer')
status = 0
} catch (error) {
console.error(error)
} finally {
clearTimeout(timeout)
window.destroy()
app.exit(status)
}
}).catch(error => { console.error(error); app.exit(1) })
}
133 changes: 124 additions & 9 deletions src/renderer/src/workspace/terminal/xtermWebglRenderer.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import webglPackage from '@xterm/addon-webgl/package.json'

import { attachXtermWebglRenderer } from './xtermWebglRenderer'

Expand All @@ -17,7 +18,20 @@ function deferred<T>(): Deferred<T> {

function addonHarness() {
let loseContext: (() => void) | null = null
let addPage: (() => void) | null = null
let removePage: (() => void) | null = null
const disposeAddListener = vi.fn()
const disposeRemoveListener = vi.fn()
const onAddTextureAtlasCanvas = vi.fn((handler: () => void) => {
addPage = handler
return { dispose: disposeAddListener }
})
const onRemoveTextureAtlasCanvas = vi.fn((handler: () => void) => {
removePage = handler
return { dispose: disposeRemoveListener }
})
const construct = vi.fn()
const invalidateTextureBindings = vi.fn(() => true)
const activate = vi.fn()
const disposeContextListener = vi.fn()
const disposeAddon = vi.fn()
Expand All @@ -31,11 +45,21 @@ function addonHarness() {
constructor() { construct() }
activate = activate
dispose = disposeAddon
invalidateTextureBindings = invalidateTextureBindings
onContextLoss = onContextLoss
onAddTextureAtlasCanvas = onAddTextureAtlasCanvas
onRemoveTextureAtlasCanvas = onRemoveTextureAtlasCanvas
}
return {
WebglAddon,
onAddTextureAtlasCanvas,
onRemoveTextureAtlasCanvas,
disposeAddListener,
disposeRemoveListener,
addPage: () => addPage?.(),
removePage: () => removePage?.(),
construct,
invalidateTextureBindings,
activate,
onContextLoss,
disposeAddon,
Expand All @@ -44,10 +68,100 @@ function addonHarness() {
}
}

function terminalHarness() {
return { loadAddon: vi.fn(), refresh: vi.fn(), rows: 24 }
}

describe('xtermWebglRenderer', () => {
it('keeps the private texture bridge pinned to the audited addon version', () => {
// A dependency bump must deliberately remove/re-audit the private seam,
// not silently retain a workaround for internals that may have changed.
expect(webglPackage.version).toBe('0.19.0')
})

it('repairs a whole atlas-layout burst after the current frame, without idle repainting', async () => {
const addon = addonHarness()
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)
await renderer.ready
expect(terminal.refresh).not.toHaveBeenCalled()

// The real addon emits four removals and an addition during a page merge.
// Rendering synchronously here would re-enter a half-reorganized atlas.
for (let i = 0; i < 4; i++) addon.removePage()
addon.addPage()
expect(terminal.refresh).not.toHaveBeenCalled()
terminal.rows = 32
await Promise.resolve()
expect(terminal.refresh.mock.calls).toEqual([[0, 31]])
expect(addon.invalidateTextureBindings).toHaveBeenCalledTimes(1)
expect(addon.invalidateTextureBindings.mock.invocationCallOrder[0])
.toBeLessThan(terminal.refresh.mock.invocationCallOrder[0])
await Promise.resolve()
expect(terminal.refresh).toHaveBeenCalledTimes(1)

addon.addPage()
await Promise.resolve()
expect(terminal.refresh).toHaveBeenCalledTimes(2)
renderer.dispose()
expect(addon.disposeAddListener).toHaveBeenCalledTimes(1)
expect(addon.disposeRemoveListener).toHaveBeenCalledTimes(1)
})

it.each(['unmount', 'context loss'] as const)('cancels deferred repair after %s', async reason => {
const addon = addonHarness()
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)
await renderer.ready
addon.removePage()
if (reason === 'unmount') renderer.dispose()
else addon.loseContext()
// Simulate an already-dispatched event even after its listener is removed.
addon.addPage()
await Promise.resolve()
expect(terminal.refresh).not.toHaveBeenCalled()
expect(addon.invalidateTextureBindings).not.toHaveBeenCalled()
renderer.dispose()
expect(addon.disposeAddListener).toHaveBeenCalledTimes(1)
expect(addon.disposeRemoveListener).toHaveBeenCalledTimes(1)
expect(addon.disposeAddon).toHaveBeenCalledTimes(1)
})

it('cleans up a partial atlas subscription if registration fails', async () => {
const addon = addonHarness()
addon.onRemoveTextureAtlasCanvas.mockImplementation(() => { throw new Error('registration failed') })
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)
await expect(renderer.ready).resolves.toBe(false)
expect(addon.disposeAddListener).toHaveBeenCalledTimes(1)
expect(addon.disposeRemoveListener).not.toHaveBeenCalled()
expect(addon.disposeContextListener).toHaveBeenCalledTimes(1)
expect(addon.disposeAddon).toHaveBeenCalledTimes(1)
expect(terminal.loadAddon).not.toHaveBeenCalled()
renderer.dispose()
})

it.each(['incompatible', 'throws'] as const)('restores DOM fallback when texture invalidation %s', async failure => {
const addon = addonHarness()
addon.invalidateTextureBindings.mockImplementation(() => {
if (failure === 'throws') throw new Error('GPU unavailable')
return false
})
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)
await renderer.ready
addon.removePage()
await Promise.resolve()
expect(addon.disposeAddon).toHaveBeenCalledTimes(1)
expect(addon.disposeAddListener).toHaveBeenCalledTimes(1)
expect(addon.disposeRemoveListener).toHaveBeenCalledTimes(1)
expect(terminal.refresh).not.toHaveBeenCalled()
renderer.dispose()
})

it('reports readiness after handing a complete addon to the live terminal', async () => {
const addon = addonHarness()
const terminal = { loadAddon: vi.fn() }
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)

await expect(renderer.ready).resolves.toBe(true)
Expand All @@ -66,7 +180,7 @@ describe('xtermWebglRenderer', () => {

it('disposes the context listener and addon exactly once during ordinary host teardown', async () => {
const addon = addonHarness()
const renderer = attachXtermWebglRenderer({ loadAddon: vi.fn() }, async () => addon)
const renderer = attachXtermWebglRenderer(terminalHarness(), async () => addon)
await expect(renderer.ready).resolves.toBe(true)

renderer.dispose()
Expand All @@ -78,7 +192,7 @@ describe('xtermWebglRenderer', () => {

it('loads WebGL into a live terminal and falls back by disposing it on context loss', async () => {
const addon = addonHarness()
const terminal = { loadAddon: vi.fn() }
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)

await expect(renderer.ready).resolves.toBe(true)
Expand All @@ -100,7 +214,7 @@ describe('xtermWebglRenderer', () => {

it('does not attach an addon whose import resolves after host teardown', async () => {
const pending = deferred<ReturnType<typeof addonHarness>>()
const terminal = { loadAddon: vi.fn() }
const terminal = terminalHarness()
const load = vi.fn(() => pending.promise)
const renderer = attachXtermWebglRenderer(terminal, load)
// Fence a genuinely in-flight import, not only a loader that never started.
Expand All @@ -119,7 +233,7 @@ describe('xtermWebglRenderer', () => {
it.each(['rejection', 'synchronous throw'] as const)(
'keeps fallback usable after an import %s',
async failure => {
const terminal = { loadAddon: vi.fn() }
const terminal = terminalHarness()
const load = () => {
if (failure === 'synchronous throw') throw new Error('loader unavailable')
return Promise.reject(new Error('chunk unavailable'))
Expand All @@ -136,7 +250,7 @@ describe('xtermWebglRenderer', () => {
it('resolves false when construction fails without disposing an unowned addon', async () => {
const addon = addonHarness()
addon.construct.mockImplementation(() => { throw new Error('unsupported GPU') })
const terminal = { loadAddon: vi.fn() }
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)

await expect(renderer.ready).resolves.toBe(false)
Expand All @@ -151,6 +265,7 @@ describe('xtermWebglRenderer', () => {
it('cleans both owned resources when terminal activation fails', async () => {
const addon = addonHarness()
const terminal = {
...terminalHarness(),
loadAddon: vi.fn(() => { throw new Error('context allocation failed') }),
}
const renderer = attachXtermWebglRenderer(terminal, async () => addon)
Expand All @@ -167,7 +282,7 @@ describe('xtermWebglRenderer', () => {
it('disposes the constructed addon when context listener registration fails', async () => {
const addon = addonHarness()
addon.onContextLoss.mockImplementation(() => { throw new Error('registration failed') })
const terminal = { loadAddon: vi.fn() }
const terminal = terminalHarness()
const renderer = attachXtermWebglRenderer(terminal, async () => addon)

await expect(renderer.ready).resolves.toBe(false)
Expand All @@ -181,7 +296,7 @@ describe('xtermWebglRenderer', () => {
const addon = addonHarness()
addon.disposeContextListener.mockImplementation(() => { throw new Error('listener cleanup failed') })
addon.disposeAddon.mockImplementation(() => { throw new Error('GPU cleanup failed') })
const renderer = attachXtermWebglRenderer({ loadAddon: vi.fn() }, async () => addon)
const renderer = attachXtermWebglRenderer(terminalHarness(), async () => addon)
await expect(renderer.ready).resolves.toBe(true)
const disposeHost = vi.fn()

Expand All @@ -200,7 +315,7 @@ describe('xtermWebglRenderer', () => {
it('clears ownership before a disposer re-enters context-loss cleanup', async () => {
const addon = addonHarness()
addon.disposeContextListener.mockImplementation(() => addon.loseContext())
const renderer = attachXtermWebglRenderer({ loadAddon: vi.fn() }, async () => addon)
const renderer = attachXtermWebglRenderer(terminalHarness(), async () => addon)
await expect(renderer.ready).resolves.toBe(true)

renderer.dispose()
Expand Down
Loading