Repository navigation
Conversation
…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]>
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 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: 1f296242-fea0-4823-8cfb-aa1f3f11b906
📒 Files selected for processing (7)
src/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/lib/pane-manager/pane-lifecycle.tssrc/renderer/src/lib/pane-manager/terminal-scroll-intent-dom-tracking.tssrc/renderer/src/lib/pane-manager/terminal-scroll-intent-rebuild.tssrc/renderer/src/lib/pane-manager/terminal-scroll-intent.test.tssrc/renderer/src/lib/pane-manager/terminal-scroll-intent.tstests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts
| 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) |
There was a problem hiding this comment.
🩺 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.tsRepository: 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 -nRepository: 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 5Repository: 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 -nRepository: 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.
| 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) |
There was a problem hiding this comment.
🩺 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
|
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. |
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:enforceTerminalWriteScrollIntentat the end ofapplyMainBufferSnapshot,safeFitinside it (captures + enforces internally),enforceTerminalCurrentScrollIntent,Any of them that reads the buffer mid-parse sees
viewportY=0with a partially regrownbaseY, re-latches the intent as "pinned at line 0", and every subsequent batch holds the viewport there. Deterministic e2e on current main settles atviewportY=0, baseY=284after pinning at 248.Fix
terminal-scroll-intent-rebuild.ts):applyMainBufferSnapshotmarks the terminal's buffer rebuild in flight. While marked,captureTerminalWriteScrollIntentreturns null and enforcement no-ops — no racer (stream batches, safeFit, visibility resume) can latch transient coordinates.terminal-scroll-intent.tscrossed the 300-line limit; the DOM wheel/pointer tracking moved toterminal-scroll-intent-dom-tracking.ts(nomax-linesdisables 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.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
terminal-scroll-intent-follow.spec.ts,terminal-pinned-viewport-worktree-switch.spec.ts, TUI wheel reports/drain, long-table scroll restore — all pass.pnpm typecheckpasses.pnpm lint's only failure is a pre-existing warning insrc/main/browser/agent-browser-bridge.test.ts(untouched by this PR).Made with Orca 🐋