Skip to content

fix(terminal): invalidate cached glyphs when WebGL atlas changes - #8899

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/terminal-render-desync-sentinel
Jul 17, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/terminal-render-desync-sentinel

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

What

Fix terminal glyph garbling caused by cached WebGL vertices surviving a shared glyph-atlas replacement.

This PR now:

  • invalidates the xterm WebGL glyph model whenever GlyphRenderer attaches a different atlas,
  • adds a deterministic E2E regression using two real WebGL terminals with distinct atlas populations,
  • keeps the flag-gated render-desync sentinel and persists its canvas/buffer evidence under app-owned user data,
  • includes the investigation notes and reproduction tooling used to narrow the field report.

WebGL remains enabled. The diagnostic sentinel remains off by default.

Root cause

GlyphRenderer.setAtlas() attached a replacement shared atlas and set _lastSeenClearModelGeneration to that atlas's current generation. Cached vertices still held page and UV coordinates from the previous atlas, but when both atlases happened to have the same generation, the next frame considered the cached geometry synchronized and sampled unrelated glyphs.

The fix sets _lastSeenClearModelGeneration to -1 when atlas identity changes, forcing the cached geometry to rebuild. This matches current upstream xterm behavior.

Deterministic reproduction

The regression test:

  1. renders terminal A and captures its canvas,
  2. populates terminal B with a distinct atlas,
  3. attaches A's glyph renderer to B's atlas without changing A's terminal buffer,
  4. renders A again and compares pixels.
  • Before the fix: 327,165 pixels differed.
  • After the fix: 0 pixels differed; the result is byte-identical to the baseline.

The existing sampler-budget and eviction scenario also remains green.

Review hardening

A deep correctness, security, and performance review also fixed the following issues in the flag-gated diagnostics and investigation tooling:

  • compare rendered pixels against xterm's active theme background so light themes do not false-trigger,
  • reuse one readback canvas during the bounded burst and release its backing store afterward,
  • require consecutive qualifying samples and stable manager/pane identities,
  • release full PNG/buffer payloads after persistence and cap renderer capture attempts,
  • authorize evidence IPC against the trusted UI renderer,
  • serialize evidence writes, cap metadata, and enforce four-directory / 96 MiB aggregate retention,
  • make the production repro fail closed when its buffer or image oracle is unavailable,
  • use the real pre-trigger baseline, quote replay arguments, use platform temp paths, and stub external URL launches by default.

Reliability contract

  • Invariant: whenever a glyph renderer attaches a different shared atlas, cached glyph vertices are rebuilt before the next draw, even if both atlases have the same clear-model generation.
  • Failure source: atlas object identity changed while cached vertices retained the old atlas's texture page and UV coordinates; adopting the replacement atlas's generation suppressed the rebuild.
  • Oracle: two live WebGL terminals with distinct atlases; after replacement, terminal A's pixels must remain byte-equivalent to its unchanged-buffer baseline.
  • Gate: terminal-render.atlas-identity-invalidation in config/reliability-gates.jsonc.
  • Coverage: deterministic macOS Electron/WebGL evidence. The atlas path is renderer-local and provider-independent; Linux/Windows GPU coverage remains explicit follow-up work.
  • Performance budget: one existing full-model rebuild only on atlas object identity change. Normal frames and repeated calls with the same atlas retain the existing path. The sentinel is off by default and bounded to a ten-second modifier-click burst.
  • Diagnostics: flag-gated local pixel/buffer/renderer-state capture, trusted-renderer IPC, bounded renderer memory, and bounded private on-disk evidence.
  • Residual gaps: the rc.2 field capture predates atlas identity diagnostics, the regression drives the renderer transition directly rather than reproducing the original Cmd/Ctrl-click lifecycle trigger, and Windows GPU evidence is not yet recorded.

Field evidence

The failure signature and violated invariant agree with the reported rc.2 corruption. That build did not capture renderer-internal atlas identity/generation data, so the historical occurrence cannot be retrospectively proven to have taken this exact transition. The fix is nevertheless high confidence because the corruption is deterministic, the rendered signature matches, and upstream xterm independently uses the same invalidation behavior.

Validation

  • frozen lockfile install
  • pnpm typecheck
  • focused oxlint
  • focused Vitest: 5 files / 33 tests
  • broader terminal reliability slice: 14 files / 75 tests
  • reliability-gate manifest and max-lines ratchet
  • syntax checks for all three investigation tools
  • git diff --check
  • exact registered real-WebGL gate command, one worker: 2/2 tests passed; atlas-replacement scenario 4.2s, full Playwright run 38.4s

