xterm.js icon indicating copy to clipboard operation
xterm.js copied to clipboard

[webgl] Partial row ghosting with transparent theme background on WKWebView / Tauri (stable macOS)

Open longshuaige opened this issue 7 months ago • 9 comments

Summary

On a Tauri (WKWebView) app using @xterm/addon-webgl with allowTransparency: true and a semi-transparent theme.background, lines with ANSI background colors (diff rows, cursor row, selection) progressively develop partial ghosting / overlap during streaming output such as Claude Code / git diff / tree. A window resize temporarily clears it.

This appears related to but distinct from #5816 — that one is the fully broken rendering on macOS 26.5 beta Safari. Mine reproduces on stable macOS inside Tauri (WKWebView) only, without needing any beta OS, and the visual symptom is partial rather than complete corruption. Filing separately per the pattern suggested in discussion.

Environment

  • @xterm/xterm 6.0 (latest)
  • @xterm/addon-webgl ^0.19.0 (latest)
  • Tauri (WKWebView) on macOS stable (not 26.5 beta)
  • MacBook Pro Retina display, devicePixelRatio = 2
  • allowTransparency: true, theme.background: "rgba(20, 20, 25, 0.25)" (or similar alpha < 1)
  • Custom wallpaper visible behind the terminal

Visual symptom

[screenshot: renderErrIng1.png]

  • Upper half of the screen (diff lines with red/green ANSI backgrounds): severe character overlap / ghosting
  • Lower half (plain text lines): perfectly clean
  • The ghosting is localized to lines that have a non-null cell background color — which is the key asymmetry that rules out "every frame is being overlaid globally"

Steps to reproduce

  1. Inside a Tauri WKWebView window on stable macOS, instantiate an xterm Terminal with:
    new Terminal({
      allowTransparency: true,
      theme: { background: 'rgba(20,20,25,0.25)', foreground: '#fff' },
    });
    term.loadAddon(new WebglAddon());
    
    
    
Image Image

longshuaige avatar Apr 27 '26 07:04 longshuaige

@longshuaige Does this happen right from the start (like running ls -lR /usr) or after a while of pumping a lot of content to the screen?

jerch avatar Apr 27 '26 11:04 jerch

It happens after a while of heavy output, not from the start. In our repro (Claude Code streaming large amounts of text), the first few screens render perfectly fine. The ghosting gradually builds up on the bottom rows as more content keeps being pushed and the viewport scrolls. Around the 60%+ mark of continuous output we start seeing clear character overlap on the last visible line(s).

It looks like stale vertex data on rows that _updateModel skips because the cells appear "unchanged" — on Tauri's WebView the GPU seems to hold onto the previous frame's glyph on those cells. Force-updating the last row every frame makes the ghosting

longshuaige avatar Apr 27 '26 23:04 longshuaige

Please run this snippet in the terminal with node (save it to a file and run with node filename) and check if the issue repros:

const TEXT = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';

async function stress() {
  for (let fr = 0; fr < 256; fr += 2) {
    for (let fg = 0; fg < 256; fg += 2) {
      for (let fb = 0; fb < 256; fb += 2) {
        console.log('\x1b[H\x1b[2J\x1b[mThis should be readable with white FG color.');
        console.log(`r: ${fr} g:${fg} b:${fb}`);
        console.log(`\x1b[38;2;${fr};${fg};${fb}m${TEXT}`);
        await new Promise(r => setTimeout(r, 20));
      }
    }
  }
}

stress();

You might need to run it for a while and keep watching the output (if it glitches it might heal itself after a while).

@Tyriar I think #4534 is still a thing - it glitches for me in all three major browser engines (firefox, chromium, webkit), but at different positions. I get this error in chromium:

GL_INVALID_OPERATION: Error: 0x00000502, in ../../third_party/angle/src/libANGLE/renderer/gl/TextureGL.cpp, allocateMipmapLevelsForGeneration:1593. Internal error: 0x00000502: Unexpected driver error.

