Skip to content

fix(terminal): preserve pinned scroll across live redraws - #12783

Merged
nwparker merged 1 commit into
stablyai:mainfrom
nwparker:nwparker/pi-scroll
Aug 7, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
nwparker:nwparker/pi-scroll

Conversation

@nwparker

@nwparker nwparker commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #12663

Summary

Preserve a reader's pinned terminal viewport when a live TUI redraw erases the scrollback, including redraws split across PTY delivery and scheduler chunks.

Orca registers guarded CSI handlers on the pane's terminal. When xterm is about to run an erase-scrollback, the handler records how far from the bottom the reader is; once the redraw goes quiet, that distance is restored — once. Capture and restore both hang off xterm's own events (registerCsiHandler and onWriteParsed), so installing it is the whole integration.

Root cause

Pi compaction emits a full-screen redraw containing:

ESC[2J ESC[H ESC[3J

xterm's eraseInDisplay(3) clamps a scrolled-up viewport to line 0 and leaves isUserScrolling latched, so the pane never resumes following on its own — the reader is stranded wherever the erase dropped them. Orca's PTY scheduler can parse the clear in one chunk and the rest of the redraw in later chunks, so the position is lost regardless of where the chunk boundary falls.

ELI5

Imagine bookmarking page 50 of a book. Pi throws the book away and prints a new copy. This notes how far from the end you were reading when the old copy was discarded, waits for the new copy to finish printing, and puts you back the same distance from the end — once. If the new copy never gets that long, it leaves you where you already were rather than holding the bookmark forever.

Behaviour

Situation Result
Redraw completes Reader restored to their distance from the bottom
Redraw spans many writes Pin waits for the quiet period, then lands once
Redraw never goes quiet Pin lands once at a 1s cap
Rebuild stays shorter than the offset Pin is dropped; reader left where the erase clamped them
Reader scrolls during the window Pin abandoned — their new position wins
Alternate screen (vim, less) Never armed; an erase there touches no scrollback we pinned
Pane following output Never armed
Repeated clear loop One deadline per pin, so it still lands

The pin fires exactly once. Re-applying it per write would turn a pinned viewport into follow-output-at-an-offset and drag the reader through whatever printed next.

Reproduction

  1. Run Pi in an Orca terminal with enough context for compaction.
  2. Start /compact.
  3. Scroll up while Pi waits for its summary.
  4. Let compaction finish.
  5. The terminal stays pinned instead of jumping away.

Reproduced against a live Electron Orca session with Pi v0.83.0 (compacted 32,354 tokens; after the redraw xterm remained pinned with baseY=316, viewportY=262, isUserScrolling=true).

Review

Six rounds of readiness review with adversarial verification ran against successive revisions. Rounds 1–3 found real defects, each now fixed — several by deleting the machinery they lived in rather than patching it:

  • Byte-scanning the PTY stream (r1) defeated the output scheduler's callback dedupe and could stitch a CSI 3 J out of a replayed byte range, yanking a pinned viewport. Replaced by observing the erase inside xterm's parser, so there is no scanner and no pre-write hook — beforeWrite is untouched by this PR.
  • Re-applying the pin while the buffer grew (r2) dragged the reader through live output, self-cancelled via the intent revision bump, and died on any write that added no rows — the common case for a redraw streamed token by token. Replaced by a single shot after a quiet period.
  • Capturing from the wrong place (r3): a second erase re-measured against the stub the first had already left; durable pre-remount coordinates were trusted over what the reader could actually see; the deadline restarted on every erase; and a stalled frame spent the pin against a half-rebuilt buffer.
  • Unguarded parser handlers (r2): xterm runs custom handlers inside WriteBuffer._innerWrite with no try/catch, where one throw wedges the pane's write pipeline permanently. Both handlers now use the repo's guardParserHandler.
  • CSI ? 3 J was missed entirely — xterm routes the private form to its own handler and it erases scrollback too.

Rounds 4–6 found no behavioural defects; their findings were test-coverage gaps, proven by mutation and now closed. Round 6 returned clean and measured the feature against a control (installed vs not) on headless xterm: identical end position for short and slow rebuilds, strictly better for a long rebuild. Because eraseInDisplay(3) always clamps to line 0 and the restore target is clamp(baseY - bottomOffset), the pin can only ever move the reader down from row 0 — never up, and never onto the bottom.

Security, back-compat and cross-platform: three renderer files, no dependency, lockfile, schema, migration, persisted state, settings, wire surface, mobile or relay consumer, and no network sink.

Validation

  • xterm-user-scrolling-contract: 39 passed (30 covering this path).
  • src/renderer/src/lib/pane-manager/: 662 passed, 1 skipped across 58 files.
  • src/renderer/src/components/terminal-pane/: 3154 passed across 245 files.
  • pnpm run typecheck:web, oxlint, React Doctor, oxfmt, git diff --check.

Tests drive real escape sequences through xterm's parser — the same path production uses. Each guard is mutation-verified: removing it fails a test. Four guards are deliberately redundant with checks inside restoreTerminalStructuralScrollIntent or with the live-at-bottom gate, and are commented as such so nobody mistakes them for independently covered.

Known trade-offs

  • The reader sits at the clamped position for the settle window (120ms, up to the 1s cap) before the pin lands.
  • The pin restores a row offset, not content — the content the reader was on is destroyed by the erase, so "same distance from the bottom" is an approximation by construction.
  • Cancellation depends on a scroll-intent revision bump. Every current scroll path bumps it; a future scroll-to-bottom path added without an intent write would need the same.

@coderabbitai

coderabbitai Bot commented Aug 5, 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
📝 Walkthrough

Walkthrough

Adds plain CSI 3J and private CSI ?3J detection for live scrollback erases. Captures pinned normal-buffer viewport state and restores it during parsed terminal writes. Integrates restoration installation and disposal with the PTY pane lifecycle. Adds tests for deferred restoration, redraws, cancellation, expiration, follow-output behavior, alternate-screen erases, and disposal.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation directly addresses issue #12663 by preventing Pi redraws from moving a pinned terminal viewport to the top.
Out of Scope Changes check ✅ Passed The code and tests are limited to terminal scrollback restoration and directly support the linked issue.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and concisely describes preserving pinned terminal scroll during live redraws.
Description check ✅ Passed The description clearly covers the change, behavior, root cause, review, validation, security, cross-platform scope, and trade-offs.

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 (2)
src/renderer/src/components/terminal-pane/pty-connection.ts (1)

6415-6428: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Give restoreLiveScrollback explicit per-PTY-stream ownership.

Every other recovery variable in this closure is retired on a stream change. clearHiddenOutputRestoreState and resetHiddenOutputRestoreIfPtyChanged reset hiddenOutputRestore*, restoredSnapshotBaseline*, and the renderer seq marks. restoreLiveScrollback is never reset. Two effects follow:

  • A pin captured on the previous PTY stream survives a reattach or fresh spawn. It is only retired indirectly, when isTerminalStructuralScrollIntentCurrent reports the snapshot is stale.
  • A second CSI 3J that arrives while a pin is pending replaces the older pin at line 6425. The replacement snapshot was taken after the first clear, so the original pinned offset is lost.

Clear the field where the other per-stream state is cleared, and keep the existing pin when one is already pending.

♻️ Proposed change
       const beforeWrite = (writeData: string): void => {
         const capturedRestore = captureTerminalLiveScrollbackRestore(pane.terminal, writeData)
-        if (capturedRestore) {
+        // Why: a pending pin holds the pre-clear viewport; a later capture already reads the cleared buffer.
+        if (capturedRestore && restoreLiveScrollback === null) {
           restoreLiveScrollback = capturedRestore
         }
         beforeTerminalOutputWrite(writeData)
       }

Also clear the field in clearHiddenOutputRestoreState:

function clearHiddenOutputRestoreState(): void {
  restoreLiveScrollback = null
  cancelSnapshotScrollRestore()
  // ...
}
src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts (1)

223-226: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document that line 223 is required setup, not only an assertion.

The call at line 223 stores the pending '\x1b[' prefix in the module-level WeakMap. Line 225 depends on that stored prefix to detect the split sequence. A future edit could delete line 223 as a redundant assertion and break line 226 in a way that is hard to diagnose.

Add one short comment that names the carried prefix.

♻️ Proposed change
+    // The first call carries the partial '\x1b[' prefix that the second call completes.
     expect(captureTerminalLiveScrollbackRestore(term, '\x1b[')).toBeNull()
     await write(term, '\x1b[')
     const restore = captureTerminalLiveScrollbackRestore(term, '3J')
     expect(restore).not.toBeNull()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 89e60b46-d6eb-401f-916b-008968d33400

📥 Commits

Reviewing files that changed from the base of the PR and between 2c2a326 and 4751a8facd3ff7bf8987554e45930390c6ffb857.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/pane-manager/terminal-live-scrollback-clear.ts
  • src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts

@nwparker
nwparker force-pushed the nwparker/pi-scroll branch from 4751a8f to f299cc7 Compare August 6, 2026 06:53
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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 Plus

Run ID: 956e2a8d-04e3-4e9d-93f5-5b4b33bf9f69

📥 Commits

Reviewing files that changed from the base of the PR and between f299cc7eaaa7c0fcf2cbf7794bead3d8c7b4ac1c and 76f466a29ad69f6fd97e984d4c25f5885e084e12.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/pane-manager/terminal-live-scrollback-clear.ts
  • src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/lib/pane-manager/terminal-live-scrollback-clear.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

@nwparker
nwparker force-pushed the nwparker/pi-scroll branch from 76f466a to 838d382 Compare August 6, 2026 08:15
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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.

♻️ Duplicate comments (1)
src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts (1)

307-313: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make the replacement viewport scrollable before testing cancellation.

After line 307, the rebuilt buffer has no scrollback. term.scrollLines(-2) is a no-op. The assertion only verifies the updated intent marker. It does not verify that a new user viewport position remains unchanged.

Write enough rows after CSI 3J to make baseY positive. Then scroll, record the new viewportY, and append more rows.

Proposed test adjustment
-    await write(term, '\x1b[2J\x1b[H\x1b[3Jafter-0\r\n')
+    await write(term, `\x1b[2J\x1b[H\x1b[3J${'after\r\n'.repeat(50)}`)
     term.scrollLines(-2)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a8408d09-9f65-4f85-bb54-f974c72cf69d

📥 Commits

Reviewing files that changed from the base of the PR and between c3db2b8 and 838d38225b238f7a39901a6cd7cf90290dd5c055.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/pane-manager/terminal-live-scrollback-clear.ts
  • src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts

@nwparker
nwparker force-pushed the nwparker/pi-scroll branch from 838d382 to 3ec1f7b Compare August 6, 2026 09:43
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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: 1

🧹 Nitpick comments (1)
src/renderer/src/lib/pane-manager/terminal-live-scrollback-clear.ts (1)

51-68: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce the documentation block.

Keep the JSDoc to the function contract. Retain only comments that describe non-obvious invariants not clear from the code.

As per coding guidelines: “Comments must be concise, limited to non-obvious information, and preferably one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 371f1c7a-401a-4ca6-9b58-644019c7bd06

📥 Commits

Reviewing files that changed from the base of the PR and between ead6b8e and 3ec1f7bf2733ce6d151f6dc0fd54730ad5b6addd.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/pane-manager/terminal-live-scrollback-clear.ts
  • src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/pane-manager/xterm-user-scrolling-contract.test.ts

@mmarabel

mmarabel commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Extra field context (not necessarily blocking this PR)

Left fuller notes on #12663: #12663 (comment)

Short version: we also hit a Pi regular-TUI “wheel does nothing” case (long session / after sub-agent; short Pi tab still scrolls). That may be adjacent to the clear-scrollback/redraw family this PR fixes (jump-to-top), or a separate sticky-mode path. Worth a re-test of dead-wheel after this lands; happy to open a dedicated issue if jump-to-top is fixed and dead-wheel remains.

@nwparker
nwparker force-pushed the nwparker/pi-scroll branch from 42d13c2 to 682b1c1 Compare August 6, 2026 20:44
Fixes stablyai#12663

A full-screen TUI redraw that erases the scrollback — Pi's /compact emits
ESC[2J ESC[H ESC[3J — took a reader who had scrolled up with it. xterm's
eraseInDisplay(3) clamps a scrolled-up viewport to line 0 and leaves
isUserScrolling latched, so the pane never resumes following on its own
and the reader is stranded wherever the erase dropped them. Orca's PTY
scheduler can parse the erase in one chunk and the rest of the redraw in
later ones, so the position is lost wherever the chunk boundary falls.

Observe the erase inside xterm's parser instead of scanning the byte
stream for it. The parser already carries a sequence split across writes,
and its handler runs at the exact point the erase is about to happen —
the only place where the rows written earlier in the same chunk are
already reflected in baseY, and where the buffer type says whether the
erase touches the scrollback we pinned at all. Both the plain CSI 3 J and
the private CSI ? 3 J are registered; xterm routes the private form to
its own handler and it erases scrollback too.

The pin is captured from the reader's live coordinates and restored once,
after output goes quiet, bounded by a deadline so a redraw that never
settles still lands. It fires exactly once: re-applying it per write
would turn a pinned viewport into follow-output-at-an-offset and drag the
reader through whatever the program printed next. It is abandoned if the
reader scrolls again, if the app switches screens, or if the rebuild
never grows enough to honour the offset — in which case the reader is
left where the erase already put them.

Both handlers go through guardParserHandler: xterm runs custom handlers
inside WriteBuffer._innerWrite with no try/catch, where one throw wedges
the pane's write pipeline for good.

Capture and restore both hang off xterm's own events, so installing this
is the whole integration — connectPanePty adds an install and a dispose
and nothing else. Verified against a control on headless xterm: the pin
can only ever move the reader down from the row the erase clamped them
to, never up and never onto the bottom, so it cannot leave anyone worse
off than the feature's absence.

Each guard is covered by a test that fails without it. Four guards are
deliberately redundant with checks inside restoreTerminalStructuralScrollIntent
or with the live-at-bottom gate and are commented as such.
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] Pi - sometimes it scroll to top

2 participants