Detects the buffer-clean/render-stale glyph garble class in the field: per
visible WebGL pane, compare the cells the xterm buffer says hold glyphs
against the ink actually present on the canvas, sampled in the same task as
a forced synchronous redraw so a divergence proves the render model/atlas is
wrong rather than a missed present. A trip requires the same screen cells to
stay divergent across three samples (real desync is pinned; scroll lag moves),
then records a webgl-render-desync breadcrumb, stashes evidence (canvas PNG +
buffer text) for bug reports, and runs the same shared-atlas recovery a tab
reveal performs, so a stuck-garbled pane self-heals within seconds.

Off by default; arm on any build via
localStorage.setItem('orca:render-desync-sentinel', '1') and reload.
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 777144df-0d4b-427d-b47c-f3d123c9fed5

📥 Commits

Reviewing files that changed from the base of the PR and between b91397a and a7f0c36.

📒 Files selected for processing (1)
  • config/reliability-gates.jsonc
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/reliability-gates.jsonc

📝 Walkthrough

Walkthrough

Adds a localStorage-gated WebGL render-desynchronization sentinel for terminal panes, with live-pane enumeration, canvas-versus-buffer sampling, diagnostics, evidence persistence, and atlas recovery. It also adds an atlas replacement regression test, investigation documentation, and tooling for terminal replay, production reproduction, frame analysis, and terminal reference recovery.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: invalidating cached glyphs when the WebGL atlas changes.
Description check ✅ Passed The description covers the required summary, testing, review, security, and notes content, though the headings differ from the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: dcbaae52-a8fe-4118-a7f5-8e5ba7d9e3c7

📥 Commits

Reviewing files that changed from the base of the PR and between c8986ca and eab0e59.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/terminal-freeze-breadcrumbs.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.test.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.ts
  • src/renderer/src/lib/pane-manager/pane-manager-registry.ts

Comment on lines +3 to +15
const forEachLivePaneForDesyncSentinel = vi.fn()
const resetAndRefreshAllTerminalWebglAtlases = vi.fn()
vi.mock('@/lib/pane-manager/pane-manager-registry', () => ({
forEachLivePaneForDesyncSentinel: (
...args: Parameters<typeof forEachLivePaneForDesyncSentinel>
) => forEachLivePaneForDesyncSentinel(...args),
resetAndRefreshAllTerminalWebglAtlases: () => resetAndRefreshAllTerminalWebglAtlases()
}))

