Repository navigation
fix(terminal): defer metric option writes to unmeasurable panes - #12944
Conversation
Writing fontSize/fontFamily/fontWeight/lineHeight makes xterm re-measure cell size against the pane's current box. A hidden or mid-layout pane can measure a wrong-but-nonzero size, which latches (hasValidSize) and mis-keys the shared WebGL glyph atlas until a manual resize — the stuck variant of the P0 bold/blurry-font reports. Metric writes now land only on measurable panes; otherwise the latest values park per-pane and flush on the next safe fit or reveal (with a refit on the light tab-resume path, which otherwise skips fitting). Measurability helpers move to pane-fit-measurability.ts to stay under the pane-fit.ts line cap.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughTerminal metric options now defer when pane dimensions cannot be measured. Latest deferred values replace earlier values and flush after measurement succeeds. Safe fitting validates pane dimensions before fitting. Appearance updates route font and line-height options through the deferred path. Visibility resume flushes measurable panes and refits revealed panes when deferred metrics are applied. Tests cover deferral, replacement, fitting, and light tab reveal behavior. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 021ec59c-311a-4690-aefe-728c73dc80db
📒 Files selected for processing (8)
src/renderer/src/components/terminal-pane/terminal-appearance.test.tssrc/renderer/src/components/terminal-pane/terminal-appearance.tssrc/renderer/src/components/terminal-pane/terminal-visibility-resume.test.tssrc/renderer/src/components/terminal-pane/terminal-visibility-resume.tssrc/renderer/src/lib/pane-manager/pane-fit-measurability.tssrc/renderer/src/lib/pane-manager/pane-fit.tssrc/renderer/src/lib/pane-manager/pane-metric-options-deferral.test.tssrc/renderer/src/lib/pane-manager/pane-metric-options-deferral.ts
| // Why here: metric options deferred while the pane was unmeasurable must land | ||
| // before this fit reads dimensions, or the fit pins cols/rows to stale metrics. | ||
| flushDeferredPaneMetricOptions(pane) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep deferred metrics deferred for display-none panes.
Line 80 validates dimensions but not display visibility. A hidden pane with cached nonzero dimensions can reach Line 85 and apply xterm metrics against an invalid layout. Use canApplyPaneMetricOptions for this safe-fit gate. Add a display-none fixture that reports nonzero dimensions.
Proposed fix
-import { canMeasurePaneForFit, getProposedPaneDimensions } from './pane-fit-measurability'
+import { canApplyPaneMetricOptions, getProposedPaneDimensions } from './pane-fit-measurability'
@@
- if (!canMeasurePaneForFit(pane)) {
+ if (!canApplyPaneMetricOptions(pane)) {
return false
}Based on PR objectives, safe fitting must validate pane visibility before a deferred flush.
getPanes() returns a fresh toPublicPane() wrapper per call, so a WeakMap keyed on ManagedPane never matched across call sites: deferred metric options were dropped, not deferred. Key on pane.terminal, which is carried by reference and dies with the pane. Also from review: - flushDeferredPaneMetricOptionsIfMeasurable checks the pending WeakMap before the measurability probe, so the common no-deferral case costs zero forced style/layout on every reveal. - applyTerminalAppearance skips the apply (and the probe) when all five values are already live and nothing is parked; any settings write re-runs the pass over every mounted pane, and arming a no-op deferral would trigger a refit on the next reveal. - fitRevealedPane flushes first: its pixel/grid checks can both no-op and return without fitting, stranding parked options. - Font zoom folds its direct fontSize write into any pending deferral so the flush inside safeFit cannot clobber the user's zoom. Corrects comments that asserted a cell-size re-measure mechanism xterm does not have: CharSizeService measures via OffscreenCanvas TextMetrics, independent of the pane box, and only fontSize/fontFamily re-measure. Test fixtures now allocate a fresh pane view per getPanes() call, which is what production does and what hid the keying bug.
performSafeFit evaluated the min cols/rows gate with the pre-flush cell size, then flushed and fit unconditionally. A large font jump on a narrow pane passes the gate at the old size and lands under it at the new one, so fit() pinned the PTY to the tiny grid the floor exists to reject. Re-check after a flush that actually landed. The parked values still apply, so the pane is never stuck on stale metrics; only the fit is skipped.
Electron manual validation — 4/4 PASSIsolated Orca dev instance (dedicated
Scenario A is the direct on-screen disproof of the keying regression fixed in Gaps — stated explicitly rather than implied
Screenshots are saved locally at |
fitRevealedPane's new flush branch called safeFit directly, which is exactly what the function's contract forbids on reveal: resumeRendering has just re-attached WebGL, whose cell metrics transiently differ from the DOM renderer's, so a raw fit can propose a one-column-off grid and reflow — and xterm's wrap/unwrap is not a perfect inverse, leaving a diff-painting inline TUI corrupted. A landed flush leaves pixels unchanged with a diverged grid, the same shape as a snapshot resize, so it takes the same steady-grid repair. A real resize still fits synchronously, after the flush. Reachable via window wake, which calls fitAllRevealedPanes with no pre-flush loop.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d1d0bad0-28d8-48f0-98a9-90e89d03f1b1
📒 Files selected for processing (2)
src/renderer/src/lib/pane-manager/pane-reveal-fit.test.tssrc/renderer/src/lib/pane-manager/pane-reveal-fit.ts
| it('still flushes parked metric options when the pane also resized while hidden', () => { | ||
| mocks.flushDeferredPaneMetricOptionsIfMeasurable.mockReturnValue(true) | ||
| const pane = createPane({ | ||
| lastFitClientSize: { width: 800, height: 600 }, | ||
| currentSize: { width: 640, height: 480 }, | ||
| terminal: { cols: 80, rows: 24 }, | ||
| proposed: { cols: 64, rows: 20 } | ||
| }) | ||
|
|
||
| fitRevealedPane(pane) | ||
|
|
||
| expect(mocks.flushDeferredPaneMetricOptionsIfMeasurable).toHaveBeenCalledWith(pane) | ||
| // A real resize still takes the synchronous path, and the flush already landed. | ||
| expect(mocks.safeFit).toHaveBeenCalledWith(pane) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Assert the resize routing in this test.
This test verifies only that deferred options are flushed. It does not verify that a client-size change calls safeFit and avoids requestStablePaneFit. Add both assertions so a regression to stable routing does not pass.
Proposed assertions
expect(mocks.flushDeferredPaneMetricOptionsIfMeasurable).toHaveBeenCalledWith(pane)
+ expect(mocks.safeFit).toHaveBeenCalledWith(pane)
+ expect(mocks.requestStablePaneFit).not.toHaveBeenCalled()
// A real resize still takes the synchronous path, and the flush already landed.canApplyPaneMetricOptions reused canMeasurePaneForFit, whose >=8 cols / >=4 rows floor exists to stop a fit pinning the PTY to a sliver. But the divider clamp is 50px, which clears the 48px pixel floor and proposes ~5 cols — so a pane dragged to the clamp deferred every font change and never flushed: it never hides, and its box never changes, so no reveal and no ResizeObserver entry ever arrives. It rendered a stale font until widened, where pre-PR the write was unconditional. Gate metric writes on display plus the pixel box only. Hidden panes and the transient worktree-switch overlay are near-zero, so they still defer — the deferral's purpose is unchanged. The cols/rows floor stays on the fit, including the post-flush re-check in performSafeFit. Apply and flush share the same predicate, so no "applies but never flushes" state can open up.
Conflict was the predicted one in pane-fit.ts: #12945 and this branch each split the file differently to stay under the max-lines cap. Resolution keeps both splits: - main's pane-fit-client-size.ts extraction (readFitClientSize is now re-exported from there; the local copies are dropped) - this branch's pane-fit-measurability.ts extraction (canMeasurePaneForFit and getProposedPaneDimensions), so main's local getProposedDimensions and duplicate min-size constants are dropped - main's notifyPaneFitSucceeded in safeFit, alongside the deferred metric flush and post-flush fit-floor re-check in performSafeFit
…lyai#12944) * fix(terminal): defer metric option writes to unmeasurable panes Writing fontSize/fontFamily/fontWeight/lineHeight makes xterm re-measure cell size against the pane's current box. A hidden or mid-layout pane can measure a wrong-but-nonzero size, which latches (hasValidSize) and mis-keys the shared WebGL glyph atlas until a manual resize — the stuck variant of the P0 bold/blurry-font reports. Metric writes now land only on measurable panes; otherwise the latest values park per-pane and flush on the next safe fit or reveal (with a refit on the light tab-resume path, which otherwise skips fitting). Measurability helpers move to pane-fit-measurability.ts to stay under the pane-fit.ts line cap. * fix(terminal): key metric deferral by terminal, not pane view getPanes() returns a fresh toPublicPane() wrapper per call, so a WeakMap keyed on ManagedPane never matched across call sites: deferred metric options were dropped, not deferred. Key on pane.terminal, which is carried by reference and dies with the pane. Also from review: - flushDeferredPaneMetricOptionsIfMeasurable checks the pending WeakMap before the measurability probe, so the common no-deferral case costs zero forced style/layout on every reveal. - applyTerminalAppearance skips the apply (and the probe) when all five values are already live and nothing is parked; any settings write re-runs the pass over every mounted pane, and arming a no-op deferral would trigger a refit on the next reveal. - fitRevealedPane flushes first: its pixel/grid checks can both no-op and return without fitting, stranding parked options. - Font zoom folds its direct fontSize write into any pending deferral so the flush inside safeFit cannot clobber the user's zoom. Corrects comments that asserted a cell-size re-measure mechanism xterm does not have: CharSizeService measures via OffscreenCanvas TextMetrics, independent of the pane box, and only fontSize/fontFamily re-measure. Test fixtures now allocate a fresh pane view per getPanes() call, which is what production does and what hid the keying bug. * fix(terminal): re-check the fit floor after a metric flush performSafeFit evaluated the min cols/rows gate with the pre-flush cell size, then flushed and fit unconditionally. A large font jump on a narrow pane passes the gate at the old size and lands under it at the new one, so fit() pinned the PTY to the tiny grid the floor exists to reject. Re-check after a flush that actually landed. The parked values still apply, so the pane is never stuck on stale metrics; only the fit is skipped. * fix(terminal): route a reveal metric flush through the stable fit fitRevealedPane's new flush branch called safeFit directly, which is exactly what the function's contract forbids on reveal: resumeRendering has just re-attached WebGL, whose cell metrics transiently differ from the DOM renderer's, so a raw fit can propose a one-column-off grid and reflow — and xterm's wrap/unwrap is not a perfect inverse, leaving a diff-painting inline TUI corrupted. A landed flush leaves pixels unchanged with a diverged grid, the same shape as a snapshot resize, so it takes the same steady-grid repair. A real resize still fits synchronously, after the flush. Reachable via window wake, which calls fitAllRevealedPanes with no pre-flush loop. * fix(terminal): gate metric writes on the pixel box, not the fit floor canApplyPaneMetricOptions reused canMeasurePaneForFit, whose >=8 cols / >=4 rows floor exists to stop a fit pinning the PTY to a sliver. But the divider clamp is 50px, which clears the 48px pixel floor and proposes ~5 cols — so a pane dragged to the clamp deferred every font change and never flushed: it never hides, and its box never changes, so no reveal and no ResizeObserver entry ever arrives. It rendered a stale font until widened, where pre-PR the write was unconditional. Gate metric writes on display plus the pixel box only. Hidden panes and the transient worktree-switch overlay are near-zero, so they still defer — the deferral's purpose is unchanged. The cols/rows floor stays on the fit, including the post-flush re-check in performSafeFit. Apply and flush share the same predicate, so no "applies but never flushes" state can open up. * fix(terminal): flush heavy reveal metrics after WebGL resume




Summary
Terminal metric options —
fontSize/fontFamily/fontWeight/fontWeightBold/lineHeight— now land only on panes that can actually be measured. On an unmeasurable pane the latest values park per-pane (WeakMap keyed on the terminal, latest-wins) and flush at the next safe fit or reveal, before the fit reads dimensions so cols/rows are computed from the new metrics.Why: writing any of these makes xterm's renderer
clear()+handleResize(cols, rows)+_fullRefresh()(RenderService). On a pane with no usable box that repaint is wasted — with WebGL suspended it lands in the DOM-renderer fallback — and the cols/rows re-fit that has to follow the write cannot run there. Deferring keeps that churn off hidden panes across every tab and keeps the metric write coupled to the fit that must follow it.Non-metric options (theme, cursor, scroll sensitivity) are untouched — they are safe while hidden. Measurability helpers moved from
pane-fit.tstopane-fit-measurability.tsto stay under the max-lines cap (no behavior change in the move). Ametric-options-deferred-flushdiagnostic breadcrumb records each flush for crash-report forensics.Correction to the original rationale
This PR was originally described as fixing the P0 "terminal stuck on bold/blurry font until resize" reports, on the theory that writing a metric option to a hidden pane re-measures cell size against a wrong box, latches it via
hasValidSize, and mis-keys the shared WebGL glyph atlas. That mechanism was investigated and disproved — noting it here so reviewers don't build on it:CharSizeServiceconstructsTextMetricsMeasureStrategy(anOffscreenCanvas+measureText) and only falls back toDomMeasureStrategyif that constructor throws. Chromium supports bothOffscreenCanvasandfontBoundingBoxAscent/Descent, so the TextMetrics path is what runs in Electron. It reads no DOM, no layout, and no visibility state — a hidden pane measures identically to a visible one.BaseMeasureStategy._validateAndSetdiscards a 0-width/height result and retains the previous value rather than latching it.hasValidSizeis justwidth > 0 && height > 0. It can be false; it cannot be wrongly true from a bad box, because the box is never an input.CharAtlasUtils.generateConfigkeys the atlas on dpr, cell/char metrics, font and colors — not cols/rows or canvas size — so a hidden-pane atlas is keyed identically to a visible-pane one.CharSizeServicere-measures only on['fontFamily', 'fontSize']. Three of the five options deferred here (fontWeight,fontWeightBold,lineHeight) never trigger a cell-size measure at all.Upstream has no issue matching the described bug; the closest, xterm.js #3029 "FitAddon and display:none", was closed as designed with the position that only cols/rows need a real box — which Orca already gates via
canMeasurePaneForFit.So this PR is a repaint/perf improvement plus the correctness fixes below, not a fix for the bold/blurry-font P0. That P0's DOM-fallback-frame route is handled by the separate per-pane WebGL attach latch + fit-anchored reattach PR. The two are independent and land in either order; both touch the
pane-fit.tsimport block, so whichever lands second needs a trivial rebase.Review fixes (commit 2)
ManagedPane, butPaneManager.getPanes()returns a freshtoPublicPane()wrapper on every call, so the writer and every reader used different keys. The net effect was dropping metric writes on hidden panes rather than deferring them — change the font with a tab hidden and that tab kept the old font indefinitely. Now keyed onpane.terminal, which is carried by reference through the wrapper and dies with the pane.flushDeferredPaneMetricOptionsIfMeasurableprobed measurability (agetComputedStyleancestor walk +getBoundingClientRect+proposeDimensions) before checking whether anything was parked, per pane on every resume. The O(1) WeakMap check now comes first, so the common no-deferral case costs zero DOM reads — this matters because the light tab-resume path is built to do no layout work at all.paneMetricOptionsAlreadySettlednow short-circuits when all five values are already live and nothing is parked, which also stops a no-op deferral arming a pointless refit on the next reveal.fitRevealedPane's pixel and grid checks can both say "nothing to do" and return without fitting. It now flushes first and fits when a flush lands.useTerminalFontZoomwritesfontSizedirectly then callssafeFit, which flushes — overwriting the user's zoom with the parked value. The zoom now folds its value into any pending deferral, so other parked keys still apply.performSafeFitchecked the minimum cols/rows gate at the old cell size, then flushed and fit unconditionally. A large font jump on a narrow pane passes at the old size and lands under the floor at the new one, sofit()pinned the PTY to exactly the sliver grid that floor exists to reject. It now re-checks after a flush that actually landed; the parked values still apply, only the fit is skipped.fitRevealedPane's flush branch calledsafeFitdirectly, which its own contract forbids on reveal:resumeRenderinghas just re-attached WebGL, whose cell metrics transiently differ from the DOM renderer's, and xterm's wrap→unwrap is not a perfect inverse — so a raw fit there can leave a diff-painting inline TUI corrupted. A landed flush leaves pixels unchanged with a diverged grid, the same shape as a snapshot resize, so it now takes the same steady-grid repair. Reachable via window wake, which callsfitAllRevealedPaneswith no pre-flush loop.canApplyPaneMetricOptionsreusedcanMeasurePaneForFit, but the divider clamp is 50px — over the 48px pixel floor, yet only ~5 cols, under the ≥8 cols fit floor. Such a pane deferred every font change and never flushed: it never hides, and its box never changes, so no reveal and no ResizeObserver entry arrives. Metric writes now gate on display plus the pixel box only. Hidden panes and the transient worktree-switch overlay are near-zero, so they still defer; the cols/rows floor stays on the fit. Apply and flush share one predicate, so no "applies but never flushes" state can open up.Testing
pnpm typecheckoxlint+audit:code-quality:native+audit:code-quality:type-awaresrc/renderer/src/lib/pane-manager/andsrc/renderer/src/components/terminal-pane/— 304 files / 3803 tests greenpnpm testandpnpm build— left to CITest notes: the keying bug survived round 1 because the fixtures were identity-blind —
getPanesreturned the same objects every call, unlike production.makeManagernow allocates a fresh pane view per call, and there are direct regression tests that defer through onetoPublicPane()view and flush through another and through the internal pane. Both fail if the key is reverted to the pane object. Also covered: the settled gate (including that a parked deferral is never "settled", so an equal-valued apply can't strand it), the zoom fold-in, andfitRevealedPanefitting when a flush lands on a pane the size checks would otherwise skip.Security Audit
Renderer-internal state only. No input handling, command execution, path handling, auth, secrets, dependency, or IPC changes. The diagnostics breadcrumb carries only a numeric pane id through the existing
terminal_webgl_diagnosticsink.Notes
measureTextresolves against whatever face is loaded at that instant, so a late-arriving@font-faceleaves cached metrics diverged until a resize. Unrelated to visibility and untouched here.