Skip to content

fix(terminal): preserve follow output through streaming refocus - #11915

Merged
nwparker merged 4 commits into
stablyai:mainfrom
nwparker:nwparker/bug-terminal-viewport-jumps-to-top-while-kiro-cl
Aug 1, 2026
Merged

nwparker merged 4 commits into
stablyai:mainfrom
nwparker:nwparker/bug-terminal-viewport-jumps-to-top-while-kiro-cl

Conversation

@nwparker

@nwparker nwparker commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Keep a terminal that was following live output at the bottom when Orca refocuses or reveals it while queued agent output is streaming. A user-pinned historical viewport remains pinned.

Fixes #11753

Description

Refocus and heavy visibility recovery could sample xterm's viewport after queued output began parsing. During that write, xterm can transiently expose viewportY = 0 while its native scrolling flag is set, so Orca records the top as the user's pinned position and enforces it after recovery.

This change:

  • latches each pane's scroll intent before requesting or flushing backlog output;
  • removes the second heavy-resume sample that could overwrite the pre-recovery intent;
  • adds ordering unit coverage and a frame-by-frame Electron regression test.

The production behavior is renderer-local and uses the existing terminal abstractions, so it applies equally to native, folder-workspace, and SSH-backed terminals.

ELI5

When Orca refocused a busy terminal, it sometimes looked at the scroll position during the split second that xterm was rearranging new output. That temporary position looked like “the user scrolled to the top,” so Orca faithfully kept it there. Orca now remembers whether you were following output before it pours in the backlog, then preserves that intent through recovery.

Screenshots

[email protected]

Original WebM: VP8, 1920×1080. The streaming terminal stays on the newest rows through refocus and finishes with REFOCUS_STREAM_DONE visible at the bottom.

Proof

The new Electron test starts a real terminal with scrollback, queues a 400-row streaming burst, reproduces xterm's transient top-of-buffer geometry inside the queued write, and dispatches the same refocus recovery event. It samples the visible scrollbar thumb on every animation frame and verifies the final output marker is rendered.

Controlled red/green result:

  • Restoring the previous production ordering makes the test fail because the visible scrollbar remains away from the bottom.
  • With this fix, the recorded proof passes 3/3 and the hardened deterministic oracle passes 5/5; every sampled frame and the final visible scrollbar remain at the bottom.
SKIP_BUILD=1 ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test \
  tests/e2e/terminal-streaming-refocus-viewport.spec.ts \
  --config tests/playwright.config.ts \
  --project electron-headless \
  --workers=1 \
  --repeat-each=5

Testing

  • pnpm lint — the repository-wide command stops on existing unrelated warning gates detailed below; every changed file passes targeted oxlint.
  • pnpm typecheck
  • pnpm test — not run as one local monolithic command; the complete CI unit matrix passes on Node 24 and Node 26.
  • pnpm build — not run as one local command; CI packaging passes on macOS and Windows.
  • Added high-quality unit and Electron coverage that red/greens against the old ordering.

Proof of no regressions

  • Current-head CI: 44 checks passed, including static analysis, typecheck, all 32 Node 24/26 test shards, Git compatibility, shell contracts, macOS/Windows packaging, and the changed-spec Electron run. Two non-applicable conditional E2E jobs were skipped.
  • pnpm typecheck — passed locally.
  • Focused viewport intent/output scheduler unit suite — 5 files, 143 tests passed.
  • Hardened Electron regression — 5/5 repeated runs passed after removing the fixed sleep and stale active-tab capture.
  • Adjacent Electron coverage — 12 scenarios passed across follow-output, pinned viewport, streaming worktree switch, and inline-TUI reveal behavior. Eleven passed in the combined serial run; the remaining case initially could not create its fixture because the shared temporary repo was missing (ENOENT), then passed in isolation (1/1).
  • Targeted oxlint for all changed files — passed.
  • pnpm run check:reliability-gates — passed (59 gates).
  • pnpm run check:max-lines-ratchet — passed with no new bypasses.
  • git diff --check — passed.

Repository-wide pnpm lint reaches unrelated existing warning gates and stops on duplicate imports in two tests/tools/benchmarks/terminal-cold-park-*.mjs files. The type-aware repository audit likewise stops on unrelated restrict-template-expressions warnings in tests/tools/win-update-e2e/.

AI Review Report

The review checked the recovery ordering, follow-output and pinned-viewport state transitions, test observability, SSH/folder-workspace behavior, and cross-platform compatibility for macOS, Linux, and Windows. No shortcuts, labels, or Electron platform branches change.

