Skip to content

fix(terminal): repair stale-dpr WebGL canvas backing on reveal and fit - #13159

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/terminal-canvas-dpr-repair
Aug 8, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/terminal-canvas-dpr-repair

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes the mechanism behind the field reports of a normal pane going blurry after switching back to a worktree (Jinjing, Aug 7, on an RC already containing #12944/#12945) — reproduced deterministically, healed live, and now self-repairing.

Root cause: when devicePixelRatio changes while a pane is hidden (window moved between retina and non-retina displays, then the worktree revealed), xterm's WebGL renderer re-measures its cell dimensions at the new dpr but its canvas keeps the old backing store — the addon's device-pixel observer misses changes that land while the element has no box. The browser then composites the stale-scale bitmap into the css box: half-size text (dpr 2 backing on a dpr 1 display) or full-size smeared text (dpr 1 backing upscaled on retina). It self-corrects only on a real resize or when the window returns to the original display — which made it look transient and unreproducible.

Deterministic repro (CDP rig, dev app): render pane at dpr 2 → hide the worktree → Emulation.setDeviceMetricsOverride(deviceScaleFactor: 1) → reveal → the live renderer's canvas measured 2160×1856 backing behind a 1080×928 css box, cell dims correctly at dpr 1 — text painted at half size. Verified heal primitive: renderer.handleDevicePixelRatioChange() then renderer.handleResize(cols, rows) + refresh rebuilds the backing at the current scale.

The fix (terminal-canvas-dpr-repair.ts) runs that check event-anchored, never on a timer:

  • on every successful fit, via the existing fit-success hook (covers heavy reveals through fitAllRevealedPanes, user resizes, late mounts), and
  • on the light tab-resume path, which never fits and otherwise had no repair point.

The check compares the renderer canvas's backing width against cssWidth × devicePixelRatio with 1 device px of rounding tolerance and is a no-op in the healthy case. A webgl-canvas-dpr-repair diagnostic records each repair (stale + expected backing widths, dpr), so field occurrences finally show in crash-report breadcrumbs.

End-to-end verification in the rig: the identical break sequence now self-heals on reveal with no user action — canvas backing 1080 (= css × dpr), text full-size and crisp.

Screenshots

Rig captures (available on request / can be attached at review): broken state shows the pane's content rendered at half size in the pane corner (2160 backing in 1080 css box at dpr 1); fixed build shows the same reveal rendering full-size crisp text. No visual change in the healthy path.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — targeted locally: new repair unit tests plus pane-webgl-renderer and terminal-visibility-resume suites (38 tests, all green); full suite left to CI
  • pnpm build — left to CI
  • Added or updated high-quality tests that would catch regressions: repair on both mismatch directions with call-order assertion (dpr refresh before resize), healthy no-op, sub-pixel rounding tolerance (no churn), detached/zero-box/renderer-less guards, throw-safe mid-teardown behavior

AI Review Report

Reviewed by the implementing agent with the rig evidence in hand. Main risks checked: (1) false positives — the check requires a connected canvas with a nonzero box and 1 device px tolerance for fractional-width rounding (UI zoom produces fractional dpr, where a real mismatch is ≥25% of the width); (2) churn — the repair path only runs on actual mismatch, and handleResize with unchanged cols/rows does not touch the buffer or PTY, so no rewrap and no PTY resize traffic; (3) internals coupling — _canvas/_gl.canvas/handleResize access follows the existing XtermWebglAddonInternals pattern in pane-webgl-renderer.ts and is wrapped in a throw-safe guard that reports false mid-teardown; (4) placement — fit-success hook covers every path that fits; the light tab-resume loop covers the one reveal path that doesn't; both are idempotent. Cross-platform: renderer-only; the dpr-change scenario is most common on macOS (retina + external display) but identical logic applies to Windows/Linux mixed-dpi setups; no shortcuts, labels, paths, or shell behavior touched.

Security Audit

Renderer-internal rendering state only. No input handling, command execution, path handling, auth, secrets, dependency, or IPC changes. Diagnostics carry numeric widths and dpr through the existing terminal_webgl_diagnostic sink.

Notes

When devicePixelRatio changes while a pane is hidden (window moved between
retina and non-retina displays, worktree then revealed), xterm's WebGL
renderer re-measures cell dimensions but its canvas keeps the old backing
store — the addon's device-pixel observer misses changes that land while the
element has no box. The browser composites the stale-scale bitmap into the
css box: half/double-size or smeared text until a manual resize. Reproduced
deterministically (2160px backing behind a 1080px css box at dpr 1) — this is
the mechanism behind the field reports of a normal pane going blurry after
switching back to a worktree.

A repair check now runs on every successful fit (via the fit-success hook)
and on the light tab-resume path (which never fits): when the canvas backing
diverges from cssWidth x devicePixelRatio beyond rounding tolerance, it
replays xterm's own dpr + resize path to rebuild the backing at the current
scale, then refreshes. Verified live: the same break sequence now self-heals
on reveal with no user action. A webgl-canvas-dpr-repair diagnostic records
each repair with the stale and expected backing widths.
@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added repairPaneWebglCanvasDprMismatch to detect and repair stale terminal WebGL canvas backing dimensions. Added tests for repair, no-op, invalid-state, and error paths. Integrated the repair into pane fitting and light tab-resume handling after deferred metric flushing.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: repairing stale DPR WebGL canvas backing dimensions during reveal and fitting.
Description check ✅ Passed The description follows the template and covers the change, screenshots, testing, AI review, security audit, and platform notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ca044e1d-ddbd-4ba8-8b3c-cb2cb572697a

📥 Commits

Reviewing files that changed from the base of the PR and between 7691167 and 0c96956.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts
  • src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts
  • src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts

Comment on lines +35 to +38
const repairPaneWebglCanvasDprMismatch = vi.fn((_pane: unknown) => false)
vi.mock('@/lib/pane-manager/terminal-canvas-dpr-repair', () => ({
repairPaneWebglCanvasDprMismatch: (pane: unknown) => repairPaneWebglCanvasDprMismatch(pane)
}))

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

🧩 Analysis chain

🏁 Script executed:

rg -n -C 4 "vi\\.mock|vi\\.hoisted|repairPaneWebglCanvasDprMismatch" "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts"

Repository: stablyai/orca

Length of output: 5346


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Package files:"
git ls-files | rg '(^|/)(package\.json|vitest\.config\..*|vite\.config\..*|tsconfig.*\.json)$' || true

echo
echo "Vitest references:"
rg -n '"vitest"|"`@vitest/`|vi\.hoisted|happy-dom|jsdom|globals' package.json package-lock.json pnpm-lock.yaml yarn.lock 2>/dev/null || true

echo
echo "Targeted test file section:"
sed -n '1,60p' "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts"

echo
echo "Imported module and target mock module:"
sed -n '1,120p' src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts
for f in src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.ts src/renderer/src/components/terminal-pane/pane-helpers.ts src/renderer/src/lib/pane-manager/terminal-webgl-atlas-recovery.ts; do
  if [ -f "$f" ]; then
    echo "--- $f"
    sed -n '1,120p' "$f"
  fi
done

Repository: stablyai/orca

Length of output: 15017


Create the spy with vi.hoisted.

repairPaneWebglCanvasDprMismatch is a top-level spy used inside vi.mock(). In Vitest, vi.mock factories are hoisted and cannot reference values declared after the vi.mock call, so this mocked exported call fails the test setup. Wrapping the spy initialization in vi.hoisted() is the documented fix.

Proposed fix
-const repairPaneWebglCanvasDprMismatch = vi.fn((_pane: unknown) => false)
+const repairPaneWebglCanvasDprMismatch = vi.hoisted(() => vi.fn((_pane: unknown) => false))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const repairPaneWebglCanvasDprMismatch = vi.fn((_pane: unknown) => false)
vi.mock('@/lib/pane-manager/terminal-canvas-dpr-repair', () => ({
repairPaneWebglCanvasDprMismatch: (pane: unknown) => repairPaneWebglCanvasDprMismatch(pane)
}))
const repairPaneWebglCanvasDprMismatch = vi.hoisted(() => vi.fn((_pane: unknown) => false))
vi.mock('`@/lib/pane-manager/terminal-canvas-dpr-repair`', () => ({
repairPaneWebglCanvasDprMismatch: (pane: unknown) => repairPaneWebglCanvasDprMismatch(pane)
}))

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Visual QA evidence (hidden-pane DPR transition)

Isolated Electron dev profile, CDP port 9333, renderer 5175, worktree identity verified:

  • devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/pinniped
  • devBranch: brennanb2025/terminal-canvas-dpr-repair
  • name: Orca: brennanb2025/terminal-canvas-dpr-repair

Exact reproduction

  1. Baseline render at dpr 2 with a live WebGL terminal pane (backing 2160×1856 / CSS 1080×928).
  2. Hide primary worktree by switching to a second worktree (setActiveWorktree — real store/UI path; pane stays mounted).
  3. While hidden: Emulation.setDeviceMetricsOverride({ deviceScaleFactor: 1 }) via CDP.
  4. Reveal primary worktree (setActiveWorktree back + terminal tab).
  5. Measure live canvas: backing must equal CSS × active DPR within rounding tolerance.

Also exercised reverse (dpr 1 → 2 while hidden) and healthy hide/reveal with no DPR change.

Observed measurements

Phase DPR Backing CSS Result
Baseline healthy 2 2160×1856 1080×928 match ✓
Reveal after dpr 2→1 while hidden 1 1080×928 1080×928 healed ✓ (would be 2160 stale without fix)
Healthy reveal (no dpr change) 1 1080×928 1080×928 unchanged ✓
Reveal after dpr 1→2 while hidden 2 2160×1856 1080×928 healed ✓

Terminal text is full-size and crisp in screenshots (not half-size corner paint). Console: 0 errors; only unrelated warnings (Tooltip controlled/uncontrolled, React Grab version, one xterm task-queue deadline). No WebGL/DPR repair exceptions.

Screenshots

Healed reveal at dpr 1 (full-size text):

05-healed-reveal-dpr1-full-size-text.png

Healed reveal after reverse dpr 1→2:

07-healed-reveal-dpr1-to-2.png

Healthy reveal (no dpr change):

06-healthy-reveal-no-dpr-change.png

Baseline at dpr 2:

02-baseline-dpr2-with-text.png

Residual notes

  • Dev profile path was long enough that the daemon socket failed (EINVAL on unix path); app fell back to local PTYs. Terminal canvas path under test still exercised fully.
  • Temporary parking worktree dpr-qa-* was created only for hide/reveal; safe to delete from the disposable profile.

@brennanb2025
brennanb2025 merged commit 04f7123 into main Aug 8, 2026
45 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#13159)

* fix(terminal): repair stale-dpr WebGL canvas backing on reveal and fit

When devicePixelRatio changes while a pane is hidden (window moved between
retina and non-retina displays, worktree then revealed), xterm's WebGL
renderer re-measures cell dimensions but its canvas keeps the old backing
store — the addon's device-pixel observer misses changes that land while the
element has no box. The browser composites the stale-scale bitmap into the
css box: half/double-size or smeared text until a manual resize. Reproduced
deterministically (2160px backing behind a 1080px css box at dpr 1) — this is
the mechanism behind the field reports of a normal pane going blurry after
switching back to a worktree.

A repair check now runs on every successful fit (via the fit-success hook)
and on the light tab-resume path (which never fits): when the canvas backing
diverges from cssWidth x devicePixelRatio beyond rounding tolerance, it
replays xterm's own dpr + resize path to rebuild the backing at the current
scale, then refreshes. Verified live: the same break sequence now self-heals
on reveal with no user action. A webgl-canvas-dpr-repair diagnostic records
each repair with the stale and expected backing widths.

* fix(terminal): keep dpr repair off the layout path
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