jerch avatar Apr 28 '26 07:04 jerch

Thanks @jerch! I'd like to clarify that the symptom in my original report may not be the same failure mode as what your stress script exercises.

## Your stress script — we hit this one too, and it's urgent for us

In our Tauri/WKWebView environment (macOS stable, Retina devicePixelRatio=2, allowTransparency: true, rgba(20,20,25,0.25) theme background), glitches appear on the continuously-rewritten \x1b[38;2;r;g;b m… line — previous-frame fragments leak into the new frame on the line that gets rewritten every 20ms. I did not observe automatic recovery within ~2 minutes of continuous running.

Image

Differences from my original scenario

Aspect Your stress script My original scenario (Claude Code / git diff)
Cell write pattern Same line rewritten every 20ms Different cells written once as output streams in
Onset Visible relatively quickly Only after substantial continuous output (roughly 60%+ of a screenful)
Affected area The single rewritten line Only rows that carry ANSI background colors; plain-text rows stay clean
Extra symptoms Pixel fragments from prior frames Glyph substitution — typing the Chinese character 红 (U+7EA2, "red") consistently renders as an unrelated glyph; the ASCII string node_modules renders cleanly in a dark color but appears visually distorted when drawn in white on the same screen

The glyph-substitution symptom in particular looks like the atlas is handing back coordinates that point at the wrong glyph, or at a glyph rasterized for different attributes. Example of how typing 红 (U+7EA2) is rendered in our terminal after ghosting has accumulated:

Image

The row-selectivity in my original scenario (only ANSI-background-colored rows accumulate ghosting, plain rows never do) also doesn't match a pure frame-residue model.

Recovery behavior in my original scenario

  • Window resize — fully clears it

longshuaige avatar Apr 28 '26 09:04 longshuaige

@longshuaige The atlas merge logic seems broken to me. At a first glance it looks like the atlas page number is not correct in some circumstances.

jerch avatar Apr 28 '26 09:04 jerch

Thanks @jerch — that matches what we've been suspecting from the second pattern in our report (the one with glyph substitution and color-dependent distortion). The fact that the exact same character reliably renders as the same wrong glyph, and that it's recovered by clearTextureAtlas(), pointed strongly at _cacheMap / atlas-page coordinates drifting out of sync, but we weren't able to narrow it down to a specific path.

A few questions to help us help you:

  1. Is the broken atlas merge logic something you've already been tracking internally, or a hypothesis worth us instrumenting further?
  2. Are there specific conditions that tend to trigger the wrong page number? (e.g. when a merge happens while the glyph renderer is mid-frame, when maxAtlasPages is unset vs. set, when overflow-sized glyphs are involved)
  3. If it's useful, we can run @xterm/addon-webgl with extra logging around _mergePages / _deletePage / acquireTextureAtlas and capture a trace from a reliable repro on our side. Any particular fields / invariants you'd like us to log?

Happy to help drive this if you can point us at what would move the investigation forward fastest.

longshuaige avatar Apr 28 '26 10:04 longshuaige

I have a possible fix for this in #5883 would appreciate testing

before:

Image

after:

Image

vsych avatar May 18 '26 23:05 vsych

@vsych Wow - thank you for patching that long standing issue.

@longshuaige Can you check if it also fixes your original issue?

jerch avatar May 23 '26 20:05 jerch

@jerch — answering your open question from May 23 (whether #5883 fixes the original issue): it does not. I tested @xterm/[email protected] + @xterm/[email protected] straight from npm and the corruption still reproduces. It moves to different cells, but it is still there.

Also worth noting for triage: this is not WKWebView/Tauri-specific. My environment is Chromium on Windows 11 — Electron 43, where our users hit it, and desktop Chrome, where I built the bench — at devicePixelRatio: 1.5. Same failure mode as the original report.

Deterministic reproduction

The trigger is a large number of distinct (glyph, fg, bg) triples combined with viewport scrolling. Foreground variety alone was not enough for me — I needed background colors too, which matches the "wide character style ranges" theory from #5883.

// Terminal options are the ones our app ships; the ones that matter for this issue are
// allowTransparency + a scrollback large enough to scroll through.
const term = new Terminal({
  fontFamily: "'JetBrains Mono', monospace",
  fontSize: 11, lineHeight: 1.3, letterSpacing: 0.4,
  minimumContrastRatio: 1.15,        // see note below — this one matters
  allowTransparency: true,
  scrollback: 5000,
  theme: { background: '#0a0b12', foreground: '#c8ccd8' },
});
term.open(el);
term.loadAddon(new WebglAddon());

// 1500 lines of prose, every word in its own fg+bg, one word in three bold.
// Deterministic LCG so two runs are byte-identical and can be compared as images.
const PHRASES = [ /* five ~150-char sentences of natural prose */ ];
let seed = 1;
const next = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff);
for (let i = 0; i < 1500; i++) {
  const line = PHRASES[i % PHRASES.length].split(' ').map(word => {
    const c = next(), f = next();
    const bold = next() % 3 === 0 ? '\x1b[1m' : '';
    return `${bold}\x1b[38;2;${(c>>16)&255};${(c>>8)&255};${c&255}m` +
           `\x1b[48;2;${(f>>17)&63};${(f>>9)&63};${(f>>1)&63}m${word}\x1b[22m`;
  }).join(' ');
  term.write(line + '\x1b[0m\r\n');
}

// Then scroll the viewport back and forth — this is what surfaces it.
term.scrollToTop();
for (let i = 0; i < 40; i++) { term.scrollLines(13); term.scrollLines(-5); }

Use prose, not lorem ipsum or digit columns: the failure is easiest to spot as a misspelling.

What it looks like

Two distinct signatures, both after scrolling:

  1. Glyph substitution — the same letter rendered as the same letter in a different case, deterministically: lumières → lumiÈres, tramway → tramWaY, aussitôt → aussitÔt, bureaux → bureauX. The buffer is correct (buffer.active.getLine(y).translateToString() returns the right text), so this is purely a texture read.
  2. Dropped glyphs — background rectangle painted, no glyph inside. More frequent when the number of distinct colors is very high.

Configurations measured

Same content, same seed, same scroll sequence; only the renderer/options change.

configuration result
[email protected] (stable), WebGL corrupt
+ maxAtlasPages raised to 64 (merge threshold never reached) corrupt
+ minimumContrastRatio: 1 corrupt — and mostly invisible, see note
[email protected] + [email protected] corrupt (different cells)
DOM renderer (no WebGL addon) clean

I verified the beta was actually the code under test by comparing the exported constructors, not the version number — my first attempt silently fell back to the stable module through a bundler quirk, which would have produced a false "still broken" result.

Two side observations that may matter:

  • Raising maxAtlasPages does not prevent merges below 4 pages: the threshold is Math.max(4, maxAtlasPages), so pages 1–4 always merge regardless of the option.
  • clearTextureAtlas() is guarded by if (!(this._pages[0].currentRow.x === 0 && this._pages[0].currentRow.y === 0)), so it can be a silent no-op depending on atlas state. Since it is being used in this thread as the recovery signal, a "clearTextureAtlas didn't help" report may not mean what it appears to mean — it did not help in our app, yet the DOM renderer is clean on identical content.
  • minimumContrastRatio: 1.15 (a per-cell adjusted color, so many more atlas entries) makes it appear sooner. Setting it to 1 is not a workaround: it removes the contrast lift, which made a lot of our synthetic colors unreadable.

Happy to instrument anything specific — I have a bench where I can flip one option at a time and diff the rendered output byte-for-byte, so if you have a hypothesis about which page number or cache key drifts, I can go looking for it.

vio-h avatar Aug 11 '26 09:08 vio-h