Automated review flagged missing sync call-count coverage, opaque frame failures, Windows/POSIX shell quoting for the E2E fixture path, mistaken getTerminalContent timeout arguments, and undocumented test coupling to xterm internals/synchronous focus dispatch. All were corrected and the unit, typecheck, lint, and Electron regression checks were rerun. The latest Greptile review rates the change 5/5 and reports no files needing attention.

Terminal reliability contract

  • Invariant: queued output during refocus or reveal cannot turn a follow-output viewport into pinned-top intent; adjacent scroll-intent coverage continues to protect genuinely pinned viewports.
  • Oracle: unit tests require one pre-flush intent sync, while Electron samples the visible scrollbar on every animation frame and requires the final streamed marker at the bottom.
  • Determinism: readiness is based on rendered scrollback, viewport state, and scrollbar geometry; there is no fixed sleep.
  • Red/green: the controlled xterm wobble fails with post-flush sampling and passes with pre-flush intent latching.
  • Maturity: registered as experimental terminal-scroll.streaming-refocus-intent; 5/5 local Electron iterations passed.
  • Coverage gap: the shared renderer path applies to local, folder, SSH, WSL, and remote terminals, but this exact live race has only been exercised on macOS with a local PTY through the daemon.

Performance audit

PASS with no P0/P1/P2 findings. Wake recovery still performs one O(panes) intent pass before the existing bounded 64 KiB-per-pane flush. Heavy resume drops from two intent passes to one and retains its bounded 256 KiB-per-pane flush. No polling, timers, subprocesses, IPC, output parsing, global session scans, fit, or repaint work was added.

Production release scan

PASS with no P0/P1/P2 security, malware, supply-chain, dependency, or packaging findings across v1.4.163..593dd82efa (33 commits, 29 matched PRs). There are no lockfile, dependency, install-hook, native-module, binary, signing, packaged-resource, or release-workflow changes attributable to this PR. pnpm audit --prod reports zero vulnerabilities across 144 production dependencies.

Security Audit

No production input handling, authentication, secrets, dependencies, IPC contracts, filesystem access, or command execution are added. The E2E-only command uses the shared nodeTerminalCommand quoting path so macOS, Linux, and Windows invoke the runner Node executable safely even when PATH or fixture paths differ. PTY data injection remains confined to the existing E2E hook and uses static generated test data. The proof video is hosted as a GitHub attachment and is not committed.

Notes

  • The E2E wobble harness deliberately accesses xterm's private _core._bufferService fields to reproduce the transient geometry; it fails loudly if that version-coupled path changes.
  • The focus dispatch assertion deliberately verifies that the current recovery chain flushes synchronously through terminal.write.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Viewport intent synchronization now occurs before backlog requests and queued output flushes during window-wake recovery. Heavy visible-resume processing no longer synchronizes intents after flushing. Regression tests cover window-wake and heavy-reveal ordering. An end-to-end test verifies terminal presentation, bottom-following behavior, stream completion, and final scrollbar placement during streaming refocus.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes directly address issue #11753 by preserving bottom-following behavior during streaming output and refocus recovery.
Out of Scope Changes check ✅ Passed All code and test changes support the terminal viewport recovery fix described in issue #11753.
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 follow-output behavior during terminal streaming refocus.
Description check ✅ Passed The description includes all required sections, explains the change, documents testing exceptions, and provides AI review, security, and platform coverage.

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

🧹 Nitpick comments (2)
src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts (1)

171-174: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the sync call count so the removed post-flush sync stays removed.

The test pins only the first invocation order. If a later change reintroduces syncTerminalViewportIntents after the pane loop, this assertion still passes. The heavy-reveal test at line 191 already pins the count. Apply the same assertion here.

♻️ Proposed assertion
     expect(flushTerminalOutput).toHaveBeenCalledOnce()
+    expect(syncTerminalScrollIntentFromViewport).toHaveBeenCalledOnce()
     expect(syncTerminalScrollIntentFromViewport.mock.invocationCallOrder[0]).toBeLessThan(
       flushTerminalOutput.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
     )
tests/e2e/terminal-streaming-refocus-viewport.spec.ts (1)

187-199: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Report the offending frames instead of collapsing to a boolean.

Each assertion reduces the sampled frames to true or false. On failure the report shows only expected true, received false. The frame index and the thumb geometry are lost, which makes an intermittent failure hard to diagnose. Assert on the filtered frames so the values appear in the failure output.

