Repository navigation
fix(terminal): reconcile PTY size after spawn to fix first-mount column desync - #6644
Conversation
…mn desync Interactive TUIs (e.g. Claude Code) could render garbled — output wrapped at ~1 column, overlapping text — when a terminal's pane layout had not settled by the first animation frame. The deferred-rAF fit then spawned the PTY at the wide window width while xterm later reflowed to the real (narrower) pane width. The corrective onResize was dropped (cols already matched at fit time, or isRendererPtyResizeAuthoritative() was false mid-mount), so process.stdout.columns stayed pinned to the stale width forever and the TUI emitted wide output into a narrow pane. Fix: after the PTY id resolves, re-fit once layout has settled and force the PTY to xterm's current dimensions if they differ from the spawn dimensions. The initial spawn-time sync is authoritative by definition, so it bypasses the visibility gate — but still respects the mobile-fit override/lock, which legitimately parks the PTY at phone dims. Verified with tests/e2e/terminal-column-desync-repro.spec.ts: the 'during initial mount' golden repro fails without this change and passes with it; all 5 scenarios (visible resize, hidden resize, repeated background resize, split reparent, initial mount) pass. Repro spec co-authored via orchestration. Co-authored-by: Orca <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughA new 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 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: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: ae0f577f-a89b-413b-bd4a-08ed0df863ec
📒 Files selected for processing (2)
src/renderer/src/components/terminal-pane/pty-connection.tstests/e2e/terminal-column-desync-repro.spec.ts
AmethystLiang
left a comment
There was a problem hiding this comment.
Verdict: LGTM. I reviewed this adversarially against the fresh-spawn rAF, normal resize forwarding, hidden/visible resume, reattach/attach paths, remote-runtime transport, and the new e2e spec. I do not see a blocking correctness bug.
Findings: none blocking.
Notes from the review:
- The new forced post-spawn sync at src/renderer/src/components/terminal-pane/pty-connection.ts:2122 is scoped tightly: it rechecks disposal and PTY identity before touching the transport, and it preserves the mobile-fit/driver guards at :2124-2128. That is enough to avoid resizing a torn-down StrictMode mount or sibling PTY.
- A single extra rAF is not a general layout-settlement proof by itself, but in this codebase it appears sufficient as the spawn-time backstop: if layout continues changing afterward, the per-pane ResizeObserver stability loop in src/renderer/src/lib/pane-manager/pane-fit-resize-observer.ts:39-90 should refit xterm, and the visible resize path at src/renderer/src/components/terminal-pane/pty-connection.ts:2042-2055 forwards the final size. The new path specifically covers the otherwise-lost initial size where xterm/PTY were born stale and no authoritative resize made it through.
- Bypassing isRendererPtyResizeAuthoritative() here looks intentional and safe for this narrow moment. The renderer still skips mobile override/lock, and the main-process pty:resize handler has the mobile driver defense-in-depth at src/main/ipc/pty.ts:3033-3057. Since this resize only happens when the dimensions differ from spawnCols/spawnRows, the normal PTY resize should deliver SIGWINCH when needed; I do not see the resume-path explicit SIGWINCH requirement applying to this spawn correction.
- I do not think reattach omission is a gap for this PR. Reattach/attach paths already pass measured cols/rows into transport.connect/attach at src/renderer/src/components/terminal-pane/pty-connection.ts:3924-3928, :4103-4107, :4198-4201, and :4257-4260, with reattach doing an explicit resize+SIGWINCH after replay at :3740-3750. The bug being fixed is fresh-spawn birth at stale dimensions; existing live sessions have separate reattach/resume correction paths.
- Remote-runtime fresh PTYs are included because startFreshSpawn calls reconcile for any resolvedPtyId at src/renderer/src/components/terminal-pane/pty-connection.ts:2526-2528, and remote resize is a viewport update through src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts:580-588. Existing remote attaches similarly get initial desiredViewport on attach/connect.
- The e2e invariant is the right one: compare xterm terminal.cols against process.stdout.columns from inside the PTY. tests/e2e/terminal-column-desync-repro.spec.ts:276-321 is a reasonable regression guard for the initial-mount race, and the probe in tests/e2e/terminal-column-probes.ts:66-105 reads the live PTY value rather than only renderer state. Minor non-blocking caveat: attempt 0 may depend on the runner's default viewport, but attempts 1-7 force wide reload -> narrow resize, so the test still has repeated race coverage.
Verification: pnpm exec oxlint src/renderer/src/components/terminal-pane/pty-connection.ts tests/e2e/terminal-column-desync-repro.spec.ts --quiet
Follow-up to #6644. The merged fix used a single post-spawn requestAnimationFrame, which did not fully close the first-mount column race: the pane's real layout can keep changing for several frames (split equalize, sidebar/title reflow), so a one-shot re-fit could still measure a stale width and leave the PTY pinned. The golden 'during initial mount' e2e test failed ~1 in 9 runs with the single-frame version. Poll for up to 12 frames, forwarding the settled size to the PTY only when it differs from what the PTY was last told (mirroring the existing ResizeObserver stability loop). Each resize is gated on an actual change, so a TUI sees at most a couple of SIGWINCH during startup, not a loop. Verified: golden test passes 6/6 with repeat-each + retries; full spec 15/15. Without this change the single-frame version is intermittently flaky. Co-authored-by: Orca <[email protected]>
…unt column desync Follow-up to #6644/#6649. Those added a post-spawn PTY reconcile but capped it at a FIXED 12 requestAnimationFrames whose counter advanced even on frames where the pane was unmeasurable or the split layout had not yet equalized. When a tab MOUNTS with a split layout already present (a new worktree opened with the side split panel on), the real narrow split width settles AFTER frame 12, so the reconcile gave up while xterm had reflowed narrow and the PTY stayed pinned at the wide spawn width. The corrective xterm onResize is dropped during the hidden mount window (isRendererPtyResizeAuthoritative() is false), so process.stdout.columns stayed wide and interactive TUIs (Claude Code) rendered garbled until a manual resize. Extract the reconcile into pty-size-reconcile.ts with an authoritative-gated convergence loop instead of a fixed frame budget: - While the pane is hidden (onResize dropped), the reconcile is the SOLE corrector: it keeps polling and forwarding every grid change (its transport.resize bypasses the visibility gate). Hidden frames never advance the settle counter. - Once visible AND stable for SETTLE_FRAMES, it hands off to the live onResize/ResizeObserver path, which reliably catches any later reflow. - Hard cap (MAX_FRAMES) guarantees termination; mobile-fit/locked frames are skipped; the reconcile handle is cancelled on dispose. Harness: pty-size-reconcile.test.ts (14 tests) drives the loop with a deterministic frame scheduler; the desync-repro tests fail against the old 12-frame logic and pass on the fix. Adds an e2e "MOUNTS with a split layout present" test. Caveat: headless Electron does not reproduce this layout-settle-after-rAF race (the existing golden e2e passes even against the old buggy logic), which is why #6644/#6649 merged with green e2e yet the bug persisted. The unit test is the real regression harness; the e2e tests are integration smoke. Made with [Orca](https://github.com/stablyai/orca) Co-authored-by: Orca <[email protected]>
…unt column desync (#6725) * fix(terminal): converge post-spawn PTY size reconcile to fix split-mount column desync Follow-up to #6644/#6649. Those added a post-spawn PTY reconcile but capped it at a FIXED 12 requestAnimationFrames whose counter advanced even on frames where the pane was unmeasurable or the split layout had not yet equalized. When a tab MOUNTS with a split layout already present (a new worktree opened with the side split panel on), the real narrow split width settles AFTER frame 12, so the reconcile gave up while xterm had reflowed narrow and the PTY stayed pinned at the wide spawn width. The corrective xterm onResize is dropped during the hidden mount window (isRendererPtyResizeAuthoritative() is false), so process.stdout.columns stayed wide and interactive TUIs (Claude Code) rendered garbled until a manual resize. Extract the reconcile into pty-size-reconcile.ts with an authoritative-gated convergence loop instead of a fixed frame budget: - While the pane is hidden (onResize dropped), the reconcile is the SOLE corrector: it keeps polling and forwarding every grid change (its transport.resize bypasses the visibility gate). Hidden frames never advance the settle counter. - Once visible AND stable for SETTLE_FRAMES, it hands off to the live onResize/ResizeObserver path, which reliably catches any later reflow. - Hard cap (MAX_FRAMES) guarantees termination; mobile-fit/locked frames are skipped; the reconcile handle is cancelled on dispose. Harness: pty-size-reconcile.test.ts (14 tests) drives the loop with a deterministic frame scheduler; the desync-repro tests fail against the old 12-frame logic and pass on the fix. Adds an e2e "MOUNTS with a split layout present" test. Caveat: headless Electron does not reproduce this layout-settle-after-rAF race (the existing golden e2e passes even against the old buggy logic), which is why #6644/#6649 merged with green e2e yet the bug persisted. The unit test is the real regression harness; the e2e tests are integration smoke. Made with [Orca](https://github.com/stablyai/orca) Co-authored-by: Orca <[email protected]> * fix(terminal): re-assert PTY size on visibility resume to heal stubborn column desync Follow-up within the same fix: the user reported "sometimes even resizing doesn't fix it." Root cause beyond the mount-timing race — the renderer forwards resizes fire-and-forget and dedupes on the size it THINKS it sent, but never learns the PTY's actual size. A resize dropped main-side (the pane was hidden, a mobile take-back resize-suppression window, or a provider no-op) leaves xterm and the PTY silently diverged; a later same-cols layout fires no onResize, so it never self-corrects. Expose the PTY's last-APPLIED size to the renderer and re-assert on show: - New read-only IPC pty:getSize -> ptySizes.get(id) (the size written only when a resize actually lands or at spawn — the authoritative "what the PTY believes it is"). Wired through preload (window.api.pty.getSize) + api-types. - On visibility resume (noteVisibilityResume), the pane re-fits, reads the PTY's real size, and re-asserts via forwardPtyResize ONLY on genuine drift — so no spurious SIGWINCH on an already-synced resume (which would jar alt-screen TUIs). Routed through forwardPtyResize so the authoritative/mobile gates are re-checked at send time; remote-runtime PTYs (separate viewport channel) are skipped; overlapping resumes coalesce to one query. Also register pty:getSize in the registerPtyHandlers removeHandler cleanup block so re-registration (macOS re-activate / new window) doesn't throw on a duplicate ipcMain.handle, and make the pty IPC test mock throw on duplicate channels like real Electron so this class of omission is caught going forward. Tests: 7 resume-reassert cases (drift / match / null / remote-skip / mobile-fit-skip / hide-during-hop / overlap-coalesce), all non-vacuous. Full terminal-pane + pty IPC suites green (1494 tests); typecheck (web+node) + oxlint clean; e2e desync specs pass against a fresh build. Made with [Orca](https://github.com/stablyai/orca) Co-authored-by: Orca <[email protected]> * Stub PTY getSize API and skip redundant Wayland GPU sandbox tests - Implement PTY `getSize` stub in `web-preload-api.ts` to satisfy API requirements for the web-preload environment. - Skip the unfixed Wayland GPU sandbox negative control test if the target base branch already contains the sandbox workaround. --------- Co-authored-by: Orca <[email protected]> Co-authored-by: Jinjing <[email protected]>
…ai#6649) Follow-up to stablyai#6644. The merged fix used a single post-spawn requestAnimationFrame, which did not fully close the first-mount column race: the pane's real layout can keep changing for several frames (split equalize, sidebar/title reflow), so a one-shot re-fit could still measure a stale width and leave the PTY pinned. The golden 'during initial mount' e2e test failed ~1 in 9 runs with the single-frame version. Poll for up to 12 frames, forwarding the settled size to the PTY only when it differs from what the PTY was last told (mirroring the existing ResizeObserver stability loop). Each resize is gated on an actual change, so a TUI sees at most a couple of SIGWINCH during startup, not a loop. Verified: golden test passes 6/6 with repeat-each + retries; full spec 15/15. Without this change the single-frame version is intermittently flaky. Co-authored-by: Orca <[email protected]>
…unt column desync (stablyai#6725) * fix(terminal): converge post-spawn PTY size reconcile to fix split-mount column desync Follow-up to stablyai#6644/stablyai#6649. Those added a post-spawn PTY reconcile but capped it at a FIXED 12 requestAnimationFrames whose counter advanced even on frames where the pane was unmeasurable or the split layout had not yet equalized. When a tab MOUNTS with a split layout already present (a new worktree opened with the side split panel on), the real narrow split width settles AFTER frame 12, so the reconcile gave up while xterm had reflowed narrow and the PTY stayed pinned at the wide spawn width. The corrective xterm onResize is dropped during the hidden mount window (isRendererPtyResizeAuthoritative() is false), so process.stdout.columns stayed wide and interactive TUIs (Claude Code) rendered garbled until a manual resize. Extract the reconcile into pty-size-reconcile.ts with an authoritative-gated convergence loop instead of a fixed frame budget: - While the pane is hidden (onResize dropped), the reconcile is the SOLE corrector: it keeps polling and forwarding every grid change (its transport.resize bypasses the visibility gate). Hidden frames never advance the settle counter. - Once visible AND stable for SETTLE_FRAMES, it hands off to the live onResize/ResizeObserver path, which reliably catches any later reflow. - Hard cap (MAX_FRAMES) guarantees termination; mobile-fit/locked frames are skipped; the reconcile handle is cancelled on dispose. Harness: pty-size-reconcile.test.ts (14 tests) drives the loop with a deterministic frame scheduler; the desync-repro tests fail against the old 12-frame logic and pass on the fix. Adds an e2e "MOUNTS with a split layout present" test. Caveat: headless Electron does not reproduce this layout-settle-after-rAF race (the existing golden e2e passes even against the old buggy logic), which is why stablyai#6644/stablyai#6649 merged with green e2e yet the bug persisted. The unit test is the real regression harness; the e2e tests are integration smoke. Made with [Orca](https://github.com/stablyai/orca) Co-authored-by: Orca <[email protected]> * fix(terminal): re-assert PTY size on visibility resume to heal stubborn column desync Follow-up within the same fix: the user reported "sometimes even resizing doesn't fix it." Root cause beyond the mount-timing race — the renderer forwards resizes fire-and-forget and dedupes on the size it THINKS it sent, but never learns the PTY's actual size. A resize dropped main-side (the pane was hidden, a mobile take-back resize-suppression window, or a provider no-op) leaves xterm and the PTY silently diverged; a later same-cols layout fires no onResize, so it never self-corrects. Expose the PTY's last-APPLIED size to the renderer and re-assert on show: - New read-only IPC pty:getSize -> ptySizes.get(id) (the size written only when a resize actually lands or at spawn — the authoritative "what the PTY believes it is"). Wired through preload (window.api.pty.getSize) + api-types. - On visibility resume (noteVisibilityResume), the pane re-fits, reads the PTY's real size, and re-asserts via forwardPtyResize ONLY on genuine drift — so no spurious SIGWINCH on an already-synced resume (which would jar alt-screen TUIs). Routed through forwardPtyResize so the authoritative/mobile gates are re-checked at send time; remote-runtime PTYs (separate viewport channel) are skipped; overlapping resumes coalesce to one query. Also register pty:getSize in the registerPtyHandlers removeHandler cleanup block so re-registration (macOS re-activate / new window) doesn't throw on a duplicate ipcMain.handle, and make the pty IPC test mock throw on duplicate channels like real Electron so this class of omission is caught going forward. Tests: 7 resume-reassert cases (drift / match / null / remote-skip / mobile-fit-skip / hide-during-hop / overlap-coalesce), all non-vacuous. Full terminal-pane + pty IPC suites green (1494 tests); typecheck (web+node) + oxlint clean; e2e desync specs pass against a fresh build. Made with [Orca](https://github.com/stablyai/orca) Co-authored-by: Orca <[email protected]> * Stub PTY getSize API and skip redundant Wayland GPU sandbox tests - Implement PTY `getSize` stub in `web-preload-api.ts` to satisfy API requirements for the web-preload environment. - Skip the unfixed Wayland GPU sandbox negative control test if the target base branch already contains the sandbox workaround. --------- Co-authored-by: Orca <[email protected]> Co-authored-by: Jinjing <[email protected]>
Problem
Interactive TUIs (e.g. Claude Code) could render badly garbled — output wrapping at ~1 column, lines overprinting each other — for an entire session, surviving Ctrl+L and even widening the pane.
After ruling out (via live DevTools probing of an affected session) the xterm version, font/letter-spacing, pane width, and GPU/DOM renderer, the real cause was confirmed via an Electron e2e repro: an xterm ↔ PTY column desync at first mount.
Root cause
The PTY spawn is deferred to a single
requestAnimationFramesoFitAddoncan measure the laid-out container. But when the pane's real (e.g. split or otherwise narrower) layout hasn't settled by that first frame, the fit measures the wide window width, and the PTY is spawned at that width. xterm later reflows to the true (narrower) pane width, but the correctiveonResize → forwardPtyResizeis dropped because:onResizefires; orisRendererPtyResizeAuthoritative()returnsfalseduring the mount window.So
process.stdout.columnsstays pinned at the wide startup width forever, and the TUI keeps emitting wide output into a narrow pane → the garbled render.The asymmetry confirmed it: plain hidden-resize and divider-split paths self-heal via the resume-time
safeFit + transport.resize, but the very first mount has no such correction.Fix
After the PTY id resolves, re-fit once layout has settled and force the PTY to xterm's current dimensions if they differ from the spawn dimensions. The initial spawn-time sync is authoritative by definition, so it bypasses the visibility gate — but it still respects the mobile-fit override / driver lock, which legitimately parks the PTY at phone dims.
Verification
New spec
tests/e2e/terminal-column-desync-repro.spec.tscomparesprocess.stdout.columns(PTY) againstterminal.cols(xterm):pnpm typecheckclean; oxlint clean on the changed file.🤖 Root cause reproduced and spec authored via multi-agent orchestration.
Made with Orca 🐋