Skip to content

fix(terminal): converge post-spawn PTY size reconcile to fix split-mount column desync - #6725

Merged
AmethystLiang merged 3 commits into
mainfrom
nwparker/claude-code-resize
Jun 29, 2026
Merged

AmethystLiang merged 3 commits into
mainfrom
nwparker/claude-code-resize

Conversation

@nwparker

@nwparker nwparker commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #6762

Problem

Slack report: Claude Code still renders garbled — wide PTY output wrapping ~1 char per line into a narrow pane — when starting a new worktree with the side split panel on. PRs #6644/#6649 improved things so that resizing recovered ("resizing fixed it"), but the terminal still desynced on first mount.

Root cause

The post-spawn PTY reconcile added by #6644/#6649 capped at a fixed 12 requestAnimationFrames, and advanced the frame counter even on frames where the pane wasn't measurable or the split layout hadn't equalized yet. When a tab mounts with a split layout already present, the real (narrow) split width settles after frame 12, so the reconcile gave up while:

  • xterm had already reflowed to the narrow pane width, but
  • the corrective onResize → forwardPtyResize is dropped during the hidden mount window (isRendererPtyResizeAuthoritative() returns false).

So process.stdout.columns stayed pinned at the wide spawn width forever, and the TUI kept emitting wide output into a narrow pane → the garbled render. A later manual resize fired onResize while visible, which is why resizing recovered.

Fix

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 (live onResize dropped), the reconcile is the sole corrector: it keeps polling and forwarding every grid change. Its transport.resize is authoritative by definition, so it 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 (xterm fires onResize on every grid-changing fit(), and the desktop split-reflow path is never suppressed for a visible pane).
  • A hard MAX_FRAMES cap guarantees termination; mobile-fit / pty-locked frames are skipped; the reconcile handle is cancelled on dispose().

Reproduction harness

