Skip to content

fix(terminal): reconcile PTY size after spawn to fix first-mount column desync - #6644

Merged
AmethystLiang merged 2 commits into
mainfrom
fix-terminal-column-desync
Jun 28, 2026
Merged

AmethystLiang merged 2 commits into
mainfrom
fix-terminal-column-desync

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

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 requestAnimationFrame so FitAddon can 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 corrective onResize → forwardPtyResize is dropped because:

  • the cols already matched xterm's pre-layout value at fit time, so no onResize fires; or
  • isRendererPtyResizeAuthoritative() returns false during the mount window.

So process.stdout.columns stays 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.ts compares process.stdout.columns (PTY) against terminal.cols (xterm):

  • The "during initial mount" golden repro (reloads 8×, resizes mid-mount) fails without this change (PTY pinned at window width, e.g. 203, while xterm fit the pane to 79) and passes with it.
  • All 5 scenarios pass with the fix: visible resize, hidden resize, repeated background resize, vertical split reparent, initial mount.
  • pnpm typecheck clean; oxlint clean on the changed file.

🤖 Root cause reproduced and spec authored via multi-agent orchestration.

Made with Orca 🐋

…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]>
@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9a54f718-9b11-4479-bfa4-c0e324354c5c

📥 Commits

Reviewing files that changed from the base of the PR and between 98e3511 and 6b4cc2f.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • tests/e2e/terminal-column-desync-repro.spec.ts

📝 Walkthrough

Walkthrough

A new reconcilePtySizeAfterSpawn helper is added to pty-connection.ts. It defers a safeFit to the next animation frame after spawn, checks pane binding and fit/lock state, and resizes the PTY only when the post-fit xterm dimensions differ from the spawn dimensions. The fresh-spawn completion path now calls this helper. A new Playwright spec adds five scenarios that compare xterm and PTY column counts across resize, hidden state, split panes, and initial-mount timing cases.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the problem and fix, but it omits required template sections like Screenshots, Testing, AI Review Report, Security Audit, and Notes. Reformat the PR body to match the template and add each required section, including testing, screenshots or no visual change, AI review report, security audit, and notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, specific, and accurately summarizes the main first-mount PTY resize fix.
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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ae0f577f-a89b-413b-bd4a-08ed0df863ec

📥 Commits

Reviewing files that changed from the base of the PR and between ca6c3c2 and 98e3511.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • tests/e2e/terminal-column-desync-repro.spec.ts

@AmethystLiang AmethystLiang left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

@AmethystLiang
AmethystLiang merged commit 8430a10 into main Jun 28, 2026
1 check passed
AmethystLiang added a commit that referenced this pull request Jun 28, 2026
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]>
AmethystLiang pushed a commit that referenced this pull request Jun 29, 2026
…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]>
AmethystLiang added a commit that referenced this pull request Jun 29, 2026
…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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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