♻️ Proposed refactor
-    expect(frames.every((frame) => frame.targetPresented)).toBe(true)
-    expect(
-      frames.every(
-        (frame) =>
-          frame.thumbTop !== null &&
-          frame.maxThumbTop !== null &&
-          Math.abs(frame.maxThumbTop - frame.thumbTop) <= 2
-      )
-    ).toBe(true)
+    expect(frames.filter((frame) => !frame.targetPresented)).toEqual([])
+    expect(
+      frames.filter(
+        (frame) =>
+          frame.thumbTop === null ||
+          frame.maxThumbTop === null ||
+          Math.abs(frame.maxThumbTop - frame.thumbTop) > 2
+      )
+    ).toEqual([])

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 91757da6-d002-4063-9fc8-474fc83dbf1b

📥 Commits

Reviewing files that changed from the base of the PR and between edb5607 and fa996ae.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts
  • src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts
  • tests/e2e/terminal-streaming-refocus-viewport.spec.ts

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a scroll-position race in terminal focus/visibility recovery. When xterm was processing backlog output during a refocus, it could transiently expose viewportY = 0 (with isUserScrolling = true), causing Orca to record "top of buffer" as the user's intent and enforce it for the rest of the session.

  • Production fix: syncTerminalViewportIntents is hoisted to run before flushTerminalOutput in recoverVisibleTerminalWindowWake, and the duplicate call inside resumeTerminalVisibilityHeavy is removed — the single pre-flush latch is now the only source of truth.
  • Unit coverage: Two new ordering tests use Vitest invocationCallOrder to assert that syncTerminalScrollIntentFromViewport always precedes flushTerminalOutput for both the window-wake and heavy-visibility-resume paths.
  • Electron E2E: A new spec injects xterm's transient top-of-buffer geometry via private _core._bufferService fields, dispatches a focus event, and verifies via per-frame scrollbar sampling that the thumb stays at the bottom throughout.

Confidence Score: 5/5

Safe to merge — the change is a two-line reordering of an existing call with no new state, no new IPC, and full unit + Electron E2E red/green coverage.

The fix moves a single function call earlier in both recovery paths so scroll intent is captured before xterm can transiently corrupt it. Minimal change with no new logic, no new state, and no side effects. Two new unit tests enforce the ordering invariant and a new Electron E2E test reproduces the exact race and validates frame-by-frame scrollbar position.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts Core fix: moves syncTerminalViewportIntents before the backlog flush loop in recoverVisibleTerminalWindowWake and removes the now-duplicate call from resumeTerminalVisibilityHeavy; logic is correct and the ordering invariant is enforced
src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts Two new unit tests verify the pre-flush intent-latch ordering via invocationCallOrder for both recoverVisibleTerminalWindowWake and the heavy resumeTerminalVisibility path; existing tests unchanged
tests/e2e/terminal-streaming-refocus-viewport.spec.ts New Electron E2E spec that reproduces the transient xterm geometry wobble and validates per-frame scrollbar position; relies on xterm private buffer fields (acknowledged in PR) and synchronous focus-event dispatch (noted in existing review thread)
config/reliability-gates.jsonc Adds a well-formed reliability gate entry covering the new unit and Electron E2E coverage, with appropriate maturity=experimental and promotion criteria

Sequence Diagram

sequenceDiagram
    participant App as App (focus/reveal event)
    participant RVR as recoverVisibleTerminalWindowWake
    participant RTV as resumeTerminalVisibility
    participant RTVH as resumeTerminalVisibilityHeavy
    participant SI as syncTerminalViewportIntents
    participant FO as flushTerminalOutput
    participant EI as enforceTerminalViewportIntents

    Note over RVR: Window wake / refocus path (FIXED)
    App->>RVR: focus event
    RVR->>SI: latch scroll intent (BEFORE flush)
    RVR->>FO: "flush backlog (xterm write - transient ydisp=0 here)"
    RVR->>EI: enforce latched intent

    Note over RTV,RTVH: Heavy visibility resume path (FIXED)
    App->>RTV: reveal event
    RTV->>SI: latch scroll intent (BEFORE heavy resume)
    RTV->>RTVH: resumeTerminalVisibilityHeavy
    RTVH->>FO: "flush backlog (xterm write - transient ydisp=0 here)"
    Note over RTVH: second syncTerminalViewportIntents removed
    RTV->>EI: enforce latched intent
Loading

Reviews (4): Last reviewed commit: "test(terminal): register refocus reliabi..." | Re-trigger Greptile

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]: Terminal viewport jumps to top while Kiro CLI is streaming output

1 participant