pty-size-reconcile.test.ts (14 tests) drives the loop with a deterministic frame scheduler. Verified non-vacuous: the desync-repro tests fail against the old fixed-12-frame logic and pass against the fix (confirmed by temporarily swapping the loop body). Also adds an e2e test, "both panes stay PTY-synced when a tab MOUNTS with a split layout present" (split → reload → assert both panes' process.stdout.columns == xterm cols).

Important

Headless Electron does not reproduce this layout-settle-after-rAF race — the existing golden "during initial mount" e2e test passes even against the buggy old logic. That's why #6644/#6649 merged with green e2e yet the bug persisted in production. The unit test is the real regression harness; the e2e tests are integration smoke. (The e2e fixture is also unrunnable on macOS without the realpathSync fix from already-merged #6718, deliberately left out of this branch so it comes from main on rebase.)

Verification

  • pty-size-reconcile.test.ts: 14/14 pass on the fix; ≥7 fail against the simulated old 12-frame logic.
  • Full terminal-pane unit suite: 1300/1300 pass.
  • New + existing e2e desync tests pass against a fresh build.
  • pnpm typecheck (web + node) clean; oxlint clean.
  • Adversarial multi-agent review drove two refinements: stability counts only while authoritative, and an exact handoff-frame assertion.

Made with Orca 🐋


Update: "sometimes even resizing doesn't fix it"

A further report said the desync occasionally survives a manual resize. That points past the mount-timing race to a second, more stubborn cause: the renderer forwards resizes fire-and-forget and dedupes on the size it thinks it sent, but never learns the PTY's actual size. So a resize dropped main-side — the pane was hidden (isRendererPtyResizeAuthoritative() false), a mobile take-back resize-suppression window, or a provider no-op — leaves xterm and the PTY silently diverged. A later manual resize that lands on the same column count fires no onResize, so nothing re-forwards and the pane stays garbled.

Fix (second commit)

Make the renderer able to see the PTY's truth and re-assert on show:

  • New read-only IPC pty:getSize → returns ptySizes.get(id), the size that is written only when a resize actually lands (or at spawn). That makes it the authoritative "what the PTY believes it is". Exposed via preload as window.api.pty.getSize.
  • Re-assert on visibility resume: when a pane becomes visible, it re-fits, reads the PTY's real size, and re-asserts only on genuine drift — so an already-synced resume emits no SIGWINCH (which would jar alt-screen TUIs like Claude Code). Routed through the existing 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.
  • Hardening: registered 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 made the pty IPC test mock throw on duplicate channels like real Electron so this class of omission is caught going forward.

Verification (second commit)

  • 7 new resume-reassert unit tests (drift / match / null / remote-skip / mobile-fit-skip / hide-during-hop / overlap-coalesce), all proven non-vacuous.
  • Full terminal-pane + pty IPC suites green (1494 tests); typecheck (web + node) + oxlint clean; e2e desync specs pass against a fresh build.
  • Adversarial multi-agent review of this commit caught the missing removeHandler (high-severity, would throw on macOS re-activation) before merge.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 78831d72-fa10-42d6-9887-3afac01fdaa9

📥 Commits

Reviewing files that changed from the base of the PR and between 2610895641de7a0706426a60da9310d48dcf658c and 01c2761.

📒 Files selected for processing (11)
  • .github/workflows/linux-wayland-gpu-sandbox.yml
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/pty-size-reconcile.test.ts
  • src/renderer/src/components/terminal-pane/pty-size-reconcile.ts
  • src/renderer/src/web/web-preload-api.ts
  • tests/e2e/terminal-column-desync-repro.spec.ts
🚧 Files skipped from review as they are similar to previous changes (11)
  • src/renderer/src/web/web-preload-api.ts
  • src/preload/index.ts
  • src/main/ipc/pty.ts
  • .github/workflows/linux-wayland-gpu-sandbox.yml
  • src/preload/api-types.ts
  • src/renderer/src/components/terminal-pane/pty-size-reconcile.test.ts
  • src/renderer/src/components/terminal-pane/pty-size-reconcile.ts
  • src/main/ipc/pty.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • tests/e2e/terminal-column-desync-repro.spec.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

📝 Walkthrough

Walkthrough

A shared reconcilePtySizeAcrossFrames helper now measures terminal dimensions across animation frames, forwards changed sizes to the PTY, and stops on stability, cancellation, liveness loss, or a frame cap. connectPanePty uses that helper for post-spawn sizing, reasserts PTY size on visibility resume, and cancels active reconciliation on dispose. Main-process and preload IPC expose pty:getSize/getSize for reading the last applied PTY geometry. New unit, renderer, e2e, and workflow changes cover the sizing flow.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the bug, fix, and verification, but it misses required template sections like Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes. Reformat it to the repo template and add the missing sections, especially Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% 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 clearly summarizes the main change: extracting and converging PTY size reconciliation to fix split-mount desync.
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.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-size-reconcile.test.ts (1)

8-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Trim these narrative comments to the repo’s 1–2 line “why” format.

The test names/assertions already carry most of this detail, so the repeated multi-line bug history is making the file harder to scan than necessary. Keep only the non-obvious reason inline and leave the longer repro story in the PR description or test names. As per coding guidelines, **/*.{ts,tsx,js,jsx} comments should stay to one or two lines and capture only the non-obvious reason.

Also applies to: 89-95, 105-110, 142-151, 239-242

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4af68031-c796-42bc-8e86-8424c4ed2ee6

📥 Commits

Reviewing files that changed from the base of the PR and between d877d94 and 3d669ef.

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

@brennanb2025

Copy link
Copy Markdown
Contributor

Picked this up from the Slack thread (Neil offered takeover, and #6762 has more user reports). Pushed one commit — bf1c1b4bf — to turn CI green.

Why verify was red: it was a real typecheck failure, not flake:

src/renderer/src/web/web-preload-api.ts(2531,3): error TS2741:
Property 'getSize' is missing … in type … PtyManagementApi

The PR adds pty.getSize to the shared PreloadApi type and implements it in the Electron preload + main IPC, but the web/remote-client preload shim (createPtyApi in web-preload-api.ts) must implement every pty method too. The commit adds a getSize: () => Promise.resolve(null) stub next to its getCwd sibling. That's safe by construction: web/remote PTYs are remote-runtime, and reassertPtySizeOnResume early-outs on isRemoteRuntimePtyId before it ever calls getSize, so null ("unknown") is all the type contract needs there.

(The other red check, wayland terminal input, is the known non-required harness that fails on any preload-touching PR — unrelated to this PR's logic.)

Verified locally on the branch: all three typecheck configs (tc.web/tc.cli/node) pass; pty-size-reconcile.test.ts + main pty.test.ts green (201 tests).

On the approach: the converging reconcile + pty:getSize resume re-assert is the right fix. I also ran the /ref-oss ghostty comparison Jinjing suggested — ghostty uses wait-for-layout-then-spawn (opens the pty via openpty at the already-measured size, defers surface creation until first layout; the invariant is commented at src/apprt/gtk/class/surface.zig:1578). That mechanism doesn't port cleanly to Orca because our spawn is async/remote-capable and we run headless background terminals (orchestration workers, terminal create without --focus, SSH) that never get a layout callback — coupling spawn to layout would delay agent startup and hang those. Orca's spawn-then-converge is the correct pattern for our constraints; this PR fixes the actual defect (the old fixed 12-frame budget expiring before the split equalized). A visible-path-only "wait 1–2 frames for a stable measurement before spawn" could shrink the wrong-width window further as a future optimization, but it'd sit on top of the reconcile, not replace it.

I won't merge — leaving that to you/@nwparker once CI is green.

@AmethystLiang
AmethystLiang force-pushed the nwparker/claude-code-resize branch from bf1c1b4 to 2610895 Compare June 29, 2026 18:52
@AmethystLiang

Copy link
Copy Markdown
Contributor

I'll try to land it

nwparker and others added 3 commits June 29, 2026 12:08
…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]>
…rn 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]>
- 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.
@AmethystLiang
AmethystLiang force-pushed the nwparker/claude-code-resize branch from 2610895 to 01c2761 Compare June 29, 2026 19:08
@AmethystLiang
AmethystLiang merged commit 2739310 into main Jun 29, 2026
2 checks passed
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.

[Bug]: Claude terminal breaking formatting when switching worktrees

3 participants