Skip to content

fix(terminal): keep pinned panes off the scrollback top across streaming snapshot restores - #8667

Closed
Jinwoo-H wants to merge 1 commit into
mainfrom
Jinwoo-H/codex-pinned-switch-top-jump
Closed

Jinwoo-H wants to merge 1 commit into
mainfrom
Jinwoo-H/codex-pinned-switch-top-jump

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Symptom (reported on v1.4.139-rc.2, which includes #8625)

With a Codex agent actively running ("Working…" animation), pin the terminal slightly above the bottom, switch to another workspace, then return: the terminal is scrolled to the very top of the scrollback.

Why #8625 doesn't cover it

A pane whose agent keeps streaming while hidden comes back through the hidden-output snapshot restore (applyMainBufferSnapshot): the xterm buffer is discarded, cleared (2J/3J/H), and rewritten from the serialized snapshot. Those bytes parse asynchronously — but several scroll-intent actors run against the half-parsed buffer in that window:

  • the restore's own synchronous enforceTerminalWriteScrollIntent at the end of applyMainBufferSnapshot,
  • the safeFit inside it (captures + enforces internally),
  • visibility-resume's enforceTerminalCurrentScrollIntent,
  • and — decisive in the streaming case — live PTY write batches that keep arriving during the replay, each doing capture→enforce.

Any of them that reads the buffer mid-parse sees viewportY=0 with a partially regrown baseY, re-latches the intent as "pinned at line 0", and every subsequent batch holds the viewport there. Deterministic e2e on current main settles at viewportY=0, baseY=284 after pinning at 248.

Fix

  1. Rebuild bracket (terminal-scroll-intent-rebuild.ts): applyMainBufferSnapshot marks the terminal's buffer rebuild in flight. While marked, captureTerminalWriteScrollIntent returns null and enforcement no-ops — no racer (stream batches, safeFit, visibility resume) can latch transient coordinates.
  2. Post-parse restore: the pre-replay intent is applied exactly once, from an empty-write completion callback that xterm's FIFO write queue certifies runs after every replay byte has parsed (same contract as the replay guard), restoring pinned panes by bottom offset. A 2s timeout fallback ends the bracket if the write pipeline wedges.
  3. Defense-in-depth for unbracketed rebuild paths: enforcement no longer re-latches a pinned intent from a scrollback shorter than the stored pin's (mirrors the existing sync-side guard), and capture only normalizes pinned-at-bottom→follow when the scrollback is at least as long as the pin's — so fix(terminal): stop phantom pinned-viewport pins from freezing follow-output #8625's phantom-pin healing can't misfire against a cleared buffer.
  4. terminal-scroll-intent.ts crossed the 300-line limit; the DOM wheel/pointer tracking moved to terminal-scroll-intent-dom-tracking.ts (no max-lines disables per AGENTS.md).

Deterministic reproduction

New e2e terminal-pinned-viewport-streaming-switch.spec.ts + inline fixture: 300 rows of scrollback, then a continuous synchronized-output "Working…" stream (frame every 50ms) that keeps running while hidden; pin 6 rows above bottom, switch worktree, wait 3s, return, wait for the viewport to settle.

  • Before this fix (current main): settles at viewportY=0 (top), baseY=284 — fails.
  • After: restores near the pin — passes.

Three new unit tests cover the same shapes at module level (transient-shrink re-latch, capture racing a cleared buffer, full suspend/restore bracket); all were red before the fix.

Verification

  • pane-manager + terminal-pane unit suites: 2,504 tests pass (two consecutive clean runs).
  • e2e: new repro spec + fix(terminal): stop phantom pinned-viewport pins from freezing follow-output #8625's terminal-scroll-intent-follow.spec.ts, terminal-pinned-viewport-worktree-switch.spec.ts, TUI wheel reports/drain, long-table scroll restore — all pass.
  • pnpm typecheck passes. pnpm lint's only failure is a pre-existing warning in src/main/browser/agent-browser-bridge.test.ts (untouched by this PR).

Made with Orca 🐋

…ing snapshot restores

Returning to a worktree whose agent kept streaming (Codex "Working…")
replays a main-buffer snapshot: the buffer is cleared and rewritten, but
xterm parses those bytes asynchronously. Scroll-intent capture/enforce that
raced the parse — live stream batches, safeFit, visibility resume, and the
restore's own synchronous enforcement — read the half-cleared buffer and
re-latched the intent as "pinned at line 0", parking the returned pane at
the very top of the scrollback (#8625 does not cover this).

- Bracket the snapshot replay with a per-terminal rebuild marker
  (terminal-scroll-intent-rebuild.ts); while it is in flight, intent
  capture returns null and enforcement no-ops, so no racer can latch
  transient coordinates.
- Re-apply the pre-replay intent once, in a FIFO-ordered empty-write
  completion after the replay bytes have parsed (bottom-offset restore),
  with a timeout fallback so a wedged pipeline cannot suppress intent
  forever.
- Defense-in-depth for unbracketed rebuilds: enforcement no longer
  re-latches a pinned intent from a scrollback shorter than the stored
  pin's, and capture only normalizes pinned-at-bottom to follow when the
  scrollback is at least as long as the pin's.
- Split the DOM wheel/pointer tracking into
  terminal-scroll-intent-dom-tracking.ts (max-lines).

Deterministic e2e repro: a synchronized-output streaming fixture, pinned
six rows above bottom, worktree switch away and back — settled at
viewportY=0 (baseY=284) before this fix, restores near the pin after.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds rebuild-aware terminal scroll-intent tracking, separates xterm DOM event handling into a dedicated module, and updates terminal opening to use it. Snapshot restoration now brackets replay parsing and reapplies saved scroll intent after completion, with guarded-write and timeout fallbacks. Unit tests cover rebuild races and pinned intent preservation, while an end-to-end test covers streaming output across a worktree switch.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and is missing Summary, Screenshots, AI Review Report, Security Audit, and Notes sections. Rewrite it using the repo template headings, add a Summary, Screenshots or 'No visual change', testing checklist, AI Review Report with cross-platform review, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Clear, specific title matches the main fix to pinned terminal panes during snapshot restores.
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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1f296242-fea0-4823-8cfb-aa1f3f11b906

📥 Commits

Reviewing files that changed from the base of the PR and between 9924b07 and 31e1b3a.

📒 Files selected for processing (7)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/pane-manager/pane-lifecycle.ts
  • src/renderer/src/lib/pane-manager/terminal-scroll-intent-dom-tracking.ts
  • src/renderer/src/lib/pane-manager/terminal-scroll-intent-rebuild.ts
  • src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts
  • src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts
  • tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts

Comment on lines 5993 to +6012
const scrollIntent = captureTerminalWriteScrollIntent(pane.terminal)
// Why: the replay below parses asynchronously. Until it has, viewportY/
// baseY describe a half-cleared buffer; any intent capture/enforce that
// races it (live stream batches, safeFit, visibility resume) latches
// "pinned at line 0" and parks the pane at the top of the scrollback.
beginTerminalScrollIntentBufferRebuild(pane.terminal)
let scrollIntentRestored = false
const finishScrollIntentRestore = (): void => {
if (scrollIntentRestored) {
return
}
scrollIntentRestored = true
endTerminalScrollIntentBufferRebuild(pane.terminal)
enforceTerminalWriteScrollIntent(pane.terminal, scrollIntent, {
restoreBy: 'bottomOffset'
})
}
// Why: if the write pipeline wedges, the FIFO completion below never
// fires; the rebuild bracket must not suppress intent forever.
setTimeout(finishScrollIntentRestore, SNAPSHOT_RESTORE_SCROLL_INTENT_SETTLE_MS)

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect isTerminalScrollIntentRebuildInFlight and confirm it gates on a shared counter
# rather than per-call identity, and check for any existing reentrancy guard.
cat -n src/renderer/src/lib/pane-manager/terminal-scroll-intent-rebuild.ts
rg -n "applyMainBufferSnapshot" -B3 -A3 src/renderer/src/components/terminal-pane/pty-connection.ts

Repository: stablyai/orca

Length of output: 2361


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file=src/renderer/src/components/terminal-pane/pty-connection.ts

# Read the relevant regions with line numbers.
sed -n '5984,6045p' "$file" | cat -n
printf '\n---\n'
sed -n '6140,6285p' "$file" | cat -n
printf '\n---\n'
sed -n '6045,6145p' "$file" | cat -n

Repository: stablyai/orca

Length of output: 16564


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check whether applyMainBufferSnapshot is invoked synchronously or can overlap
# via multiple async paths around hidden-output restore.
rg -n "applyMainBufferSnapshot\(" src/renderer/src/components/terminal-pane/pty-connection.ts -n -C 5

Repository: stablyai/orca

Length of output: 1088


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file=src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts
sed -n '1,260p' "$file" | cat -n

Repository: stablyai/orca

Length of output: 10198


Overlapping snapshot replays can skip the scroll-intent restore. applyMainBufferSnapshot can run again before the prior pane.terminal.write('', cb) drains. Because captureTerminalWriteScrollIntent() returns null whenever any rebuild is in flight, the later pass records no intent, and the earlier pass's enforceTerminalWriteScrollIntent(...) is suppressed while the shared per-terminal rebuild counter stays nonzero. In multi-iteration hidden-output restores, neither pass reapplies the saved scroll position.

Comment on lines +5998 to +6012
beginTerminalScrollIntentBufferRebuild(pane.terminal)
let scrollIntentRestored = false
const finishScrollIntentRestore = (): void => {
if (scrollIntentRestored) {
return
}
scrollIntentRestored = true
endTerminalScrollIntentBufferRebuild(pane.terminal)
enforceTerminalWriteScrollIntent(pane.terminal, scrollIntent, {
restoreBy: 'bottomOffset'
})
}
// Why: if the write pipeline wedges, the FIFO completion below never
// fires; the rebuild bracket must not suppress intent forever.
setTimeout(finishScrollIntentRestore, SNAPSHOT_RESTORE_SCROLL_INTENT_SETTLE_MS)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Timeout/dispose fallback isn't guarded like the write-completion path.

The FIFO write-completion path wraps finishScrollIntentRestore in runGuardedWriteCompletionStep (line 6097), but the two other call sites for the same function don't:

  • The setTimeout(finishScrollIntentRestore, SNAPSHOT_RESTORE_SCROLL_INTENT_SETTLE_MS) fallback (line 6012) calls it raw.
  • The catch { finishScrollIntentRestore() } fallback (line 6100) calls it raw too.

Both can run after the pane is disposed (no disposed check, unlike every other timer callback in this file), and the timer handle is never tracked/cleared in dispose() — inconsistent with the pattern used for every sibling timer here (cleanupHiddenOutputRestoreDeferredRetry, cleanupHiddenOutputRestoreForegroundDeadline, etc.). If finishScrollIntentRestore throws (e.g. touching a torn-down terminal), it will be an unguarded/uncaught exception in these two paths.

🔧 Suggested fix: guard consistently and track/clear the timer
       const scrollIntent = captureTerminalWriteScrollIntent(pane.terminal)
       beginTerminalScrollIntentBufferRebuild(pane.terminal)
       let scrollIntentRestored = false
       const finishScrollIntentRestore = (): void => {
         if (scrollIntentRestored) {
           return
         }
         scrollIntentRestored = true
+        if (scrollIntentSettleTimer !== null) {
+          clearTimeout(scrollIntentSettleTimer)
+          scrollIntentSettleTimer = null
+        }
         endTerminalScrollIntentBufferRebuild(pane.terminal)
         enforceTerminalWriteScrollIntent(pane.terminal, scrollIntent, {
           restoreBy: 'bottomOffset'
         })
       }
-      setTimeout(finishScrollIntentRestore, SNAPSHOT_RESTORE_SCROLL_INTENT_SETTLE_MS)
+      let scrollIntentSettleTimer: ReturnType<typeof setTimeout> | null = setTimeout(() => {
+        scrollIntentSettleTimer = null
+        if (disposed) {
+          return
+        }
+        runGuardedWriteCompletionStep('snapshot-restore-scroll-intent-timeout', finishScrollIntentRestore)
+      }, SNAPSHOT_RESTORE_SCROLL_INTENT_SETTLE_MS)
       try {
         pane.terminal.write('', () =>
           runGuardedWriteCompletionStep('snapshot-restore-scroll-intent', finishScrollIntentRestore)
         )
       } catch {
-        finishScrollIntentRestore()
+        runGuardedWriteCompletionStep('snapshot-restore-scroll-intent', finishScrollIntentRestore)
       }

(Also track scrollIntentSettleTimer in a var reachable from dispose(), or route it through an existing cleanup-collection pattern, so it can't outlive the pane.)

Also applies to: 6095-6101

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Superseded by the PR above — same branch history plus the removal of per-batch scroll enforcement in favor of xterm's native user-scrolling ownership, with a pinned-version contract test guarding the emulator semantics the write path now relies on.

@Jinwoo-H Jinwoo-H closed this Jul 14, 2026
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