const recordTerminalWebglDiagnostic = vi.fn()
vi.mock('../../../../shared/terminal-webgl-diagnostics', () => ({
recordTerminalWebglDiagnostic: (...args: Parameters<typeof recordTerminalWebglDiagnostic>) =>
recordTerminalWebglDiagnostic(...args)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '1,120p' src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.test.ts

Repository: stablyai/orca

Length of output: 4321


🏁 Script executed:

rg -n "vi\.hoisted|vi\.mock\(" src/renderer/src/components/terminal-pane -g '*.test.ts' -g '*.test.tsx'

Repository: stablyai/orca

Length of output: 18826


🏁 Script executed:

python3 - <<'PY'
# Lightweight semantic probe is not possible without repo execution, so just record
# the key Vitest hoisting rule we're checking against:
# - vi.mock is hoisted to the top of the module.
# - top-level const/let referenced inside a hoisted factory can TDZ if initialized later.
print("noop")
PY

Repository: stablyai/orca

Length of output: 156


Create these shared mocks with vi.hoisted()
vi.mock() is hoisted, so these factories can hit a TDZ when they close over top-level const mocks declared later in the file. Move them into vi.hoisted(), as in the other terminal-pane tests.

Comment on lines +263 to +277
const history = missingHistoryByPane.get(paneKey) ?? []
history.push(divergence.missingCells)
while (history.length > PERSISTENT_SAMPLES) {
history.shift()
}
missingHistoryByPane.set(paneKey, history)

if (divergence.missPct < MISSING_PCT_THRESHOLD || history.length < PERSISTENT_SAMPLES) {
return
}
for (let i = 1; i < history.length; i++) {
if (!missingSetsOverlap(history[i - 1], history[i])) {
return
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Require three fully qualifying, persistent samples.

History is appended before missPct validation, so two subthreshold samples followed by one threshold breach can trip. Adjacent-only overlap also permits a gradually moving set to pass. Clear history on subthreshold samples and require common overlap across the complete window.

Reproduce the WebGL atlas identity mismatch with two live terminals and force cached geometry to rebuild whenever a different shared atlas is attached. Persist flag-gated render-desync evidence and retain the investigation tooling used to validate the field signature.
@brennanb2025 brennanb2025 changed the title feat(terminal): add flag-gated render-desync sentinel for WebGL panes fix(terminal): invalidate cached glyphs when WebGL atlas changes Jul 17, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5f9cdb66-ee67-4a2e-9e6e-f3552757ac5a

📥 Commits

Reviewing files that changed from the base of the PR and between eab0e59 and 85f8df4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (18)
  • TERMINAL-GARBLE-INVESTIGATION.md
  • config/patches/@[email protected]
  • src/main/ipc/register-core-handlers.test.ts
  • src/main/ipc/register-core-handlers.ts
  • src/main/ipc/terminal-render-desync-evidence.test.ts
  • src/main/ipc/terminal-render-desync-evidence.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-frame.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.test.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/terminal-render-desync-evidence.ts
  • tests/e2e/terminal-webgl-atlas-budget.spec.ts
  • tools/terminal-garble-frame-analysis.mjs
  • tools/terminal-garble-production-repro.mjs
  • tools/terminal-garble-react-terminal-recovery.mjs
  • tools/terminal-garble-session-replay.mjs

Comment thread TERMINAL-GARBLE-INVESTIGATION.md Resolved
Comment thread TERMINAL-GARBLE-INVESTIGATION.md Outdated
Comment on lines +246 to +247
- Live-rig tooling (replayer for Orca terminal-history logs, CDP driver):
`/tmp/garble-rig/` — do not rerun without stubbing `shell.openUrl`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Name the actual Electron API in the safety warning.

The tool patches shell.openExternal, not shell.openUrl. Point readers to shell.openExternal and the --stub-open-url option so the warning is actionable.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
package.json (1)

193-193: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Move pngjs to devDependencies. It’s only imported from scripts, tools, and tests, so keeping it in production dependencies adds unnecessary install and packaging weight.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 02240612-1179-43cc-9f78-aa09de64cbbb

📥 Commits

Reviewing files that changed from the base of the PR and between 85f8df4 and b91397a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (15)
  • TERMINAL-GARBLE-INVESTIGATION.md
  • config/reliability-gates.jsonc
  • package.json
  • src/main/ipc/terminal-render-desync-evidence.test.ts
  • src/main/ipc/terminal-render-desync-evidence.ts
  • src/main/ipc/ui.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-frame.test.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-frame.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.test.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.ts
  • src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts
  • src/renderer/src/lib/pane-manager/pane-manager-registry.ts
  • tools/terminal-garble-frame-analysis.mjs
  • tools/terminal-garble-production-repro.mjs
  • tools/terminal-garble-session-replay.mjs
🚧 Files skipped from review as they are similar to previous changes (6)
  • tools/terminal-garble-session-replay.mjs
  • src/renderer/src/lib/pane-manager/pane-manager-registry.ts
  • src/renderer/src/components/terminal-pane/terminal-render-desync-frame.ts
  • tools/terminal-garble-frame-analysis.mjs
  • src/renderer/src/components/terminal-pane/terminal-render-desync-sentinel.ts
  • tools/terminal-garble-production-repro.mjs

Comment thread config/reliability-gates.jsonc Resolved
Comment on lines +71 to +72
also redrew before measuring and waited three five-second samples; either choice
could erase a failure that self-heals in about five seconds. The revised design

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Clarify the sampling wording.

“Waited three five-second samples” is awkward and ambiguous. Use “waited for three five-second sampling intervals” instead.

🧰 Tools
🪛 LanguageTool

[grammar] ~71-~71: Ensure spelling is correct
Context: ...currence. The initial #8899 design also redrew before measuring and waited three five-...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

Source: Linters/SAST tools

@brennanb2025
brennanb2025 merged commit 7c0b84f into main Jul 17, 2026
4 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…blyai#8899)

* feat(terminal): add flag-gated render-desync sentinel for WebGL panes

Detects the buffer-clean/render-stale glyph garble class in the field: per
visible WebGL pane, compare the cells the xterm buffer says hold glyphs
against the ink actually present on the canvas, sampled in the same task as
a forced synchronous redraw so a divergence proves the render model/atlas is
wrong rather than a missed present. A trip requires the same screen cells to
stay divergent across three samples (real desync is pinned; scroll lag moves),
then records a webgl-render-desync breadcrumb, stashes evidence (canvas PNG +
buffer text) for bug reports, and runs the same shared-atlas recovery a tab
reveal performs, so a stuck-garbled pane self-heals within seconds.

Off by default; arm on any build via
localStorage.setItem('orca:render-desync-sentinel', '1') and reload.

* fix(terminal): invalidate glyph cache on atlas replacement

Reproduce the WebGL atlas identity mismatch with two live terminals and force cached geometry to rebuild whenever a different shared atlas is attached. Persist flag-gated render-desync evidence and retain the investigation tooling used to validate the field signature.

* fix(terminal): harden render desync diagnostics

* docs(reliability): clarify Linux WebGL evidence gap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant