diff --git a/docs/superpowers/plans/2026-09-05-terminal-atlas-repaint.md b/docs/superpowers/plans/2026-09-05-terminal-atlas-repaint.md
new file mode 100644
index 000000000..e20257d80
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-05-terminal-atlas-repaint.md
@@ -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.
diff --git a/scripts/smoke-terminal-renderer.mjs b/scripts/smoke-terminal-renderer.mjs
new file mode 100644
index 000000000..b6222fdf9
--- /dev/null
+++ b/scripts/smoke-terminal-renderer.mjs
@@ -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'), `
+
+
+
+
`)
+ 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) })
+}
diff --git a/src/renderer/src/workspace/terminal/xtermWebglRenderer.test.ts b/src/renderer/src/workspace/terminal/xtermWebglRenderer.test.ts
index cc0b80e98..89f3be0ac 100644
--- a/src/renderer/src/workspace/terminal/xtermWebglRenderer.test.ts
+++ b/src/renderer/src/workspace/terminal/xtermWebglRenderer.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
+import webglPackage from '@xterm/addon-webgl/package.json'
import { attachXtermWebglRenderer } from './xtermWebglRenderer'
@@ -17,7 +18,20 @@ function deferred(): Deferred {
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()
@@ -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,
@@ -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)
@@ -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()
@@ -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)
@@ -100,7 +214,7 @@ describe('xtermWebglRenderer', () => {
it('does not attach an addon whose import resolves after host teardown', async () => {
const pending = deferred>()
- 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.
@@ -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'))
@@ -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)
@@ -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)
@@ -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)
@@ -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()
@@ -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()
diff --git a/src/renderer/src/workspace/terminal/xtermWebglRenderer.ts b/src/renderer/src/workspace/terminal/xtermWebglRenderer.ts
index a8d90361e..c1ba39403 100644
--- a/src/renderer/src/workspace/terminal/xtermWebglRenderer.ts
+++ b/src/renderer/src/workspace/terminal/xtermWebglRenderer.ts
@@ -4,20 +4,54 @@ type Disposable = { dispose(): void }
type WebglAddonLike = ITerminalAddon & {
onContextLoss(handler: () => void): Disposable
+ onAddTextureAtlasCanvas(handler: () => void): Disposable
+ onRemoveTextureAtlasCanvas(handler: () => void): Disposable
+ invalidateTextureBindings(): boolean
}
type WebglAddonModule = {
WebglAddon: new () => WebglAddonLike
}
-type TerminalAddonHost = Pick
+type TerminalAddonHost = Pick
export type XtermWebglRenderer = Disposable & {
/** Resolves true only when WebGL became the active xterm renderer. */
ready: Promise
}
-const loadWebglAddon = (): Promise => import('@xterm/addon-webgl')
+const loadWebglAddon = async (): Promise => {
+ const { WebglAddon } = await import('@xterm/addon-webgl')
+ return {
+ WebglAddon: class extends WebglAddon {
+ invalidateTextureBindings(): boolean {
+ // WHY this one version-pinned private seam: 0.19.0 numbers texture
+ // versions per page. When a merge moves a different page into the same
+ // GPU slot, equal version numbers can suppress its texture upload.
+ // Terminal.refresh repairs cell coordinates but NOT these stale pixels;
+ // clearTextureAtlas destroys the shared glyph cache and still doesn't
+ // reliably invalidate all bindings. Upstream fixes this with globally
+ // unique versions (xterm.js #5883), unavailable in our stable addon.
+ //
+ // setAtlas with the *same* atlas invalidates only this renderer's GPU
+ // bindings: no glyph eviction, theme/OSC palette reset, new GPU context,
+ // terminal resize, or PTY work. Keep the private dependency HERE, shape
+ // check it, and exercise it with the real Electron regression script.
+ // Remove this bridge on upgrade to a stable addon containing #5883.
+ const renderer = (this as unknown as {
+ _renderer?: {
+ _charAtlas?: object
+ _glyphRenderer?: { value?: { setAtlas?: (atlas: object) => void } }
+ }
+ })._renderer
+ const glyphs = renderer?._glyphRenderer?.value
+ if (!renderer?._charAtlas || typeof glyphs?.setAtlas !== 'function') return false
+ glyphs.setAtlas(renderer._charAtlas)
+ return true
+ }
+ },
+ }
+}
/**
* Upgrade an already-open xterm from its DOM renderer to WebGL when available.
@@ -41,15 +75,58 @@ export function attachXtermWebglRenderer(
let disposed = false
let addon: WebglAddonLike | null = null
let contextLossDisposable: Disposable | null = null
+ let atlasDisposables: Disposable[] = []
+ let repaintPending = false
+
+ // WHY atlas changes, not scroll/write events: our pinned WebGL 0.19.0 can
+ // reorganize atlas pages *during* renderRows. Earlier cells in that same frame
+ // retain the old texture coordinates. Its next frame rebuilds the model, but
+ // an idle/scrolled terminal need not produce another frame, leaving garbled
+ // glyphs on screen indefinitely (#789; upstream xterm.js #5883/#6038).
+ //
+ // Defer until the current render stack finishes, then let Terminal.refresh
+ // schedule the repair through xterm's own frame coalescer. One merge removes
+ // several pages and adds another; one microtask covers that whole burst.
+ // Never clear the shared atlas or repaint on every scroll/output chunk: those
+ // would repeatedly rasterize glyphs or duplicate the hot path we accelerated.
+ // This event-driven workaround can go once a stable addon with the upstream
+ // merge/retry fixes passes the colored-output/scroll regression workload.
+ const scheduleAtlasRepaint = (): void => {
+ const current = addon
+ if (disposed || !current || repaintPending) return
+ repaintPending = true
+ queueMicrotask(() => {
+ repaintPending = false
+ // Context loss/unmount can happen before this runs. A stale GPU callback
+ // must not touch a disposed terminal or refresh the replacement renderer.
+ if (disposed || addon !== current) return
+ try {
+ if (!current.invalidateTextureBindings()) {
+ disposeAddon()
+ return
+ }
+ terminal.refresh(0, terminal.rows - 1)
+ } catch {
+ // An incompatible addon/GPU failure must leave a usable DOM terminal,
+ // not throw asynchronously and strand the pane in a corrupt state.
+ disposeAddon()
+ }
+ })
+ }
const disposeAddon = (): void => {
const listener = contextLossDisposable
const current = addon
contextLossDisposable = null
addon = null
+ const atlasListeners = atlasDisposables
+ atlasDisposables = []
// Clear ownership before invoking third-party cleanup. A context-loss
// callback can re-enter cleanup; it must never dispose the same addon twice.
try { listener?.dispose() } catch { /* Keep host teardown progressing. */ }
+ for (const atlasListener of atlasListeners) {
+ try { atlasListener.dispose() } catch { /* One failed removal cannot leak the others. */ }
+ }
try { current?.dispose() } catch { /* GPU cleanup cannot strand the PTY host. */ }
}
@@ -66,6 +143,10 @@ export function attachXtermWebglRenderer(
// still under the same pressure that evicted the first context.
disposeAddon()
})
+ // Register separately: if the second registration throws, the first
+ // subscription is already owned and gets cleaned up by the catch path.
+ atlasDisposables.push(addon.onAddTextureAtlasCanvas(scheduleAtlasRepaint))
+ atlasDisposables.push(addon.onRemoveTextureAtlasCanvas(scheduleAtlasRepaint))
terminal.loadAddon(addon)
return addon !== null
} catch {
diff --git a/testing/fixtures/terminal-renderer/smoke.ts b/testing/fixtures/terminal-renderer/smoke.ts
new file mode 100644
index 000000000..e29f3a497
--- /dev/null
+++ b/testing/fixtures/terminal-renderer/smoke.ts
@@ -0,0 +1,144 @@
+import { Terminal } from '@xterm/xterm'
+import { WebglAddon } from '@xterm/addon-webgl'
+import { attachXtermWebglRenderer } from '../../../src/renderer/src/workspace/terminal/xtermWebglRenderer'
+
+const frame = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))
+const write = (terminal: Terminal, data: string) => new Promise(resolve => terminal.write(data, resolve))
+
+// Pixel reads happen after paint, so preserve the test canvases' drawing buffer.
+// The application still uses the default false; no product options are changed.
+// Intercept only the public canvas factory, leaving the production loader and
+// its version-specific invalidation path intact (a mock addon would miss it).
+const getContext = HTMLCanvasElement.prototype.getContext
+HTMLCanvasElement.prototype.getContext = function (type: string, options?: object) {
+ return getContext.call(this, type as '2d', type === 'webgl2' ? { ...options, preserveDrawingBuffer: true } : options)
+} as typeof getContext
+
+let removedPages = 0
+const removedCanvases = new WeakSet()
+const activate = WebglAddon.prototype.activate
+WebglAddon.prototype.activate = function (terminal) {
+ // Shared terminals forward the same page removal. Count the page once, not
+ // once per subscriber, so the report describes actual atlas churn.
+ this.onRemoveTextureAtlasCanvas(canvas => {
+ if (removedCanvases.has(canvas)) return
+ removedCanvases.add(canvas)
+ removedPages++
+ })
+ activate.call(this, terminal)
+}
+
+async function make(id: string, control: boolean, reference = false) {
+ const terminal = new Terminal({
+ cols: 90, rows: 35, fontSize: 13, cursorBlink: false, scrollback: 2000,
+ // Identical font metrics, different cache key: the reference must NOT share
+ // the tested atlas or a symmetric cache bug could make bad pixels agree.
+ fontFamily: reference ? 'monospace, monospace' : 'monospace',
+ theme: { background: '#17191d' },
+ })
+ terminal.open(document.getElementById(id)!)
+ let renderer: ReturnType | undefined
+ if (control || reference) terminal.loadAddon(new WebglAddon())
+ else {
+ renderer = attachXtermWebglRenderer(terminal)
+ if (!await renderer.ready) throw new Error('WebGL unavailable; this GPU check cannot run')
+ }
+ const canvas = [...terminal.element!.querySelectorAll('canvas')].find(candidate => candidate.getContext('webgl2'))
+ if (!canvas) throw new Error('No WebGL canvas: fallback is not a passing GPU test')
+ const gl = canvas.getContext('webgl2')!
+ return { terminal, renderer, canvas, gl }
+}
+
+type Host = Awaited>
+
+function pixels({ canvas, gl }: Host) {
+ const data = new Uint8Array(canvas.width * canvas.height * 4)
+ gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, data)
+ if (!data.some(channel => channel !== 0)) throw new Error('Blank GPU readback')
+ return data
+}
+
+function difference(a: Uint8Array, b: Uint8Array) {
+ if (a.length !== b.length) throw new Error('Reference dimensions differ')
+ let count = 0
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) count++
+ return count
+}
+
+function viewportText(terminal: Terminal) {
+ return Array.from({ length: terminal.rows }, (_, y) =>
+ terminal.buffer.active.getLine(terminal.buffer.active.viewportY + y)?.translateToString()).join('\n')
+}
+
+async function checkRepaint(host: Host) {
+ const before = pixels(host)
+ const text = viewportText(host.terminal)
+ host.terminal.refresh(0, host.terminal.rows - 1)
+ await frame()
+ if (text !== viewportText(host.terminal)) throw new Error('Buffer changed during pixel comparison')
+ return difference(before, pixels(host))
+}
+
+// Synthetic ASCII/RGB only: no credentials, provider calls, user history, or
+// private xterm fields. The repeatable workload forces cache layout changes,
+// then verifies both frame stability and a fresh, independently cached oracle.
+// The parent script owns the BrowserWindow and destroys it in finally on both
+// success and failure, after capture. Keeping hosts alive until then lets the
+// screenshot inspect the actual GPU renderer rather than its disposed fallback.
+export async function run(control: boolean) {
+ const a = await make('a', control)
+ const b = await make('b', control)
+ const differences: { step: number; kind: string; changed: number }[] = []
+ await write(b.terminal, '\x1b[?25lFIXED HEADER\r\n')
+ for (let step = 0; step < 40; step++) {
+ let data = '\x1b[?25l'
+ for (let y = 0; y < 35; y++) {
+ for (let x = 0; x < 85; x++) {
+ const k = step * 2975 + y * 85 + x
+ data += `\x1b[38;2;${k % 256};${Math.floor(k / 256) % 256};${Math.floor(k / 65536) % 256}m\x1b[48;2;${y % 2 ? 80 : 0};${y % 2 ? 0 : 80};0m${String.fromCharCode(33 + k % 94)}`
+ }
+ data += '\x1b[0m\r\n'
+ }
+ await write(a.terminal, data)
+ await frame()
+ const changed = await checkRepaint(a)
+ if (changed) differences.push({ step, kind: 'output', changed })
+ await write(b.terminal, `\x1b[3;1Hupdate ${step}`)
+ await frame()
+ const sharedChanged = await checkRepaint(b)
+ if (sharedChanged) differences.push({ step, kind: 'shared', changed: sharedChanged })
+ }
+ for (let step = 0; step < 40; step++) {
+ a.terminal.scrollLines(-11)
+ await frame()
+ const changed = await checkRepaint(a)
+ if (changed) differences.push({ step, kind: 'scroll', changed })
+ }
+ const before = pixels(a)
+ const expectedText = viewportText(a.terminal)
+ const referenceElement = document.createElement('div')
+ referenceElement.id = 'reference'
+ referenceElement.style.position = 'absolute'
+ document.body.appendChild(referenceElement)
+ const reference = await make('reference', true, true)
+ let visible = '\x1b[?25l'
+ for (let y = 0; y < a.terminal.rows; y++) {
+ const line = a.terminal.buffer.active.getLine(a.terminal.buffer.active.viewportY + y)!
+ for (let x = 0; x < a.terminal.cols; x++) {
+ const cell = line.getCell(x)!
+ const fg = cell.getFgColor(), bg = cell.getBgColor()
+ visible += '\x1b[0m'
+ if (cell.isFgRGB()) visible += `\x1b[38;2;${fg >>> 16};${fg >>> 8 & 255};${fg & 255}m`
+ if (cell.isBgRGB()) visible += `\x1b[48;2;${bg >>> 16};${bg >>> 8 & 255};${bg & 255}m`
+ visible += cell.getChars() || ' '
+ }
+ if (y < a.terminal.rows - 1) visible += '\r\n'
+ }
+ await write(reference.terminal, visible)
+ await frame()
+ if (viewportText(reference.terminal) !== expectedText) throw new Error('Reference buffer differs')
+ const referenceDifference = difference(before, pixels(reference))
+ // Keep the tested surface, not its oracle, visible for the screenshot.
+ referenceElement.style.visibility = 'hidden'
+ return { control, removedPages, differences, referenceDifference, viewport: a.terminal.buffer.active.viewportY }
+}